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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5f6a229791a1b3a78a97bdcde8b21c81d8f737fd | [
"super().__init__(frequencies, intensities, **meta)\nself.broadening_type = broadening_type\nself.breadth = breadth",
"from scipy.stats import norm\nif adjust_width:\n h = height\n if h < 1:\n h = 1\n z = target_zero / h\n breadth = np.sqrt(breadth ** 2 / (2 * np.log(1 / z)))\nbd = norm(loc=cen... | <|body_start_0|>
super().__init__(frequencies, intensities, **meta)
self.broadening_type = broadening_type
self.breadth = breadth
<|end_body_0|>
<|body_start_1|>
from scipy.stats import norm
if adjust_width:
h = height
if h < 1:
h = 1
... | A stick spectrum with associated broadening function | BroadenedSpectrum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadenedSpectrum:
"""A stick spectrum with associated broadening function"""
def __init__(self, frequencies, intensities, broadening_type='gaussian', breadth=10, **meta):
""":param frequencies: :type frequencies: :param intensities: :type intensities: :param broadening_type: the typ... | stack_v2_sparse_classes_36k_train_030500 | 14,581 | permissive | [
{
"docstring": ":param frequencies: :type frequencies: :param intensities: :type intensities: :param broadening_type: the type of broadening to apply (can be any function) :type broadening_type: \"gaussian\" | \"lorentzian\" | function :param breadth: the breadth or list of breads for the peaks in the spectrum ... | 5 | stack_v2_sparse_classes_30k_train_014288 | Implement the Python class `BroadenedSpectrum` described below.
Class description:
A stick spectrum with associated broadening function
Method signatures and docstrings:
- def __init__(self, frequencies, intensities, broadening_type='gaussian', breadth=10, **meta): :param frequencies: :type frequencies: :param intens... | Implement the Python class `BroadenedSpectrum` described below.
Class description:
A stick spectrum with associated broadening function
Method signatures and docstrings:
- def __init__(self, frequencies, intensities, broadening_type='gaussian', breadth=10, **meta): :param frequencies: :type frequencies: :param intens... | a4cd5ab76aed55a32bdc99c38d4295e2cace8026 | <|skeleton|>
class BroadenedSpectrum:
"""A stick spectrum with associated broadening function"""
def __init__(self, frequencies, intensities, broadening_type='gaussian', breadth=10, **meta):
""":param frequencies: :type frequencies: :param intensities: :type intensities: :param broadening_type: the typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BroadenedSpectrum:
"""A stick spectrum with associated broadening function"""
def __init__(self, frequencies, intensities, broadening_type='gaussian', breadth=10, **meta):
""":param frequencies: :type frequencies: :param intensities: :type intensities: :param broadening_type: the type of broadeni... | the_stack_v2_python_sparse | Psience/Spectra/BaseSpectrum.py | McCoyGroup/Psience | train | 7 |
4ac58a08175a5f50eee8a26ea3620fb596f4c4f8 | [
"for iout in range(0, len(nums) - 2):\n if iout > 0 and nums[iout - 1] == nums[iout]:\n continue\n j, k = (iout + 1, len(nums) - 1)\n while j < k:\n if nums[iout] + nums[j] + nums[k] == target - first_num:\n numj, numk = (nums[j], nums[k])\n while j < k and numj == nums[... | <|body_start_0|>
for iout in range(0, len(nums) - 2):
if iout > 0 and nums[iout - 1] == nums[iout]:
continue
j, k = (iout + 1, len(nums) - 1)
while j < k:
if nums[iout] + nums[j] + nums[k] == target - first_num:
numj, numk =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_030501 | 1,432 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, target, first_num, result)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, n... | 2 | stack_v2_sparse_classes_30k_train_015667 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target, first_num, result): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums, target, first_num, result): :type nums: List[int] :rtype: List[List[int]]
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rty... | 22f208400cd7e13fcf2ebf189e61ccad7e22b098 | <|skeleton|>
class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums, target, first_num, result):
""":type nums: List[int] :rtype: List[List[int]]"""
for iout in range(0, len(nums) - 2):
if iout > 0 and nums[iout - 1] == nums[iout]:
continue
j, k = (iout + 1, len(nums) - 1)
wh... | the_stack_v2_python_sparse | previously_completed/1-30/18-4sum.py | learnerjiahao/leetcode-solve | train | 0 | |
01cd4e1db7e8ae99266325317bf43a283b5a3c59 | [
"self._client = None\npool = redis.ConnectionPool\nif blocking_pool:\n pool = redis.BlockingConnectionPool\nself.pool = pool(host=host, port=port, db=db, **kwargs)",
"if self._client is None:\n self._client = redis.Redis(connection_pool=self.pool)\nreturn self._client"
] | <|body_start_0|>
self._client = None
pool = redis.ConnectionPool
if blocking_pool:
pool = redis.BlockingConnectionPool
self.pool = pool(host=host, port=port, db=db, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self._client is None:
self._client = redis.Re... | A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (int, optional): The REDIS port. Defaul... | RedisClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisClient:
"""A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port ... | stack_v2_sparse_classes_36k_train_030502 | 1,504 | permissive | [
{
"docstring": "Initialize class properties",
"name": "__init__",
"signature": "def __init__(self, host='localhost', port=6379, db=0, blocking_pool=False, **kwargs)"
},
{
"docstring": "Return an instance of redis.client.Redis.",
"name": "client",
"signature": "def client(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016078 | Implement the Python class `RedisClient` described below.
Class description:
A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The R... | Implement the Python class `RedisClient` described below.
Class description:
A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The R... | 7cf04fec048fadc71ff851970045b8a587269ccf | <|skeleton|>
class RedisClient:
"""A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisClient:
"""A shared REDIS client connection using a Connection Pool. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (int, optiona... | the_stack_v2_python_sparse | tcex/key_value_store/redis_client.py | TpyoKnig/tcex | train | 0 |
9c299051abb7e8dab6f12a35b9038c0d49fd05bc | [
"from apysc.expression import expression_file_util\nif not self._last_scope_is_if_or_elif():\n raise ValueError('Elif interface can only use right after If or Elif interfaces.\\n\\nMaybe you are using Int or String, or anything else comparison expression at Elif constructor (e.g., `with Elif(any_value == 10, ...... | <|body_start_0|>
from apysc.expression import expression_file_util
if not self._last_scope_is_if_or_elif():
raise ValueError('Elif interface can only use right after If or Elif interfaces.\n\nMaybe you are using Int or String, or anything else comparison expression at Elif constructor (e.g.,... | Elif | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
... | stack_v2_sparse_classes_36k_train_030503 | 1,724 | permissive | [
{
"docstring": "Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.",
"name": "_append_enter_expression",
"signature": "def _append_enter_expression(self) -> None"
},
{
"docstring": "Set expression last scope value.",
"nam... | 2 | null | Implement the Python class `Elif` described below.
Class description:
Implement the Elif class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.
- def _set_last_scop... | Implement the Python class `Elif` described below.
Class description:
Implement the Elif class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.
- def _set_last_scop... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
from apysc.expression import expression_file_util
if not self._last_scope_is_if_or_elif():
raise... | the_stack_v2_python_sparse | apysc/branch/_elif.py | TrendingTechnology/apysc | train | 0 | |
1a0adde30986b3e5e56cb18d8a120f8c73aafa5a | [
"if self._scId is not None:\n self._lines.append(data)\nelif self._chId is not None:\n if not self.novel.chapters[self._chId].title:\n self.novel.chapters[self._chId].title = data.strip()",
"if self._scId is not None:\n if tag == 'div':\n text = ''.join(self._lines)\n if text.startsw... | <|body_start_0|>
if self._scId is not None:
self._lines.append(data)
elif self._chId is not None:
if not self.novel.chapters[self._chId].title:
self.novel.chapters[self._chId].title = data.strip()
<|end_body_0|>
<|body_start_1|>
if self._scId is not None:... | ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions. | OdtRSceneDesc | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OdtRSceneDesc:
"""ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions."""
def handle_data(self, data):
"""Collect data withi... | stack_v2_sparse_classes_36k_train_030504 | 2,405 | permissive | [
{
"docstring": "Collect data within scene sections. Positional arguments: data: str -- text to be stored. Overrides the superclass method.",
"name": "handle_data",
"signature": "def handle_data(self, data)"
},
{
"docstring": "Recognize the end of the scene section and save data. Positional argum... | 2 | stack_v2_sparse_classes_30k_test_000292 | Implement the Python class `OdtRSceneDesc` described below.
Class description:
ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions.
Method signatures and docs... | Implement the Python class `OdtRSceneDesc` described below.
Class description:
ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions.
Method signatures and docs... | 33a868daed653c3371f5991d243a034668a80884 | <|skeleton|>
class OdtRSceneDesc:
"""ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions."""
def handle_data(self, data):
"""Collect data withi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OdtRSceneDesc:
"""ODT scene summaries file reader. Public methods: handle_data -- Collect data within scene sections. handle_endtag -- Recognize the paragraph's end. Import a full synopsis with invisibly tagged scene descriptions."""
def handle_data(self, data):
"""Collect data within scene secti... | the_stack_v2_python_sparse | src/pywriter/odt_r/odt_r_scenedesc.py | peter88213/PyWriter | train | 3 |
02caefed8e6134c5fc7c5f7a2a8e911d06ad1484 | [
"if isinstance(value, cls):\n if hasattr(value, table):\n return 1\nreturn 0",
"if cls.check(value):\n return value\nif isinstance(value, dbschema.TableSchema):\n return cls(table=value)\nelse:\n raise TypeError(\"%r couldn't be converted to a %s\" % (value, cls.__name__))"
] | <|body_start_0|>
if isinstance(value, cls):
if hasattr(value, table):
return 1
return 0
<|end_body_0|>
<|body_start_1|>
if cls.check(value):
return value
if isinstance(value, dbschema.TableSchema):
return cls(table=value)
else:... | A Join of a table, basically just a name:table item | JoinTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinTable:
"""A Join of a table, basically just a name:table item"""
def check(cls, value):
"""Check that value is a proper instance of this class"""
<|body_0|>
def coerce(cls, value):
"""Coerce a value to an instance of this class"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_030505 | 2,661 | no_license | [
{
"docstring": "Check that value is a proper instance of this class",
"name": "check",
"signature": "def check(cls, value)"
},
{
"docstring": "Coerce a value to an instance of this class",
"name": "coerce",
"signature": "def coerce(cls, value)"
}
] | 2 | null | Implement the Python class `JoinTable` described below.
Class description:
A Join of a table, basically just a name:table item
Method signatures and docstrings:
- def check(cls, value): Check that value is a proper instance of this class
- def coerce(cls, value): Coerce a value to an instance of this class | Implement the Python class `JoinTable` described below.
Class description:
A Join of a table, basically just a name:table item
Method signatures and docstrings:
- def check(cls, value): Check that value is a proper instance of this class
- def coerce(cls, value): Coerce a value to an instance of this class
<|skeleto... | 86410d2e8bece963ee7e7306560c94930467a1a7 | <|skeleton|>
class JoinTable:
"""A Join of a table, basically just a name:table item"""
def check(cls, value):
"""Check that value is a proper instance of this class"""
<|body_0|>
def coerce(cls, value):
"""Coerce a value to an instance of this class"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JoinTable:
"""A Join of a table, basically just a name:table item"""
def check(cls, value):
"""Check that value is a proper instance of this class"""
if isinstance(value, cls):
if hasattr(value, table):
return 1
return 0
def coerce(cls, value):
... | the_stack_v2_python_sparse | build/pytable/pytable/viewschema.py | icot/euler | train | 0 |
158bdea06384f951d854ad12c064e19c7407be56 | [
"if not s:\n return False\nreturn self.isSamme(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)",
"if not t1 and (not t2):\n return True\nelif t1 and t2:\n if t1.val == t2.val and self.isSamme(t1.left, t2.left) and self.isSamme(t1.right, t2.right):\n return True\nreturn False"
] | <|body_start_0|>
if not s:
return False
return self.isSamme(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
<|end_body_0|>
<|body_start_1|>
if not t1 and (not t2):
return True
elif t1 and t2:
if t1.val == t2.val and self.isSamme(t1.le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_0|>
def isSamme(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return False
... | stack_v2_sparse_classes_36k_train_030506 | 924 | no_license | [
{
"docstring": ":type s: TreeNode :type t: TreeNode :rtype: bool",
"name": "isSubtree",
"signature": "def isSubtree(self, s, t)"
},
{
"docstring": ":param t1: :param t2: :return:",
"name": "isSamme",
"signature": "def isSamme(self, t1, t2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000121 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
- def isSamme(self, t1, t2): :param t1: :param t2: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
- def isSamme(self, t1, t2): :param t1: :param t2: :return:
<|skeleton|>
class Solution:
def isS... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_0|>
def isSamme(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
if not s:
return False
return self.isSamme(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSamme(self, t1, t2):
""":param t1: :param t2: :return:"... | the_stack_v2_python_sparse | leetcode/tree/code/572.py | skyxyz-lang/CS_Note | train | 0 | |
7a0a387e5c7fb098f9aefd5cadb386b809e6e1c7 | [
"if user_id is None:\n return None\nsession_id = super().create_session(user_id)\nif session_id is None:\n return None\nnew_user_session = UserSession(session_id=session_id, user_id=user_id)\nnew_user_session.save()\nreturn session_id",
"if session_id is None:\n return None\nUserSession.load_from_file()\... | <|body_start_0|>
if user_id is None:
return None
session_id = super().create_session(user_id)
if session_id is None:
return None
new_user_session = UserSession(session_id=session_id, user_id=user_id)
new_user_session.save()
return session_id
<|end_... | Instance of the SessionDBAuth class | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""Instance of the SessionDBAuth class"""
def create_session(self, user_id=None) -> Union[str, None]:
"""Creates a session for a user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id=None) -> Union[str, None]:
"""Returns a user_id from ... | stack_v2_sparse_classes_36k_train_030507 | 2,164 | no_license | [
{
"docstring": "Creates a session for a user_id",
"name": "create_session",
"signature": "def create_session(self, user_id=None) -> Union[str, None]"
},
{
"docstring": "Returns a user_id from a session_id",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, ... | 3 | stack_v2_sparse_classes_30k_train_018829 | Implement the Python class `SessionDBAuth` described below.
Class description:
Instance of the SessionDBAuth class
Method signatures and docstrings:
- def create_session(self, user_id=None) -> Union[str, None]: Creates a session for a user_id
- def user_id_for_session_id(self, session_id=None) -> Union[str, None]: Re... | Implement the Python class `SessionDBAuth` described below.
Class description:
Instance of the SessionDBAuth class
Method signatures and docstrings:
- def create_session(self, user_id=None) -> Union[str, None]: Creates a session for a user_id
- def user_id_for_session_id(self, session_id=None) -> Union[str, None]: Re... | 5c340db92bf2a6cdff49574ce009c752772c051c | <|skeleton|>
class SessionDBAuth:
"""Instance of the SessionDBAuth class"""
def create_session(self, user_id=None) -> Union[str, None]:
"""Creates a session for a user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id=None) -> Union[str, None]:
"""Returns a user_id from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionDBAuth:
"""Instance of the SessionDBAuth class"""
def create_session(self, user_id=None) -> Union[str, None]:
"""Creates a session for a user_id"""
if user_id is None:
return None
session_id = super().create_session(user_id)
if session_id is None:
... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | OctopusHugz/holbertonschool-web_back_end | train | 0 |
b92683a12163d0187bfaff6a88eadd8b02cecf3a | [
"self.RootKey = RootKey\nself.OffsetToSubKeyName = OffsetToSubKeyName\nself.OffsetToValueName = OffsetToValueName\nself.OffsetToValue = OffsetToValue\nself.SubKeyName = SubKeyName\nself.ValueName = ValueName\nself.Value = PolicyValue(Value.valueType, Value.value)",
"if self.RootKey == other.RootKey and self.SubKe... | <|body_start_0|>
self.RootKey = RootKey
self.OffsetToSubKeyName = OffsetToSubKeyName
self.OffsetToValueName = OffsetToValueName
self.OffsetToValue = OffsetToValue
self.SubKeyName = SubKeyName
self.ValueName = ValueName
self.Value = PolicyValue(Value.valueType, Val... | Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements | Rule | [
"BSD-2-Clause-Patent"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements"""
def __init__(self, RootKey: int, SubKeyName: str, ValueName: str, Value, OffsetToSubKeyName: int=0, OffsetToValueName: int=0, OffsetToValue: int=0) -> None:
"""Init... | stack_v2_sparse_classes_36k_train_030508 | 33,094 | permissive | [
{
"docstring": "Inits the Rule Object. Args: RootKey (int): The root key value SubKeyName (str): the subkey name ValueName (str): Name of the rule value Value (PolicyValue): The value. OffsetToSubKeyName (:obj:`int`, optional): Offset to read the subkey name OffsetToValueName (:obj:`int`, optional): Offset to r... | 6 | stack_v2_sparse_classes_30k_train_012823 | Implement the Python class `Rule` described below.
Class description:
Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements
Method signatures and docstrings:
- def __init__(self, RootKey: int, SubKeyName: str, ValueName: str, Value, OffsetToSubKeyName: int=0, Offs... | Implement the Python class `Rule` described below.
Class description:
Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements
Method signatures and docstrings:
- def __init__(self, RootKey: int, SubKeyName: str, ValueName: str, Value, OffsetToSubKeyName: int=0, Offs... | 78295929b37af62a8cfc4c28eab72ed0c468f350 | <|skeleton|>
class Rule:
"""Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements"""
def __init__(self, RootKey: int, SubKeyName: str, ValueName: str, Value, OffsetToSubKeyName: int=0, OffsetToValueName: int=0, OffsetToValue: int=0) -> None:
"""Init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule:
"""Class for managing Rule structures. Class for storing, serializing, deserializing, & printing RULE elements"""
def __init__(self, RootKey: int, SubKeyName: str, ValueName: str, Value, OffsetToSubKeyName: int=0, OffsetToValueName: int=0, OffsetToValue: int=0) -> None:
"""Inits the Rule Ob... | the_stack_v2_python_sparse | edk2toollib/windows/policy/firmware_policy.py | tianocore/edk2-pytool-library | train | 47 |
36e2af7d7c44ce0ffb513bf610c33357a903fb5a | [
"N = len(s)\ncandidateSuffixStarts = []\nfor i in range(1, N):\n if s[i] == s[0]:\n candidateSuffixStarts.append(i)\nmaxLen = 0\nfor start in candidateSuffixStarts:\n if s[:N - start] == s[start:]:\n if N - start > maxLen:\n maxLen = N - start\nreturn s[:maxLen]",
"N = len(s)\nmaxLe... | <|body_start_0|>
N = len(s)
candidateSuffixStarts = []
for i in range(1, N):
if s[i] == s[0]:
candidateSuffixStarts.append(i)
maxLen = 0
for start in candidateSuffixStarts:
if s[:N - start] == s[start:]:
if N - start > maxLe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPrefix(self, s: str) -> str:
"""Brutal force."""
<|body_0|>
def longestPrefix2(self, s: str) -> str:
"""Rolling hash: 1. Calculate hash value for both prefix and suffix. 2. When the hash values are equal, it means we find a match. 3. For hash col... | stack_v2_sparse_classes_36k_train_030509 | 1,481 | no_license | [
{
"docstring": "Brutal force.",
"name": "longestPrefix",
"signature": "def longestPrefix(self, s: str) -> str"
},
{
"docstring": "Rolling hash: 1. Calculate hash value for both prefix and suffix. 2. When the hash values are equal, it means we find a match. 3. For hash collision, since s only con... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPrefix(self, s: str) -> str: Brutal force.
- def longestPrefix2(self, s: str) -> str: Rolling hash: 1. Calculate hash value for both prefix and suffix. 2. When the has... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPrefix(self, s: str) -> str: Brutal force.
- def longestPrefix2(self, s: str) -> str: Rolling hash: 1. Calculate hash value for both prefix and suffix. 2. When the has... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def longestPrefix(self, s: str) -> str:
"""Brutal force."""
<|body_0|>
def longestPrefix2(self, s: str) -> str:
"""Rolling hash: 1. Calculate hash value for both prefix and suffix. 2. When the hash values are equal, it means we find a match. 3. For hash col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPrefix(self, s: str) -> str:
"""Brutal force."""
N = len(s)
candidateSuffixStarts = []
for i in range(1, N):
if s[i] == s[0]:
candidateSuffixStarts.append(i)
maxLen = 0
for start in candidateSuffixStarts:
... | the_stack_v2_python_sparse | 2022/longest_happy_prefix.py | eronekogin/leetcode | train | 0 | |
cdd7d53e7076a12223cfe9a047fa457d007ff587 | [
"self.Id = id\nif transitions == None:\n self.Transitions = []\nself.IsStart = False\nself.IsEnd = False",
"for l in range(len(self.Transitions)):\n conditions = self.Transitions[l].Conditions\n transitionActions = TransitionActions([], [])\n transitionActions.Actions = [action for action in self.Tran... | <|body_start_0|>
self.Id = id
if transitions == None:
self.Transitions = []
self.IsStart = False
self.IsEnd = False
<|end_body_0|>
<|body_start_1|>
for l in range(len(self.Transitions)):
conditions = self.Transitions[l].Conditions
transitionAc... | # PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
"""# PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA"""
def __init__(self, id=None, transitions=None):
"""Constructor"""
<|body_0|>
def NextStateWithActions(self, word, charIndex=None, charIndexForward=True):
"""[charIndexForward] is used ... | stack_v2_sparse_classes_36k_train_030510 | 3,795 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, id=None, transitions=None)"
},
{
"docstring": "[charIndexForward] is used to specify the look ahead direction is it forward or backward.",
"name": "NextStateWithActions",
"signature": "def NextStateWithAct... | 2 | stack_v2_sparse_classes_30k_train_010807 | Implement the Python class `State` described below.
Class description:
# PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA
Method signatures and docstrings:
- def __init__(self, id=None, transitions=None): Constructor
- def NextStateWithActions(self, word, charIndex=None, charIndexForward=True): [charI... | Implement the Python class `State` described below.
Class description:
# PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA
Method signatures and docstrings:
- def __init__(self, id=None, transitions=None): Constructor
- def NextStateWithActions(self, word, charIndex=None, charIndexForward=True): [charI... | e02cf223442d50c4b11d926c79133496c79a4405 | <|skeleton|>
class State:
"""# PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA"""
def __init__(self, id=None, transitions=None):
"""Constructor"""
<|body_0|>
def NextStateWithActions(self, word, charIndex=None, charIndexForward=True):
"""[charIndexForward] is used ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
"""# PyUML: Do not remove this line! # XMI_ID:_qzIH5I35Ed-gg8GOK1TmhA"""
def __init__(self, id=None, transitions=None):
"""Constructor"""
self.Id = id
if transitions == None:
self.Transitions = []
self.IsStart = False
self.IsEnd = False
def ... | the_stack_v2_python_sparse | SourceCode/Controllers/Transducers/State.py | Qutuf/Qutuf | train | 112 |
dfa4e8a3b835f727db2f547abb07baa15e14b723 | [
"result = {}\nfor into in inputs:\n for i in into:\n if i in self.sim.agents:\n agentTags = self.sim.agents[i].access['tags']\n if tag in agentTags:\n result[i] = agentTags[tag]\nreturn result",
"result = {}\nag = bpy.context.scene.objects[self.userid]\nfor into in i... | <|body_start_0|>
result = {}
for into in inputs:
for i in into:
if i in self.sim.agents:
agentTags = self.sim.agents[i].access['tags']
if tag in agentTags:
result[i] = agentTags[tag]
return result
<|end_b... | Used to get information about other agent in a scene | AgentInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentInfo:
"""Used to get information about other agent in a scene"""
def getTag(self, inputs, tag):
"""For each agent in the input look up their tag"""
<|body_0|>
def headingRz(self, inputs):
"""For each agent in the input look up the relative heading about the ... | stack_v2_sparse_classes_36k_train_030511 | 4,006 | no_license | [
{
"docstring": "For each agent in the input look up their tag",
"name": "getTag",
"signature": "def getTag(self, inputs, tag)"
},
{
"docstring": "For each agent in the input look up the relative heading about the z axis",
"name": "headingRz",
"signature": "def headingRz(self, inputs)"
... | 3 | stack_v2_sparse_classes_30k_test_000045 | Implement the Python class `AgentInfo` described below.
Class description:
Used to get information about other agent in a scene
Method signatures and docstrings:
- def getTag(self, inputs, tag): For each agent in the input look up their tag
- def headingRz(self, inputs): For each agent in the input look up the relati... | Implement the Python class `AgentInfo` described below.
Class description:
Used to get information about other agent in a scene
Method signatures and docstrings:
- def getTag(self, inputs, tag): For each agent in the input look up their tag
- def headingRz(self, inputs): For each agent in the input look up the relati... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class AgentInfo:
"""Used to get information about other agent in a scene"""
def getTag(self, inputs, tag):
"""For each agent in the input look up their tag"""
<|body_0|>
def headingRz(self, inputs):
"""For each agent in the input look up the relative heading about the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentInfo:
"""Used to get information about other agent in a scene"""
def getTag(self, inputs, tag):
"""For each agent in the input look up their tag"""
result = {}
for into in inputs:
for i in into:
if i in self.sim.agents:
agentTag... | the_stack_v2_python_sparse | All_In_One/addons/CrowdMaster/cm_channels/cm_agentInfoChannels.py | 2434325680/Learnbgame | train | 0 |
531ca95260e3eeb6d3fd0a3bef7dcbbe36825420 | [
"super().__init__()\nself.common_tower = nn.Sequential(nn.Conv2d(3, channels, (3, 3), padding=(1, 1), bias=False), nn.BatchNorm2d(channels), nn.ReLU(), *(ResBlock(channels, res, separable, squeeze_size, squeeze_bias) for _ in range(blocks)))\nself.policy_head = nn.Sequential(nn.Conv2d(channels, 17, (1, 1)))\nself.w... | <|body_start_0|>
super().__init__()
self.common_tower = nn.Sequential(nn.Conv2d(3, channels, (3, 3), padding=(1, 1), bias=False), nn.BatchNorm2d(channels), nn.ReLU(), *(ResBlock(channels, res, separable, squeeze_size, squeeze_bias) for _ in range(blocks)))
self.policy_head = nn.Sequential(nn.Con... | GoogleModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle u... | stack_v2_sparse_classes_36k_train_030512 | 3,514 | no_license | [
{
"docstring": "Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle uses 32 channels for both heads.",
"name": "__init__",
"signature": "def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool... | 2 | stack_v2_sparse_classes_30k_train_004967 | Implement the Python class `GoogleModel` described below.
Class description:
Implement the GoogleModel class.
Method signatures and docstrings:
- def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool): Parameters us... | Implement the Python class `GoogleModel` described below.
Class description:
Implement the GoogleModel class.
Method signatures and docstrings:
- def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool): Parameters us... | 42d2fd7f67fb3ea093c2c170cee36dba402313bf | <|skeleton|>
class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle uses 32 channel... | the_stack_v2_python_sparse | python/models/google.py | KarelPeeters/STTT-Zero | train | 0 | |
3f4d30f8eb1acfb5021f625b7e7ad52c6ed27933 | [
"super(RNNEncoder, self).__init__(model_proto, is_training)\nif not isinstance(model_proto, text_encoders_pb2.RNNEncoder):\n raise ValueError('The model_proto has to be an instance of RNNEncoder.')\nif model_proto.cell_type != 'LSTM':\n raise ValueError('Only LSTM is supported.')\n\ndef _rnn_cell():\n cell... | <|body_start_0|>
super(RNNEncoder, self).__init__(model_proto, is_training)
if not isinstance(model_proto, text_encoders_pb2.RNNEncoder):
raise ValueError('The model_proto has to be an instance of RNNEncoder.')
if model_proto.cell_type != 'LSTM':
raise ValueError('Only LS... | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
<|body_0|>
def _set_init_fn(self, embedding_weights, filename):
"""Sets the init... | stack_v2_sparse_classes_36k_train_030513 | 4,861 | no_license | [
{
"docstring": "Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid.",
"name": "__init__",
"signature": "def __init__(self, model_proto, is_training)"
},
{
"docstring": "Sets the initialization function. Args: embedding_weight... | 3 | stack_v2_sparse_classes_30k_train_008730 | Implement the Python class `RNNEncoder` described below.
Class description:
Implement the RNNEncoder class.
Method signatures and docstrings:
- def __init__(self, model_proto, is_training): Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid.
- def... | Implement the Python class `RNNEncoder` described below.
Class description:
Implement the RNNEncoder class.
Method signatures and docstrings:
- def __init__(self, model_proto, is_training): Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid.
- def... | 2ea5e1405b1ab178b95f9c2cd9158b16847ac6a3 | <|skeleton|>
class RNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
<|body_0|>
def _set_init_fn(self, embedding_weights, filename):
"""Sets the init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes RNNEncoder. Args: model_proto: an instance of RNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
super(RNNEncoder, self).__init__(model_proto, is_training)
if not isinstance(model_proto, text_enco... | the_stack_v2_python_sparse | text_encoders/rnn_encoder.py | yekeren/ADVISE-Image_ads_understanding | train | 22 | |
a212f9177cddfd21f26c38cde85dfd683783b905 | [
"self.inputs = inputs\nself.activation = activation\nself.dropout = dropout\nself.training = tf.placeholder(tf.bool)\nshape = inputs.get_shape().as_list()\nblock = tf.reshape(inputs, [-1, 1, shape[1], shape[2]])\nfor i, f in enumerate(filters):\n with tf.variable_scope('block{0}'.format(i)):\n block = sel... | <|body_start_0|>
self.inputs = inputs
self.activation = activation
self.dropout = dropout
self.training = tf.placeholder(tf.bool)
shape = inputs.get_shape().as_list()
block = tf.reshape(inputs, [-1, 1, shape[1], shape[2]])
for i, f in enumerate(filters):
... | ResNet-style architecture for speech denoising. | ResNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
"""ResNet-style architecture for speech denoising."""
def __init__(self, inputs, output_size, filters=[128, 128, 256, 256], fc_layers=2, fc_nodes=2048, activation=tf.nn.relu, dropout=0.3):
"""Build the graph. Parameters ---------- inputs : Placeholder Spectral inputs to this ... | stack_v2_sparse_classes_36k_train_030514 | 4,326 | no_license | [
{
"docstring": "Build the graph. Parameters ---------- inputs : Placeholder Spectral inputs to this model, of the shape (batchsize, frames, frequencies) output_size : int Size of the output filters : list of ints Size of each block fc_layers : int Number of fully-connected hidden layers fc_nodes : int Number of... | 3 | stack_v2_sparse_classes_30k_train_012795 | Implement the Python class `ResNet` described below.
Class description:
ResNet-style architecture for speech denoising.
Method signatures and docstrings:
- def __init__(self, inputs, output_size, filters=[128, 128, 256, 256], fc_layers=2, fc_nodes=2048, activation=tf.nn.relu, dropout=0.3): Build the graph. Parameters... | Implement the Python class `ResNet` described below.
Class description:
ResNet-style architecture for speech denoising.
Method signatures and docstrings:
- def __init__(self, inputs, output_size, filters=[128, 128, 256, 256], fc_layers=2, fc_nodes=2048, activation=tf.nn.relu, dropout=0.3): Build the graph. Parameters... | 43a4ab5902a3247ee480df83de85f2b734097bc4 | <|skeleton|>
class ResNet:
"""ResNet-style architecture for speech denoising."""
def __init__(self, inputs, output_size, filters=[128, 128, 256, 256], fc_layers=2, fc_nodes=2048, activation=tf.nn.relu, dropout=0.3):
"""Build the graph. Parameters ---------- inputs : Placeholder Spectral inputs to this ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNet:
"""ResNet-style architecture for speech denoising."""
def __init__(self, inputs, output_size, filters=[128, 128, 256, 256], fc_layers=2, fc_nodes=2048, activation=tf.nn.relu, dropout=0.3):
"""Build the graph. Parameters ---------- inputs : Placeholder Spectral inputs to this model, of the... | the_stack_v2_python_sparse | resnet.py | OSU-slatelab/residual_mimic_net | train | 4 |
80c6b8358432cf7154f8f49aee162932d6dd34a4 | [
"super(PipedImagerPQProcess, self).__init__(group=None, target=None, name='PipedImagerPQ')\nself.__cmndpipe = cmndpipe\nself.__rspdpipe = rspdpipe\nself.__app = None\nself.__viewer = None",
"self.__app = QApplication(['PipedImagerPQ'])\nself.__viewer = PipedImagerPQ(self.__cmndpipe, self.__rspdpipe)\nmyresult = s... | <|body_start_0|>
super(PipedImagerPQProcess, self).__init__(group=None, target=None, name='PipedImagerPQ')
self.__cmndpipe = cmndpipe
self.__rspdpipe = rspdpipe
self.__app = None
self.__viewer = None
<|end_body_0|>
<|body_start_1|>
self.__app = QApplication(['PipedImager... | A Process specifically tailored for creating a PipedImagerPQ. | PipedImagerPQProcess | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
<|body_0|>
def run(self):
"""Create a ... | stack_v2_sparse_classes_36k_train_030515 | 40,479 | permissive | [
{
"docstring": "Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.",
"name": "__init__",
"signature": "def __init__(self, cmndpipe, rspdpipe)"
},
{
"docstring": "Create a PipedImagerPQ that is attached to the Pipe of this instance.",
"name": "run",
"... | 2 | stack_v2_sparse_classes_30k_val_000088 | Implement the Python class `PipedImagerPQProcess` described below.
Class description:
A Process specifically tailored for creating a PipedImagerPQ.
Method signatures and docstrings:
- def __init__(self, cmndpipe, rspdpipe): Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.
- def... | Implement the Python class `PipedImagerPQProcess` described below.
Class description:
A Process specifically tailored for creating a PipedImagerPQ.
Method signatures and docstrings:
- def __init__(self, cmndpipe, rspdpipe): Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run.
- def... | f21d878c776286ee333a44b99e0b31ad53d8917a | <|skeleton|>
class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
<|body_0|>
def run(self):
"""Create a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipedImagerPQProcess:
"""A Process specifically tailored for creating a PipedImagerPQ."""
def __init__(self, cmndpipe, rspdpipe):
"""Create a Process that will produce a PipedImagerPQ attached to the given Pipes when run."""
super(PipedImagerPQProcess, self).__init__(group=None, target=No... | the_stack_v2_python_sparse | pviewmod/pipedimagerpq.py | NOAA-PMEL/PyFerret | train | 61 |
87b39bb78b00a29a1a8e08aa10b1c673fa16f3cc | [
"self.file_name = str(file_name)\nself.idx_file = open(self.file_name, 'rb')\nself.bin_data = self.idx_file.read()\nself.magic_no, self.item_no, self.row_no, self.col_no = self.unpack()\nself.array = self.array_generation()",
"self.idx_file.seek(0)\nmagic_no = st.unpack('>4B', self.idx_file.read(4))\nitem_no = st... | <|body_start_0|>
self.file_name = str(file_name)
self.idx_file = open(self.file_name, 'rb')
self.bin_data = self.idx_file.read()
self.magic_no, self.item_no, self.row_no, self.col_no = self.unpack()
self.array = self.array_generation()
<|end_body_0|>
<|body_start_1|>
sel... | De_idx_set | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class De_idx_set:
def __init__(self, file_name):
"""Initiates decoding idx file for instance defined."""
<|body_0|>
def unpack(self):
"""Unpacks header info in idx file's first 15 bytes."""
<|body_1|>
def array_generation(self):
"""Generates a numpy ar... | stack_v2_sparse_classes_36k_train_030516 | 2,873 | no_license | [
{
"docstring": "Initiates decoding idx file for instance defined.",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "Unpacks header info in idx file's first 15 bytes.",
"name": "unpack",
"signature": "def unpack(self)"
},
{
"docstring": "Generat... | 3 | stack_v2_sparse_classes_30k_train_001239 | Implement the Python class `De_idx_set` described below.
Class description:
Implement the De_idx_set class.
Method signatures and docstrings:
- def __init__(self, file_name): Initiates decoding idx file for instance defined.
- def unpack(self): Unpacks header info in idx file's first 15 bytes.
- def array_generation(... | Implement the Python class `De_idx_set` described below.
Class description:
Implement the De_idx_set class.
Method signatures and docstrings:
- def __init__(self, file_name): Initiates decoding idx file for instance defined.
- def unpack(self): Unpacks header info in idx file's first 15 bytes.
- def array_generation(... | 45ccdfac84a348998d53bb75ed6bfbdad17344a9 | <|skeleton|>
class De_idx_set:
def __init__(self, file_name):
"""Initiates decoding idx file for instance defined."""
<|body_0|>
def unpack(self):
"""Unpacks header info in idx file's first 15 bytes."""
<|body_1|>
def array_generation(self):
"""Generates a numpy ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class De_idx_set:
def __init__(self, file_name):
"""Initiates decoding idx file for instance defined."""
self.file_name = str(file_name)
self.idx_file = open(self.file_name, 'rb')
self.bin_data = self.idx_file.read()
self.magic_no, self.item_no, self.row_no, self.col_no = sel... | the_stack_v2_python_sparse | Students/khalednakhleh/challenge_2/de_idx.py | CourseReps/ECEN689-Fall2018 | train | 5 | |
72f802d8f52419c39180f2005c7d5d769a5baf24 | [
"form = self.form_class(self.request.GET)\nform.is_valid()\nreturn form.get_queryset()",
"context = super().get_context_data(**kwargs)\ncontext['form'] = self.form_class(self.request.GET)\nreturn context"
] | <|body_start_0|>
form = self.form_class(self.request.GET)
form.is_valid()
return form.get_queryset()
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['form'] = self.form_class(self.request.GET)
return context
<|end_body_1|>
| View for searching for products to purchase. | ProductSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductSearch:
"""View for searching for products to purchase."""
def get_queryset(self):
"""Return a queryset of product ranges filtered by the request's GET params."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return context for the template."""
... | stack_v2_sparse_classes_36k_train_030517 | 5,763 | no_license | [
{
"docstring": "Return a queryset of product ranges filtered by the request's GET params.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Return context for the template.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
... | 2 | stack_v2_sparse_classes_30k_train_000028 | Implement the Python class `ProductSearch` described below.
Class description:
View for searching for products to purchase.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of product ranges filtered by the request's GET params.
- def get_context_data(self, **kwargs): Return context for t... | Implement the Python class `ProductSearch` described below.
Class description:
View for searching for products to purchase.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of product ranges filtered by the request's GET params.
- def get_context_data(self, **kwargs): Return context for t... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class ProductSearch:
"""View for searching for products to purchase."""
def get_queryset(self):
"""Return a queryset of product ranges filtered by the request's GET params."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Return context for the template."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductSearch:
"""View for searching for products to purchase."""
def get_queryset(self):
"""Return a queryset of product ranges filtered by the request's GET params."""
form = self.form_class(self.request.GET)
form.is_valid()
return form.get_queryset()
def get_contex... | the_stack_v2_python_sparse | purchases/views.py | stcstores/stcadmin | train | 0 |
2abd1c7e25e082d561d3ae07576d90ab0448832b | [
"h_median = detectionScratchLineMedian(img)\nh_std = detectionScratchLineStd(img)\nreturn (False, True)[h_median != 0 and h_std != 0]",
"h_median = detectionScratchLineMedian(img)\nimg_solved = defectCorrection(h_median, img)\nh_std = detectionScratchLineStd(img)\nimg_solved_v2 = defectCorrection(h_std, img_solve... | <|body_start_0|>
h_median = detectionScratchLineMedian(img)
h_std = detectionScratchLineStd(img)
return (False, True)[h_median != 0 and h_std != 0]
<|end_body_0|>
<|body_start_1|>
h_median = detectionScratchLineMedian(img)
img_solved = defectCorrection(h_median, img)
h_s... | BWFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BWFilter:
def check(self, img):
"""Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image"""
<|body_0|>
def clean(self, img):
"""Néttoie l'image du problème corrigé par le filtre img : Un tabl... | stack_v2_sparse_classes_36k_train_030518 | 944 | permissive | [
{
"docstring": "Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image",
"name": "check",
"signature": "def check(self, img)"
},
{
"docstring": "Néttoie l'image du problème corrigé par le filtre img : Un tableau Numpy RGB... | 2 | stack_v2_sparse_classes_30k_train_020982 | Implement the Python class `BWFilter` described below.
Class description:
Implement the BWFilter class.
Method signatures and docstrings:
- def check(self, img): Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image
- def clean(self, img): Né... | Implement the Python class `BWFilter` described below.
Class description:
Implement the BWFilter class.
Method signatures and docstrings:
- def check(self, img): Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image
- def clean(self, img): Né... | 90b59fc674fc2146634d1c1681f9b65083a7aa91 | <|skeleton|>
class BWFilter:
def check(self, img):
"""Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image"""
<|body_0|>
def clean(self, img):
"""Néttoie l'image du problème corrigé par le filtre img : Un tabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BWFilter:
def check(self, img):
"""Vérifie si le problème corrigé par le filtre est présent sur l'image d'entrée img : Un tableau Numpy RGB (576, 720, 3) de l'image"""
h_median = detectionScratchLineMedian(img)
h_std = detectionScratchLineStd(img)
return (False, True)[h_median ... | the_stack_v2_python_sparse | libs/filters/bw_filter.py | EpicKiwi/projet-datascience | train | 0 | |
4e2b53bbae950995afaec2bb6f69615fa982b8b0 | [
"self.sort_algorithms = _sort_algorithms\nself.costed_time = {}\nself.costed_space = {}\nself.question_size = {}\nfor name in list(self.sort_algorithms.values()):\n self.costed_time[name] = []\n self.costed_space[name] = []\n self.question_size[name] = []",
"data_loader = dataset.load_data\nif datastyle ... | <|body_start_0|>
self.sort_algorithms = _sort_algorithms
self.costed_time = {}
self.costed_space = {}
self.question_size = {}
for name in list(self.sort_algorithms.values()):
self.costed_time[name] = []
self.costed_space[name] = []
self.questio... | algorithm_analysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class algorithm_analysis:
def __init__(self, _sort_algorithms):
""":param _sort_algorithms: 排序算法的列表"""
<|body_0|>
def test_time(self, n, start, step, datastyle):
"""测试各个算法所用的时间 :param n: 数据的规模 :return: 数据保存再costed_time 里面"""
<|body_1|>
def test_space(self, n):... | stack_v2_sparse_classes_36k_train_030519 | 3,268 | no_license | [
{
"docstring": ":param _sort_algorithms: 排序算法的列表",
"name": "__init__",
"signature": "def __init__(self, _sort_algorithms)"
},
{
"docstring": "测试各个算法所用的时间 :param n: 数据的规模 :return: 数据保存再costed_time 里面",
"name": "test_time",
"signature": "def test_time(self, n, start, step, datastyle)"
},... | 3 | stack_v2_sparse_classes_30k_train_021393 | Implement the Python class `algorithm_analysis` described below.
Class description:
Implement the algorithm_analysis class.
Method signatures and docstrings:
- def __init__(self, _sort_algorithms): :param _sort_algorithms: 排序算法的列表
- def test_time(self, n, start, step, datastyle): 测试各个算法所用的时间 :param n: 数据的规模 :return: ... | Implement the Python class `algorithm_analysis` described below.
Class description:
Implement the algorithm_analysis class.
Method signatures and docstrings:
- def __init__(self, _sort_algorithms): :param _sort_algorithms: 排序算法的列表
- def test_time(self, n, start, step, datastyle): 测试各个算法所用的时间 :param n: 数据的规模 :return: ... | 02e86e8c6c08c565fa958541057fd79fc5c9f6ff | <|skeleton|>
class algorithm_analysis:
def __init__(self, _sort_algorithms):
""":param _sort_algorithms: 排序算法的列表"""
<|body_0|>
def test_time(self, n, start, step, datastyle):
"""测试各个算法所用的时间 :param n: 数据的规模 :return: 数据保存再costed_time 里面"""
<|body_1|>
def test_space(self, n):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class algorithm_analysis:
def __init__(self, _sort_algorithms):
""":param _sort_algorithms: 排序算法的列表"""
self.sort_algorithms = _sort_algorithms
self.costed_time = {}
self.costed_space = {}
self.question_size = {}
for name in list(self.sort_algorithms.values()):
... | the_stack_v2_python_sparse | statistic.py | CUIT-algorithm-analysis-team/algorithm-analysis | train | 0 | |
43d76d82a3febc268f235315ece3a3e5423d0b62 | [
"if fx is None:\n\n def fx(x):\n np.logical_not(np.isnan(x).sum(0))\nself._fx = fx",
"mask = self._fx(ds.samples)\nds_ = ds[:, mask]\nreturn ds_"
] | <|body_start_0|>
if fx is None:
def fx(x):
np.logical_not(np.isnan(x).sum(0))
self._fx = fx
<|end_body_0|>
<|body_start_1|>
mask = self._fx(ds.samples)
ds_ = ds[:, mask]
return ds_
<|end_body_1|>
| FeatureExpressionSlicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str... | stack_v2_sparse_classes_36k_train_030520 | 7,736 | no_license | [
{
"docstring": "This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str The sample attribute to use for slicing and calculating values. compar... | 2 | stack_v2_sparse_classes_30k_train_004877 | Implement the Python class `FeatureExpressionSlicer` described below.
Class description:
Implement the FeatureExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, fx=np.greater): This object is used when we want to slice samples based on some values and thresholds. For example if we want to ... | Implement the Python class `FeatureExpressionSlicer` described below.
Class description:
Implement the FeatureExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, fx=np.greater): This object is used when we want to slice samples based on some values and thresholds. For example if we want to ... | 3adbbd4feaaac4d1bb00e88f9ed62debef2a0483 | <|skeleton|>
class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str The sample at... | the_stack_v2_python_sparse | pyitab/preprocessing/slicers.py | robbisg/pyitab | train | 1 | |
796e5e6b4b46acac20093dad291aec99ae8ff88d | [
"self._ptnmap_var_val: Optional[Dict[str, Tuple[re.Pattern, str]]] = None\nif var_val_pairs:\n self._ptnmap_var_val = dict()\n for var_val_pair in var_val_pairs:\n cnt_eq_sym = var_val_pair.count(ARGPARSER_VARARG_SUBVAR_VAL_SEP)\n if cnt_eq_sym < 1:\n raise RuntimeError(f'No f{ARGPARS... | <|body_start_0|>
self._ptnmap_var_val: Optional[Dict[str, Tuple[re.Pattern, str]]] = None
if var_val_pairs:
self._ptnmap_var_val = dict()
for var_val_pair in var_val_pairs:
cnt_eq_sym = var_val_pair.count(ARGPARSER_VARARG_SUBVAR_VAL_SEP)
if cnt_eq_... | Utility class to process variable/substituting-value specification and perform lookup and substitution in strings. | VariableSub | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariableSub:
"""Utility class to process variable/substituting-value specification and perform lookup and substitution in strings."""
def __init__(self, var_val_pairs: Optional[List[str]]):
"""Constructor. :param var_val_pairs: A dict where keys are variables (without '$') while valu... | stack_v2_sparse_classes_36k_train_030521 | 19,298 | permissive | [
{
"docstring": "Constructor. :param var_val_pairs: A dict where keys are variables (without '$') while values are tuples of compiled Pattern instances for the variable (with '$') and values (to substitute) for variables.",
"name": "__init__",
"signature": "def __init__(self, var_val_pairs: Optional[List... | 3 | stack_v2_sparse_classes_30k_train_016308 | Implement the Python class `VariableSub` described below.
Class description:
Utility class to process variable/substituting-value specification and perform lookup and substitution in strings.
Method signatures and docstrings:
- def __init__(self, var_val_pairs: Optional[List[str]]): Constructor. :param var_val_pairs:... | Implement the Python class `VariableSub` described below.
Class description:
Utility class to process variable/substituting-value specification and perform lookup and substitution in strings.
Method signatures and docstrings:
- def __init__(self, var_val_pairs: Optional[List[str]]): Constructor. :param var_val_pairs:... | 72fe76eb715d4e0be60616d282230fa90ad7250f | <|skeleton|>
class VariableSub:
"""Utility class to process variable/substituting-value specification and perform lookup and substitution in strings."""
def __init__(self, var_val_pairs: Optional[List[str]]):
"""Constructor. :param var_val_pairs: A dict where keys are variables (without '$') while valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VariableSub:
"""Utility class to process variable/substituting-value specification and perform lookup and substitution in strings."""
def __init__(self, var_val_pairs: Optional[List[str]]):
"""Constructor. :param var_val_pairs: A dict where keys are variables (without '$') while values are tuples... | the_stack_v2_python_sparse | src/mixcli/command/run/data.py | zhuoyanli/nuance_mix_pycli | train | 0 |
1bdf9ceedbcd9b610ad929694d57c8950e452418 | [
"res = []\n\ndef dfs_preorder(node):\n if not node:\n return\n res.append(str(node.val))\n dfs_preorder(node.left)\n dfs_preorder(node.right)\ndfs_preorder(root)\nreturn '' if not res else '|'.join(res)",
"def dfs_restore(lis):\n father = TreeNode(lis[0])\n length = len(lis)\n if lengt... | <|body_start_0|>
res = []
def dfs_preorder(node):
if not node:
return
res.append(str(node.val))
dfs_preorder(node.left)
dfs_preorder(node.right)
dfs_preorder(root)
return '' if not res else '|'.join(res)
<|end_body_0|>
<|b... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
... | stack_v2_sparse_classes_36k_train_030522 | 2,043 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
res = []
def dfs_preorder(node):
if not node:
return
res.append(str(node.val))
dfs_preorder(node.left)
dfs_preorder(node.right)
... | the_stack_v2_python_sparse | _CodeTopics/LeetCode/401-600/000449/000449.py3 | BIAOXYZ/variousCodes | train | 0 | |
a04044e9a977cc2b8cfb06e16ffbda1078b23b7b | [
"try:\n in_progress = self._published_tls.in_progress\nexcept AttributeError:\n in_progress = self._published_tls.in_progress = set()\nif self.pk and self in in_progress:\n return\nif self.pk:\n in_progress.add(self)\nfields = api.utils.walk_model_fields(type(self))\nfor kind, field_name, model_class in... | <|body_start_0|>
try:
in_progress = self._published_tls.in_progress
except AttributeError:
in_progress = self._published_tls.in_progress = set()
if self.pk and self in in_progress:
return
if self.pk:
in_progress.add(self)
fields = a... | Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.py. | PublishableMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublishableMixin:
"""Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.py."""
def _mark_children_published... | stack_v2_sparse_classes_36k_train_030523 | 11,905 | no_license | [
{
"docstring": "Figure out all this model's related fields, then walk all of them and set their is_published=True.",
"name": "_mark_children_published",
"signature": "def _mark_children_published(self)"
},
{
"docstring": "If we're inside a web request and there is an authenticated user, automati... | 2 | stack_v2_sparse_classes_30k_train_000614 | Implement the Python class `PublishableMixin` described below.
Class description:
Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.p... | Implement the Python class `PublishableMixin` described below.
Class description:
Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.p... | 5ca3b26d7414c6a32626a6192345efd158f81128 | <|skeleton|>
class PublishableMixin:
"""Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.py."""
def _mark_children_published... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublishableMixin:
"""Model mix-in that adds fields representing approved/unapproved state of some object. Django rest_framework API is configured to implement our permission rules if an object about to be modified inherits from this class. See api/viewsets.py."""
def _mark_children_published(self):
... | the_stack_v2_python_sparse | core_types/models.py | u4i-admin2/IPA | train | 1 |
eed4b5c8e95548a1e2158ca10e1455e5398fc8aa | [
"super().__init__(hass, car, coordinator)\nself.type = 'polling'\nself._attr_icon = 'mdi:car-connected'\nself._attr_entity_category = EntityCategory.DIAGNOSTIC",
"if self._coordinator.controller.get_updates(vin=self._car.vin) is None:\n return None\nreturn bool(self._coordinator.controller.get_updates(vin=self... | <|body_start_0|>
super().__init__(hass, car, coordinator)
self.type = 'polling'
self._attr_icon = 'mdi:car-connected'
self._attr_entity_category = EntityCategory.DIAGNOSTIC
<|end_body_0|>
<|body_start_1|>
if self._coordinator.controller.get_updates(vin=self._car.vin) is None:
... | Representation of a polling switch. | TeslaCarPolling | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeslaCarPolling:
"""Representation of a polling switch."""
def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None:
"""Initialize polling entity."""
<|body_0|>
def is_on(self):
"""Return True if updates available.""... | stack_v2_sparse_classes_36k_train_030524 | 7,384 | no_license | [
{
"docstring": "Initialize polling entity.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None"
},
{
"docstring": "Return True if updates available.",
"name": "is_on",
"signature": "def is_on(self)"
... | 4 | stack_v2_sparse_classes_30k_train_014610 | Implement the Python class `TeslaCarPolling` described below.
Class description:
Representation of a polling switch.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None: Initialize polling entity.
- def is_on(self): Return True if... | Implement the Python class `TeslaCarPolling` described below.
Class description:
Representation of a polling switch.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None: Initialize polling entity.
- def is_on(self): Return True if... | 27da147c784cb91fc616f4b2fb89127c5ef044b4 | <|skeleton|>
class TeslaCarPolling:
"""Representation of a polling switch."""
def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None:
"""Initialize polling entity."""
<|body_0|>
def is_on(self):
"""Return True if updates available.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeslaCarPolling:
"""Representation of a polling switch."""
def __init__(self, hass: HomeAssistant, car: TeslaCar, coordinator: TeslaDataUpdateCoordinator) -> None:
"""Initialize polling entity."""
super().__init__(hass, car, coordinator)
self.type = 'polling'
self._attr_ic... | the_stack_v2_python_sparse | custom_components/tesla_custom/switch.py | rtclauss/hass-config | train | 10 |
e3eb1b02ae921519e55242884e0d2cd2a382534f | [
"self.verify_batch_spec_sampling_kwargs_exists(batch_spec)\nself.verify_batch_spec_sampling_kwargs_key_exists('n', batch_spec)\nn: int = batch_spec['sampling_kwargs']['n']\nreturn df.limit(n)",
"p: float = self.get_sampling_kwargs_value_or_default(batch_spec=batch_spec, sampling_kwargs_key='p', default_value=0.1)... | <|body_start_0|>
self.verify_batch_spec_sampling_kwargs_exists(batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists('n', batch_spec)
n: int = batch_spec['sampling_kwargs']['n']
return df.limit(n)
<|end_body_0|>
<|body_start_1|>
p: float = self.get_sampling_kwargs_value_... | Methods for sampling a Spark dataframe. | SparkDataSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparkDataSampler:
"""Methods for sampling a Spark dataframe."""
def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Sample the first n rows of data. Args: df: Spark dataframe. batch_spec: Should contain key `n` in sampling_kwargs, the n... | stack_v2_sparse_classes_36k_train_030525 | 6,827 | permissive | [
{
"docstring": "Sample the first n rows of data. Args: df: Spark dataframe. batch_spec: Should contain key `n` in sampling_kwargs, the number of values in the sample e.g. sampling_kwargs={\"n\": 100}. Returns: Sampled dataframe Raises: SamplerError",
"name": "sample_using_limit",
"signature": "def sampl... | 5 | null | Implement the Python class `SparkDataSampler` described below.
Class description:
Methods for sampling a Spark dataframe.
Method signatures and docstrings:
- def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame: Sample the first n rows of data. Args: df: Spark dataframe. bat... | Implement the Python class `SparkDataSampler` described below.
Class description:
Methods for sampling a Spark dataframe.
Method signatures and docstrings:
- def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame: Sample the first n rows of data. Args: df: Spark dataframe. bat... | b0290e2fd2aa05aec6d7d8871b91cb4478e9501d | <|skeleton|>
class SparkDataSampler:
"""Methods for sampling a Spark dataframe."""
def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Sample the first n rows of data. Args: df: Spark dataframe. batch_spec: Should contain key `n` in sampling_kwargs, the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparkDataSampler:
"""Methods for sampling a Spark dataframe."""
def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Sample the first n rows of data. Args: df: Spark dataframe. batch_spec: Should contain key `n` in sampling_kwargs, the number of valu... | the_stack_v2_python_sparse | great_expectations/execution_engine/split_and_sample/sparkdf_data_sampler.py | great-expectations/great_expectations | train | 8,931 |
080f763229dc6df2d2a54807ffab2b120f726c4e | [
"super(TimeAwareMultiHeadAttention, self).__init__()\nself.Q_w = torch.nn.Linear(hidden_size, hidden_size)\nself.K_w = torch.nn.Linear(hidden_size, hidden_size)\nself.V_w = torch.nn.Linear(hidden_size, hidden_size)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.softmax = torch.nn.Softmax(dim=-1)\nself.hidde... | <|body_start_0|>
super(TimeAwareMultiHeadAttention, self).__init__()
self.Q_w = torch.nn.Linear(hidden_size, hidden_size)
self.K_w = torch.nn.Linear(hidden_size, hidden_size)
self.V_w = torch.nn.Linear(hidden_size, hidden_size)
self.dropout = torch.nn.Dropout(p=dropout_rate)
... | TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description] | TimeAwareMultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeAwareMultiHeadAttention:
"""TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_size, head_num, dropout_rate):
"""Class Initialization. Args: hidden_size ([type]): [description] head_num ([type]): [description] dropout_rate... | stack_v2_sparse_classes_36k_train_030526 | 15,823 | permissive | [
{
"docstring": "Class Initialization. Args: hidden_size ([type]): [description] head_num ([type]): [description] dropout_rate ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, hidden_size, head_num, dropout_rate)"
},
{
"docstring": "Forward function. Args: queries ([... | 2 | stack_v2_sparse_classes_30k_train_008211 | Implement the Python class `TimeAwareMultiHeadAttention` described below.
Class description:
TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_size, head_num, dropout_rate): Class Initialization. Args: hidden_size ([type]): [d... | Implement the Python class `TimeAwareMultiHeadAttention` described below.
Class description:
TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_size, head_num, dropout_rate): Class Initialization. Args: hidden_size ([type]): [d... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class TimeAwareMultiHeadAttention:
"""TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_size, head_num, dropout_rate):
"""Class Initialization. Args: hidden_size ([type]): [description] head_num ([type]): [description] dropout_rate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeAwareMultiHeadAttention:
"""TimeAwareMultiHeadAttention forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_size, head_num, dropout_rate):
"""Class Initialization. Args: hidden_size ([type]): [description] head_num ([type]): [description] dropout_rate ([type]): [d... | the_stack_v2_python_sparse | beta_rec/models/tisasrec.py | beta-team/beta-recsys | train | 156 |
44f5671b19b1cff8a3a7ed858ff730707a2a3a52 | [
"super().__init__()\nself.mean = mean\nself.std = std",
"g = g.local_var()\nh = g.ndata.pop('atom_features')\ng.ndata['atom_features'] = (h - self.mean) / self.std\nreturn g"
] | <|body_start_0|>
super().__init__()
self.mean = mean
self.std = std
<|end_body_0|>
<|body_start_1|>
g = g.local_var()
h = g.ndata.pop('atom_features')
g.ndata['atom_features'] = (h - self.mean) / self.std
return g
<|end_body_1|>
| Standardize atom_features: subtract mean and divide by std. | Standardize | [
"NIST-PD"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Standardize:
"""Standardize atom_features: subtract mean and divide by std."""
def __init__(self, mean: torch.Tensor, std: torch.Tensor):
"""Register featurewise mean and standard deviation."""
<|body_0|>
def forward(self, g: dgl.DGLGraph):
"""Apply standardizati... | stack_v2_sparse_classes_36k_train_030527 | 22,706 | permissive | [
{
"docstring": "Register featurewise mean and standard deviation.",
"name": "__init__",
"signature": "def __init__(self, mean: torch.Tensor, std: torch.Tensor)"
},
{
"docstring": "Apply standardization to atom_features.",
"name": "forward",
"signature": "def forward(self, g: dgl.DGLGraph... | 2 | stack_v2_sparse_classes_30k_test_000946 | Implement the Python class `Standardize` described below.
Class description:
Standardize atom_features: subtract mean and divide by std.
Method signatures and docstrings:
- def __init__(self, mean: torch.Tensor, std: torch.Tensor): Register featurewise mean and standard deviation.
- def forward(self, g: dgl.DGLGraph)... | Implement the Python class `Standardize` described below.
Class description:
Standardize atom_features: subtract mean and divide by std.
Method signatures and docstrings:
- def __init__(self, mean: torch.Tensor, std: torch.Tensor): Register featurewise mean and standard deviation.
- def forward(self, g: dgl.DGLGraph)... | 1c44aba9e648b21744b0d306b1ea9b3c73a5b0fb | <|skeleton|>
class Standardize:
"""Standardize atom_features: subtract mean and divide by std."""
def __init__(self, mean: torch.Tensor, std: torch.Tensor):
"""Register featurewise mean and standard deviation."""
<|body_0|>
def forward(self, g: dgl.DGLGraph):
"""Apply standardizati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Standardize:
"""Standardize atom_features: subtract mean and divide by std."""
def __init__(self, mean: torch.Tensor, std: torch.Tensor):
"""Register featurewise mean and standard deviation."""
super().__init__()
self.mean = mean
self.std = std
def forward(self, g: dg... | the_stack_v2_python_sparse | jarvis/core/graphs.py | tavazza/jarvis | train | 0 |
a3baa22307cf1f2b3fe36efffea78c0dc62ea697 | [
"assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.LassoModel(_py2java(sc, self._coeff), self.intercept)\njava_model.save(sc._jsc.sc(), path)",
"assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.LassoModel.load(sc._jsc.sc(), path)\nweights = _java2... | <|body_start_0|>
assert sc._jvm is not None
java_model = sc._jvm.org.apache.spark.mllib.regression.LassoModel(_py2java(sc, self._coeff), self.intercept)
java_model.save(sc._jsc.sc(), path)
<|end_body_0|>
<|body_start_1|>
assert sc._jvm is not None
java_model = sc._jvm.org.apache... | A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, [1.0]), ... LabeledPoint... | LassoModel | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LassoModel:
"""A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... Labe... | stack_v2_sparse_classes_36k_train_030528 | 36,577 | permissive | [
{
"docstring": "Save a LassoModel.",
"name": "save",
"signature": "def save(self, sc: SparkContext, path: str) -> None"
},
{
"docstring": "Load a LassoModel.",
"name": "load",
"signature": "def load(cls, sc: SparkContext, path: str) -> 'LassoModel'"
}
] | 2 | null | Implement the Python class `LassoModel` described below.
Class description:
A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [... | Implement the Python class `LassoModel` described below.
Class description:
A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [... | 60d8fc49bec5dae1b8cf39a0670cb640b430f520 | <|skeleton|>
class LassoModel:
"""A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... Labe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LassoModel:
"""A linear regression model derived from a least-squares fit with an l_1 penalty term. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0,... | the_stack_v2_python_sparse | python/pyspark/mllib/regression.py | apache/spark | train | 39,983 |
e91db422cfa51cc16646b53f7c3e28bfa1eb264a | [
"self.costo.form.validate()\nself.errlist.extend(self.costo.form.errlist)\nif self.modo_trasp.data == 'spec' and (not self.costo_trasporto.validate(self)):\n self.errlist.append('errore spese di trasporto')\nreturn len(self.errlist) == 0",
"ret = fk.Markup(' Importo: ') + self.costo.rend... | <|body_start_0|>
self.costo.form.validate()
self.errlist.extend(self.costo.form.errlist)
if self.modo_trasp.data == 'spec' and (not self.costo_trasporto.validate(self)):
self.errlist.append('errore spese di trasporto')
return len(self.errlist) == 0
<|end_body_0|>
<|body_star... | Form per costo+trasporto | CostoPiuTrasporto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CostoPiuTrasporto:
"""Form per costo+trasporto"""
def validate(self, *_unused1, **_unused2):
"""Validazione del form"""
<|body_0|>
def renderme(self, **_unused):
"""Rendering del form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.costo.fo... | stack_v2_sparse_classes_36k_train_030529 | 29,683 | no_license | [
{
"docstring": "Validazione del form",
"name": "validate",
"signature": "def validate(self, *_unused1, **_unused2)"
},
{
"docstring": "Rendering del form",
"name": "renderme",
"signature": "def renderme(self, **_unused)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002307 | Implement the Python class `CostoPiuTrasporto` described below.
Class description:
Form per costo+trasporto
Method signatures and docstrings:
- def validate(self, *_unused1, **_unused2): Validazione del form
- def renderme(self, **_unused): Rendering del form | Implement the Python class `CostoPiuTrasporto` described below.
Class description:
Form per costo+trasporto
Method signatures and docstrings:
- def validate(self, *_unused1, **_unused2): Validazione del form
- def renderme(self, **_unused): Rendering del form
<|skeleton|>
class CostoPiuTrasporto:
"""Form per cos... | 66f5899eaddc4e0bfcb24cfa04f8573d6dc2eb47 | <|skeleton|>
class CostoPiuTrasporto:
"""Form per costo+trasporto"""
def validate(self, *_unused1, **_unused2):
"""Validazione del form"""
<|body_0|>
def renderme(self, **_unused):
"""Rendering del form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CostoPiuTrasporto:
"""Form per costo+trasporto"""
def validate(self, *_unused1, **_unused2):
"""Validazione del form"""
self.costo.form.validate()
self.errlist.extend(self.costo.form.errlist)
if self.modo_trasp.data == 'spec' and (not self.costo_trasporto.validate(self)):
... | the_stack_v2_python_sparse | bin/forms.py | lfini/acquisti | train | 0 |
18d469840d0f33d2799d913dd1cad491db1d907a | [
"ret = []\nencoder = ': '\nfor string in strs:\n for char in string:\n if char == ':':\n ret.append('::')\n else:\n ret.append(char)\n ret.append(encoder)\nreturn ''.join(ret)",
"encoder = ': '\nret = []\ntemp = []\nindex = 0\nwhile index < len(s):\n if s[index] == ':'... | <|body_start_0|>
ret = []
encoder = ': '
for string in strs:
for char in string:
if char == ':':
ret.append('::')
else:
ret.append(char)
ret.append(encoder)
return ''.join(ret)
<|end_body_0|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
... | stack_v2_sparse_classes_36k_train_030530 | 1,233 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_002389 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | fdb6bcb4c721e03e853890dd89122f2c4196a1ea | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
ret = []
encoder = ': '
for string in strs:
for char in string:
if char == ':':
ret.append('::')
else:
... | the_stack_v2_python_sparse | python/string/encode_decode_string.py | XifeiNi/LeetCode-Traversal | train | 2 | |
3210ed7d08087d6b661015e132d5d636506c3fbb | [
"if not self.total_money:\n self.total_money = self.price * self.amount\nif not self.has_updated_account:\n self.update_account()\nsuper(Transaction, self).save(*args, **kwargs)",
"if self.has_updated_account:\n return\naccount_stock_query = self.account.stocks.filter(stock=self.stock)\nif self.action ==... | <|body_start_0|>
if not self.total_money:
self.total_money = self.price * self.amount
if not self.has_updated_account:
self.update_account()
super(Transaction, self).save(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self.has_updated_account:
re... | 一笔买入、卖出交易 | Transaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transaction:
"""一笔买入、卖出交易"""
def save(self, *args, **kwargs):
"""如果没有填交易额,在save之前自动计算。"""
<|body_0|>
def update_account(self):
"""只更新股票,不更新现金和负债。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.total_money:
self.total_mon... | stack_v2_sparse_classes_36k_train_030531 | 41,807 | no_license | [
{
"docstring": "如果没有填交易额,在save之前自动计算。",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "只更新股票,不更新现金和负债。",
"name": "update_account",
"signature": "def update_account(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001142 | Implement the Python class `Transaction` described below.
Class description:
一笔买入、卖出交易
Method signatures and docstrings:
- def save(self, *args, **kwargs): 如果没有填交易额,在save之前自动计算。
- def update_account(self): 只更新股票,不更新现金和负债。 | Implement the Python class `Transaction` described below.
Class description:
一笔买入、卖出交易
Method signatures and docstrings:
- def save(self, *args, **kwargs): 如果没有填交易额,在save之前自动计算。
- def update_account(self): 只更新股票,不更新现金和负债。
<|skeleton|>
class Transaction:
"""一笔买入、卖出交易"""
def save(self, *args, **kwargs):
... | d9108961ea3aef507f61e056ee6d4b2cf43a1f55 | <|skeleton|>
class Transaction:
"""一笔买入、卖出交易"""
def save(self, *args, **kwargs):
"""如果没有填交易额,在save之前自动计算。"""
<|body_0|>
def update_account(self):
"""只更新股票,不更新现金和负债。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transaction:
"""一笔买入、卖出交易"""
def save(self, *args, **kwargs):
"""如果没有填交易额,在save之前自动计算。"""
if not self.total_money:
self.total_money = self.price * self.amount
if not self.has_updated_account:
self.update_account()
super(Transaction, self).save(*args... | the_stack_v2_python_sparse | stocks/models.py | fruitschen/fruits_learning | train | 1 |
2ae658fb70be67d32d912bd4e7ece57b26895e9e | [
"music = Music(**validated_data)\nmusic.save()\nreturn music",
"music = Music.objects.filter(pk=instance.pk)\nmusic.update(**validated_data)\nmusic = music.first()\nroom = instance.room\nif room.current_music == music:\n Events.get(room).cancel()\n event = Events.set(room, Timer(room.get_current_remaining_t... | <|body_start_0|>
music = Music(**validated_data)
music.save()
return music
<|end_body_0|>
<|body_start_1|>
music = Music.objects.filter(pk=instance.pk)
music.update(**validated_data)
music = music.first()
room = instance.room
if room.current_music == musi... | Serializing all the Music | MusicSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MusicSerializer:
"""Serializing all the Music"""
def create(self, validated_data):
"""Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing music to the Serializer update(..) method NEED to be imp... | stack_v2_sparse_classes_36k_train_030532 | 2,944 | permissive | [
{
"docstring": "Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing music to the Serializer update(..) method NEED to be implemented too ! :param self: Instance param :param validated_data: A dict of validated data from th... | 2 | stack_v2_sparse_classes_30k_train_003384 | Implement the Python class `MusicSerializer` described below.
Class description:
Serializing all the Music
Method signatures and docstrings:
- def create(self, validated_data): Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing... | Implement the Python class `MusicSerializer` described below.
Class description:
Serializing all the Music
Method signatures and docstrings:
- def create(self, validated_data): Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing... | 77b0e426fe9cc6c9cd12346a5e5e81a62362bb83 | <|skeleton|>
class MusicSerializer:
"""Serializing all the Music"""
def create(self, validated_data):
"""Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing music to the Serializer update(..) method NEED to be imp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MusicSerializer:
"""Serializing all the Music"""
def create(self, validated_data):
"""Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing music to the Serializer update(..) method NEED to be implemented too ... | the_stack_v2_python_sparse | music/serializers.py | Amoki/Amoki-Music | train | 3 |
cce2681597a753edd19cb76d9017794a4fc8af10 | [
"if len(self) < 2:\n raise IndexError(f'Cannot obtain the penultimate set of coordinates, only had {len(self)}')\nreturn self[-2]",
"if len(self) < 1:\n raise IndexError('Cannot obtain the final set of coordinates from an empty history')\nreturn self[-1]",
"if len(self) == 0:\n raise IndexError('No min... | <|body_start_0|>
if len(self) < 2:
raise IndexError(f'Cannot obtain the penultimate set of coordinates, only had {len(self)}')
return self[-2]
<|end_body_0|>
<|body_start_1|>
if len(self) < 1:
raise IndexError('Cannot obtain the final set of coordinates from an empty his... | Sequential history of coordinates | OptimiserHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_030533 | 33,069 | permissive | [
{
"docstring": "Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):",
"name": "penultimate",
"signature": "def penultimate(self) -> OptCoordinates"
},
{
"docstring": "Last set of coordinates ----... | 5 | stack_v2_sparse_classes_30k_train_008486 | Implement the Python class `OptimiserHistory` described below.
Class description:
Sequential history of coordinates
Method signatures and docstrings:
- def penultimate(self) -> OptCoordinates: Last but one set of coordinates (the penultimate set) -----------------------------------------------------------------------... | Implement the Python class `OptimiserHistory` described below.
Class description:
Sequential history of coordinates
Method signatures and docstrings:
- def penultimate(self) -> OptCoordinates: Last but one set of coordinates (the penultimate set) -----------------------------------------------------------------------... | 4d6667592f083dfcf38de6b75c4222c0a0e7b60b | <|skeleton|>
class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimiserHistory:
"""Sequential history of coordinates"""
def penultimate(self) -> OptCoordinates:
"""Last but one set of coordinates (the penultimate set) ----------------------------------------------------------------------- Returns: (OptCoordinates):"""
if len(self) < 2:
r... | the_stack_v2_python_sparse | autode/opt/optimisers/base.py | duartegroup/autodE | train | 132 |
fc101d6073ea1f5225bc9dc31622a733fd1fdae3 | [
"print(f'Connected with result code {rc}')\nif isinstance(userdata, list):\n for topic in userdata:\n if not isinstance(topic, str):\n print('Error in on_connect. Expected topic to be type a list of strings.')\n client.subscribe(topic.lower(), qos=1)\n print(f'Listening on {topic.... | <|body_start_0|>
print(f'Connected with result code {rc}')
if isinstance(userdata, list):
for topic in userdata:
if not isinstance(topic, str):
print('Error in on_connect. Expected topic to be type a list of strings.')
client.subscribe(topi... | Callbacks | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Callbacks:
def on_connect(client, userdata, flags, rc):
"""MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of connection to server :param userdata: User-defined data passed to callbacks :param flags: Response flag... | stack_v2_sparse_classes_36k_train_030534 | 7,843 | permissive | [
{
"docstring": "MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of connection to server :param userdata: User-defined data passed to callbacks :param flags: Response flags sent by broker :param rc: Connection result, Successful = 0",
... | 3 | null | Implement the Python class `Callbacks` described below.
Class description:
Implement the Callbacks class.
Method signatures and docstrings:
- def on_connect(client, userdata, flags, rc): MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of conne... | Implement the Python class `Callbacks` described below.
Class description:
Implement the Callbacks class.
Method signatures and docstrings:
- def on_connect(client, userdata, flags, rc): MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of conne... | 85102bb41aa0d558a3fa088e4fd6f51613599ad0 | <|skeleton|>
class Callbacks:
def on_connect(client, userdata, flags, rc):
"""MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of connection to server :param userdata: User-defined data passed to callbacks :param flags: Response flag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Callbacks:
def on_connect(client, userdata, flags, rc):
"""MQTT Callback for when client receives connection-acknowledgement response from MQTT server. :param client: Class instance of connection to server :param userdata: User-defined data passed to callbacks :param flags: Response flags sent by brok... | the_stack_v2_python_sparse | orchestrator/transport/mqtt/MQTT/callbacks.py | g2-inc/openc2-oif-orchestrator | train | 1 | |
50256ce678508d0ac734d1e3e6a1bbcd4edae1c3 | [
"self.central_occupation_model = ZuMandelbaum15Cens(prim_haloprop_key=prim_haloprop_key, threshold=threshold)\nOccupationComponent.__init__(self, gal_type='satellites', threshold=threshold, upper_occupation_bound=float('inf'), prim_haloprop_key=prim_haloprop_key)\nself._initialize_param_dict()\nself.param_dict.upda... | <|body_start_0|>
self.central_occupation_model = ZuMandelbaum15Cens(prim_haloprop_key=prim_haloprop_key, threshold=threshold)
OccupationComponent.__init__(self, gal_type='satellites', threshold=threshold, upper_occupation_bound=float('inf'), prim_haloprop_key=prim_haloprop_key)
self._initialize_... | HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial on the ``zu_mandelbaum15`` composite model, see :ref:`zu_mandelbaum15_composite_mode... | ZuMandelbaum15Sats | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZuMandelbaum15Sats:
"""HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial on the ``zu_mandelbaum15`` composite m... | stack_v2_sparse_classes_36k_train_030535 | 12,633 | permissive | [
{
"docstring": "Parameters ---------- threshold : float, optional Stellar mass threshold of the mock galaxy sample in h=1 solar mass units. Default value is specified in the `~halotools.empirical_models.model_defaults` module. prim_haloprop_key : string, optional String giving the column name of the primary hal... | 4 | null | Implement the Python class `ZuMandelbaum15Sats` described below.
Class description:
HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial... | Implement the Python class `ZuMandelbaum15Sats` described below.
Class description:
HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial... | 405b175a5a63a05326ba58b9076291f267a04f1d | <|skeleton|>
class ZuMandelbaum15Sats:
"""HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial on the ``zu_mandelbaum15`` composite m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZuMandelbaum15Sats:
"""HOD-style model for a satellite galaxy occupation based on Zu & Mandelbaum 2015. .. note:: The `~halotools.empirical_models.ZuMandelbaum15Sats` model is part of the ``zu_mandelbaum15`` prebuilt composite HOD-style model. For a tutorial on the ``zu_mandelbaum15`` composite model, see :re... | the_stack_v2_python_sparse | halotools/empirical_models/occupation_models/zu_mandelbaum15_components.py | aphearin/halotools | train | 2 |
f5e5db35917a9b85959de29f28114886cd06398b | [
"super(PositionalEncoding, self).__init__()\nself.dropout = dropout\nposi_block = np.arange(0, length, dtype=np.float32)[:, None]\nunit_block = np.exp(np.arange(0, n_units, 2, dtype=np.float32) * -(np.log(10000.0) / n_units))\nself.pe = np.zeros((length, n_units), dtype=np.float32)\nself.pe[:, ::2] = np.sin(posi_bl... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.dropout = dropout
posi_block = np.arange(0, length, dtype=np.float32)[:, None]
unit_block = np.exp(np.arange(0, n_units, 2, dtype=np.float32) * -(np.log(10000.0) / n_units))
self.pe = np.zeros((length, n_units), dty... | Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length"""
def __init__(self, n_units, dropout=0.1, length=5000):
"""Initialize Positional Encoding."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_030536 | 1,204 | permissive | [
{
"docstring": "Initialize Positional Encoding.",
"name": "__init__",
"signature": "def __init__(self, n_units, dropout=0.1, length=5000)"
},
{
"docstring": "Forward Positional Encoding.",
"name": "forward",
"signature": "def forward(self, e)"
}
] | 2 | null | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length
Method signatures and docstrings:
- def __init__(self, n_units, dropout=0.1, length=5000): Initia... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length
Method signatures and docstrings:
- def __init__(self, n_units, dropout=0.1, length=5000): Initia... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class PositionalEncoding:
"""Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length"""
def __init__(self, n_units, dropout=0.1, length=5000):
"""Initialize Positional Encoding."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding module. :param int n_units: embedding dim :param float dropout: dropout rate :param int length: maximum input length"""
def __init__(self, n_units, dropout=0.1, length=5000):
"""Initialize Positional Encoding."""
super(PositionalEncoding, self)._... | the_stack_v2_python_sparse | espnet/nets/chainer_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
5c8681a6edfe120479a4d663235935e2e5882fa1 | [
"super().__init__()\nself.bn1 = nn.BatchNorm2d(in_channels)\nself.conv1 = conv1x1(in_channels, out_channels, **kwargs)\nself.bn2 = nn.BatchNorm2d(out_channels)\nself.conv2 = conv3x3(out_channels, out_channels, stride=stride, **kwargs)\nself.bn3 = nn.BatchNorm2d(out_channels)\nself.conv3 = conv1x1(out_channels, out_... | <|body_start_0|>
super().__init__()
self.bn1 = nn.BatchNorm2d(in_channels)
self.conv1 = conv1x1(in_channels, out_channels, **kwargs)
self.bn2 = nn.BatchNorm2d(out_channels)
self.conv2 = conv3x3(out_channels, out_channels, stride=stride, **kwargs)
self.bn3 = nn.BatchNorm2d... | bottleneck. | BottleneckBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottleneckBlock:
"""bottleneck."""
def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs):
"""CTOR."""
<|body_0|>
def forward(self, x):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
... | stack_v2_sparse_classes_36k_train_030537 | 6,340 | permissive | [
{
"docstring": "CTOR.",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003481 | Implement the Python class `BottleneckBlock` described below.
Class description:
bottleneck.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs): CTOR.
- def forward(self, x): forward | Implement the Python class `BottleneckBlock` described below.
Class description:
bottleneck.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs): CTOR.
- def forward(self, x): forward
<|skeleton|>
class BottleneckBlock:
"""bottleneck."""
def... | f81c417d3754102c902bd153809130e12607bd7d | <|skeleton|>
class BottleneckBlock:
"""bottleneck."""
def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs):
"""CTOR."""
<|body_0|>
def forward(self, x):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BottleneckBlock:
"""bottleneck."""
def __init__(self, in_channels, out_channels, stride=1, downsample=None, **kwargs):
"""CTOR."""
super().__init__()
self.bn1 = nn.BatchNorm2d(in_channels)
self.conv1 = conv1x1(in_channels, out_channels, **kwargs)
self.bn2 = nn.Batc... | the_stack_v2_python_sparse | gumi/models/preresnet.py | kumasento/gconv-prune | train | 10 |
afa55dbe2cdaa34e663554603d092de59a9b1105 | [
"self.__rmax = 100\nself.__s = None\nself.__a = None\naccoes = [Mover(a, ang_abs=True) for a in dirmov()]\nself.__mec_aprend = MecAprend(accoes)",
"sn = percepcao.posicao\nif self.__s is not None:\n r = self.gerar_reforco(percepcao)\n self.__mec_aprend.aprender(self.__s, self.__a, r, sn)\nan = self.__mec_ap... | <|body_start_0|>
self.__rmax = 100
self.__s = None
self.__a = None
accoes = [Mover(a, ang_abs=True) for a in dirmov()]
self.__mec_aprend = MecAprend(accoes)
<|end_body_0|>
<|body_start_1|>
sn = percepcao.posicao
if self.__s is not None:
r = self.gerar... | ControloAprendRef | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControloAprendRef:
def __init__(self):
"""Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem"""
<|body_0|>
def processar(self, percepcao):
"""Executa um passo do algoritmo Q-Learning Parameters ---------- percepcao... | stack_v2_sparse_classes_36k_train_030538 | 1,740 | no_license | [
{
"docstring": "Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Executa um passo do algoritmo Q-Learning Parameters ---------- percepcao : Percepcao uma perceo Retur... | 3 | stack_v2_sparse_classes_30k_train_021080 | Implement the Python class `ControloAprendRef` described below.
Class description:
Implement the ControloAprendRef class.
Method signatures and docstrings:
- def __init__(self): Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem
- def processar(self, percepcao): Ex... | Implement the Python class `ControloAprendRef` described below.
Class description:
Implement the ControloAprendRef class.
Method signatures and docstrings:
- def __init__(self): Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem
- def processar(self, percepcao): Ex... | 121a0ab55bc3ec2fad2156a58aee770a0eded308 | <|skeleton|>
class ControloAprendRef:
def __init__(self):
"""Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem"""
<|body_0|>
def processar(self, percepcao):
"""Executa um passo do algoritmo Q-Learning Parameters ---------- percepcao... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControloAprendRef:
def __init__(self):
"""Construtor da classe; Cria os atributos do reforo mximo, estado e ao atuais e mecanismo de aprendizagem"""
self.__rmax = 100
self.__s = None
self.__a = None
accoes = [Mover(a, ang_abs=True) for a in dirmov()]
self.__mec_... | the_stack_v2_python_sparse | agente_prosp/controlo_aprend/controlo_aprend_ref.py | GiodoAldeima/iasa-cp3 | train | 0 | |
11a26cb3c5d6ef0924f2e676a1033f6532f0118d | [
"self._value = None\nself._left = None\nself._right = None",
"if pre_order == [] or in_order == []:\n return None\nelse:\n head = pre_order[0]\n head_index = in_order.index(head)\n self._value = head\n if len(pre_order[1:1 + head_index]) > 0:\n self._left = BinaryTree()\n self._left.b... | <|body_start_0|>
self._value = None
self._left = None
self._right = None
<|end_body_0|>
<|body_start_1|>
if pre_order == [] or in_order == []:
return None
else:
head = pre_order[0]
head_index = in_order.index(head)
self._value = he... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def __init__(self):
"""Initialize tree's value, left, right to None"""
<|body_0|>
def build_tree(self, pre_order, in_order):
"""This my recursive method that takes two lists of integers; the preorder traversal and the inorder traversal of the tree and ret... | stack_v2_sparse_classes_36k_train_030539 | 4,316 | no_license | [
{
"docstring": "Initialize tree's value, left, right to None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This my recursive method that takes two lists of integers; the preorder traversal and the inorder traversal of the tree and returns the tree parameter: pre_orde... | 4 | stack_v2_sparse_classes_30k_train_020118 | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def __init__(self): Initialize tree's value, left, right to None
- def build_tree(self, pre_order, in_order): This my recursive method that takes two lists of integers; the p... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def __init__(self): Initialize tree's value, left, right to None
- def build_tree(self, pre_order, in_order): This my recursive method that takes two lists of integers; the p... | 2f558a5ccc28d79a234729fcd6ff540ef8458499 | <|skeleton|>
class BinaryTree:
def __init__(self):
"""Initialize tree's value, left, right to None"""
<|body_0|>
def build_tree(self, pre_order, in_order):
"""This my recursive method that takes two lists of integers; the preorder traversal and the inorder traversal of the tree and ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryTree:
def __init__(self):
"""Initialize tree's value, left, right to None"""
self._value = None
self._left = None
self._right = None
def build_tree(self, pre_order, in_order):
"""This my recursive method that takes two lists of integers; the preorder traversa... | the_stack_v2_python_sparse | huffman.py | JazzPiece/Python-projects | train | 0 | |
1eb7238384a6d9e1615d96255c0c2d9e00bdd6b5 | [
"if not coins:\n return -1\nlength = len(coins)\nif length == 0:\n return -1\ndp = [[float('inf')] * (length + 1) for _ in range(amount + 1)]\nfor j in range(length + 1):\n dp[0][j] = 0\nfor value in range(1, amount + 1):\n for j in range(1, length + 1):\n if coins[j - 1] <= value:\n m... | <|body_start_0|>
if not coins:
return -1
length = len(coins)
if length == 0:
return -1
dp = [[float('inf')] * (length + 1) for _ in range(amount + 1)]
for j in range(length + 1):
dp[0][j] = 0
for value in range(1, amount + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_030540 | 2,492 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange2",
"signature": "def coinChange2(self, coins, amou... | 2 | stack_v2_sparse_classes_30k_train_007156 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | 8d9eb98fa5e897602eae9c37b47fd8abae72b1dc | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if not coins:
return -1
length = len(coins)
if length == 0:
return -1
dp = [[float('inf')] * (length + 1) for _ in range(amount + 1)]
... | the_stack_v2_python_sparse | misc/322_coin_change.py | wanlipu/coding-python | train | 0 | |
3743d81693706e1fe6b1c34ebaaea9dde08d6fa8 | [
"if pat == None:\n pat = 'S\\\\d{2}E\\\\d{2}'\nfor old_name in os.listdir(path):\n mid = re.findall(pat, old_name)[0]\n end = old_name.split('.')[-1]\n new_name = head + '-' + mid + '.' + end\n os.rename(path + old_name, path + new_name)\nprint('NumPat: {};\\nPath: {};'.format(pat, path))",
"with o... | <|body_start_0|>
if pat == None:
pat = 'S\\d{2}E\\d{2}'
for old_name in os.listdir(path):
mid = re.findall(pat, old_name)[0]
end = old_name.split('.')[-1]
new_name = head + '-' + mid + '.' + end
os.rename(path + old_name, path + new_name)
... | 整理文件名(字幕/视频);整理文件内容(字幕) | TvShow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TvShow:
"""整理文件名(字幕/视频);整理文件内容(字幕)"""
def renames(self, path, head, pat=None):
"""文件名批量命名"""
<|body_0|>
def to_tidy_txt(self, file):
"""去掉字幕文件的冗余信息"""
<|body_1|>
def to_audio_from_video(self, video_path='F:\\Miranda\\-S01E04.mp4', audio_ext='.mp3'):
... | stack_v2_sparse_classes_36k_train_030541 | 48,309 | no_license | [
{
"docstring": "文件名批量命名",
"name": "renames",
"signature": "def renames(self, path, head, pat=None)"
},
{
"docstring": "去掉字幕文件的冗余信息",
"name": "to_tidy_txt",
"signature": "def to_tidy_txt(self, file)"
},
{
"docstring": "将一个视频转化为音频",
"name": "to_audio_from_video",
"signature... | 3 | stack_v2_sparse_classes_30k_train_014131 | Implement the Python class `TvShow` described below.
Class description:
整理文件名(字幕/视频);整理文件内容(字幕)
Method signatures and docstrings:
- def renames(self, path, head, pat=None): 文件名批量命名
- def to_tidy_txt(self, file): 去掉字幕文件的冗余信息
- def to_audio_from_video(self, video_path='F:\\Miranda\\-S01E04.mp4', audio_ext='.mp3'): 将一个视... | Implement the Python class `TvShow` described below.
Class description:
整理文件名(字幕/视频);整理文件内容(字幕)
Method signatures and docstrings:
- def renames(self, path, head, pat=None): 文件名批量命名
- def to_tidy_txt(self, file): 去掉字幕文件的冗余信息
- def to_audio_from_video(self, video_path='F:\\Miranda\\-S01E04.mp4', audio_ext='.mp3'): 将一个视... | b6f6897721adc616d31059f703a494bba0834b74 | <|skeleton|>
class TvShow:
"""整理文件名(字幕/视频);整理文件内容(字幕)"""
def renames(self, path, head, pat=None):
"""文件名批量命名"""
<|body_0|>
def to_tidy_txt(self, file):
"""去掉字幕文件的冗余信息"""
<|body_1|>
def to_audio_from_video(self, video_path='F:\\Miranda\\-S01E04.mp4', audio_ext='.mp3'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TvShow:
"""整理文件名(字幕/视频);整理文件内容(字幕)"""
def renames(self, path, head, pat=None):
"""文件名批量命名"""
if pat == None:
pat = 'S\\d{2}E\\d{2}'
for old_name in os.listdir(path):
mid = re.findall(pat, old_name)[0]
end = old_name.split('.')[-1]
ne... | the_stack_v2_python_sparse | code-drop/english.2020_5_8.py | y2sinx/dyslexia | train | 0 |
ec07ba7279d8e8176b4bb602260dbb999d413c17 | [
"self.input_arr = [7, 6, 4, -1, 1, 2]\nself.targetSum = 16\nself.output = [[7, 6, 4, -1], [7, 6, 1, 2]]\nreturn (self.input_arr, self.targetSum, self.output)",
"input_arr, targetSum, output_arr = self.setUp()\noutput = fourNumberSum(input_arr, targetSum)\nself.assertEqual(output, output_arr)"
] | <|body_start_0|>
self.input_arr = [7, 6, 4, -1, 1, 2]
self.targetSum = 16
self.output = [[7, 6, 4, -1], [7, 6, 1, 2]]
return (self.input_arr, self.targetSum, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, targetSum, output_arr = self.setUp()
output = fourNumberS... | Class with unittests for FourNumberSum.py | test_FourNumberSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_FourNumberSum:
"""Class with unittests for FourNumberSum.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_36k_train_030542 | 931 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_FourNumberSum` described below.
Class description:
Class with unittests for FourNumberSum.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_FourNumberSum` described below.
Class description:
Class with unittests for FourNumberSum.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_FourNumberSum:
"""Cl... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_FourNumberSum:
"""Class with unittests for FourNumberSum.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_FourNumberSum:
"""Class with unittests for FourNumberSum.py"""
def setUp(self):
"""Sets up input."""
self.input_arr = [7, 6, 4, -1, 1, 2]
self.targetSum = 16
self.output = [[7, 6, 4, -1], [7, 6, 1, 2]]
return (self.input_arr, self.targetSum, self.output)
... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/FourNumberSort/test_FourNumberSum.py | JakubKazimierski/PythonPortfolio | train | 9 |
a583ff237a5174de626d73368f6419c3b0a4b128 | [
"try:\n return cls.get(*query, **kwargs)\nexcept:\n raise",
"if not type(Model) == SelectQuery:\n return None\nlist = []\nfor con in Model:\n if type(con) == dict:\n if not key == None:\n list.append(con[key])\n else:\n list.append(con)\n else:\n list.appe... | <|body_start_0|>
try:
return cls.get(*query, **kwargs)
except:
raise
<|end_body_0|>
<|body_start_1|>
if not type(Model) == SelectQuery:
return None
list = []
for con in Model:
if type(con) == dict:
if not key == Non... | MyBaseModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyBaseModel:
def getOne(cls, *query, **kwargs):
"""为了方便使用,新增此接口,查询不到返回None,而不抛出异常"""
<|body_0|>
def returnList(cls, Model=None, key=None):
"""将结果返回成一个列表嵌套字典的结构返回"""
<|body_1|>
def returnList2(cls, Model=None, key=None):
"""将结果返回成一个列表嵌套字典的结构返回"""
... | stack_v2_sparse_classes_36k_train_030543 | 8,457 | no_license | [
{
"docstring": "为了方便使用,新增此接口,查询不到返回None,而不抛出异常",
"name": "getOne",
"signature": "def getOne(cls, *query, **kwargs)"
},
{
"docstring": "将结果返回成一个列表嵌套字典的结构返回",
"name": "returnList",
"signature": "def returnList(cls, Model=None, key=None)"
},
{
"docstring": "将结果返回成一个列表嵌套字典的结构返回",
... | 3 | stack_v2_sparse_classes_30k_train_017715 | Implement the Python class `MyBaseModel` described below.
Class description:
Implement the MyBaseModel class.
Method signatures and docstrings:
- def getOne(cls, *query, **kwargs): 为了方便使用,新增此接口,查询不到返回None,而不抛出异常
- def returnList(cls, Model=None, key=None): 将结果返回成一个列表嵌套字典的结构返回
- def returnList2(cls, Model=None, key=No... | Implement the Python class `MyBaseModel` described below.
Class description:
Implement the MyBaseModel class.
Method signatures and docstrings:
- def getOne(cls, *query, **kwargs): 为了方便使用,新增此接口,查询不到返回None,而不抛出异常
- def returnList(cls, Model=None, key=None): 将结果返回成一个列表嵌套字典的结构返回
- def returnList2(cls, Model=None, key=No... | a31364869894c72349e3587944ecb4fda018e020 | <|skeleton|>
class MyBaseModel:
def getOne(cls, *query, **kwargs):
"""为了方便使用,新增此接口,查询不到返回None,而不抛出异常"""
<|body_0|>
def returnList(cls, Model=None, key=None):
"""将结果返回成一个列表嵌套字典的结构返回"""
<|body_1|>
def returnList2(cls, Model=None, key=None):
"""将结果返回成一个列表嵌套字典的结构返回"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyBaseModel:
def getOne(cls, *query, **kwargs):
"""为了方便使用,新增此接口,查询不到返回None,而不抛出异常"""
try:
return cls.get(*query, **kwargs)
except:
raise
def returnList(cls, Model=None, key=None):
"""将结果返回成一个列表嵌套字典的结构返回"""
if not type(Model) == SelectQuery:
... | the_stack_v2_python_sparse | tornado/data_pretreatment/calculate/orm.py | fxrc/care-system | train | 1 | |
9da0217b0d7b2f92c19e794eae1c8eefd4359b64 | [
"self.domain1 = FEDomain()\nself.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())\nself.d1 = FERefinementGrid(name='d1', domain=self.domain1)\nself.g1 = FEGrid(coord_max=(1.0, 1.0, 0.0), shape=(2, 2), fets_eval=self.fets_eval, level=self.d1)",
"elem_X_map = self.g1.elem_X_map\negm = [0.0, 0.0, 0.5, 0.0, 0.5, 0.5, ... | <|body_start_0|>
self.domain1 = FEDomain()
self.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())
self.d1 = FERefinementGrid(name='d1', domain=self.domain1)
self.g1 = FEGrid(coord_max=(1.0, 1.0, 0.0), shape=(2, 2), fets_eval=self.fets_eval, level=self.d1)
<|end_body_0|>
<|body_start_1|>
... | Test the retrieval of geometric information of FEDomain. | FEDomainGeoMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
<|body_0|>
def test_elem_X_map(self):
"""Test the retrieval of geometric information of FEDomain."""
... | stack_v2_sparse_classes_36k_train_030544 | 5,633 | no_license | [
{
"docstring": "Construct the FEDomain with one FERefinementGrids (2,2)",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the retrieval of geometric information of FEDomain.",
"name": "test_elem_X_map",
"signature": "def test_elem_X_map(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004714 | Implement the Python class `FEDomainGeoMap` described below.
Class description:
Test the retrieval of geometric information of FEDomain.
Method signatures and docstrings:
- def setUp(self): Construct the FEDomain with one FERefinementGrids (2,2)
- def test_elem_X_map(self): Test the retrieval of geometric information... | Implement the Python class `FEDomainGeoMap` described below.
Class description:
Test the retrieval of geometric information of FEDomain.
Method signatures and docstrings:
- def setUp(self): Construct the FEDomain with one FERefinementGrids (2,2)
- def test_elem_X_map(self): Test the retrieval of geometric information... | 00de9f0eec52835d839a3c6c1407cac11a496339 | <|skeleton|>
class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
<|body_0|>
def test_elem_X_map(self):
"""Test the retrieval of geometric information of FEDomain."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FEDomainGeoMap:
"""Test the retrieval of geometric information of FEDomain."""
def setUp(self):
"""Construct the FEDomain with one FERefinementGrids (2,2)"""
self.domain1 = FEDomain()
self.fets_eval = FETS2D4Q(mats_eval=MATS2DElastic())
self.d1 = FERefinementGrid(name='d1'... | the_stack_v2_python_sparse | ibvpy/mesh/__test__.py | simvisage/bmcs | train | 1 |
d7d0345c706f58f7ac97e75821a2af7253794d94 | [
"try:\n v = datetime.datetime.strptime(s, self.date_format)\n return v.replace(tzinfo=pytz.UTC)\nexcept ValueError:\n return pendulum.parse(s, tz=pytz.UTC)",
"if dt is None:\n return str(dt)\nreturn dt.strftime(self.date_format)",
"if dt is None:\n return None\nif not isinstance(dt, datetime.date... | <|body_start_0|>
try:
v = datetime.datetime.strptime(s, self.date_format)
return v.replace(tzinfo=pytz.UTC)
except ValueError:
return pendulum.parse(s, tz=pytz.UTC)
<|end_body_0|>
<|body_start_1|>
if dt is None:
return str(dt)
return dt.st... | DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``2013-07-10T190738`` specifies July 10, 2013 at 19:07:38. | DateTimeValueType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateTimeValueType:
"""DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``2013-07-10T190738`` specifies July 10, 20... | stack_v2_sparse_classes_36k_train_030545 | 3,720 | permissive | [
{
"docstring": "Parses a string to a :py:class:`~datetime.datetime`.",
"name": "parse_from_str",
"signature": "def parse_from_str(self, s)"
},
{
"docstring": "Converts the date to a string using the :py:attr:`~_DatetimeValueTypeBase.date_format`.",
"name": "to_str",
"signature": "def to_... | 3 | stack_v2_sparse_classes_30k_train_003553 | Implement the Python class `DateTimeValueType` described below.
Class description:
DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``20... | Implement the Python class `DateTimeValueType` described below.
Class description:
DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``20... | d59c99dcdcd280d7eec36a693dd80f8c8c831ea2 | <|skeleton|>
class DateTimeValueType:
"""DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``2013-07-10T190738`` specifies July 10, 20... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateTimeValueType:
"""DateTimeValueType whose value is a :py:class:`~datetime.datetime` specified to the second. A DateSecondValueType is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the second. For example, ``2013-07-10T190738`` specifies July 10, 2013 at 19:07:3... | the_stack_v2_python_sparse | modules/dbnd/src/targets/values/datetime_value.py | databand-ai/dbnd | train | 257 |
228fd3a16f05e2c4fa660d6927e06519fd74164e | [
"LOGGER.info('Invoked Provides.clean()')\nfor provide in self.keys():\n if self[provide] is not None:\n del self[provide]",
"super(ProvidesV2, self).parse_cs_str(src, tooling)\nservices = {}\nsrc = src[1:-1].split('|')\nif len(src) >= 2:\n for svc in src[1].split('&'):\n services[svc] = Servic... | <|body_start_0|>
LOGGER.info('Invoked Provides.clean()')
for provide in self.keys():
if self[provide] is not None:
del self[provide]
<|end_body_0|>
<|body_start_1|>
super(ProvidesV2, self).parse_cs_str(src, tooling)
services = {}
src = src[1:-1].split... | API version 2 compatible Provides object | ProvidesV2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvidesV2:
"""API version 2 compatible Provides object"""
def clean(self):
"""remove non-None provides should be called after sending the values"""
<|body_0|>
def parse_cs_str(self, src, tooling):
"""Description: Parse the provides parameters text message sent f... | stack_v2_sparse_classes_36k_train_030546 | 5,249 | permissive | [
{
"docstring": "remove non-None provides should be called after sending the values",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Description: Parse the provides parameters text message sent from the Config Server. Input: Format: |name1&name2...&nameN|service1&service2| e.g... | 2 | stack_v2_sparse_classes_30k_train_016123 | Implement the Python class `ProvidesV2` described below.
Class description:
API version 2 compatible Provides object
Method signatures and docstrings:
- def clean(self): remove non-None provides should be called after sending the values
- def parse_cs_str(self, src, tooling): Description: Parse the provides parameter... | Implement the Python class `ProvidesV2` described below.
Class description:
API version 2 compatible Provides object
Method signatures and docstrings:
- def clean(self): remove non-None provides should be called after sending the values
- def parse_cs_str(self, src, tooling): Description: Parse the provides parameter... | fadf3ef6d2f978dfd6ab92ad33716c69087eb92e | <|skeleton|>
class ProvidesV2:
"""API version 2 compatible Provides object"""
def clean(self):
"""remove non-None provides should be called after sending the values"""
<|body_0|>
def parse_cs_str(self, src, tooling):
"""Description: Parse the provides parameters text message sent f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProvidesV2:
"""API version 2 compatible Provides object"""
def clean(self):
"""remove non-None provides should be called after sending the values"""
LOGGER.info('Invoked Provides.clean()')
for provide in self.keys():
if self[provide] is not None:
del se... | the_stack_v2_python_sparse | agent/src/audrey/provides.py | martinpovolny/audrey | train | 0 |
b56536f902c7431e296a9dc130e2f05936723980 | [
"super(Model, self).__init__()\nself.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2... | <|body_start_0|>
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_... | CNN. | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_chan... | stack_v2_sparse_classes_36k_train_030547 | 5,133 | no_license | [
{
"docstring": "CNN Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021151 | Implement the Python class `Model` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward. | Implement the Python class `Model` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward.
<|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(se... | a91698b940e7e69720ef26c4ac98f7a9d4c30285 | <|skeleton|>
class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
"""CNN."""
def __init__(self):
"""CNN Builder."""
super(Model, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_... | the_stack_v2_python_sparse | Neural Networks with CV/run_q6.1.3.py | shayeree96/Computer-Vision---16720 | train | 0 |
02c141efde6a52a793778a645e0e8e21243c1736 | [
"encoder_1 = Conv1DEncoder()\nself.assertEqual(len(encoder_1.layers), 4)\nself.assertTrue(isinstance(encoder_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))\nfor layer in encoder_1.layers[0].layers:\n self.assertTrue(isinstance(layer, tx.core.SequentialLayer))\ninputs_1 = tf.ones([64, 16, 300], tf.float32)\... | <|body_start_0|>
encoder_1 = Conv1DEncoder()
self.assertEqual(len(encoder_1.layers), 4)
self.assertTrue(isinstance(encoder_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))
for layer in encoder_1.layers[0].layers:
self.assertTrue(isinstance(layer, tx.core.SequentialLayer))... | Tests :class:`~texar.tf.modules.Conv1DEncoder` class. | Conv1DEncoderTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1DEncoderTest:
"""Tests :class:`~texar.tf.modules.Conv1DEncoder` class."""
def test_encode(self):
"""Tests encode."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
<|b... | stack_v2_sparse_classes_36k_train_030548 | 3,909 | permissive | [
{
"docstring": "Tests encode.",
"name": "test_encode",
"signature": "def test_encode(self)"
},
{
"docstring": "Tests use of pooling layer when the seq_length dimension of inputs is `None`.",
"name": "test_unknown_seq_length",
"signature": "def test_unknown_seq_length(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005847 | Implement the Python class `Conv1DEncoderTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DEncoder` class.
Method signatures and docstrings:
- def test_encode(self): Tests encode.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of inputs is `... | Implement the Python class `Conv1DEncoderTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DEncoder` class.
Method signatures and docstrings:
- def test_encode(self): Tests encode.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of inputs is `... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class Conv1DEncoderTest:
"""Tests :class:`~texar.tf.modules.Conv1DEncoder` class."""
def test_encode(self):
"""Tests encode."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv1DEncoderTest:
"""Tests :class:`~texar.tf.modules.Conv1DEncoder` class."""
def test_encode(self):
"""Tests encode."""
encoder_1 = Conv1DEncoder()
self.assertEqual(len(encoder_1.layers), 4)
self.assertTrue(isinstance(encoder_1.layer_by_name('conv_pool_1'), tx.core.Merge... | the_stack_v2_python_sparse | texar/tf/modules/encoders/conv_encoders_test.py | arita37/texar | train | 2 |
8d5b41c37cb068490bb3cafe719cea9e64cb1d21 | [
"self.linha = int(linha)\nself.coluna = int(coluna)\nself.robo = robo\nself.arena = []\nself.robo.posicao = 0\nfor i in range(linha):\n entrada = input()\n line = []\n for j in range(coluna):\n line.append(entrada[j])\n if not self.robo.posicao != 0:\n self.encontraPos(entrada[j], ... | <|body_start_0|>
self.linha = int(linha)
self.coluna = int(coluna)
self.robo = robo
self.arena = []
self.robo.posicao = 0
for i in range(linha):
entrada = input()
line = []
for j in range(coluna):
line.append(entrada[j])... | Classe Arena. | Arena | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
<|body_0|>
def __repr__(self):
"""Plota arena."""
<|body_1|>
def encontraPos(self, entrada, x, y):
"""Enc."""
<|body_2|>
def posAnteior(self):
... | stack_v2_sparse_classes_36k_train_030549 | 3,220 | no_license | [
{
"docstring": "Construtor.",
"name": "__init__",
"signature": "def __init__(self, linha, coluna, robo)"
},
{
"docstring": "Plota arena.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Enc.",
"name": "encontraPos",
"signature": "def encontraPos(... | 6 | stack_v2_sparse_classes_30k_train_012865 | Implement the Python class `Arena` described below.
Class description:
Classe Arena.
Method signatures and docstrings:
- def __init__(self, linha, coluna, robo): Construtor.
- def __repr__(self): Plota arena.
- def encontraPos(self, entrada, x, y): Enc.
- def posAnteior(self): Altera na Arena a posicao anterior.
- de... | Implement the Python class `Arena` described below.
Class description:
Classe Arena.
Method signatures and docstrings:
- def __init__(self, linha, coluna, robo): Construtor.
- def __repr__(self): Plota arena.
- def encontraPos(self, entrada, x, y): Enc.
- def posAnteior(self): Altera na Arena a posicao anterior.
- de... | e79b79c8b78693bf1d5d8843f7b0121be70bca70 | <|skeleton|>
class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
<|body_0|>
def __repr__(self):
"""Plota arena."""
<|body_1|>
def encontraPos(self, entrada, x, y):
"""Enc."""
<|body_2|>
def posAnteior(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Arena:
"""Classe Arena."""
def __init__(self, linha, coluna, robo):
"""Construtor."""
self.linha = int(linha)
self.coluna = int(coluna)
self.robo = robo
self.arena = []
self.robo.posicao = 0
for i in range(linha):
entrada = input()
... | the_stack_v2_python_sparse | roboColecionadorOO.py | jonathasfsilva/lab-jfs-20181 | train | 0 |
e8e1b6d01c20845e118259f704b02842d3ab6e24 | [
"selected = set([x, y])\nif root.val in selected:\n return False\nprev = [root]\nwhile prev:\n cur = []\n for node in prev:\n left, right = (node.left, node.right)\n if left and right and set([left.val, right.val]).issubset(selected):\n return False\n if left:\n c... | <|body_start_0|>
selected = set([x, y])
if root.val in selected:
return False
prev = [root]
while prev:
cur = []
for node in prev:
left, right = (node.left, node.right)
if left and right and set([left.val, right.val]).is... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
<|body_0|>
def isCousins2(self, root, x, y):
"""DFS, 32ms"""
<|body_1|>
def isCousins3(self, root, x, y):
"""BFS 2, 32ms"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030550 | 3,166 | permissive | [
{
"docstring": "BFS, 28ms",
"name": "isCousins1",
"signature": "def isCousins1(self, root, x, y)"
},
{
"docstring": "DFS, 32ms",
"name": "isCousins2",
"signature": "def isCousins2(self, root, x, y)"
},
{
"docstring": "BFS 2, 32ms",
"name": "isCousins3",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_019998 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins1(self, root, x, y): BFS, 28ms
- def isCousins2(self, root, x, y): DFS, 32ms
- def isCousins3(self, root, x, y): BFS 2, 32ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins1(self, root, x, y): BFS, 28ms
- def isCousins2(self, root, x, y): DFS, 32ms
- def isCousins3(self, root, x, y): BFS 2, 32ms
<|skeleton|>
class Solution:
def i... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
<|body_0|>
def isCousins2(self, root, x, y):
"""DFS, 32ms"""
<|body_1|>
def isCousins3(self, root, x, y):
"""BFS 2, 32ms"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isCousins1(self, root, x, y):
"""BFS, 28ms"""
selected = set([x, y])
if root.val in selected:
return False
prev = [root]
while prev:
cur = []
for node in prev:
left, right = (node.left, node.right)
... | the_stack_v2_python_sparse | leetcode/0993_cousins_in_binary_tree.py | chaosWsF/Python-Practice | train | 1 | |
d0656be1ba7e240196b46156659514a71da34235 | [
"logger.info(f' Running csv reader')\nwith open(csv_file) as csvfile:\n hpnorton_db_reader = csv.DictReader(csvfile, delimiter=',')\n logger.info(f' File {csv_file} Found')\n return [documents for documents in hpnorton_db_reader]",
"for document in documents:\n customer = {'customer_id': document['cus... | <|body_start_0|>
logger.info(f' Running csv reader')
with open(csv_file) as csvfile:
hpnorton_db_reader = csv.DictReader(csvfile, delimiter=',')
logger.info(f' File {csv_file} Found')
return [documents for documents in hpnorton_db_reader]
<|end_body_0|>
<|body_start_... | csv handler class | CsvHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvHandler:
"""csv handler class"""
def csv_reader(csv_file):
"""ingests csv file and returns an ordered dict"""
<|body_0|>
def customer_format(documents):
"""formats customer data to dictionary"""
<|body_1|>
def product_format(documents):
""... | stack_v2_sparse_classes_36k_train_030551 | 2,832 | no_license | [
{
"docstring": "ingests csv file and returns an ordered dict",
"name": "csv_reader",
"signature": "def csv_reader(csv_file)"
},
{
"docstring": "formats customer data to dictionary",
"name": "customer_format",
"signature": "def customer_format(documents)"
},
{
"docstring": "format... | 5 | stack_v2_sparse_classes_30k_train_006575 | Implement the Python class `CsvHandler` described below.
Class description:
csv handler class
Method signatures and docstrings:
- def csv_reader(csv_file): ingests csv file and returns an ordered dict
- def customer_format(documents): formats customer data to dictionary
- def product_format(documents): formats produc... | Implement the Python class `CsvHandler` described below.
Class description:
csv handler class
Method signatures and docstrings:
- def csv_reader(csv_file): ingests csv file and returns an ordered dict
- def customer_format(documents): formats customer data to dictionary
- def product_format(documents): formats produc... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class CsvHandler:
"""csv handler class"""
def csv_reader(csv_file):
"""ingests csv file and returns an ordered dict"""
<|body_0|>
def customer_format(documents):
"""formats customer data to dictionary"""
<|body_1|>
def product_format(documents):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CsvHandler:
"""csv handler class"""
def csv_reader(csv_file):
"""ingests csv file and returns an ordered dict"""
logger.info(f' Running csv reader')
with open(csv_file) as csvfile:
hpnorton_db_reader = csv.DictReader(csvfile, delimiter=',')
logger.info(f' F... | the_stack_v2_python_sparse | students/billy_galloway/lesson_5/assignment/hp_norton_inventory/csv_handler.py | JavaRod/SP_Python220B_2019 | train | 1 |
98060b4873157f332869b13137b4263e473d0e4e | [
"self.logger = logger\nself._loop = loop\nself._in_path = in_path\nself._out_path = out_path\nself._in = -1\nself._out = -1\nself._stream_reader = None\nself._reader_protocol = None\nself._fileobj = None\nself._connection_attempts = PIPE_CONN_ATTEMPTS\nself._connection_timeout = PIPE_CONN_TIMEOUT",
"if self._loop... | <|body_start_0|>
self.logger = logger
self._loop = loop
self._in_path = in_path
self._out_path = out_path
self._in = -1
self._out = -1
self._stream_reader = None
self._reader_protocol = None
self._fileobj = None
self._connection_attempts = ... | Posix named pipes async wrapper communication protocol. | PosixNamedPipeProtocol | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosixNamedPipeProtocol:
"""Posix named pipes async wrapper communication protocol."""
def __init__(self, in_path: str, out_path: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None:
"""Initialize a new posix named pipe. :param in_path: rendezv... | stack_v2_sparse_classes_36k_train_030552 | 23,051 | permissive | [
{
"docstring": "Initialize a new posix named pipe. :param in_path: rendezvous point for incoming data :param out_path: rendezvous point for outgoing data :param logger: the logger :param loop: the event loop",
"name": "__init__",
"signature": "def __init__(self, in_path: str, out_path: str, logger: logg... | 6 | null | Implement the Python class `PosixNamedPipeProtocol` described below.
Class description:
Posix named pipes async wrapper communication protocol.
Method signatures and docstrings:
- def __init__(self, in_path: str, out_path: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None: I... | Implement the Python class `PosixNamedPipeProtocol` described below.
Class description:
Posix named pipes async wrapper communication protocol.
Method signatures and docstrings:
- def __init__(self, in_path: str, out_path: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None: I... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class PosixNamedPipeProtocol:
"""Posix named pipes async wrapper communication protocol."""
def __init__(self, in_path: str, out_path: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None:
"""Initialize a new posix named pipe. :param in_path: rendezv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PosixNamedPipeProtocol:
"""Posix named pipes async wrapper communication protocol."""
def __init__(self, in_path: str, out_path: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None:
"""Initialize a new posix named pipe. :param in_path: rendezvous point for... | the_stack_v2_python_sparse | aea/helpers/pipe.py | fetchai/agents-aea | train | 192 |
19835ed45949f2d465c913b10b5c10214b61719b | [
"n = len(matrix)\npointers = [0] * n\nwhile k:\n temp = [(matrix[pointers[i]][i], i) for i in xrange(n) if pointers[i] < n]\n min_val, min_col = min(temp, key=lambda x: x[0])\n pointers[min_col] += 1\n k -= 1\nreturn min_val",
"n = len(matrix)\nfrom Queue import PriorityQueue\nvisited = set()\nqueue =... | <|body_start_0|>
n = len(matrix)
pointers = [0] * n
while k:
temp = [(matrix[pointers[i]][i], i) for i in xrange(n) if pointers[i] < n]
min_val, min_col = min(temp, key=lambda x: x[0])
pointers[min_col] += 1
k -= 1
return min_val
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest_priority_queue(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_030553 | 1,470 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix, k)"
},
{
"docstring": ":type matrix: List[List[int]] :type k: int :rtype: int",
"name": "kthSmallest_priority_queue",
"signature": "def kthSmallest_... | 2 | stack_v2_sparse_classes_30k_train_016112 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest_priority_queue(self, matrix, k): :type matrix: List[List[int]] :type k:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix, k): :type matrix: List[List[int]] :type k: int :rtype: int
- def kthSmallest_priority_queue(self, matrix, k): :type matrix: List[List[int]] :type k:... | d2cbd0aabff2f0b617d34a59b62771f6764adf95 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_0|>
def kthSmallest_priority_queue(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, matrix, k):
""":type matrix: List[List[int]] :type k: int :rtype: int"""
n = len(matrix)
pointers = [0] * n
while k:
temp = [(matrix[pointers[i]][i], i) for i in xrange(n) if pointers[i] < n]
min_val, min_col = min(temp, k... | the_stack_v2_python_sparse | 378.有序矩阵中第k小的元素.py | ChenghaoZHU/LeetCode | train | 0 | |
042dd0d150b1e9fee2b95c743d6cbd160c3a4f8a | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"sqdist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\nreturn self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)\n'\\n K = np.zeros((X1.shape[0], X2.shape[0])... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
sqdist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
return self.sigma_f ** 2... | represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of black-box function for each input in X_init t is the number o... | stack_v2_sparse_classes_36k_train_030554 | 2,762 | no_license | [
{
"docstring": "X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of black-box function for each input in X_init t is the number of initial samples l is the length parameter for the kernel sigma_f is the standard deviation given to the output of the black-box fun... | 2 | stack_v2_sparse_classes_30k_train_002274 | Implement the Python class `GaussianProcess` described below.
Class description:
represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of blac... | Implement the Python class `GaussianProcess` described below.
Class description:
represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of blac... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of black-box function for each input in X_init t is the number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""X_init ndarray (t, 1) inputs already sampled with black-box function Y_init ndarray (t, 1) outputs of black-box function for each input in X_init t is the number of initial sam... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp copy.py | icculp/holbertonschool-machine_learning | train | 0 |
55e17c5fe78b7814489c6648ae1d6a49dc0b3471 | [
"self.logger.info('点击更多按钮')\nself.move_to(self.find_element(*Portal_Wait_Handle_Ele.wait_More_loc))\nself.logger.info('点击我的任务')\nself.find_element(*Portal_Wait_Handle_Ele.wait_My_Task_loc).click()\nself.logger.info('点击新待办')\nself.find_element(*Portal_Wait_Handle_Ele.wait_handle_loc).click()",
"self.logger.info('输... | <|body_start_0|>
self.logger.info('点击更多按钮')
self.move_to(self.find_element(*Portal_Wait_Handle_Ele.wait_More_loc))
self.logger.info('点击我的任务')
self.find_element(*Portal_Wait_Handle_Ele.wait_My_Task_loc).click()
self.logger.info('点击新待办')
self.find_element(*Portal_Wait_Handl... | 待办页面继承基础basepage类 | Wait_Handle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wait_Handle:
"""待办页面继承基础basepage类"""
def Wait_Page(self):
"""打开待办页面 :return:"""
<|body_0|>
def Select_OrderNo(self, oderno=None, state='审批中'):
""":param oderno:需要传入单据编号 单据编号由 submit_from 方法获取 :return:返回查询结果中的单据状态用于验证单据是否审批成功"""
<|body_1|>
def Get_Ord... | stack_v2_sparse_classes_36k_train_030555 | 3,290 | no_license | [
{
"docstring": "打开待办页面 :return:",
"name": "Wait_Page",
"signature": "def Wait_Page(self)"
},
{
"docstring": ":param oderno:需要传入单据编号 单据编号由 submit_from 方法获取 :return:返回查询结果中的单据状态用于验证单据是否审批成功",
"name": "Select_OrderNo",
"signature": "def Select_OrderNo(self, oderno=None, state='审批中')"
},
... | 3 | stack_v2_sparse_classes_30k_train_014436 | Implement the Python class `Wait_Handle` described below.
Class description:
待办页面继承基础basepage类
Method signatures and docstrings:
- def Wait_Page(self): 打开待办页面 :return:
- def Select_OrderNo(self, oderno=None, state='审批中'): :param oderno:需要传入单据编号 单据编号由 submit_from 方法获取 :return:返回查询结果中的单据状态用于验证单据是否审批成功
- def Get_OrderNo... | Implement the Python class `Wait_Handle` described below.
Class description:
待办页面继承基础basepage类
Method signatures and docstrings:
- def Wait_Page(self): 打开待办页面 :return:
- def Select_OrderNo(self, oderno=None, state='审批中'): :param oderno:需要传入单据编号 单据编号由 submit_from 方法获取 :return:返回查询结果中的单据状态用于验证单据是否审批成功
- def Get_OrderNo... | ea09f7a9728a0a7084e7c778a9c8916ef1144e91 | <|skeleton|>
class Wait_Handle:
"""待办页面继承基础basepage类"""
def Wait_Page(self):
"""打开待办页面 :return:"""
<|body_0|>
def Select_OrderNo(self, oderno=None, state='审批中'):
""":param oderno:需要传入单据编号 单据编号由 submit_from 方法获取 :return:返回查询结果中的单据状态用于验证单据是否审批成功"""
<|body_1|>
def Get_Ord... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wait_Handle:
"""待办页面继承基础basepage类"""
def Wait_Page(self):
"""打开待办页面 :return:"""
self.logger.info('点击更多按钮')
self.move_to(self.find_element(*Portal_Wait_Handle_Ele.wait_More_loc))
self.logger.info('点击我的任务')
self.find_element(*Portal_Wait_Handle_Ele.wait_My_Task_loc).... | the_stack_v2_python_sparse | public/pages/GM_Portal_Wait_Handle.py | dumingxu/oa_auto_test | train | 0 |
cc17d071b4a5186f64619792d23a41a1018ffd9c | [
"self.clustering = clustering\nself.cluster_stabilities = cluster_stabilities\nself._descendant_cache = dict()",
"cache_id = (cluster_id_1, cluster_id_2)\nif cache_id in self._descendant_cache:\n return self._descendant_cache[cache_id]\ncluster_intersection = self.clustering[cluster_id_1] & self.clustering[clu... | <|body_start_0|>
self.clustering = clustering
self.cluster_stabilities = cluster_stabilities
self._descendant_cache = dict()
<|end_body_0|>
<|body_start_1|>
cache_id = (cluster_id_1, cluster_id_2)
if cache_id in self._descendant_cache:
return self._descendant_cache[c... | Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent. | ClusterDeduper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collec... | stack_v2_sparse_classes_36k_train_030556 | 4,546 | permissive | [
{
"docstring": ":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collections.Hashable]] :param cluster_stabilities: :type cluster_stabilities: dict[int, numbers.Real]",
"name": "__init__",
"signature": "def __init__(self, clustering, cluster_stabilities)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_005830 | Implement the Python class `ClusterDeduper` described below.
Class description:
Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent.
Method signatures and docstrings:
- def __init__(self, clustering, cluster_stabilities): :param clustering: cluster_i... | Implement the Python class `ClusterDeduper` described below.
Class description:
Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent.
Method signatures and docstrings:
- def __init__(self, clustering, cluster_stabilities): :param clustering: cluster_i... | bbf24fa7b80d32fae4b8c973a8fc3654eb63cadf | <|skeleton|>
class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collections.Hashabl... | the_stack_v2_python_sparse | python/analysis/ClusterDeduper.py | nog642/himag-release-asonam | train | 0 |
d1d00ec78f28fe52a9da9e08d315b6ec64e85a86 | [
"self.pb_prm = pb_prm\nself.var_fac = self.compute_variables_factors(dvv_low, dvv_upp)\nself.obj_fac = self.compute_objective_factor(grad)\nself.con_fac = self.compute_constraints_factors(jac)",
"var_fac = np.zeros(len(dvv_low))\nfor i, (v_low, v_upp) in enumerate(zip(dvv_low, dvv_upp)):\n fact = max(abs(v_low... | <|body_start_0|>
self.pb_prm = pb_prm
self.var_fac = self.compute_variables_factors(dvv_low, dvv_upp)
self.obj_fac = self.compute_objective_factor(grad)
self.con_fac = self.compute_constraints_factors(jac)
<|end_body_0|>
<|body_start_1|>
var_fac = np.zeros(len(dvv_low))
... | `Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppad_py sparse jacobian object> Sparse... | Scaling | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppa... | stack_v2_sparse_classes_36k_train_030557 | 4,211 | no_license | [
{
"docstring": "Initialiation of the `Scaling` class",
"name": "__init__",
"signature": "def __init__(self, dvv_low, dvv_upp, jac, grad, pb_prm)"
},
{
"docstring": "Computation of the variables scale factors array Parameters ---------- dvv_low : array Decision variables lower boundaries vector d... | 4 | stack_v2_sparse_classes_30k_train_008672 | Implement the Python class `Scaling` described below.
Class description:
`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variab... | Implement the Python class `Scaling` described below.
Class description:
`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variab... | 9d4b1809e868aec674d6bf3c48958b23418290e7 | <|skeleton|>
class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppad_py sparse j... | the_stack_v2_python_sparse | collocation/GL_V/src/scaling.py | TomSemblanet/Asteroid-Retrieval-Mission | train | 1 |
70b41b08d14e25f545a9f2fa05366c4566d4746c | [
"allure.dynamic.title(\"Testing 'count_sheeps' function: positive flow\")\nallure.dynamic.severity(allure.severity_level.NORMAL)\nallure.dynamic.description_html('<h3>Codewars badge:</h3><img src=\"https://www.codewars.com/users/myFirstCode/badges/large\"><h3>Test Description:</h3><p></p>')\nlst = [True, True, True... | <|body_start_0|>
allure.dynamic.title("Testing 'count_sheeps' function: positive flow")
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.description_html('<h3>Codewars badge:</h3><img src="https://www.codewars.com/users/myFirstCode/badges/large"><h3>Test Description:</h3><p><... | Testing 'count_sheeps' function | CountingSheepTestCase | [
"Unlicense",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountingSheepTestCase:
"""Testing 'count_sheeps' function"""
def test_counting_sheep(self):
"""Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true me... | stack_v2_sparse_classes_36k_train_030558 | 5,006 | permissive | [
{
"docstring": "Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present). :return:",
"name": "test_counting_sheep",
"signature": "def test_counting_sheep(self)... | 4 | null | Implement the Python class `CountingSheepTestCase` described below.
Class description:
Testing 'count_sheeps' function
Method signatures and docstrings:
- def test_counting_sheep(self): Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that... | Implement the Python class `CountingSheepTestCase` described below.
Class description:
Testing 'count_sheeps' function
Method signatures and docstrings:
- def test_counting_sheep(self): Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that... | ba3ea81125b6082d867f0ae34c6c9be15e153966 | <|skeleton|>
class CountingSheepTestCase:
"""Testing 'count_sheeps' function"""
def test_counting_sheep(self):
"""Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountingSheepTestCase:
"""Testing 'count_sheeps' function"""
def test_counting_sheep(self):
"""Testing 'count_sheeps' function Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).... | the_stack_v2_python_sparse | kyu_8/counting_sheep/test_counting_sheep.py | qamine-test/codewars | train | 0 |
7e0522faaf76212bcb0a156e8c2e581ce54f7b6b | [
"self.alpha = 5 / len(states_df.index)\nlner = MB_MMPC_Lner(states_df, alpha, verbose, vtx_to_states, learn_later=True)\nlner.find_PC()\nself.vtx_to_nbors = lner.vtx_to_nbors\nHC_TabuLner.__init__(self, states_df, score_type, max_num_mtries, tabu_len, ess, verbose, vtx_to_states)",
"if not HC_TabuLner.move_approv... | <|body_start_0|>
self.alpha = 5 / len(states_df.index)
lner = MB_MMPC_Lner(states_df, alpha, verbose, vtx_to_states, learn_later=True)
lner.find_PC()
self.vtx_to_nbors = lner.vtx_to_nbors
HC_TabuLner.__init__(self, states_df, score_type, max_num_mtries, tabu_len, ess, verbose, vt... | The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each node. This knowledge is then used in the move_allowed() function to forbid any 'add' m... | HC_MMHC_tabu_Lner | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HC_MMHC_tabu_Lner:
"""The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each node. This knowledge is then used in the ... | stack_v2_sparse_classes_36k_train_030559 | 3,735 | permissive | [
{
"docstring": "Constructor Parameters ---------- tabu_len : int alpha : float states_df : pandas.DataFrame score_type : str max_num_mtries : int ess : float Equivalent Sample Size, a parameter in BDEU scorer. Fudge factor that is supposed to grow as the amount of prior knowledge grows. verbose : bool vtx_to_st... | 2 | stack_v2_sparse_classes_30k_train_008461 | Implement the Python class `HC_MMHC_tabu_Lner` described below.
Class description:
The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each no... | Implement the Python class `HC_MMHC_tabu_Lner` described below.
Class description:
The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each no... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class HC_MMHC_tabu_Lner:
"""The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each node. This knowledge is then used in the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HC_MMHC_tabu_Lner:
"""The class HC_MMHC_tabu_Lner (Hill Climbing Min-Max Hill Climbing Tabu Learner) is a child of HC_TabuLner. It adds to the latter a search at the beginning of the learning process of the PC (parents children, aka neighbors) set of each node. This knowledge is then used in the move_allowed(... | the_stack_v2_python_sparse | learning/HC_MMHC_tabu_Lner.py | artiste-qb-net/quantum-fog | train | 95 |
3801f7450688c70cc3cbacb46074ce45947aa055 | [
"if validated_data.get('password', None):\n validated_data['password'] = make_password(validated_data['password'])\nif validated_data.get('is_active', None) is False:\n validated_data['is_active'] = True\ninstance = super(UsersSerializer, self).create(validated_data=validated_data)\nreturn instance",
"for f... | <|body_start_0|>
if validated_data.get('password', None):
validated_data['password'] = make_password(validated_data['password'])
if validated_data.get('is_active', None) is False:
validated_data['is_active'] = True
instance = super(UsersSerializer, self).create(validated_... | UsersSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersSerializer:
def create(self, validated_data):
"""Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instance.save())前,先將明文密碼進行加密 Parameters: validated_data: 為一dict,已經過validate()驗證的資料 returns: model實例對象: instance... | stack_v2_sparse_classes_36k_train_030560 | 2,074 | no_license | [
{
"docstring": "Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instance.save())前,先將明文密碼進行加密 Parameters: validated_data: 為一dict,已經過validate()驗證的資料 returns: model實例對象: instance",
"name": "create",
"signature": "def create(self, va... | 2 | stack_v2_sparse_classes_30k_train_001968 | Implement the Python class `UsersSerializer` described below.
Class description:
Implement the UsersSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instanc... | Implement the Python class `UsersSerializer` described below.
Class description:
Implement the UsersSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instanc... | f9cb1670fb84b9eb8aaaf7cd5cf9139ab4ef4053 | <|skeleton|>
class UsersSerializer:
def create(self, validated_data):
"""Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instance.save())前,先將明文密碼進行加密 Parameters: validated_data: 為一dict,已經過validate()驗證的資料 returns: model實例對象: instance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersSerializer:
def create(self, validated_data):
"""Description: 一、當ViewSet中調用serializer.save()時,會依照實例紀錄是否存在,執行create()或update()方法,最後執行instance.save() 二、覆寫create(),讓在將資料寫入資料庫(instance.save())前,先將明文密碼進行加密 Parameters: validated_data: 為一dict,已經過validate()驗證的資料 returns: model實例對象: instance"""
if... | the_stack_v2_python_sparse | Web網頁框架/框架(Django Rest Framework)/200801_使用Swagger生成API文檔/200725_權限設計+drf-yasg/mysite/api/serializers.py | narru888/PythonWork-py37- | train | 0 | |
7e211fd2c0414dcfea889002ba45d2d8c6c78b07 | [
"try:\n project = await self.application.objects.get(Project, id=int(project_id))\n await self.application.objects.delete(project)\n return self.json(JsonResponse(code=1, data={'id': project_id}))\nexcept Project.DoesNotExist:\n self.set_status(400)\n return self.json(JsonResponse(code=10007))",
"p... | <|body_start_0|>
try:
project = await self.application.objects.get(Project, id=int(project_id))
await self.application.objects.delete(project)
return self.json(JsonResponse(code=1, data={'id': project_id}))
except Project.DoesNotExist:
self.set_status(400)... | ProjectChangeHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectChangeHandler:
async def delete(self, project_id, *args, **kwargs):
"""删除项目数据 :param project_id: 删除的项目id"""
<|body_0|>
async def patch(self, project_id, *args, **kwargs):
"""更新项目数据 :param project_id: 更新的项目id"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_030561 | 17,374 | permissive | [
{
"docstring": "删除项目数据 :param project_id: 删除的项目id",
"name": "delete",
"signature": "async def delete(self, project_id, *args, **kwargs)"
},
{
"docstring": "更新项目数据 :param project_id: 更新的项目id",
"name": "patch",
"signature": "async def patch(self, project_id, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010900 | Implement the Python class `ProjectChangeHandler` described below.
Class description:
Implement the ProjectChangeHandler class.
Method signatures and docstrings:
- async def delete(self, project_id, *args, **kwargs): 删除项目数据 :param project_id: 删除的项目id
- async def patch(self, project_id, *args, **kwargs): 更新项目数据 :param... | Implement the Python class `ProjectChangeHandler` described below.
Class description:
Implement the ProjectChangeHandler class.
Method signatures and docstrings:
- async def delete(self, project_id, *args, **kwargs): 删除项目数据 :param project_id: 删除的项目id
- async def patch(self, project_id, *args, **kwargs): 更新项目数据 :param... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class ProjectChangeHandler:
async def delete(self, project_id, *args, **kwargs):
"""删除项目数据 :param project_id: 删除的项目id"""
<|body_0|>
async def patch(self, project_id, *args, **kwargs):
"""更新项目数据 :param project_id: 更新的项目id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectChangeHandler:
async def delete(self, project_id, *args, **kwargs):
"""删除项目数据 :param project_id: 删除的项目id"""
try:
project = await self.application.objects.get(Project, id=int(project_id))
await self.application.objects.delete(project)
return self.json(... | the_stack_v2_python_sparse | apps/project/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
ca42059ced808579dcf6ce682984c0af26f66554 | [
"import warnings\nimport Bio\nwarnings.warn('Bio.Affy.CelFile.CelParser is deprecated; please use the read() function in this module instead', Bio.BiopythonDeprecationWarning)\nself._intensities = None\nself._stdevs = None\nself._npix = None\nif handle is not None:\n self.parse(handle)",
"scanner = CelScanner(... | <|body_start_0|>
import warnings
import Bio
warnings.warn('Bio.Affy.CelFile.CelParser is deprecated; please use the read() function in this module instead', Bio.BiopythonDeprecationWarning)
self._intensities = None
self._stdevs = None
self._npix = None
if handle i... | Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead. | CelParser | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CelParser:
"""Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead."""
def __init__(self, handle=None):
"""Usually load the cla... | stack_v2_sparse_classes_36k_train_030562 | 8,716 | permissive | [
{
"docstring": "Usually load the class with the cel file (not file name) as an argument.",
"name": "__init__",
"signature": "def __init__(self, handle=None)"
},
{
"docstring": "Takes a handle to a cel file, parses it and stores it in the three arrays. There is more information in the cel file th... | 3 | null | Implement the Python class `CelParser` described below.
Class description:
Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead.
Method signatures and docstrings... | Implement the Python class `CelParser` described below.
Class description:
Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead.
Method signatures and docstrings... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class CelParser:
"""Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead."""
def __init__(self, handle=None):
"""Usually load the cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CelParser:
"""Takes a handle to an Affymetrix cel file, parses the file and returns an instance of a CelRecord This class needs error handling. This class is DEPRECATED; please use the read() function in this module instead."""
def __init__(self, handle=None):
"""Usually load the class with the c... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/Affy/CelFile.py | LyonsLab/coge | train | 41 |
54f8863f6988bce47801af48cdc3ec77f1d57f7d | [
"self.a = [0] * k\nself.ix = 0\nself.k = k\nif len(nums) >= k:\n for i in xrange(0, k):\n self.a[i] = nums[i]\n self.ix = k\n for i in xrange((self.k - 1) / 2, -1, -1):\n adjust(self.a, i, self.k)\n for i in xrange(k, len(nums)):\n self.add(nums[i])\nelse:\n for t in nums:\n ... | <|body_start_0|>
self.a = [0] * k
self.ix = 0
self.k = k
if len(nums) >= k:
for i in xrange(0, k):
self.a[i] = nums[i]
self.ix = k
for i in xrange((self.k - 1) / 2, -1, -1):
adjust(self.a, i, self.k)
for i in... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.a = [0] * k
self.ix = 0
self.k = k
... | stack_v2_sparse_classes_36k_train_030563 | 1,497 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | fd6c8082f81bcd9eda084b347c77fd570cfbee4a | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.a = [0] * k
self.ix = 0
self.k = k
if len(nums) >= k:
for i in xrange(0, k):
self.a[i] = nums[i]
self.ix = k
for i in xrange((self.... | the_stack_v2_python_sparse | problems/703/test.py | neuxxm/leetcode | train | 0 | |
ebaa15f2527cd17bca734fc6cad5cc001eb9328c | [
"if not callable(func):\n raise ValueError('task function not callable')\ntask = {'func': serialize_obj(func), 'args': args, 'kwargs': kwargs}\nreturn serialize_bson(task)",
"if not isinstance(bson_obj, str):\n raise ValueError('bson object should be string')\npytask = deserialize_bson(bson_obj)\nif any((ke... | <|body_start_0|>
if not callable(func):
raise ValueError('task function not callable')
task = {'func': serialize_obj(func), 'args': args, 'kwargs': kwargs}
return serialize_bson(task)
<|end_body_0|>
<|body_start_1|>
if not isinstance(bson_obj, str):
raise ValueEr... | PythonTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonTask:
def __new__(cls, func, *args, **kwargs):
"""We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.function = pythonTask(wrapped_func)"""
<|body_0|>
def get_func_attr(bson_obj):
"""De... | stack_v2_sparse_classes_36k_train_030564 | 2,958 | permissive | [
{
"docstring": "We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.function = pythonTask(wrapped_func)",
"name": "__new__",
"signature": "def __new__(cls, func, *args, **kwargs)"
},
{
"docstring": "Deserialize function c... | 3 | null | Implement the Python class `PythonTask` described below.
Class description:
Implement the PythonTask class.
Method signatures and docstrings:
- def __new__(cls, func, *args, **kwargs): We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.functi... | Implement the Python class `PythonTask` described below.
Class description:
Implement the PythonTask class.
Method signatures and docstrings:
- def __new__(cls, func, *args, **kwargs): We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.functi... | 13852db38c96216d62130e370c1385336723b167 | <|skeleton|>
class PythonTask:
def __new__(cls, func, *args, **kwargs):
"""We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.function = pythonTask(wrapped_func)"""
<|body_0|>
def get_func_attr(bson_obj):
"""De... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonTask:
def __new__(cls, func, *args, **kwargs):
"""We handle wrapped functions here with no args or kwargs. Example: import PythonTask wrapped_func = partial(func_A, func_AB) td.function = pythonTask(wrapped_func)"""
if not callable(func):
raise ValueError('task function not c... | the_stack_v2_python_sparse | src/radical/pilot/pytask.py | radical-cybertools/radical.pilot | train | 58 | |
2e84eef0e9d645b22303d95301b8a63f355bc663 | [
"res = super(account_voucher, self).proforma_voucher()\ncommission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)])\nif commission_payment_rcs:\n commission_payment_rcs.wkf_done()\nreturn res",
"res = super(account_voucher, self).cancel_voucher()\ncm_obj = self.env['commissio... | <|body_start_0|>
res = super(account_voucher, self).proforma_voucher()
commission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)])
if commission_payment_rcs:
commission_payment_rcs.wkf_done()
return res
<|end_body_0|>
<|body_start_1|>
... | account_voucher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_voucher:
def proforma_voucher(self):
"""Surcharge pour lier l'écriture comptable du paiement à la commission"""
<|body_0|>
def cancel_voucher(self):
"""Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est ter... | stack_v2_sparse_classes_36k_train_030565 | 6,577 | no_license | [
{
"docstring": "Surcharge pour lier l'écriture comptable du paiement à la commission",
"name": "proforma_voucher",
"signature": "def proforma_voucher(self)"
},
{
"docstring": "Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est terminée",
"... | 2 | null | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def proforma_voucher(self): Surcharge pour lier l'écriture comptable du paiement à la commission
- def cancel_voucher(self): Surchage de la fonction d'annulation du... | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def proforma_voucher(self): Surcharge pour lier l'écriture comptable du paiement à la commission
- def cancel_voucher(self): Surchage de la fonction d'annulation du... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class account_voucher:
def proforma_voucher(self):
"""Surcharge pour lier l'écriture comptable du paiement à la commission"""
<|body_0|>
def cancel_voucher(self):
"""Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est ter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_voucher:
def proforma_voucher(self):
"""Surcharge pour lier l'écriture comptable du paiement à la commission"""
res = super(account_voucher, self).proforma_voucher()
commission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)])
if commis... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/commission/account_invoice.py | kazacube-mziouadi/ceci | train | 0 | |
8e437468397e9cf8e46b0d583c3120dc0cf4e559 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=UserProfileManager.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"u = self.create_user(email, name=name, password=password)\nu.is_admin = True\nu.save(using... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=UserProfileManager.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_030566 | 3,392 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_009086 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 74e285541f6f4b99dc8b09a4d6460a9784b6a3aa | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=UserProfileManager.normalize_em... | the_stack_v2_python_sparse | estudo_portatil/models/userProfile.py | salvachz/estudoPortatil | train | 0 | |
529ab3eaed51a00812b913032462f0c325d590b8 | [
"host = self.app_host\nheaders = self.headers\nlujing = '/customer/v1/member/check_phone'\nprint(self.phone)\ndata = {'phone': self.phone}\nres = RunMethod().run_main('post', host, lujing, data, headers)\nself.assertTrue(res['code'] == 0, msg=res['msg'])\nmiaoshu(url=host + lujing, method='post', data=data, check={... | <|body_start_0|>
host = self.app_host
headers = self.headers
lujing = '/customer/v1/member/check_phone'
print(self.phone)
data = {'phone': self.phone}
res = RunMethod().run_main('post', host, lujing, data, headers)
self.assertTrue(res['code'] == 0, msg=res['msg'])... | Creat_user | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Creat_user:
def test1_member_check_phone(self):
"""验证手机号是否注册 :return:"""
<|body_0|>
def test2_message_code_send(self):
"""发送注册验证码 :return:"""
<|body_1|>
def test3_message_code_check(self):
"""注册用户-检查验证码 :return:"""
<|body_2|>
def tes... | stack_v2_sparse_classes_36k_train_030567 | 4,078 | no_license | [
{
"docstring": "验证手机号是否注册 :return:",
"name": "test1_member_check_phone",
"signature": "def test1_member_check_phone(self)"
},
{
"docstring": "发送注册验证码 :return:",
"name": "test2_message_code_send",
"signature": "def test2_message_code_send(self)"
},
{
"docstring": "注册用户-检查验证码 :retu... | 5 | stack_v2_sparse_classes_30k_train_002424 | Implement the Python class `Creat_user` described below.
Class description:
Implement the Creat_user class.
Method signatures and docstrings:
- def test1_member_check_phone(self): 验证手机号是否注册 :return:
- def test2_message_code_send(self): 发送注册验证码 :return:
- def test3_message_code_check(self): 注册用户-检查验证码 :return:
- def t... | Implement the Python class `Creat_user` described below.
Class description:
Implement the Creat_user class.
Method signatures and docstrings:
- def test1_member_check_phone(self): 验证手机号是否注册 :return:
- def test2_message_code_send(self): 发送注册验证码 :return:
- def test3_message_code_check(self): 注册用户-检查验证码 :return:
- def t... | 7377a2d7306421d9deae88eb2edff7c9df7f125e | <|skeleton|>
class Creat_user:
def test1_member_check_phone(self):
"""验证手机号是否注册 :return:"""
<|body_0|>
def test2_message_code_send(self):
"""发送注册验证码 :return:"""
<|body_1|>
def test3_message_code_check(self):
"""注册用户-检查验证码 :return:"""
<|body_2|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Creat_user:
def test1_member_check_phone(self):
"""验证手机号是否注册 :return:"""
host = self.app_host
headers = self.headers
lujing = '/customer/v1/member/check_phone'
print(self.phone)
data = {'phone': self.phone}
res = RunMethod().run_main('post', host, lujing... | the_stack_v2_python_sparse | Case/test2_creat_user.py | qq252223804/66ifuel | train | 1 | |
0f3dfbb8cfe8a4be19b4cff0c4114b8ba29ef712 | [
"body = request.data\nproperty_view_ids = body['property_view_ids']\ntaxlot_view_ids = body['taxlot_view_ids']\nproperty_state_ids = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=organization_id).values_list('state_id', flat=True)\ntaxlot_state_ids = TaxLotView.objects.filter(id__i... | <|body_start_0|>
body = request.data
property_view_ids = body['property_view_ids']
taxlot_view_ids = body['taxlot_view_ids']
property_state_ids = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=organization_id).values_list('state_id', flat=True)
ta... | Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed | DataQualityCheckViewSet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataQualityCheckViewSet:
"""Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed"""
def start(self, request, organization_id):
"""This API endpoint will create a new data_quality check process in the background, on potential... | stack_v2_sparse_classes_36k_train_030568 | 7,400 | permissive | [
{
"docstring": "This API endpoint will create a new data_quality check process in the background, on potentially a subset of properties/taxlots, and return back a query key",
"name": "start",
"signature": "def start(self, request, organization_id)"
},
{
"docstring": "Download a CSV of the result... | 3 | null | Implement the Python class `DataQualityCheckViewSet` described below.
Class description:
Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed
Method signatures and docstrings:
- def start(self, request, organization_id): This API endpoint will create a new d... | Implement the Python class `DataQualityCheckViewSet` described below.
Class description:
Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed
Method signatures and docstrings:
- def start(self, request, organization_id): This API endpoint will create a new d... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class DataQualityCheckViewSet:
"""Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed"""
def start(self, request, organization_id):
"""This API endpoint will create a new data_quality check process in the background, on potential... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataQualityCheckViewSet:
"""Handles Data Quality API operations within Inventory backend. (1) Post, wait, get… (2) Respond with what changed"""
def start(self, request, organization_id):
"""This API endpoint will create a new data_quality check process in the background, on potentially a subset o... | the_stack_v2_python_sparse | seed/views/v3/data_quality_checks.py | SEED-platform/seed | train | 108 |
6c8f1f958353a25c2b8f1caa052b18c8a740d234 | [
"half = ''.join(choices(['a', 'b'], k=randint(1, 500000)))\nif force_palindrome:\n return f'{half}c{half[::-1]}'\nelse:\n i = randint(0, len(half))\n return f'{half[:i]}c{half[i:]}'",
"for force_palindrome in (True, False):\n s = self.generate_palindrome(force_palindrome)\n self.assertEqual(is_pali... | <|body_start_0|>
half = ''.join(choices(['a', 'b'], k=randint(1, 500000)))
if force_palindrome:
return f'{half}c{half[::-1]}'
else:
i = randint(0, len(half))
return f'{half[:i]}c{half[i:]}'
<|end_body_0|>
<|body_start_1|>
for force_palindrome in (True... | Test the `chapter4.is_palindrome` function | TestIsPalindrome | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIsPalindrome:
"""Test the `chapter4.is_palindrome` function"""
def generate_palindrome(self, force_palindrome=True):
"""Generate a palindrome (or not)"""
<|body_0|>
def test_is_palindrome(self):
"""Test the `is_palindrome` function using a random string"""
... | stack_v2_sparse_classes_36k_train_030569 | 3,457 | no_license | [
{
"docstring": "Generate a palindrome (or not)",
"name": "generate_palindrome",
"signature": "def generate_palindrome(self, force_palindrome=True)"
},
{
"docstring": "Test the `is_palindrome` function using a random string",
"name": "test_is_palindrome",
"signature": "def test_is_palindr... | 2 | stack_v2_sparse_classes_30k_train_005307 | Implement the Python class `TestIsPalindrome` described below.
Class description:
Test the `chapter4.is_palindrome` function
Method signatures and docstrings:
- def generate_palindrome(self, force_palindrome=True): Generate a palindrome (or not)
- def test_is_palindrome(self): Test the `is_palindrome` function using ... | Implement the Python class `TestIsPalindrome` described below.
Class description:
Test the `chapter4.is_palindrome` function
Method signatures and docstrings:
- def generate_palindrome(self, force_palindrome=True): Generate a palindrome (or not)
- def test_is_palindrome(self): Test the `is_palindrome` function using ... | b73f0596d7e4a52a284dd1a072f37a65257dc357 | <|skeleton|>
class TestIsPalindrome:
"""Test the `chapter4.is_palindrome` function"""
def generate_palindrome(self, force_palindrome=True):
"""Generate a palindrome (or not)"""
<|body_0|>
def test_is_palindrome(self):
"""Test the `is_palindrome` function using a random string"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestIsPalindrome:
"""Test the `chapter4.is_palindrome` function"""
def generate_palindrome(self, force_palindrome=True):
"""Generate a palindrome (or not)"""
half = ''.join(choices(['a', 'b'], k=randint(1, 500000)))
if force_palindrome:
return f'{half}c{half[::-1]}'
... | the_stack_v2_python_sparse | chapter4/tests.py | lptorres/data-structures-exercises | train | 0 |
398ad1d98d188f5b67c7ea1de5386f3c9d4a8114 | [
"EasyFrame.__init__(self, 'Check Button Demo')\nself.chickCB = self.addCheckbutton(text='Chicken', row=0, column=0)\nself.taterCB = self.addCheckbutton(text='French fries', row=0, column=1)\nself.beanCB = self.addCheckbutton(text='Green beans', row=1, column=0)\nself.sauceCB = self.addCheckbutton(text='Applesauce',... | <|body_start_0|>
EasyFrame.__init__(self, 'Check Button Demo')
self.chickCB = self.addCheckbutton(text='Chicken', row=0, column=0)
self.taterCB = self.addCheckbutton(text='French fries', row=0, column=1)
self.beanCB = self.addCheckbutton(text='Green beans', row=1, column=0)
self.... | Allows the user to place a restaurant order from a set of options. | CheckbuttonDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckbuttonDemo:
"""Allows the user to place a restaurant order from a set of options."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def placeOrder(self):
"""Display a message box with the order information."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_030570 | 1,763 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display a message box with the order information.",
"name": "placeOrder",
"signature": "def placeOrder(self)"
}
] | 2 | null | Implement the Python class `CheckbuttonDemo` described below.
Class description:
Allows the user to place a restaurant order from a set of options.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def placeOrder(self): Display a message box with the order information. | Implement the Python class `CheckbuttonDemo` described below.
Class description:
Allows the user to place a restaurant order from a set of options.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def placeOrder(self): Display a message box with the order information.
<|skele... | 30375264cf0103e3455fdf92c35a2c5c15b5d7ef | <|skeleton|>
class CheckbuttonDemo:
"""Allows the user to place a restaurant order from a set of options."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def placeOrder(self):
"""Display a message box with the order information."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckbuttonDemo:
"""Allows the user to place a restaurant order from a set of options."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, 'Check Button Demo')
self.chickCB = self.addCheckbutton(text='Chicken', row=0, column=0)
self.taterC... | the_stack_v2_python_sparse | Student_Files/ch_08_Student_Files/checkbuttondemo.py | davelpat/Fundamentals_of_Python | train | 1 |
6c466735505a7f34bd2a953f7b30d61c22164565 | [
"fs = fs or self.fs\nassert fs is not None and fs > 0, '`fs` must be positive'\nassert granularity > 0, '`granularity` must be positive'\nif not hasattr(self, 'sleep_stage_names'):\n assert class_map is not None, '`class_map` must be provided'\nelse:\n class_map = class_map or {k: len(self.sleep_stage_names) ... | <|body_start_0|>
fs = fs or self.fs
assert fs is not None and fs > 0, '`fs` must be positive'
assert granularity > 0, '`granularity` must be positive'
if not hasattr(self, 'sleep_stage_names'):
assert class_map is not None, '`class_map` must be provided'
else:
... | A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting | PSGDataBaseMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSGDataBaseMixin:
"""A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting"""
def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, cla... | stack_v2_sparse_classes_36k_train_030571 | 49,393 | permissive | [
{
"docstring": "Convert sleep stage intervals to sleep stage mask. Parameters ---------- intervals : dict Sleep stage intervals, in the format of dict of list of lists of int. Keys are sleep stages and values are lists of lists of start and end indices of the sleep stages. fs : int, optional Sampling frequency ... | 2 | null | Implement the Python class `PSGDataBaseMixin` described below.
Class description:
A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting
Method signatures and docstrings:
- def sleep_stage_intervals_to_mask(self, intervals: Dict[str... | Implement the Python class `PSGDataBaseMixin` described below.
Class description:
A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting
Method signatures and docstrings:
- def sleep_stage_intervals_to_mask(self, intervals: Dict[str... | a40c65f4fefa83ba7d3d184072a4c05627b7e226 | <|skeleton|>
class PSGDataBaseMixin:
"""A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting"""
def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSGDataBaseMixin:
"""A mixin class for PSG databases. Contains methods for - convertions between sleep stage intervals and sleep stage masks - hypnogram plotting"""
def sleep_stage_intervals_to_mask(self, intervals: Dict[str, List[List[int]]], fs: Optional[int]=None, granularity: int=30, class_map: Optio... | the_stack_v2_python_sparse | torch_ecg/databases/base.py | DeepPSP/torch_ecg | train | 111 |
2b782743723498231c27a07436a3858ddfdffcc2 | [
"sort_nums = sorted(nums)\nstart, end = (0, len(sort_nums) - 1)\nwhile True:\n s = sort_nums[start] + sort_nums[end]\n if s == target:\n s = nums.index(sort_nums[start])\n e = len(nums) - nums[::-1].index(sort_nums[end]) - 1\n return [s, e]\n elif s < target:\n start += 1\n e... | <|body_start_0|>
sort_nums = sorted(nums)
start, end = (0, len(sort_nums) - 1)
while True:
s = sort_nums[start] + sort_nums[end]
if s == target:
s = nums.index(sort_nums[start])
e = len(nums) - nums[::-1].index(sort_nums[end]) - 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum3(self, nums, targe... | stack_v2_sparse_classes_36k_train_030572 | 2,661 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum3(self, nums, targe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
sort_nums = sorted(nums)
start, end = (0, len(sort_nums) - 1)
while True:
s = sort_nums[start] + sort_nums[end]
if s == target:
s = ... | the_stack_v2_python_sparse | HashTable/q001_two_sum.py | sevenhe716/LeetCode | train | 0 | |
3564600436bd5a12aafe90d7889ac570eb8a79eb | [
"ans = [-1] * len(workers)\nrecord = dict()\nfor b, bike in enumerate(bikes):\n xb, yb = (bike[0], bike[1])\n for w, worker in enumerate(workers):\n xw, yw = (worker[0], worker[1])\n distance = abs(xb - xw) + abs(yb - yw)\n if distance in record:\n record[distance].append([b, w... | <|body_start_0|>
ans = [-1] * len(workers)
record = dict()
for b, bike in enumerate(bikes):
xb, yb = (bike[0], bike[1])
for w, worker in enumerate(workers):
xw, yw = (worker[0], worker[1])
distance = abs(xb - xw) + abs(yb - yw)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def assignBikes(self, workers, bikes):
""":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]"""
<|body_0|>
def assignBikes2(self, workers, bikes):
""":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]"""... | stack_v2_sparse_classes_36k_train_030573 | 3,472 | no_license | [
{
"docstring": ":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]",
"name": "assignBikes",
"signature": "def assignBikes(self, workers, bikes)"
},
{
"docstring": ":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]",
"name": "assignBikes2... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def assignBikes(self, workers, bikes): :type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]
- def assignBikes2(self, workers, bikes): :type workers: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def assignBikes(self, workers, bikes): :type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]
- def assignBikes2(self, workers, bikes): :type workers: List... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def assignBikes(self, workers, bikes):
""":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]"""
<|body_0|>
def assignBikes2(self, workers, bikes):
""":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def assignBikes(self, workers, bikes):
""":type workers: List[List[int]] :type bikes: List[List[int]] :rtype: List[int]"""
ans = [-1] * len(workers)
record = dict()
for b, bike in enumerate(bikes):
xb, yb = (bike[0], bike[1])
for w, worker in e... | the_stack_v2_python_sparse | contest/全国高校春季编程大赛/2. 校园自行车分配.py | lovehhf/LeetCode | train | 0 | |
d239cc2644067092752e4b96b644f850b02137e9 | [
"events = Event.objects.filter(start_at__lt=now())\nevents = events.order_by('-start_at')\nevents = events.annotate(created=F('start_at'), title=F('name'), category=Value('Eventos', output_field=CharField()))\nreturn aux_qs_to_list_for_context(events)",
"jobs = Job.objects.order_by('-created')\njobs = jobs.annota... | <|body_start_0|>
events = Event.objects.filter(start_at__lt=now())
events = events.order_by('-start_at')
events = events.annotate(created=F('start_at'), title=F('name'), category=Value('Eventos', output_field=CharField()))
return aux_qs_to_list_for_context(events)
<|end_body_0|>
<|body_... | HomePageView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomePageView:
def get_events_for_context(self):
"""Ensure events have 'category', created' and 'title' fields"""
<|body_0|>
def get_jobs_for_context(self):
"""Ensure jobs have a 'category' field"""
<|body_1|>
def get_news_for_context(self):
"""En... | stack_v2_sparse_classes_36k_train_030574 | 4,332 | permissive | [
{
"docstring": "Ensure events have 'category', created' and 'title' fields",
"name": "get_events_for_context",
"signature": "def get_events_for_context(self)"
},
{
"docstring": "Ensure jobs have a 'category' field",
"name": "get_jobs_for_context",
"signature": "def get_jobs_for_context(s... | 4 | stack_v2_sparse_classes_30k_val_000186 | Implement the Python class `HomePageView` described below.
Class description:
Implement the HomePageView class.
Method signatures and docstrings:
- def get_events_for_context(self): Ensure events have 'category', created' and 'title' fields
- def get_jobs_for_context(self): Ensure jobs have a 'category' field
- def g... | Implement the Python class `HomePageView` described below.
Class description:
Implement the HomePageView class.
Method signatures and docstrings:
- def get_events_for_context(self): Ensure events have 'category', created' and 'title' fields
- def get_jobs_for_context(self): Ensure jobs have a 'category' field
- def g... | 5f88d1ea0cea9bd67547b70dc2c8bbaa3b8b9d03 | <|skeleton|>
class HomePageView:
def get_events_for_context(self):
"""Ensure events have 'category', created' and 'title' fields"""
<|body_0|>
def get_jobs_for_context(self):
"""Ensure jobs have a 'category' field"""
<|body_1|>
def get_news_for_context(self):
"""En... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomePageView:
def get_events_for_context(self):
"""Ensure events have 'category', created' and 'title' fields"""
events = Event.objects.filter(start_at__lt=now())
events = events.order_by('-start_at')
events = events.annotate(created=F('start_at'), title=F('name'), category=Val... | the_stack_v2_python_sparse | community/views.py | PyAr/pyarweb | train | 64 | |
6146c2f8a02c8b50ea31c23ae996256d1be9ca83 | [
"dask_array_lists = list()\narray_dtype = np.float32\nrechunk_size = 2 << 23\nfor i in range(0, MINUTES_IN_A_MONTH):\n dask_arr = dask.array.from_delayed(dask.delayed(LoadRoutines.load_array_one_minute)(test_spec), shape=INPUT_SHAPE, dtype=array_dtype)\n dask_array_lists.append(dask_arr)\nreturn xarray.Datase... | <|body_start_0|>
dask_array_lists = list()
array_dtype = np.float32
rechunk_size = 2 << 23
for i in range(0, MINUTES_IN_A_MONTH):
dask_arr = dask.array.from_delayed(dask.delayed(LoadRoutines.load_array_one_minute)(test_spec), shape=INPUT_SHAPE, dtype=array_dtype)
... | LoadRoutines | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadRoutines:
def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset:
"""Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that's lazily constructed. Therefore, creating the Xarray object doesn't consume any memory. But computin... | stack_v2_sparse_classes_36k_train_030575 | 16,105 | permissive | [
{
"docstring": "Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that's lazily constructed. Therefore, creating the Xarray object doesn't consume any memory. But computing the Xarray will.",
"name": "lazy_load_xarray_one_month",
"signature": "def lazy_load_x... | 2 | null | Implement the Python class `LoadRoutines` described below.
Class description:
Implement the LoadRoutines class.
Method signatures and docstrings:
- def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset: Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that... | Implement the Python class `LoadRoutines` described below.
Class description:
Implement the LoadRoutines class.
Method signatures and docstrings:
- def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset: Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class LoadRoutines:
def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset:
"""Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that's lazily constructed. Therefore, creating the Xarray object doesn't consume any memory. But computin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadRoutines:
def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset:
"""Lazily load an Xarray representing 1 month of data. The Xarray's data variable is a dask.array that's lazily constructed. Therefore, creating the Xarray object doesn't consume any memory. But computing the Xarray w... | the_stack_v2_python_sparse | release/nightly_tests/dask_on_ray/large_scale_test.py | ray-project/ray | train | 29,482 | |
da5330d05022cc0deeb724c22d9cfb28121ceec1 | [
"res = {}\nfor i, class_name in enumerate(classes):\n try:\n current_class = {}\n res[i] = current_class\n current_class['class_name'] = class_name\n class_obj = getattr(module, class_name)\n doc = inspect.getdoc(class_obj)\n current_class['constructor'] = self.get_param... | <|body_start_0|>
res = {}
for i, class_name in enumerate(classes):
try:
current_class = {}
res[i] = current_class
current_class['class_name'] = class_name
class_obj = getattr(module, class_name)
doc = inspect.get... | SignatureScraper | [
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignatureScraper:
def get_signatures(self, module, classes, type_table):
"""Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor': {'copy_X': 'bool', 'fit_intercept': 'bool', 'n_jobs': 'int', 'normalize': 'bool'}, 'members': {'fit': ... | stack_v2_sparse_classes_36k_train_030576 | 14,069 | permissive | [
{
"docstring": "Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor': {'copy_X': 'bool', 'fit_intercept': 'bool', 'n_jobs': 'int', 'normalize': 'bool'}, 'members': {'fit': {'X': 'list', 'y': 'list'}, '__property___': '__property___', 'get_params': {'deep':... | 5 | stack_v2_sparse_classes_30k_val_000993 | Implement the Python class `SignatureScraper` described below.
Class description:
Implement the SignatureScraper class.
Method signatures and docstrings:
- def get_signatures(self, module, classes, type_table): Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor... | Implement the Python class `SignatureScraper` described below.
Class description:
Implement the SignatureScraper class.
Method signatures and docstrings:
- def get_signatures(self, module, classes, type_table): Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor... | 26e8ab8e718730cbbc5b99ac71395c22686ae698 | <|skeleton|>
class SignatureScraper:
def get_signatures(self, module, classes, type_table):
"""Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor': {'copy_X': 'bool', 'fit_intercept': 'bool', 'n_jobs': 'int', 'normalize': 'bool'}, 'members': {'fit': ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignatureScraper:
def get_signatures(self, module, classes, type_table):
"""Getting the signatures of sklean.linear_model Examples: {0: {'class_name': 'LinearRegression', 'constructor': {'copy_X': 'bool', 'fit_intercept': 'bool', 'n_jobs': 'int', 'normalize': 'bool'}, 'members': {'fit': {'X': 'list', ... | the_stack_v2_python_sparse | cloudmesh/analytics/cms_autoapi.py | cloudmesh/cloudmesh-analytics | train | 0 | |
d893dad3bbaa52c74201ff88fbc3bb8be5eaec3a | [
"self.max_value = 0\nself.max_weight = 0\nmemo = {}\n\ndef _recur_func(i, sw, sv):\n if i == n or sw == w:\n self.max_value = max(sv, self.max_value)\n self.max_weight = max(sw, self.max_weight)\n return\n item = (i, sw)\n if item in memo and memo[item] > sv:\n return\n memo[... | <|body_start_0|>
self.max_value = 0
self.max_weight = 0
memo = {}
def _recur_func(i, sw, sv):
if i == n or sw == w:
self.max_value = max(sv, self.max_value)
self.max_weight = max(sw, self.max_weight)
return
item = (... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knapsack(self, weights, values, n, w):
"""先用回溯算法+备忘录的方式来解决"""
<|body_0|>
def knapsack2(self, weights, values, n, w):
"""动态规划解法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.max_value = 0
self.max_weight = 0
memo ... | stack_v2_sparse_classes_36k_train_030577 | 2,559 | no_license | [
{
"docstring": "先用回溯算法+备忘录的方式来解决",
"name": "knapsack",
"signature": "def knapsack(self, weights, values, n, w)"
},
{
"docstring": "动态规划解法",
"name": "knapsack2",
"signature": "def knapsack2(self, weights, values, n, w)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013991 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knapsack(self, weights, values, n, w): 先用回溯算法+备忘录的方式来解决
- def knapsack2(self, weights, values, n, w): 动态规划解法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knapsack(self, weights, values, n, w): 先用回溯算法+备忘录的方式来解决
- def knapsack2(self, weights, values, n, w): 动态规划解法
<|skeleton|>
class Solution:
def knapsack(self, weights, va... | cbdb055bfdf34ce2e143ab10af90372422984008 | <|skeleton|>
class Solution:
def knapsack(self, weights, values, n, w):
"""先用回溯算法+备忘录的方式来解决"""
<|body_0|>
def knapsack2(self, weights, values, n, w):
"""动态规划解法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def knapsack(self, weights, values, n, w):
"""先用回溯算法+备忘录的方式来解决"""
self.max_value = 0
self.max_weight = 0
memo = {}
def _recur_func(i, sw, sv):
if i == n or sw == w:
self.max_value = max(sv, self.max_value)
self.max_... | the_stack_v2_python_sparse | 32_dynamic_01package.py | turbobin/algorithm_learning | train | 0 | |
7c5e0bbd6029a7205a3272073d6fdf22dea8a335 | [
"cm = self.contents_manager\ncheckpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))\ndata = json.dumps(checkpoints, default=date_default)\nself.finish(data)",
"cm = self.contents_manager\ncheckpoint = (yield gen.maybe_future(cm.create_checkpoint(path)))\ndata = json.dumps(checkpoint, default=date_defau... | <|body_start_0|>
cm = self.contents_manager
checkpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))
data = json.dumps(checkpoints, default=date_default)
self.finish(data)
<|end_body_0|>
<|body_start_1|>
cm = self.contents_manager
checkpoint = (yield gen.maybe_f... | CheckpointsHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
<|body_0|>
def post(self, path=''):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cm = self.contents_manager
checkpoints = ... | stack_v2_sparse_classes_36k_train_030578 | 11,073 | permissive | [
{
"docstring": "get lists checkpoints for a file",
"name": "get",
"signature": "def get(self, path='')"
},
{
"docstring": "post creates a new checkpoint",
"name": "post",
"signature": "def post(self, path='')"
}
] | 2 | null | Implement the Python class `CheckpointsHandler` described below.
Class description:
Implement the CheckpointsHandler class.
Method signatures and docstrings:
- def get(self, path=''): get lists checkpoints for a file
- def post(self, path=''): post creates a new checkpoint | Implement the Python class `CheckpointsHandler` described below.
Class description:
Implement the CheckpointsHandler class.
Method signatures and docstrings:
- def get(self, path=''): get lists checkpoints for a file
- def post(self, path=''): post creates a new checkpoint
<|skeleton|>
class CheckpointsHandler:
... | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | <|skeleton|>
class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
<|body_0|>
def post(self, path=''):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
cm = self.contents_manager
checkpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))
data = json.dumps(checkpoints, default=date_default)
self.finish(data)
def post(self, pat... | the_stack_v2_python_sparse | Library/lib/python3.7/site-packages/notebook/services/contents/handlers.py | holzschu/Carnets | train | 541 | |
4ec3bdefca9fade32c04f03f46bf6f440889b099 | [
"posthog.api_key = 'phc_C44vUK9R1J6HYVdfJarTEPqVAoRPJzMXzFcj8PIrJgP'\nposthog.host = 'https://eu.posthog.com'\nfor module_name in ['posthog', 'backoff']:\n logging.getLogger(module_name).setLevel(logging.CRITICAL)\n logging.getLogger(module_name).addHandler(logging.NullHandler())\n logging.getLogger(module... | <|body_start_0|>
posthog.api_key = 'phc_C44vUK9R1J6HYVdfJarTEPqVAoRPJzMXzFcj8PIrJgP'
posthog.host = 'https://eu.posthog.com'
for module_name in ['posthog', 'backoff']:
logging.getLogger(module_name).setLevel(logging.CRITICAL)
logging.getLogger(module_name).addHandler(logg... | Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the [documentation page](https://docs.haystack.... | Telemetry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Telemetry:
"""Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the [docum... | stack_v2_sparse_classes_36k_train_030579 | 10,370 | permissive | [
{
"docstring": "Initializes the telemetry. Loads the user_id from the config file, or creates a new id and saves it if the file is not found. It also collects system information which cannot change across the lifecycle of the process (for example `is_containerized()`).",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_009056 | Implement the Python class `Telemetry` described below.
Class description:
Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for di... | Implement the Python class `Telemetry` described below.
Class description:
Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for di... | 5f1256ac7e5734c2ea481e72cb7e02c34baf8c43 | <|skeleton|>
class Telemetry:
"""Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the [docum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Telemetry:
"""Haystack reports anonymous usage statistics to support continuous software improvements for all its users. You can opt-out of sharing usage statistics by manually setting the environment variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the [documentation page... | the_stack_v2_python_sparse | haystack/telemetry.py | deepset-ai/haystack | train | 10,599 |
3e32fa0d60c79a17b4d32d09d8b7505c2feeaa88 | [
"graph = defaultdict(list)\nfor next_course, curr_course in pre_requisites:\n graph[curr_course].append(next_course)\npath = [False] * num_course\nvisited = [False] * num_course\nfor curr_course in range(num_course):\n if self.is_cycle(curr_course, graph, visited, path):\n return False\nreturn True",
... | <|body_start_0|>
graph = defaultdict(list)
for next_course, curr_course in pre_requisites:
graph[curr_course].append(next_course)
path = [False] * num_course
visited = [False] * num_course
for curr_course in range(num_course):
if self.is_cycle(curr_course,... | CourseSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseSchedule:
def can_finish_k_courses(self, num_course: int, pre_requisites: List[List[int]]) -> bool:
"""Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number of courses - E number of dependencies Space Complexity: O(|E| + |V|) - O(|E| + 2*|V|) :param num_cours... | stack_v2_sparse_classes_36k_train_030580 | 3,663 | no_license | [
{
"docstring": "Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number of courses - E number of dependencies Space Complexity: O(|E| + |V|) - O(|E| + 2*|V|) :param num_course: :param pre_requisites: :return:",
"name": "can_finish_k_courses",
"signature": "def can_finish_k_courses(s... | 2 | null | Implement the Python class `CourseSchedule` described below.
Class description:
Implement the CourseSchedule class.
Method signatures and docstrings:
- def can_finish_k_courses(self, num_course: int, pre_requisites: List[List[int]]) -> bool: Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number... | Implement the Python class `CourseSchedule` described below.
Class description:
Implement the CourseSchedule class.
Method signatures and docstrings:
- def can_finish_k_courses(self, num_course: int, pre_requisites: List[List[int]]) -> bool: Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class CourseSchedule:
def can_finish_k_courses(self, num_course: int, pre_requisites: List[List[int]]) -> bool:
"""Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number of courses - E number of dependencies Space Complexity: O(|E| + |V|) - O(|E| + 2*|V|) :param num_cours... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseSchedule:
def can_finish_k_courses(self, num_course: int, pre_requisites: List[List[int]]) -> bool:
"""Approach: DFS (Pre-order traversal) Time Complexity: O(|E| + |V|) - V number of courses - E number of dependencies Space Complexity: O(|E| + |V|) - O(|E| + 2*|V|) :param num_course: :param pre_... | the_stack_v2_python_sparse | amazon/graphs/course_schedule.py | Shiv2157k/leet_code | train | 1 | |
a5b8998b949eb91845c969352a5609834ae8907f | [
"super(Test200SmartSanityClear005, self).prepare()\nself.logger.info('Preconditions:')\nself.logger.info('1. Open Micro/WINr; ')\nself.logger.info('2. Set up connection with PLC;')\nself.logger.info('3. Download a project which has OB,DB,SDB;')\nself.MicroWIN.test_prepare('reset_factory_01.smart', False)\nself.PLC... | <|body_start_0|>
super(Test200SmartSanityClear005, self).prepare()
self.logger.info('Preconditions:')
self.logger.info('1. Open Micro/WINr; ')
self.logger.info('2. Set up connection with PLC;')
self.logger.info('3. Download a project which has OB,DB,SDB;')
self.MicroWIN.... | Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected results: 1. Clear successful, all blocks is cleared, all use... | Test200SmartSanityClear005 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected result... | stack_v2_sparse_classes_36k_train_030581 | 3,885 | no_license | [
{
"docstring": "the preparation before executing the test steps Args: Example: Return: Author: Cai, Yong IsInterface: False ChangeInfo: Cai, Yong 2019-09-20 create",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "execute the test steps Args: Example: Return: Author: Cai, ... | 3 | stack_v2_sparse_classes_30k_train_014858 | Implement the Python class `Test200SmartSanityClear005` described below.
Class description:
Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in cle... | Implement the Python class `Test200SmartSanityClear005` described below.
Class description:
Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in cle... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected results: 1. Clear s... | the_stack_v2_python_sparse | test_case/no_piling/sanity/base/clear/test_200smart_sanity_clear_005.py | Lewescaiyong/auto_test_framework | train | 1 |
4b83163dd1d632ad4e4d61fef5d6cd547ed515f9 | [
"self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_height', 'offset_width', 'target_height', 'target_width', 'dim', 'resize_side', 'label_shift'], 'float': ['scale', 'central_fraction'], 'list<float>': ['mean', '... | <|body_start_0|>
self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_height', 'offset_width', 'target_height', 'target_width', 'dim', 'resize_side', 'label_shift'], 'float': ['scale', 'central_fraction'], 'list... | Configuration type parser class. | ConfigurationParser | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
<|body_0|>
def parse(self, data: dict) -> dict:
"""Parse configuration."""
<|body_1|>
def parse_transforms(self, trans... | stack_v2_sparse_classes_36k_train_030582 | 9,825 | permissive | [
{
"docstring": "Initialize configuration type parser.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Parse configuration.",
"name": "parse",
"signature": "def parse(self, data: dict) -> dict"
},
{
"docstring": "Parse transforms list.",
"nam... | 6 | stack_v2_sparse_classes_30k_train_020931 | Implement the Python class `ConfigurationParser` described below.
Class description:
Configuration type parser class.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize configuration type parser.
- def parse(self, data: dict) -> dict: Parse configuration.
- def parse_transforms(self, transform... | Implement the Python class `ConfigurationParser` described below.
Class description:
Configuration type parser class.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize configuration type parser.
- def parse(self, data: dict) -> dict: Parse configuration.
- def parse_transforms(self, transform... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
<|body_0|>
def parse(self, data: dict) -> dict:
"""Parse configuration."""
<|body_1|>
def parse_transforms(self, trans... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_hei... | the_stack_v2_python_sparse | neural_compressor/ux/components/configuration_wizard/configuration_parser.py | Skp80/neural-compressor | train | 0 |
ed8b75b3e476686fb67f679cf349d1477648ee01 | [
"self.rects = rects\nareas = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]\nfor i in range(1, len(areas)):\n areas[i] += areas[i - 1]\nself.areas = areas",
"p = random.randint(1, self.areas[-1])\narea_idx = bisect.bisect_left(self.areas, p)\nrect = self.rects[area_idx]\npoint_idx = p - (self.areas[are... | <|body_start_0|>
self.rects = rects
areas = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]
for i in range(1, len(areas)):
areas[i] += areas[i - 1]
self.areas = areas
<|end_body_0|>
<|body_start_1|>
p = random.randint(1, self.areas[-1])
area_idx = bise... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
areas = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x i... | stack_v2_sparse_classes_36k_train_030583 | 940 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002481 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | c026f2969c784827fac702b34b07a9268b70b62a | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
areas = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]
for i in range(1, len(areas)):
areas[i] += areas[i - 1]
self.areas = areas
def pick(self):
... | the_stack_v2_python_sparse | codes/contest/leetcode/random-point-in-non-overlapping-rectangles.py | jiluhu/dirtysalt.github.io | train | 0 | |
ba47fee67b69812a638d8e87212c98725aaa657e | [
"cnt = collections.Counter(arr)\nif cnt[0] % 2 != 0:\n return False\nfor num in sorted(set(arr)):\n if cnt[num] <= 0:\n continue\n if num == 0:\n del cnt[num]\n elif num < 0:\n if num % 2 != 0 or cnt[num // 2] < cnt[num]:\n return False\n cnt[num // 2] -= cnt[num]\... | <|body_start_0|>
cnt = collections.Counter(arr)
if cnt[0] % 2 != 0:
return False
for num in sorted(set(arr)):
if cnt[num] <= 0:
continue
if num == 0:
del cnt[num]
elif num < 0:
if num % 2 != 0 or cnt[... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canReorderDoubled2(self, arr: List[int]) -> bool:
"""Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= 3 * 10^4 arr.length is even. -10^5 <= arr[i] <= 10^5 :return:"""
<|body_0|>
def canR... | stack_v2_sparse_classes_36k_train_030584 | 3,036 | permissive | [
{
"docstring": "Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= 3 * 10^4 arr.length is even. -10^5 <= arr[i] <= 10^5 :return:",
"name": "canReorderDoubled2",
"signature": "def canReorderDoubled2(self, arr: List[int]) -> bool"
... | 2 | stack_v2_sparse_classes_30k_train_021642 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled2(self, arr: List[int]) -> bool: Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled2(self, arr: List[int]) -> bool: Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def canReorderDoubled2(self, arr: List[int]) -> bool:
"""Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= 3 * 10^4 arr.length is even. -10^5 <= arr[i] <= 10^5 :return:"""
<|body_0|>
def canR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canReorderDoubled2(self, arr: List[int]) -> bool:
"""Update: 20220401 Runtime: 596 ms, faster than 97.28% Memory Usage: 16.6 MB, less than 62.22% :param arr: 2 <= arr.length <= 3 * 10^4 arr.length is even. -10^5 <= arr[i] <= 10^5 :return:"""
cnt = collections.Counter(arr)
... | the_stack_v2_python_sparse | src/954-ArrayofDoubledPairs.py | Jiezhi/myleetcode | train | 1 | |
db2841b021728d5ae82e571d6b2a038bd939a617 | [
"if not root:\n return ''\nans = []\nstack = [root]\nwhile stack:\n next_stack = []\n for node in stack:\n if node:\n ans.append(node.val)\n next_stack.extend([node.left, node.right])\n else:\n ans.append(None)\n stack = next_stack\nreturn ','.join([str(ite... | <|body_start_0|>
if not root:
return ''
ans = []
stack = [root]
while stack:
next_stack = []
for node in stack:
if node:
ans.append(node.val)
next_stack.extend([node.left, node.right])
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)"""
<|body_0|>
def deserialize(self, data: str) -> TreeNode or None:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not... | stack_v2_sparse_classes_36k_train_030585 | 2,034 | no_license | [
{
"docstring": "层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode or None"
}
] | 2 | stack_v2_sparse_classes_30k_train_015301 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: 层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)
- def deserialize(self, data: str) -> TreeNode or None: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: 层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)
- def deserialize(self, data: str) -> TreeNode or None: Decodes your encoded data to tree.
<|skeleton|>
... | d07e0ccf1794f30970bc1d459c017ef48049afbf | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)"""
<|body_0|>
def deserialize(self, data: str) -> TreeNode or None:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""层次遍历的画蛇添足版(非贬义),考虑了叶节点的左右子节点(None)"""
if not root:
return ''
ans = []
stack = [root]
while stack:
next_stack = []
for node in stack:
if node:
an... | the_stack_v2_python_sparse | leet/297answer.py | freelikeff/my_leetcode_answer | train | 0 | |
8bd4ec9398a115c5e712bc0db93537cf9f562c77 | [
"transforms_list = []\nif train:\n if horizontal_flip_prob > 0:\n transforms_list += [A.HorizontalFlip(p=horizontal_flip_prob)]\n if vertical_flip_prob > 0:\n transforms_list += [A.VerticalFlip(p=vertical_flip_prob)]\n if gaussian_blur_prob > 0:\n transforms_list += [A.GaussianBlur(p=g... | <|body_start_0|>
transforms_list = []
if train:
if horizontal_flip_prob > 0:
transforms_list += [A.HorizontalFlip(p=horizontal_flip_prob)]
if vertical_flip_prob > 0:
transforms_list += [A.VerticalFlip(p=vertical_flip_prob)]
if gaussian_... | Wrapper class to pass on albumentaions transforms into PyTorch. | Transformations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformations:
"""Wrapper class to pass on albumentaions transforms into PyTorch."""
def __init__(self, horizontal_flip_prob=0.0, vertical_flip_prob=0.0, gaussian_blur_prob=0.0, rotate_degree=0.0, cutout=0.0, cutout_height=0, cutout_width=0, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), train... | stack_v2_sparse_classes_36k_train_030586 | 3,660 | no_license | [
{
"docstring": "Create data transformation pipeline Args: horizontal_flip_prob: Probability of an image being horizontally flipped. Defaults to 0. vertical_flip_prob: Probability of an image being vertically flipped. Defaults to 0. rotate_degree: Angle of rotation for image augmentation. Defaults to 0. cutout: ... | 2 | stack_v2_sparse_classes_30k_train_009652 | Implement the Python class `Transformations` described below.
Class description:
Wrapper class to pass on albumentaions transforms into PyTorch.
Method signatures and docstrings:
- def __init__(self, horizontal_flip_prob=0.0, vertical_flip_prob=0.0, gaussian_blur_prob=0.0, rotate_degree=0.0, cutout=0.0, cutout_height... | Implement the Python class `Transformations` described below.
Class description:
Wrapper class to pass on albumentaions transforms into PyTorch.
Method signatures and docstrings:
- def __init__(self, horizontal_flip_prob=0.0, vertical_flip_prob=0.0, gaussian_blur_prob=0.0, rotate_degree=0.0, cutout=0.0, cutout_height... | d0c99802a9a2a501c74b8503a3552838d3ce8b27 | <|skeleton|>
class Transformations:
"""Wrapper class to pass on albumentaions transforms into PyTorch."""
def __init__(self, horizontal_flip_prob=0.0, vertical_flip_prob=0.0, gaussian_blur_prob=0.0, rotate_degree=0.0, cutout=0.0, cutout_height=0, cutout_width=0, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), train... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformations:
"""Wrapper class to pass on albumentaions transforms into PyTorch."""
def __init__(self, horizontal_flip_prob=0.0, vertical_flip_prob=0.0, gaussian_blur_prob=0.0, rotate_degree=0.0, cutout=0.0, cutout_height=0, cutout_width=0, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), train=True):
... | the_stack_v2_python_sparse | S9/data/processing.py | rvk007/EVA4 | train | 1 |
816d9f7bad183819ac84758e3102bbbf3cb1fab8 | [
"sc.logger.info('用户空间关注页面初始状态检查测试开始')\nfun_name = 'test_user_follows'\nsc.logger.info('点击个人中心主按钮')\np_btn = 'com.quvideo.xiaoying:id/img_studio'\nWebDriverWait(sc.driver, 10, 1).until(lambda c_btn: c_btn.find_element_by_id(p_btn)).click()\nel_tab_list = sc.driver.find_elements_by_id('com.quvideo.xiaoying:id/text_ta... | <|body_start_0|>
sc.logger.info('用户空间关注页面初始状态检查测试开始')
fun_name = 'test_user_follows'
sc.logger.info('点击个人中心主按钮')
p_btn = 'com.quvideo.xiaoying:id/img_studio'
WebDriverWait(sc.driver, 10, 1).until(lambda c_btn: c_btn.find_element_by_id(p_btn)).click()
el_tab_list = sc.driv... | 测试用户空间关注页的测试类,分步截图. | TestUserFollow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUserFollow:
"""测试用户空间关注页的测试类,分步截图."""
def test_user_follows(self):
"""测试用户空间关注页面的初始状态."""
<|body_0|>
def test_user_follow_state(self):
"""关注/取消关注测试."""
<|body_1|>
def test_user_follow_home(self):
"""点击关注用户头像进入用户空间测试."""
<|body_2|>... | stack_v2_sparse_classes_36k_train_030587 | 3,692 | no_license | [
{
"docstring": "测试用户空间关注页面的初始状态.",
"name": "test_user_follows",
"signature": "def test_user_follows(self)"
},
{
"docstring": "关注/取消关注测试.",
"name": "test_user_follow_state",
"signature": "def test_user_follow_state(self)"
},
{
"docstring": "点击关注用户头像进入用户空间测试.",
"name": "test_us... | 4 | stack_v2_sparse_classes_30k_train_008301 | Implement the Python class `TestUserFollow` described below.
Class description:
测试用户空间关注页的测试类,分步截图.
Method signatures and docstrings:
- def test_user_follows(self): 测试用户空间关注页面的初始状态.
- def test_user_follow_state(self): 关注/取消关注测试.
- def test_user_follow_home(self): 点击关注用户头像进入用户空间测试.
- def test_user_follow_list(self): 用... | Implement the Python class `TestUserFollow` described below.
Class description:
测试用户空间关注页的测试类,分步截图.
Method signatures and docstrings:
- def test_user_follows(self): 测试用户空间关注页面的初始状态.
- def test_user_follow_state(self): 关注/取消关注测试.
- def test_user_follow_home(self): 点击关注用户头像进入用户空间测试.
- def test_user_follow_list(self): 用... | 0003b68fc8e26a96ee1661c1eb1f26f96810e909 | <|skeleton|>
class TestUserFollow:
"""测试用户空间关注页的测试类,分步截图."""
def test_user_follows(self):
"""测试用户空间关注页面的初始状态."""
<|body_0|>
def test_user_follow_state(self):
"""关注/取消关注测试."""
<|body_1|>
def test_user_follow_home(self):
"""点击关注用户头像进入用户空间测试."""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUserFollow:
"""测试用户空间关注页的测试类,分步截图."""
def test_user_follows(self):
"""测试用户空间关注页面的初始状态."""
sc.logger.info('用户空间关注页面初始状态检查测试开始')
fun_name = 'test_user_follows'
sc.logger.info('点击个人中心主按钮')
p_btn = 'com.quvideo.xiaoying:id/img_studio'
WebDriverWait(sc.drive... | the_stack_v2_python_sparse | iOS/VivaVideo/test_community/test_personal/test_user_follow.py | Lemonzhulixin/UItest | train | 5 |
29127503840bdf495bfd556d9220a08d78cc0ce0 | [
"super(Base64Field, self).contribute_to_class(cls, name)\nsetattr(cls, self.name, Base64FieldCreator(self))\nsetattr(cls, 'get_%s_base64' % self.name, lambda model_instance: model_instance.__dict__[self.name])",
"if value is not None:\n if isinstance(value, Base64DecodedValue):\n value = base64_encode(v... | <|body_start_0|>
super(Base64Field, self).contribute_to_class(cls, name)
setattr(cls, self.name, Base64FieldCreator(self))
setattr(cls, 'get_%s_base64' % self.name, lambda model_instance: model_instance.__dict__[self.name])
<|end_body_0|>
<|body_start_1|>
if value is not None:
... | A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that no modifications to the text occurs and that you can read/write the data in an... | Base64Field | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base64Field:
"""A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that no modifications to the text occurs and... | stack_v2_sparse_classes_36k_train_030588 | 9,067 | no_license | [
{
"docstring": "Set attributes on a new model class. This is called when constructing a model class making use of this field. It sets the field's attribute to a :py:class:`Base64FieldCreator` and adds a :samp:`get_{fieldname}_base64()` method to the class. Args: cls (type): The class to add the arguments to. na... | 4 | stack_v2_sparse_classes_30k_train_006037 | Implement the Python class `Base64Field` described below.
Class description:
A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that ... | Implement the Python class `Base64Field` described below.
Class description:
A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that ... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class Base64Field:
"""A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that no modifications to the text occurs and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base64Field:
"""A text field for storing Base64-encoded values. This is used to store data (such as binary data or encoding-sensitive data) to the database in a Base64 encoding. This is useful if you're dealing with unknown encodings and must guarantee that no modifications to the text occurs and that you can... | the_stack_v2_python_sparse | djblets/db/fields/base64_field.py | chipx86/djblets | train | 2 |
d6dd6abb164353a62df9a490a4abc97dcd949888 | [
"pg = getToolByName(self, 'portal_groups')\ngroup = pg.getGroupById('Programacao')\nmembers = group.getGroupMembers()\nlist = DisplayList()\nfor member in members:\n memberId = member.getMemberId()\n fullname = member.getProperty('fullname', memberId)\n list.add(memberId, fullname)\nreturn list",
"list =... | <|body_start_0|>
pg = getToolByName(self, 'portal_groups')
group = pg.getGroupById('Programacao')
members = group.getGroupMembers()
list = DisplayList()
for member in members:
memberId = member.getMemberId()
fullname = member.getProperty('fullname', member... | '' | Chamada | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chamada:
"""''"""
def getListaProgramacao(self):
"""Retorna a lista de usuários do grupo programacao"""
<|body_0|>
def getStatusOff(self):
"""Retorna a lista de status de Off"""
<|body_1|>
def getStatusCabeca(self):
"""Retorna a lista de stat... | stack_v2_sparse_classes_36k_train_030589 | 5,729 | permissive | [
{
"docstring": "Retorna a lista de usuários do grupo programacao",
"name": "getListaProgramacao",
"signature": "def getListaProgramacao(self)"
},
{
"docstring": "Retorna a lista de status de Off",
"name": "getStatusOff",
"signature": "def getStatusOff(self)"
},
{
"docstring": "Re... | 3 | stack_v2_sparse_classes_30k_val_001106 | Implement the Python class `Chamada` described below.
Class description:
''
Method signatures and docstrings:
- def getListaProgramacao(self): Retorna a lista de usuários do grupo programacao
- def getStatusOff(self): Retorna a lista de status de Off
- def getStatusCabeca(self): Retorna a lista de status de Cabecas | Implement the Python class `Chamada` described below.
Class description:
''
Method signatures and docstrings:
- def getListaProgramacao(self): Retorna a lista de usuários do grupo programacao
- def getStatusOff(self): Retorna a lista de status de Off
- def getStatusCabeca(self): Retorna a lista de status de Cabecas
... | 1a77e9f47e22b60af88cf23f492a8b47ddfd27b6 | <|skeleton|>
class Chamada:
"""''"""
def getListaProgramacao(self):
"""Retorna a lista de usuários do grupo programacao"""
<|body_0|>
def getStatusOff(self):
"""Retorna a lista de status de Off"""
<|body_1|>
def getStatusCabeca(self):
"""Retorna a lista de stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Chamada:
"""''"""
def getListaProgramacao(self):
"""Retorna a lista de usuários do grupo programacao"""
pg = getToolByName(self, 'portal_groups')
group = pg.getGroupById('Programacao')
members = group.getGroupMembers()
list = DisplayList()
for member in mem... | the_stack_v2_python_sparse | ebc/pauta/content/chamada.py | lflrocha/ebc.pauta | train | 0 |
f8028f9fbedd6475467cb4383864cfb7320cd2ec | [
"self._config = config\nself._config_entry = config_entry\nself.device_id = device_id\nself.discovery_data = discovery_data\nself.hass = hass\nself._sub_state: dict[str, EntitySubscription] | None = None\nself._value_template = MqttValueTemplate(config.get(CONF_VALUE_TEMPLATE), hass=self.hass).async_render_with_pos... | <|body_start_0|>
self._config = config
self._config_entry = config_entry
self.device_id = device_id
self.discovery_data = discovery_data
self.hass = hass
self._sub_state: dict[str, EntitySubscription] | None = None
self._value_template = MqttValueTemplate(config.g... | MQTT Tag scanner. | MQTTTagScanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MQTTTagScanner:
"""MQTT Tag scanner."""
def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None:
"""Initialize."""
<|body_0|>
async def async_update(self, discovery_data: MQT... | stack_v2_sparse_classes_36k_train_030590 | 5,499 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None"
},
{
"docstring": "Handle MQTT tag discovery updates.",
"name": "async_upd... | 4 | stack_v2_sparse_classes_30k_train_003632 | Implement the Python class `MQTTTagScanner` described below.
Class description:
MQTT Tag scanner.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None: Initialize.
- async def async_... | Implement the Python class `MQTTTagScanner` described below.
Class description:
MQTT Tag scanner.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None: Initialize.
- async def async_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MQTTTagScanner:
"""MQTT Tag scanner."""
def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None:
"""Initialize."""
<|body_0|>
async def async_update(self, discovery_data: MQT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MQTTTagScanner:
"""MQTT Tag scanner."""
def __init__(self, hass: HomeAssistant, config: ConfigType, device_id: str | None, discovery_data: DiscoveryInfoType, config_entry: ConfigEntry) -> None:
"""Initialize."""
self._config = config
self._config_entry = config_entry
self.... | the_stack_v2_python_sparse | homeassistant/components/mqtt/tag.py | home-assistant/core | train | 35,501 |
66ccda5dd0103e2eeb30a221ab1c5913864098df | [
"backlog_name = ticket.values['backlog']\nif backlog_name != NO_BACKLOG:\n Backlog(self.env, name=backlog_name).add_ticket(ticket.id)",
"backlog_name = ticket.values.get('backlog', NO_BACKLOG)\nif 'backlog' in old_values.keys():\n if backlog_name == NO_BACKLOG:\n if old_values['backlog'] and old_valu... | <|body_start_0|>
backlog_name = ticket.values['backlog']
if backlog_name != NO_BACKLOG:
Backlog(self.env, name=backlog_name).add_ticket(ticket.id)
<|end_body_0|>
<|body_start_1|>
backlog_name = ticket.values.get('backlog', NO_BACKLOG)
if 'backlog' in old_values.keys():
... | Listens to the changes of tickets and updates backlogs if necessary | BacklogTicketChangeListener | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BacklogTicketChangeListener:
"""Listens to the changes of tickets and updates backlogs if necessary"""
def ticket_created(self, ticket):
"""Called when a ticket is created."""
<|body_0|>
def ticket_changed(self, ticket, comment, author, old_values):
"""Called whe... | stack_v2_sparse_classes_36k_train_030591 | 1,936 | permissive | [
{
"docstring": "Called when a ticket is created.",
"name": "ticket_created",
"signature": "def ticket_created(self, ticket)"
},
{
"docstring": "Called when a ticket is modified. Adds and removes tickets from backlogs.",
"name": "ticket_changed",
"signature": "def ticket_changed(self, tic... | 3 | null | Implement the Python class `BacklogTicketChangeListener` described below.
Class description:
Listens to the changes of tickets and updates backlogs if necessary
Method signatures and docstrings:
- def ticket_created(self, ticket): Called when a ticket is created.
- def ticket_changed(self, ticket, comment, author, ol... | Implement the Python class `BacklogTicketChangeListener` described below.
Class description:
Listens to the changes of tickets and updates backlogs if necessary
Method signatures and docstrings:
- def ticket_created(self, ticket): Called when a ticket is created.
- def ticket_changed(self, ticket, comment, author, ol... | 4fcd4aeba81d734654f5d9ec524218b91d54a0e1 | <|skeleton|>
class BacklogTicketChangeListener:
"""Listens to the changes of tickets and updates backlogs if necessary"""
def ticket_created(self, ticket):
"""Called when a ticket is created."""
<|body_0|>
def ticket_changed(self, ticket, comment, author, old_values):
"""Called whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BacklogTicketChangeListener:
"""Listens to the changes of tickets and updates backlogs if necessary"""
def ticket_created(self, ticket):
"""Called when a ticket is created."""
backlog_name = ticket.values['backlog']
if backlog_name != NO_BACKLOG:
Backlog(self.env, name... | the_stack_v2_python_sparse | backlogplugin/trunk/backlog/ticketchangelistener.py | woochica/trachacks | train | 0 |
53e0790125ca2b28fb06c84b69d63f171e698e00 | [
"for find_path, record_type, should_result in FindTest.L:\n result = self.server.lnquery.find(EXAMPLE_COM, find_path, record_type, 'traditional')\n assert result == [0, should_result], (find_path, result)",
"mini_list = [(x, y, z) for x, y, z in FindTest.L if y == 'LN']\nqueries = [x for x, y, z in mini_lis... | <|body_start_0|>
for find_path, record_type, should_result in FindTest.L:
result = self.server.lnquery.find(EXAMPLE_COM, find_path, record_type, 'traditional')
assert result == [0, should_result], (find_path, result)
<|end_body_0|>
<|body_start_1|>
mini_list = [(x, y, z) for x, ... | Test query server find function. DOC DOC | FindTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindTest:
"""Test query server find function. DOC DOC"""
def testBasicList(self):
"""Perform lookups found in basic test list."""
<|body_0|>
def testManyList(self):
"""Perform all lookups in basic test list at once."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_030592 | 3,360 | no_license | [
{
"docstring": "Perform lookups found in basic test list.",
"name": "testBasicList",
"signature": "def testBasicList(self)"
},
{
"docstring": "Perform all lookups in basic test list at once.",
"name": "testManyList",
"signature": "def testManyList(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006054 | Implement the Python class `FindTest` described below.
Class description:
Test query server find function. DOC DOC
Method signatures and docstrings:
- def testBasicList(self): Perform lookups found in basic test list.
- def testManyList(self): Perform all lookups in basic test list at once. | Implement the Python class `FindTest` described below.
Class description:
Test query server find function. DOC DOC
Method signatures and docstrings:
- def testBasicList(self): Perform lookups found in basic test list.
- def testManyList(self): Perform all lookups in basic test list at once.
<|skeleton|>
class FindTe... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class FindTest:
"""Test query server find function. DOC DOC"""
def testBasicList(self):
"""Perform lookups found in basic test list."""
<|body_0|>
def testManyList(self):
"""Perform all lookups in basic test list at once."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindTest:
"""Test query server find function. DOC DOC"""
def testBasicList(self):
"""Perform lookups found in basic test list."""
for find_path, record_type, should_result in FindTest.L:
result = self.server.lnquery.find(EXAMPLE_COM, find_path, record_type, 'traditional')
... | the_stack_v2_python_sparse | pre2007/lnresolve/test.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
b6af0ea7550831b41fa7aa8eb5f3266c538012ac | [
"if not digits or len(digits) == 0:\n return []\nMAPPING = {'1': [], '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'], '0': []}\nletters = [MAPPING[d] for d in digits]\noutput =... | <|body_start_0|>
if not digits or len(digits) == 0:
return []
MAPPING = {'1': [], '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'], '0': []}
letters... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations_dfs(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not digits or le... | stack_v2_sparse_classes_36k_train_030593 | 3,183 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations_dfs",
"signature": "def letterCombinations_dfs(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations_dfs(self, digits): :type digits: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations_dfs(self, digits): :type digits: str :rtype: List[str]
<|skeleton|>
class Solu... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations_dfs(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
if not digits or len(digits) == 0:
return []
MAPPING = {'1': [], '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p'... | the_stack_v2_python_sparse | src/lt_17.py | oxhead/CodingYourWay | train | 0 | |
9617fb23732c8e85ee2a34c0cab93060000b1f16 | [
"self.user_email = user_email\nself.msg = EmailMessage()\nself.user_id = user_id\nself.e_mail = 'mudcakegame@gmail.com'",
"with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=ssl.create_default_context()) as server:\n server.login(self.e_mail, bytes(b'$9PLnJ5NsB#!').decode('utf8', 'strict'))\n server.send_... | <|body_start_0|>
self.user_email = user_email
self.msg = EmailMessage()
self.user_id = user_id
self.e_mail = 'mudcakegame@gmail.com'
<|end_body_0|>
<|body_start_1|>
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=ssl.create_default_context()) as server:
server.l... | Basic class for interaction to User via email | EmailSender | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailSender:
"""Basic class for interaction to User via email"""
def __init__(self, user_email, user_id: str):
"""Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :param token: Token to verify User after email confirmation ... | stack_v2_sparse_classes_36k_train_030594 | 4,834 | permissive | [
{
"docstring": "Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :param token: Token to verify User after email confirmation - String",
"name": "__init__",
"signature": "def __init__(self, user_email, user_id: str)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_018548 | Implement the Python class `EmailSender` described below.
Class description:
Basic class for interaction to User via email
Method signatures and docstrings:
- def __init__(self, user_email, user_id: str): Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :pa... | Implement the Python class `EmailSender` described below.
Class description:
Basic class for interaction to User via email
Method signatures and docstrings:
- def __init__(self, user_email, user_id: str): Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :pa... | 70144e1436a86c476302754c0233a4e4c8180457 | <|skeleton|>
class EmailSender:
"""Basic class for interaction to User via email"""
def __init__(self, user_email, user_id: str):
"""Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :param token: Token to verify User after email confirmation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailSender:
"""Basic class for interaction to User via email"""
def __init__(self, user_email, user_id: str):
"""Constructor for email Sender to initiate needed parameters :param user_email: email of the recipient - String :param token: Token to verify User after email confirmation - String"""
... | the_stack_v2_python_sparse | Backend/EmailServices/EmailSender.py | LukasKlein00/SWEProjekt2021 | train | 6 |
2bb989db0c81159a0da002db5e9d419d8c9c546b | [
"if isinstance(key, int):\n return DSMIP6TLSPacket(key)\nif key not in DSMIP6TLSPacket._member_map_:\n return extend_enum(DSMIP6TLSPacket, key, default)\nreturn DSMIP6TLSPacket[key]",
"if not (isinstance(value, int) and 0 <= value <= 15):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))... | <|body_start_0|>
if isinstance(key, int):
return DSMIP6TLSPacket(key)
if key not in DSMIP6TLSPacket._member_map_:
return extend_enum(DSMIP6TLSPacket, key, default)
return DSMIP6TLSPacket[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <=... | [DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry | DSMIP6TLSPacket | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DSMIP6TLSPacket:
"""[DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_... | stack_v2_sparse_classes_36k_train_030595 | 1,955 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket'"
},
{
"docstring": "Lookup function used when value is not fo... | 2 | stack_v2_sparse_classes_30k_train_021230 | Implement the Python class `DSMIP6TLSPacket` described below.
Class description:
[DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket': Backport support for original codes. Args: key: Key to get enum item. default: Defa... | Implement the Python class `DSMIP6TLSPacket` described below.
Class description:
[DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket': Backport support for original codes. Args: key: Key to get enum item. default: Defa... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class DSMIP6TLSPacket:
"""[DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DSMIP6TLSPacket:
"""[DSMIP6TLSPacket] DSMIP6-TLS Packet Types Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'DSMIP6TLSPacket':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, i... | the_stack_v2_python_sparse | pcapkit/const/mh/dsmip6_tls_packet.py | JarryShaw/PyPCAPKit | train | 204 |
9bbc8678f4b4d6ac46012154bada29bf864fe457 | [
"self.error_message = error_message\nself.ipmi_ip = ipmi_ip\nself.node_id = node_id\nself.node_ip = node_ip",
"if dictionary is None:\n return None\nerror_message = dictionary.get('errorMessage')\nipmi_ip = dictionary.get('ipmiIp')\nnode_id = dictionary.get('nodeId')\nnode_ip = dictionary.get('nodeIp')\nreturn... | <|body_start_0|>
self.error_message = error_message
self.ipmi_ip = ipmi_ip
self.node_id = node_id
self.node_ip = node_ip
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
error_message = dictionary.get('errorMessage')
ipmi_ip = dictio... | Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_id (long|int): Specifies the ID of the ... | NodeStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_i... | stack_v2_sparse_classes_36k_train_030596 | 2,119 | permissive | [
{
"docstring": "Constructor for the NodeStatus class",
"name": "__init__",
"signature": "def __init__(self, error_message=None, ipmi_ip=None, node_id=None, node_ip=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representa... | 2 | null | Implement the Python class `NodeStatus` described below.
Class description:
Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of... | Implement the Python class `NodeStatus` described below.
Class description:
Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_id (long|int):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/node_status.py | cohesity/management-sdk-python | train | 24 |
adf72916a0f8dd10be0381de0aeb7948abcaf351 | [
"super(CustomEvaluator, self).__init__(iterator, target)\nself.model = model\nself.device = device",
"iterator = self._iterators['main']\nif self.eval_hook:\n self.eval_hook(self)\nif hasattr(iterator, 'reset'):\n iterator.reset()\n it = iterator\nelse:\n it = copy.copy(iterator)\nsummary = chainer.re... | <|body_start_0|>
super(CustomEvaluator, self).__init__(iterator, target)
self.model = model
self.device = device
<|end_body_0|>
<|body_start_1|>
iterator = self._iterators['main']
if self.eval_hook:
self.eval_hook(self)
if hasattr(iterator, 'reset'):
... | Custom evaluator. | CustomEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEvaluator:
"""Custom evaluator."""
def __init__(self, model, iterator, target, device):
"""Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validation. target (chainer.Chain): Dummy chain instance. device... | stack_v2_sparse_classes_36k_train_030597 | 26,532 | permissive | [
{
"docstring": "Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validation. target (chainer.Chain): Dummy chain instance. device (torch.device): The device to be used in evaluation.",
"name": "__init__",
"signature": "def __init_... | 2 | null | Implement the Python class `CustomEvaluator` described below.
Class description:
Custom evaluator.
Method signatures and docstrings:
- def __init__(self, model, iterator, target, device): Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validat... | Implement the Python class `CustomEvaluator` described below.
Class description:
Custom evaluator.
Method signatures and docstrings:
- def __init__(self, model, iterator, target, device): Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validat... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomEvaluator:
"""Custom evaluator."""
def __init__(self, model, iterator, target, device):
"""Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validation. target (chainer.Chain): Dummy chain instance. device... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomEvaluator:
"""Custom evaluator."""
def __init__(self, model, iterator, target, device):
"""Initilize module. Args: model (torch.nn.Module): Pytorch model instance. iterator (chainer.dataset.Iterator): Iterator for validation. target (chainer.Chain): Dummy chain instance. device (torch.devic... | the_stack_v2_python_sparse | espnet/tts/pytorch_backend/tts.py | espnet/espnet | train | 7,242 |
90aa90e677a5de86568e842f6e8e083faeac00c4 | [
"avatar = self.cleaned_data.get('avatar', None)\nif avatar is not None:\n avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2)\n if avatar_size > settings.MAX_FILE_SIZES['avatar']:\n raise forms.ValidationError(_('Image file too large'))\nreturn avatar",
"user = info.context.user\ntouched = Fals... | <|body_start_0|>
avatar = self.cleaned_data.get('avatar', None)
if avatar is not None:
avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2)
if avatar_size > settings.MAX_FILE_SIZES['avatar']:
raise forms.ValidationError(_('Image file too large'))
retu... | For used by profile settings mutation. | ProfileSettingsForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
<|body_0|>
def save(self, info, commit: bool=True) -> User:
"""Saves the changes made to the database (if any)"""... | stack_v2_sparse_classes_36k_train_030598 | 10,299 | no_license | [
{
"docstring": "Add some custom validation to our avatar field",
"name": "clean_avatar",
"signature": "def clean_avatar(self) -> str"
},
{
"docstring": "Saves the changes made to the database (if any)",
"name": "save",
"signature": "def save(self, info, commit: bool=True) -> User"
}
] | 2 | stack_v2_sparse_classes_30k_train_021508 | Implement the Python class `ProfileSettingsForm` described below.
Class description:
For used by profile settings mutation.
Method signatures and docstrings:
- def clean_avatar(self) -> str: Add some custom validation to our avatar field
- def save(self, info, commit: bool=True) -> User: Saves the changes made to the... | Implement the Python class `ProfileSettingsForm` described below.
Class description:
For used by profile settings mutation.
Method signatures and docstrings:
- def clean_avatar(self) -> str: Add some custom validation to our avatar field
- def save(self, info, commit: bool=True) -> User: Saves the changes made to the... | fe24d0bd08952647d27940a336bd0504af1bae0c | <|skeleton|>
class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
<|body_0|>
def save(self, info, commit: bool=True) -> User:
"""Saves the changes made to the database (if any)"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileSettingsForm:
"""For used by profile settings mutation."""
def clean_avatar(self) -> str:
"""Add some custom validation to our avatar field"""
avatar = self.cleaned_data.get('avatar', None)
if avatar is not None:
avatar_size = len(avatar) * 3 / 4 - avatar.count(... | the_stack_v2_python_sparse | accounts/graphql/mutations.py | ApyMajul/Zola-Backend | train | 0 |
b1d5f1fa6bf33da79ba84a7a06cd2aa2b5e0fbaa | [
"ele = self.find(MobileBy.XPATH, '//android.widget.ListView/android.widget.RelativeLayout[1]//android.widget.TextView')\nname = ele.text\nele.click()\nfrom Work_Wechat_GUI_App.page.member_info_page import member_info_page\nreturn (member_info_page(self.driver), name)",
"\"\"\"\n //*[@resource-id='com.tence... | <|body_start_0|>
ele = self.find(MobileBy.XPATH, '//android.widget.ListView/android.widget.RelativeLayout[1]//android.widget.TextView')
name = ele.text
ele.click()
from Work_Wechat_GUI_App.page.member_info_page import member_info_page
return (member_info_page(self.driver), name)
... | manage_contact_page | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class manage_contact_page:
def goto_member_info_page(self):
""":return: 跳转成员的个人信息页"""
<|body_0|>
def assert_del_succeed(self, name):
""":return: 在管理通讯录页面验证是否有该成员"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ele = self.find(MobileBy.XPATH, '//android.wi... | stack_v2_sparse_classes_36k_train_030599 | 1,850 | no_license | [
{
"docstring": ":return: 跳转成员的个人信息页",
"name": "goto_member_info_page",
"signature": "def goto_member_info_page(self)"
},
{
"docstring": ":return: 在管理通讯录页面验证是否有该成员",
"name": "assert_del_succeed",
"signature": "def assert_del_succeed(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012319 | Implement the Python class `manage_contact_page` described below.
Class description:
Implement the manage_contact_page class.
Method signatures and docstrings:
- def goto_member_info_page(self): :return: 跳转成员的个人信息页
- def assert_del_succeed(self, name): :return: 在管理通讯录页面验证是否有该成员 | Implement the Python class `manage_contact_page` described below.
Class description:
Implement the manage_contact_page class.
Method signatures and docstrings:
- def goto_member_info_page(self): :return: 跳转成员的个人信息页
- def assert_del_succeed(self, name): :return: 在管理通讯录页面验证是否有该成员
<|skeleton|>
class manage_contact_page... | 8891c10e094b13d07cf4830855c37cebd07bd3d4 | <|skeleton|>
class manage_contact_page:
def goto_member_info_page(self):
""":return: 跳转成员的个人信息页"""
<|body_0|>
def assert_del_succeed(self, name):
""":return: 在管理通讯录页面验证是否有该成员"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class manage_contact_page:
def goto_member_info_page(self):
""":return: 跳转成员的个人信息页"""
ele = self.find(MobileBy.XPATH, '//android.widget.ListView/android.widget.RelativeLayout[1]//android.widget.TextView')
name = ele.text
ele.click()
from Work_Wechat_GUI_App.page.member_info_p... | the_stack_v2_python_sparse | Work_Wechat_GUI_App/page/manage_contact_page.py | BlueZUJIUPUP/HogwartsSDE18 | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.