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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e4ff882ac432ed2ee43f9e7487b700100fccbea4 | [
"super(Watershed, self).__init__(paramlist)\nself.params['algorithm'] = 'Watershed'\nself.params['alpha1'] = 0.66\nself.paramindexes = ['alpha1']\nself.set_params(paramlist)",
"compactness = self.params['alpha1'] * 3\noutput = skimage.segmentation.watershed(img, markers=None, compactness=compactness)\nreturn outp... | <|body_start_0|>
super(Watershed, self).__init__(paramlist)
self.params['algorithm'] = 'Watershed'
self.params['alpha1'] = 0.66
self.paramindexes = ['alpha1']
self.set_params(paramlist)
<|end_body_0|>
<|body_start_1|>
compactness = self.params['alpha1'] * 3
outpu... | Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float, compactness of the basins. Higher values make more regularly-shaped basin.... | Watershed | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Watershed:
"""Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float, compactness of the basins. Higher val... | stack_v2_sparse_classes_36k_train_018100 | 29,598 | permissive | [
{
"docstring": "Get parameters from parameter list that are used in segmentation algorithm. Assign default values to these parameters.",
"name": "__init__",
"signature": "def __init__(self, paramlist=None)"
},
{
"docstring": "Evaluate segmentation algorithm on training image. Keyword arguments: ... | 2 | stack_v2_sparse_classes_30k_train_000089 | Implement the Python class `Watershed` described below.
Class description:
Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float... | Implement the Python class `Watershed` described below.
Class description:
Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float... | 9246b8b20510d4c89357a6764ed96b919eb92d5a | <|skeleton|>
class Watershed:
"""Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float, compactness of the basins. Higher val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Watershed:
"""Perform the Watershed segmentation algorithm. Uses user-markers. treats markers as basins and 'floods' them. Especially good if overlapping objects. Returns a labeled image ndarray. Parameters: image -- ndarray, input array compactness -- float, compactness of the basins. Higher values make more... | the_stack_v2_python_sparse | see/Segmentors.py | Deepak768/see-segment | train | 0 |
9f2933577bc4bf8b56ca6dc685e847be039c2b31 | [
"print('decrypt')\nwith open(key_file, 'r') as kf:\n rsa = RSA.importKey(kf.read(), passphrase=passphrase)\n with open(encrypted_file, 'rb') as df:\n data = rsa.decrypt(df.read())\n print('data:\\n')\n print(data)\n print('hex:')\n print(data.encode('hex'))\n with ope... | <|body_start_0|>
print('decrypt')
with open(key_file, 'r') as kf:
rsa = RSA.importKey(kf.read(), passphrase=passphrase)
with open(encrypted_file, 'rb') as df:
data = rsa.decrypt(df.read())
print('data:\n')
print(data)
... | RSAHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSAHelper:
def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''):
"""解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:"""
<|body_0|>
def encrypt(cls, raw_file, key_file, out_file='output_enc', passphrase=''):
... | stack_v2_sparse_classes_36k_train_018101 | 1,843 | permissive | [
{
"docstring": "解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:",
"name": "decrypt",
"signature": "def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase='')"
},
{
"docstring": "加密 :param out_file: :param raw_file: :param key_file: :p... | 2 | stack_v2_sparse_classes_30k_train_011048 | Implement the Python class `RSAHelper` described below.
Class description:
Implement the RSAHelper class.
Method signatures and docstrings:
- def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''): 解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:
- def ... | Implement the Python class `RSAHelper` described below.
Class description:
Implement the RSAHelper class.
Method signatures and docstrings:
- def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''): 解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:
- def ... | 30bbfd8bb97cda2b4762156aaf2973296f0e7cde | <|skeleton|>
class RSAHelper:
def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''):
"""解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:"""
<|body_0|>
def encrypt(cls, raw_file, key_file, out_file='output_enc', passphrase=''):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSAHelper:
def decrypt(cls, encrypted_file, key_file, out_file='output_dec', passphrase=''):
"""解密 :param out_file: :param encrypted_file: :param key_file: :param passphrase: :return:"""
print('decrypt')
with open(key_file, 'r') as kf:
rsa = RSA.importKey(kf.read(), passphr... | the_stack_v2_python_sparse | crypto/rsa/rsa_helper.py | restran/hacker-scripts | train | 31 | |
5b82728ecdb8af261742df9cdf47c4237b1d2a6e | [
"assert resource and containerOsh\nosh = self._getBuilder().buildResource(resource)\nosh.setContainer(containerOsh)\nreturn osh",
"assert pdo and containerOsh\nosh = self._getBuilder().buildResourcePdo(pdo)\nosh.setContainer(containerOsh)\nreturn osh"
] | <|body_start_0|>
assert resource and containerOsh
osh = self._getBuilder().buildResource(resource)
osh.setContainer(containerOsh)
return osh
<|end_body_0|>
<|body_start_1|>
assert pdo and containerOsh
osh = self._getBuilder().buildResourcePdo(pdo)
osh.setContaine... | ResourceReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceReporter:
def reportResource(self, resource, containerOsh):
"""@types: Resource, ObjectStateHolder -> ObjectStateHolder"""
<|body_0|>
def reportResourcePdo(self, pdo, containerOsh):
"""@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder"""
... | stack_v2_sparse_classes_36k_train_018102 | 15,554 | no_license | [
{
"docstring": "@types: Resource, ObjectStateHolder -> ObjectStateHolder",
"name": "reportResource",
"signature": "def reportResource(self, resource, containerOsh)"
},
{
"docstring": "@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder",
"name": "reportResourcePdo",
"sign... | 2 | stack_v2_sparse_classes_30k_train_012223 | Implement the Python class `ResourceReporter` described below.
Class description:
Implement the ResourceReporter class.
Method signatures and docstrings:
- def reportResource(self, resource, containerOsh): @types: Resource, ObjectStateHolder -> ObjectStateHolder
- def reportResourcePdo(self, pdo, containerOsh): @type... | Implement the Python class `ResourceReporter` described below.
Class description:
Implement the ResourceReporter class.
Method signatures and docstrings:
- def reportResource(self, resource, containerOsh): @types: Resource, ObjectStateHolder -> ObjectStateHolder
- def reportResourcePdo(self, pdo, containerOsh): @type... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class ResourceReporter:
def reportResource(self, resource, containerOsh):
"""@types: Resource, ObjectStateHolder -> ObjectStateHolder"""
<|body_0|>
def reportResourcePdo(self, pdo, containerOsh):
"""@types: ResourceBuilder.Pdo, ObjectStateHolder -> ObjectStateHolder"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceReporter:
def reportResource(self, resource, containerOsh):
"""@types: Resource, ObjectStateHolder -> ObjectStateHolder"""
assert resource and containerOsh
osh = self._getBuilder().buildResource(resource)
osh.setContainer(containerOsh)
return osh
def report... | the_stack_v2_python_sparse | reference/ucmdb/discovery/ms_cluster.py | madmonkyang/cda-record | train | 0 | |
3c13ffebfe1ea58f15465d3c14ba8aabacea5403 | [
"if not root:\n return 0\nlevel, queue, height = ([], [root], 1)\nwhile queue:\n for node in queue:\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n if level:\n height += 1\n queue = level[:]\n level = []\nreturn height... | <|body_start_0|>
if not root:
return 0
level, queue, height = ([], [root], 1)
while queue:
for node in queue:
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth1(self, root: TreeNode) -> int:
"""iterative :param root: :return:"""
<|body_0|>
def maxDepth2(self, root: TreeNode) -> int:
"""recursive 假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_018103 | 1,192 | no_license | [
{
"docstring": "iterative :param root: :return:",
"name": "maxDepth1",
"signature": "def maxDepth1(self, root: TreeNode) -> int"
},
{
"docstring": "recursive 假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度 :param root: :return:",
"name": "maxDepth2",
"signature": "def maxDepth2(self, root: TreeNode) ... | 2 | stack_v2_sparse_classes_30k_train_011238 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth1(self, root: TreeNode) -> int: iterative :param root: :return:
- def maxDepth2(self, root: TreeNode) -> int: recursive 假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度 :param root... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth1(self, root: TreeNode) -> int: iterative :param root: :return:
- def maxDepth2(self, root: TreeNode) -> int: recursive 假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度 :param root... | 25f2795b6e7f9f68833f2fddc6cc4f4d977121a6 | <|skeleton|>
class Solution:
def maxDepth1(self, root: TreeNode) -> int:
"""iterative :param root: :return:"""
<|body_0|>
def maxDepth2(self, root: TreeNode) -> int:
"""recursive 假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth1(self, root: TreeNode) -> int:
"""iterative :param root: :return:"""
if not root:
return 0
level, queue, height = ([], [root], 1)
while queue:
for node in queue:
if node.left:
level.append(node.l... | the_stack_v2_python_sparse | 104.py | Darkxiete/leetcode_python | train | 0 | |
a6fc5b3180eb0cd2ff8eec119e1d1dab309771b1 | [
"priv_key_enc_bytes = Base58Decoder.CheckDecode(priv_key_enc)\nif len(priv_key_enc_bytes) != Bip38NoEcConst.ENC_KEY_BYTE_LEN:\n raise ValueError(f'Invalid encrypted key length ({len(priv_key_enc_bytes)})')\nprefix = priv_key_enc_bytes[:2]\nflagbyte = IntegerUtils.ToBytes(priv_key_enc_bytes[2])\naddress_hash = pr... | <|body_start_0|>
priv_key_enc_bytes = Base58Decoder.CheckDecode(priv_key_enc)
if len(priv_key_enc_bytes) != Bip38NoEcConst.ENC_KEY_BYTE_LEN:
raise ValueError(f'Invalid encrypted key length ({len(priv_key_enc_bytes)})')
prefix = priv_key_enc_bytes[:2]
flagbyte = IntegerUtils.T... | BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication. | Bip38NoEcDecrypter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bip38NoEcDecrypter:
"""BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Decrypt(priv_key_enc: str, passphrase: str) -> Tuple[bytes, Bip38PubKeyModes]:
"""Decrypt the specified private key. Args: priv_key_enc (st... | stack_v2_sparse_classes_36k_train_018104 | 11,103 | permissive | [
{
"docstring": "Decrypt the specified private key. Args: priv_key_enc (str): Encrypted private key bytes passphrase (str) : Passphrase Returns: tuple[bytes, Bip38PubKeyModes]: Decrypted private key (index 0), public key mode (index 1) Raises: Base58ChecksumError: If base58 checksum is not valid ValueError: If t... | 2 | null | Implement the Python class `Bip38NoEcDecrypter` described below.
Class description:
BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication.
Method signatures and docstrings:
- def Decrypt(priv_key_enc: str, passphrase: str) -> Tuple[bytes, Bip38PubKeyModes]: ... | Implement the Python class `Bip38NoEcDecrypter` described below.
Class description:
BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication.
Method signatures and docstrings:
- def Decrypt(priv_key_enc: str, passphrase: str) -> Tuple[bytes, Bip38PubKeyModes]: ... | d15c75ddd74e4838c396a0d036ef6faf11b06a4b | <|skeleton|>
class Bip38NoEcDecrypter:
"""BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Decrypt(priv_key_enc: str, passphrase: str) -> Tuple[bytes, Bip38PubKeyModes]:
"""Decrypt the specified private key. Args: priv_key_enc (st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bip38NoEcDecrypter:
"""BIP38 decrypter class. It decrypts a private key using the algorithm specified in BIP38 without EC multiplication."""
def Decrypt(priv_key_enc: str, passphrase: str) -> Tuple[bytes, Bip38PubKeyModes]:
"""Decrypt the specified private key. Args: priv_key_enc (str): Encrypted... | the_stack_v2_python_sparse | bip_utils/bip/bip38/bip38_no_ec.py | ebellocchia/bip_utils | train | 244 |
23bae1ff26b9d029c89ab653e03a4be6a7254065 | [
"result = ''\nfor s in strs:\n result += str(len(s)) + ',' + s\nreturn result",
"result = []\nstate = 0\nlength = 0\ntemp = ''\nfor word in s:\n if state == 0:\n if word == ',':\n if length == 0:\n result.append(temp)\n else:\n state = 1\n el... | <|body_start_0|>
result = ''
for s in strs:
result += str(len(s)) + ',' + s
return result
<|end_body_0|>
<|body_start_1|>
result = []
state = 0
length = 0
temp = ''
for word in s:
if state == 0:
if word == ',':
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_018105 | 1,213 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000302 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 6ce22264a9c34d6addf4eff4c196105eec12b113 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
result = ''
for s in strs:
result += str(len(s)) + ',' + s
return result
def decode(self, s):
"""Decodes a single string to a list of st... | the_stack_v2_python_sparse | Encode_and_Decode_Strings.py | zhubw91/Leetcode | train | 0 | |
25ab05e62dc677738f00e17cb296a60cb2202421 | [
"if not isinstance(origin, math3d.VectorN) or not isinstance(direction, math3d.VectorN) or len(origin) != len(direction):\n raise ValueError(\"You must pass two equal-dimension VectorN's for the origin and direction.\")\nself.mOrigin = origin.copy()\nself.mDirection = direction.normalized()",
"if not isinstanc... | <|body_start_0|>
if not isinstance(origin, math3d.VectorN) or not isinstance(direction, math3d.VectorN) or len(origin) != len(direction):
raise ValueError("You must pass two equal-dimension VectorN's for the origin and direction.")
self.mOrigin = origin.copy()
self.mDirection = direc... | An n-dimensional ray [by definition a ray is an origin point and a direction | Ray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is... | stack_v2_sparse_classes_36k_train_018106 | 14,015 | no_license | [
{
"docstring": ":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is normalized) :return: N/A",
"name": "__init__",
"signature": "def __init__(self, origin, direction)"
},
{
"docstring": ":param... | 4 | stack_v2_sparse_classes_30k_train_019930 | Implement the Python class `Ray` described below.
Class description:
An n-dimensional ray [by definition a ray is an origin point and a direction
Method signatures and docstrings:
- def __init__(self, origin, direction): :param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param dir... | Implement the Python class `Ray` described below.
Class description:
An n-dimensional ray [by definition a ray is an origin point and a direction
Method signatures and docstrings:
- def __init__(self, origin, direction): :param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param dir... | fdf4e216b117769246154cd360b2c321f4581354 | <|skeleton|>
class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ray:
"""An n-dimensional ray [by definition a ray is an origin point and a direction"""
def __init__(self, origin, direction):
""":param origin: the origin POSITION of the ray (a copy of the passed vector is created) :param direction: the DIRECTION of the ray (the vector passed in is normalized) ... | the_stack_v2_python_sparse | Labs/Lab 5/lab05_soln/objects3d.py | ThomasMGilman/ETGG1803_ConceptsOf3DGraphicsAndMath | train | 0 |
aa031932ac1fb09bdcf9987db59fac2e6428ae28 | [
"processed_dict = {}\nfor key, value in requests.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid='2021000117625426', app_notify_url='http://127.0.0.1:8000/alipay/return/', app_private_key_path=private_key_path, alipay_public_key_path=ali_pub_key_path, de... | <|body_start_0|>
processed_dict = {}
for key, value in requests.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid='2021000117625426', app_notify_url='http://127.0.0.1:8000/alipay/return/', app_private_key_path=private_key_p... | 异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形式的返回 | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
"""异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形式的返回"""
def get(self, requests):
... | stack_v2_sparse_classes_36k_train_018107 | 16,054 | no_license | [
{
"docstring": "处理支付宝的return_url :return:",
"name": "get",
"signature": "def get(self, requests)"
},
{
"docstring": "处理支付宝的notify_url :param requests: :return:",
"name": "post",
"signature": "def post(self, requests)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013692 | Implement the Python class `AlipayView` described below.
Class description:
异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形... | Implement the Python class `AlipayView` described below.
Class description:
异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形... | 831b5bdd8abdf7d6e547b0bd3fff9341261e4afa | <|skeleton|>
class AlipayView:
"""异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形式的返回"""
def get(self, requests):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlipayView:
"""异步notify_url:通过 POST 请求的形式将支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 notify_url, 同步return_url: 通过 get请求的形式将部分支付结果作为参数通知到商户系统。对于 PC 网站支付的交易,在用户支付完成之后,支付宝会根据 API 中商户传入的 return_url, 这个view,即可以处理get,又可以处理post,只需要配置一个url就可以完成支付宝的两种形式的返回"""
def get(self, requests):
"""处理支... | the_stack_v2_python_sparse | apps/trade/views.py | tang1323/MxShop | train | 0 |
9e45e951803f47bceb45a0df5cf441f18aa30946 | [
"i, lens = (0, len(nums))\nwhile i < lens - 1:\n if nums[i] == nums[i + 1]:\n nums.pop(i)\n lens -= 1\n else:\n i += 1\nreturn len(nums)",
"for i in range(len(nums))[::-1]:\n if i == 0:\n break\n if nums[i] == nums[i - 1]:\n nums.pop(i)\nreturn len(nums)"
] | <|body_start_0|>
i, lens = (0, len(nums))
while i < lens - 1:
if nums[i] == nums[i + 1]:
nums.pop(i)
lens -= 1
else:
i += 1
return len(nums)
<|end_body_0|>
<|body_start_1|>
for i in range(len(nums))[::-1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates1(self, nums: list) -> int:
"""思想:列表移除数据时列表长度会变,所以每次长度要减一。"""
<|body_0|>
def removeDuplicates2(self, nums: list) -> int:
"""优化:逆序移除时索引不会异常。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i, lens = (0, len(nums))
... | stack_v2_sparse_classes_36k_train_018108 | 1,443 | no_license | [
{
"docstring": "思想:列表移除数据时列表长度会变,所以每次长度要减一。",
"name": "removeDuplicates1",
"signature": "def removeDuplicates1(self, nums: list) -> int"
},
{
"docstring": "优化:逆序移除时索引不会异常。",
"name": "removeDuplicates2",
"signature": "def removeDuplicates2(self, nums: list) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates1(self, nums: list) -> int: 思想:列表移除数据时列表长度会变,所以每次长度要减一。
- def removeDuplicates2(self, nums: list) -> int: 优化:逆序移除时索引不会异常。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates1(self, nums: list) -> int: 思想:列表移除数据时列表长度会变,所以每次长度要减一。
- def removeDuplicates2(self, nums: list) -> int: 优化:逆序移除时索引不会异常。
<|skeleton|>
class Solution:
d... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def removeDuplicates1(self, nums: list) -> int:
"""思想:列表移除数据时列表长度会变,所以每次长度要减一。"""
<|body_0|>
def removeDuplicates2(self, nums: list) -> int:
"""优化:逆序移除时索引不会异常。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates1(self, nums: list) -> int:
"""思想:列表移除数据时列表长度会变,所以每次长度要减一。"""
i, lens = (0, len(nums))
while i < lens - 1:
if nums[i] == nums[i + 1]:
nums.pop(i)
lens -= 1
else:
i += 1
return ... | the_stack_v2_python_sparse | 026_remove-duplicates-from-sorted-array.py | helloocc/algorithm | train | 1 | |
7dbf16c3a95994219828405eee98e835e46b5b84 | [
"super(ComboRefreshTimer, self).__init__()\nself.setSingleShot(True)\nself.owner = owner",
"super(ComboRefreshTimer, self).timerEvent(event)\nowner = self.owner\nif owner is not None:\n del owner.refresh_timer\n self.owner = None\n owner.refresh_items()"
] | <|body_start_0|>
super(ComboRefreshTimer, self).__init__()
self.setSingleShot(True)
self.owner = owner
<|end_body_0|>
<|body_start_1|>
super(ComboRefreshTimer, self).timerEvent(event)
owner = self.owner
if owner is not None:
del owner.refresh_timer
... | A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered. | ComboRefreshTimer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComboRefreshTimer:
"""A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered."""
def __init__(self, owner):
"""Initialize a ComboRefreshTimer. Parameters ---------- owner : QtObjectCombo ... | stack_v2_sparse_classes_36k_train_018109 | 6,020 | permissive | [
{
"docstring": "Initialize a ComboRefreshTimer. Parameters ---------- owner : QtObjectCombo The object combo which owns the timer.",
"name": "__init__",
"signature": "def __init__(self, owner)"
},
{
"docstring": "Handle the timer event for the timer. This handler will call the 'refresh_items' me... | 2 | stack_v2_sparse_classes_30k_train_006627 | Implement the Python class `ComboRefreshTimer` described below.
Class description:
A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered.
Method signatures and docstrings:
- def __init__(self, owner): Initialize a ComboR... | Implement the Python class `ComboRefreshTimer` described below.
Class description:
A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered.
Method signatures and docstrings:
- def __init__(self, owner): Initialize a ComboR... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class ComboRefreshTimer:
"""A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered."""
def __init__(self, owner):
"""Initialize a ComboRefreshTimer. Parameters ---------- owner : QtObjectCombo ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComboRefreshTimer:
"""A QTimer used for collapsing items refresh requests. This is a single shot timer which automatically cleans itself up when its timer event is triggered."""
def __init__(self, owner):
"""Initialize a ComboRefreshTimer. Parameters ---------- owner : QtObjectCombo The object co... | the_stack_v2_python_sparse | enaml/qt/qt_object_combo.py | MatthieuDartiailh/enaml | train | 26 |
c39e7c23ffbc1d32f298acc4ef7cb458527f0dac | [
"super().__init__()\nimport sklearn\nimport sklearn.svm\nself.model = sklearn.svm.LinearSVR",
"specs = super(LinearSVR, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{LinearSVR} \\\\textit{Linear Support Vector Regressor} is\\n similar to SVR with parameter kernel=’l... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVR
<|end_body_0|>
<|body_start_1|>
specs = super(LinearSVR, cls).getInputSpecification()
specs.description = 'The \\xmlNode{LinearSVR} \\textit{Linear Support Vector Reg... | Linear Support Vector Regressor | LinearSVR | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that s... | stack_v2_sparse_classes_36k_train_018110 | 6,358 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_test_000919 | Implement the Python class `LinearSVR` described below.
Class description:
Linear Support Vector Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refere... | Implement the Python class `LinearSVR` described below.
Class description:
Linear Support Vector Regressor
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a refere... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearSVR:
"""Linear Support Vector Regressor"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.LinearSVR
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/SVM/LinearSVR.py | idaholab/raven | train | 201 |
7c94050f616b6974e51fc1f6b470941d9f266181 | [
"self.host = host\nself.database = database\nself.user = user\nself.password = password\nself.dump_command_path = dump_command_path\nself.log = setup_rotating_logger('dump_mysql', size=50 * 1000 * 1000, directory=log_directory)",
"alist = [self.dump_command_path, '--skip-extended-insert', '--protocol=tcp', '-h' +... | <|body_start_0|>
self.host = host
self.database = database
self.user = user
self.password = password
self.dump_command_path = dump_command_path
self.log = setup_rotating_logger('dump_mysql', size=50 * 1000 * 1000, directory=log_directory)
<|end_body_0|>
<|body_start_1|>
... | Dumps MySQL database to SQL file. Can send the file to an S3 bucket. | DumpMySQL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
<|body_0|>
def get_dump_cmd(self, destinati... | stack_v2_sparse_classes_36k_train_018111 | 4,878 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.')"
},
{
"docstring": "Return list/command to dump this environment's database to SQL.",
"name": "get_dump_c... | 5 | stack_v2_sparse_classes_30k_test_000093 | Implement the Python class `DumpMySQL` described below.
Class description:
Dumps MySQL database to SQL file. Can send the file to an S3 bucket.
Method signatures and docstrings:
- def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'): Constructor.
- ... | Implement the Python class `DumpMySQL` described below.
Class description:
Dumps MySQL database to SQL file. Can send the file to an S3 bucket.
Method signatures and docstrings:
- def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'): Constructor.
- ... | 63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a | <|skeleton|>
class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
<|body_0|>
def get_dump_cmd(self, destinati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
self.host = host
self.database = database
sel... | the_stack_v2_python_sparse | bag/dump_mysql.py | nandoflorestan/bag | train | 24 |
a42c3ec743d6d37cc8434f6b2719cd63a7122586 | [
"super(TypeSplitCoder, self).__init__(structure, conf)\nif self.conf['tasklabel'] == 'True':\n self.taskindices = {t: i for i, t in enumerate(structure.tasks)}\n index = len(structure.tasks)\nelse:\n index = 0\nself.argindices = dict()\nfor task in structure.tasks:\n self.argindices[task] = dict()\n ... | <|body_start_0|>
super(TypeSplitCoder, self).__init__(structure, conf)
if self.conf['tasklabel'] == 'True':
self.taskindices = {t: i for i, t in enumerate(structure.tasks)}
index = len(structure.tasks)
else:
index = 0
self.argindices = dict()
f... | a Coder that does not shares the places for args with the same type | TypeSplitCoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeSplitCoder:
"""a Coder that does not shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
<|body_0|>
def encode(self, task):
"""encode the task representation into a ... | stack_v2_sparse_classes_36k_train_018112 | 6,204 | no_license | [
{
"docstring": "Coder constructor Args: structure: a Structure object",
"name": "__init__",
"signature": "def __init__(self, structure, conf)"
},
{
"docstring": "encode the task representation into a vector Args: task: the task reresentation as a Task object Returns: the encoded task representat... | 6 | stack_v2_sparse_classes_30k_train_016802 | Implement the Python class `TypeSplitCoder` described below.
Class description:
a Coder that does not shares the places for args with the same type
Method signatures and docstrings:
- def __init__(self, structure, conf): Coder constructor Args: structure: a Structure object
- def encode(self, task): encode the task r... | Implement the Python class `TypeSplitCoder` described below.
Class description:
a Coder that does not shares the places for args with the same type
Method signatures and docstrings:
- def __init__(self, structure, conf): Coder constructor Args: structure: a Structure object
- def encode(self, task): encode the task r... | fcbe609505f86f142cc6e78686e5c25b0e58e178 | <|skeleton|>
class TypeSplitCoder:
"""a Coder that does not shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
<|body_0|>
def encode(self, task):
"""encode the task representation into a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeSplitCoder:
"""a Coder that does not shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
super(TypeSplitCoder, self).__init__(structure, conf)
if self.conf['tasklabel'] == 'True':
... | the_stack_v2_python_sparse | assist/tasks/typesplit_coder.py | GillesDepypere/assist | train | 1 |
991390b4b5a269fa290b11ece6cf012eeb630d30 | [
"self.task_func = task_func\nself.no_parallel = no_parallel\nself.num_cpu = num_cpu or cpu_count() - 1",
"if not self.no_parallel:\n with Pool(self.num_cpu) as pool:\n for res in pool.imap(self.task_func, items, chunk_size):\n yield res\nelse:\n for res in map(self.task_func, items):\n ... | <|body_start_0|>
self.task_func = task_func
self.no_parallel = no_parallel
self.num_cpu = num_cpu or cpu_count() - 1
<|end_body_0|>
<|body_start_1|>
if not self.no_parallel:
with Pool(self.num_cpu) as pool:
for res in pool.imap(self.task_func, items, chunk_si... | ParallelTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelTask:
def __init__(self, task_func, num_cpu=None, no_parallel=False):
"""Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a global class, due to multiprocessing's limitations. - no_parallel (bool): If true, run everything in t... | stack_v2_sparse_classes_36k_train_018113 | 1,165 | permissive | [
{
"docstring": "Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a global class, due to multiprocessing's limitations. - no_parallel (bool): If true, run everything in the main thread.",
"name": "__init__",
"signature": "def __init__(self, task_func,... | 2 | null | Implement the Python class `ParallelTask` described below.
Class description:
Implement the ParallelTask class.
Method signatures and docstrings:
- def __init__(self, task_func, num_cpu=None, no_parallel=False): Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a g... | Implement the Python class `ParallelTask` described below.
Class description:
Implement the ParallelTask class.
Method signatures and docstrings:
- def __init__(self, task_func, num_cpu=None, no_parallel=False): Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a g... | e6542da84eb40e190653fd868e9b89015dfb829e | <|skeleton|>
class ParallelTask:
def __init__(self, task_func, num_cpu=None, no_parallel=False):
"""Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a global class, due to multiprocessing's limitations. - no_parallel (bool): If true, run everything in t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelTask:
def __init__(self, task_func, num_cpu=None, no_parallel=False):
"""Args: - task_func (callable): Task to run on each work item. Must be a global function, or instance of a global class, due to multiprocessing's limitations. - no_parallel (bool): If true, run everything in the main thread... | the_stack_v2_python_sparse | src/encoded/commands/parallel.py | 4dn-dcic/fourfront | train | 13 | |
78677dd6b09e70672b5802e474133a817c32a43b | [
"user = User(**validated_data)\nuser.set_password(validated_data['password'])\nuser.save()\nreturn user",
"verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')\nif verify_records:\n last_record = verify_records[0]\n five_mintes_ago = datetime.now() - timedel... | <|body_start_0|>
user = User(**validated_data)
user.set_password(validated_data['password'])
user.save()
return user
<|end_body_0|>
<|body_start_1|>
verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')
if verify_records:
... | UserRegSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegSerializer:
def create(self, validated_data):
"""重写create,对密码加密"""
<|body_0|>
def validate_code(self, code):
"""前端传过来的值都会存放serializers.ModelSerializer.initial_data里 因为是用手机号注册,所以username等于mobile"""
<|body_1|>
def validate(self, attrs):
"""直... | stack_v2_sparse_classes_36k_train_018114 | 5,145 | no_license | [
{
"docstring": "重写create,对密码加密",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "前端传过来的值都会存放serializers.ModelSerializer.initial_data里 因为是用手机号注册,所以username等于mobile",
"name": "validate_code",
"signature": "def validate_code(self, code)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_004598 | Implement the Python class `UserRegSerializer` described below.
Class description:
Implement the UserRegSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): 重写create,对密码加密
- def validate_code(self, code): 前端传过来的值都会存放serializers.ModelSerializer.initial_data里 因为是用手机号注册,所以username等于mob... | Implement the Python class `UserRegSerializer` described below.
Class description:
Implement the UserRegSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): 重写create,对密码加密
- def validate_code(self, code): 前端传过来的值都会存放serializers.ModelSerializer.initial_data里 因为是用手机号注册,所以username等于mob... | f1e2d9be379ea9e1a6e2c8278e483b3d2eb5d78a | <|skeleton|>
class UserRegSerializer:
def create(self, validated_data):
"""重写create,对密码加密"""
<|body_0|>
def validate_code(self, code):
"""前端传过来的值都会存放serializers.ModelSerializer.initial_data里 因为是用手机号注册,所以username等于mobile"""
<|body_1|>
def validate(self, attrs):
"""直... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRegSerializer:
def create(self, validated_data):
"""重写create,对密码加密"""
user = User(**validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def validate_code(self, code):
"""前端传过来的值都会存放serializers.ModelSerializer.initial_da... | the_stack_v2_python_sparse | apps/users/serializers.py | yb17821/my_internet_store | train | 0 | |
957cd4643f679242bdb9a27cfbbfc3c71777469c | [
"l = len(s)\ndp_is_palindrome = [[False] * l for _ in range(l)]\ndp_is_palindrome[0][0] = True\nfor i in range(l):\n dp_is_palindrome[i][i] = True\n if s[i] == s[i - 1]:\n dp_is_palindrome[i - 1][i] = True\nfor j in range(2, l):\n for i in range(0, j - 1):\n if s[i] == s[j] and dp_is_palindro... | <|body_start_0|>
l = len(s)
dp_is_palindrome = [[False] * l for _ in range(l)]
dp_is_palindrome[0][0] = True
for i in range(l):
dp_is_palindrome[i][i] = True
if s[i] == s[i - 1]:
dp_is_palindrome[i - 1][i] = True
for j in range(2, l):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int 666ms"""
<|body_0|>
def minCut_1(self, s):
""":type s: str :rtype: int 326ms"""
<|body_1|>
def minCut_2(self, s):
""":type s: str :rtype: int 38ms"""
<|body_2|>
def minCut_3(... | stack_v2_sparse_classes_36k_train_018115 | 3,026 | no_license | [
{
"docstring": ":type s: str :rtype: int 666ms",
"name": "minCut",
"signature": "def minCut(self, s)"
},
{
"docstring": ":type s: str :rtype: int 326ms",
"name": "minCut_1",
"signature": "def minCut_1(self, s)"
},
{
"docstring": ":type s: str :rtype: int 38ms",
"name": "minCu... | 4 | stack_v2_sparse_classes_30k_train_001377 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int 666ms
- def minCut_1(self, s): :type s: str :rtype: int 326ms
- def minCut_2(self, s): :type s: str :rtype: int 38ms
- def minCut_3(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int 666ms
- def minCut_1(self, s): :type s: str :rtype: int 326ms
- def minCut_2(self, s): :type s: str :rtype: int 38ms
- def minCut_3(... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int 666ms"""
<|body_0|>
def minCut_1(self, s):
""":type s: str :rtype: int 326ms"""
<|body_1|>
def minCut_2(self, s):
""":type s: str :rtype: int 38ms"""
<|body_2|>
def minCut_3(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCut(self, s):
""":type s: str :rtype: int 666ms"""
l = len(s)
dp_is_palindrome = [[False] * l for _ in range(l)]
dp_is_palindrome[0][0] = True
for i in range(l):
dp_is_palindrome[i][i] = True
if s[i] == s[i - 1]:
... | the_stack_v2_python_sparse | PalindromePartitioningII_HARD_132.py | 953250587/leetcode-python | train | 2 | |
aeb305f867b1b2a6c3b31bfc543aab01881bee7c | [
"self.bring_disks_online = bring_disks_online\nself.mount_volume_results = mount_volume_results\nself.other_error = other_error\nself.target_source_id = target_source_id\nself.username = username",
"if dictionary is None:\n return None\nbring_disks_online = dictionary.get('bringDisksOnline')\nmount_volume_resu... | <|body_start_0|>
self.bring_disks_online = bring_disks_online
self.mount_volume_results = mount_volume_results
self.other_error = other_error
self.target_source_id = target_source_id
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount target after attaching the disks. This option is ... | MountVolumesState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount targ... | stack_v2_sparse_classes_36k_train_018116 | 3,734 | permissive | [
{
"docstring": "Constructor for the MountVolumesState class",
"name": "__init__",
"signature": "def __init__(self, bring_disks_online=None, mount_volume_results=None, other_error=None, target_source_id=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | null | Implement the Python class `MountVolumesState` described below.
Class description:
Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volum... | Implement the Python class `MountVolumesState` described below.
Class description:
Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volum... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount targ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MountVolumesState:
"""Implementation of the 'MountVolumesState' model. Specifies the states of mounting all the volumes onto a mount target for a 'kRecoverVMs' Restore Task. Attributes: bring_disks_online (bool): Optional setting that determines if the volumes are brought online on the mount target after atta... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mount_volumes_state.py | cohesity/management-sdk-python | train | 24 |
de8b437e01f3ff3dd6c204c6403e22aabcf4fec3 | [
"self.env.revert_snapshot('deploy_kafka')\ntarget_node = {'slave-02': ['controller', self.settings.role_name]}\nself.helpers.remove_nodes_from_cluster(target_node)\nself.check_plugin_online()\nself.helpers.run_ostf()\nself.helpers.add_nodes_to_cluster(target_node)\nself.check_plugin_online()\nself.helpers.run_ostf(... | <|body_start_0|>
self.env.revert_snapshot('deploy_kafka')
target_node = {'slave-02': ['controller', self.settings.role_name]}
self.helpers.remove_nodes_from_cluster(target_node)
self.check_plugin_online()
self.helpers.run_ostf()
self.helpers.add_nodes_to_cluster(target_no... | Class for system tests for Ceilometer-Redis plugin. | TestNodesKafkaPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNodesKafkaPlugin:
"""Class for system tests for Ceilometer-Redis plugin."""
def add_remove_controller_kafka(self):
"""Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed nodes in HA configuration 2. Remove one controller node a... | stack_v2_sparse_classes_36k_train_018117 | 3,370 | no_license | [
{
"docstring": "Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed nodes in HA configuration 2. Remove one controller node and redeploy the cluster 3. Check that Kafka is running 4. Run OSTF 5. Add one controller node (return previous state) and redeploy the... | 2 | stack_v2_sparse_classes_30k_test_000254 | Implement the Python class `TestNodesKafkaPlugin` described below.
Class description:
Class for system tests for Ceilometer-Redis plugin.
Method signatures and docstrings:
- def add_remove_controller_kafka(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed ... | Implement the Python class `TestNodesKafkaPlugin` described below.
Class description:
Class for system tests for Ceilometer-Redis plugin.
Method signatures and docstrings:
- def add_remove_controller_kafka(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed ... | 179249df2d206eeabb3955c9dc8cb78cac3c36c6 | <|skeleton|>
class TestNodesKafkaPlugin:
"""Class for system tests for Ceilometer-Redis plugin."""
def add_remove_controller_kafka(self):
"""Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed nodes in HA configuration 2. Remove one controller node a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNodesKafkaPlugin:
"""Class for system tests for Ceilometer-Redis plugin."""
def add_remove_controller_kafka(self):
"""Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 5 deployed nodes in HA configuration 2. Remove one controller node and redeploy t... | the_stack_v2_python_sparse | stacklight_tests/kafka/test_system.py | rkhozinov/stacklight-integration-tests | train | 1 |
d24bf225a45e73ad6f2c9d37b4ac283ec80e9302 | [
"data = {'username': 'joseperez', 'email': 'jose@gmail.com', 'password': '123abc'}\nr = self.client.post(self.url, data)\nself.assertEqual(r.status_code, 201)",
"CustomUser.objects.create(username='joseperez', password=make_password('123abc'))\ndata = {'username': 'joseperez', 'password': '123abc'}\nr = self.clie... | <|body_start_0|>
data = {'username': 'joseperez', 'email': 'jose@gmail.com', 'password': '123abc'}
r = self.client.post(self.url, data)
self.assertEqual(r.status_code, 201)
<|end_body_0|>
<|body_start_1|>
CustomUser.objects.create(username='joseperez', password=make_password('123abc'))
... | SSO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSO:
def test_postRegister(self):
"""Este test compueba que el usuario nuevo sea creado correctamente"""
<|body_0|>
def test_getJwtToken(self):
"""Este test nos ayuda a verificar que la url para login nos regrese un access token y refresh token, de acuerdo a si el us... | stack_v2_sparse_classes_36k_train_018118 | 1,157 | no_license | [
{
"docstring": "Este test compueba que el usuario nuevo sea creado correctamente",
"name": "test_postRegister",
"signature": "def test_postRegister(self)"
},
{
"docstring": "Este test nos ayuda a verificar que la url para login nos regrese un access token y refresh token, de acuerdo a si el usua... | 2 | stack_v2_sparse_classes_30k_train_015954 | Implement the Python class `SSO` described below.
Class description:
Implement the SSO class.
Method signatures and docstrings:
- def test_postRegister(self): Este test compueba que el usuario nuevo sea creado correctamente
- def test_getJwtToken(self): Este test nos ayuda a verificar que la url para login nos regres... | Implement the Python class `SSO` described below.
Class description:
Implement the SSO class.
Method signatures and docstrings:
- def test_postRegister(self): Este test compueba que el usuario nuevo sea creado correctamente
- def test_getJwtToken(self): Este test nos ayuda a verificar que la url para login nos regres... | 0ce36ac6e9d259cf631c6d43230641d4811cb54f | <|skeleton|>
class SSO:
def test_postRegister(self):
"""Este test compueba que el usuario nuevo sea creado correctamente"""
<|body_0|>
def test_getJwtToken(self):
"""Este test nos ayuda a verificar que la url para login nos regrese un access token y refresh token, de acuerdo a si el us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSO:
def test_postRegister(self):
"""Este test compueba que el usuario nuevo sea creado correctamente"""
data = {'username': 'joseperez', 'email': 'jose@gmail.com', 'password': '123abc'}
r = self.client.post(self.url, data)
self.assertEqual(r.status_code, 201)
def test_get... | the_stack_v2_python_sparse | administrador/Aplicaciones/SSO/tests.py | mora-david/Favs-api | train | 0 | |
05d960752d2603bba67419f53c51528b4785d086 | [
"self.amazon = amazon\nself.azure = azure\nself.bucket_name = bucket_name\nself.google = google\nself.nas = nas\nself.oracle = oracle\nself.qstar = qstar",
"if dictionary is None:\n return None\namazon = cohesity_management_sdk.models.amazon_cloud_credentials.AmazonCloudCredentials.from_dictionary(dictionary.g... | <|body_start_0|>
self.amazon = amazon
self.azure = azure
self.bucket_name = bucket_name
self.google = google
self.nas = nas
self.oracle = oracle
self.qstar = qstar
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
amaz... | Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the cloud credentials to connect to a Amazon service account. Glacier, S3, and S3... | VaultConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultConfig:
"""Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the cloud credentials to connect to a Amaz... | stack_v2_sparse_classes_36k_train_018119 | 4,544 | permissive | [
{
"docstring": "Constructor for the VaultConfig class",
"name": "__init__",
"signature": "def __init__(self, amazon=None, azure=None, bucket_name=None, google=None, nas=None, oracle=None, qstar=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | null | Implement the Python class `VaultConfig` described below.
Class description:
Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the... | Implement the Python class `VaultConfig` described below.
Class description:
Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultConfig:
"""Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the cloud credentials to connect to a Amaz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VaultConfig:
"""Implementation of the 'VaultConfig' model. Specifies the settings required to connect to a specific Vault type. For some Vaults, you must also specify a storage location (bucketName). Attributes: amazon (AmazonCloudCredentials): Specifies the cloud credentials to connect to a Amazon service ac... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_config.py | cohesity/management-sdk-python | train | 24 |
df8de9c85a93c2338de6fdd722ede1ea0a1f74cd | [
"self_dc = Idc.get_local_dc()\nself.clients = []\nfor dc, client in clients.iteritems():\n if self_dc == dc:\n self.clients.insert(0, client)\n else:\n self.clients.append(client)\nself.local_cmds = set(self.READ_CMDS)\nself.local_cmds.update(local_update_cmds)",
"def wrap(*args, **kwargs):\n ... | <|body_start_0|>
self_dc = Idc.get_local_dc()
self.clients = []
for dc, client in clients.iteritems():
if self_dc == dc:
self.clients.insert(0, client)
else:
self.clients.append(client)
self.local_cmds = set(self.READ_CMDS)
... | MultiClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiClient:
def __init__(self, clients, local_update_cmds=[]):
""":param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pypi/python-memcached eg: {'hy':c1, 'lf':c2} :param local_update_cmds: all update commands will go to a... | stack_v2_sparse_classes_36k_train_018120 | 1,545 | no_license | [
{
"docstring": ":param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pypi/python-memcached eg: {'hy':c1, 'lf':c2} :param local_update_cmds: all update commands will go to all clients, except that listed in local_update_cmds :return:",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_019420 | Implement the Python class `MultiClient` described below.
Class description:
Implement the MultiClient class.
Method signatures and docstrings:
- def __init__(self, clients, local_update_cmds=[]): :param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pyp... | Implement the Python class `MultiClient` described below.
Class description:
Implement the MultiClient class.
Method signatures and docstrings:
- def __init__(self, clients, local_update_cmds=[]): :param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pyp... | c592d879fd79da4e0816a4f909e5725e385b6160 | <|skeleton|>
class MultiClient:
def __init__(self, clients, local_update_cmds=[]):
""":param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pypi/python-memcached eg: {'hy':c1, 'lf':c2} :param local_update_cmds: all update commands will go to a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiClient:
def __init__(self, clients, local_update_cmds=[]):
""":param clients: dict: idc->client where client should by compatible with memcache.Client @see https://pypi.python.org/pypi/python-memcached eg: {'hy':c1, 'lf':c2} :param local_update_cmds: all update commands will go to all clients, ex... | the_stack_v2_python_sparse | leetcode/venv/lib/python2.7/site-packages/pyutil/memcache/multi_client.py | KqSMea8/PycharmProjects | train | 0 | |
b8d4c229b24e65c0995698d2e6b7ec05cf330276 | [
"from heapq import heappush, heappop, heapreplace, heapify\nh = []\nres = ListNode(0)\np = res\nh = [(n.val, n) for n in lists if n]\nheapify(h)\nwhile h:\n value, minNode = h[0]\n p.next = minNode\n if not minNode.next:\n heappop(h)\n else:\n heapreplace(h, (minNode.next.val, minNode.next... | <|body_start_0|>
from heapq import heappush, heappop, heapreplace, heapify
h = []
res = ListNode(0)
p = res
h = [(n.val, n) for n in lists if n]
heapify(h)
while h:
value, minNode = h[0]
p.next = minNode
if not minNode.next:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists2(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from heapq import he... | stack_v2_sparse_classes_36k_train_018121 | 1,442 | permissive | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists2",
"signature": "def mergeKLists2(self, lists)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists2(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists2(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>
class Solut... | aec1ddd0c51b619c1bae1e05f940d9ed587aa82f | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists2(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
from heapq import heappush, heappop, heapreplace, heapify
h = []
res = ListNode(0)
p = res
h = [(n.val, n) for n in lists if n]
heapify(h)
while h:
... | the_stack_v2_python_sparse | Python/leetcode/MergeKLists.py | darrencheng0817/AlgorithmLearning | train | 2 | |
05cc39fe05acb5ad40058a7ce32fb4d31bdc263f | [
"super(RegistrationForm, self).__init__(*args, **kwargs)\nself.captcha_error_query_str = ''\nsiteconfig = SiteConfiguration.objects.get_current()\nif siteconfig.get('site_domain_method') == 'https':\n self.recaptcha_url = 'https://www.google.com/recaptcha/api'\nelse:\n self.recaptcha_url = 'http://www.google.... | <|body_start_0|>
super(RegistrationForm, self).__init__(*args, **kwargs)
self.captcha_error_query_str = ''
siteconfig = SiteConfiguration.objects.get_current()
if siteconfig.get('site_domain_method') == 'https':
self.recaptcha_url = 'https://www.google.com/recaptcha/api'
... | A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget can properly display the error. | RegistrationForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget can properly display the error."""
... | stack_v2_sparse_classes_36k_train_018122 | 3,199 | permissive | [
{
"docstring": "Initialize the form.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Validate all form fields.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Save the form.",
"name": "save",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_val_000679 | Implement the Python class `RegistrationForm` described below.
Class description:
A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget ... | Implement the Python class `RegistrationForm` described below.
Class description:
A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget ... | 8201715b6f1d75e07b12a736f957fd6c77f57ec8 | <|skeleton|>
class RegistrationForm:
"""A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget can properly display the error."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""A registration form with reCAPTCHA support. This is a version of the Djblets RegistrationForm which knows how to validate a reCAPTCHA widget. Any error received is stored in the form for use when generating the widget so that the widget can properly display the error."""
def __init__... | the_stack_v2_python_sparse | reviewboard/accounts/forms/registration.py | hsccorp/reviewboard | train | 1 |
ebd398b203a877cefb7f6991044a4ad0d85b36d7 | [
"pivot = 1\nsmaller = 0\nlarger = len(nums) - 1\nfor i in range(len(nums)):\n if nums[i] < pivot:\n temp = nums[i]\n nums[i] = nums[smaller]\n nums[smaller] = temp\n smaller += 1\nfor i in range(len(nums) - 1, -1, -1):\n if nums[i] > pivot:\n temp = nums[i]\n nums[i] ... | <|body_start_0|>
pivot = 1
smaller = 0
larger = len(nums) - 1
for i in range(len(nums)):
if nums[i] < pivot:
temp = nums[i]
nums[i] = nums[smaller]
nums[smaller] = temp
smaller += 1
for i in range(len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_one_pass(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place ins... | stack_v2_sparse_classes_36k_train_018123 | 2,963 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColors_one_pass(self, nums): :type nums: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColors_one_pass(self, nums): :type nums: List[int] ... | 66a4325c5999535e64e8e985bac4e3a96108bf1a | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors_one_pass(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place ins... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
pivot = 1
smaller = 0
larger = len(nums) - 1
for i in range(len(nums)):
if nums[i] < pivot:
temp = nums[i]
... | the_stack_v2_python_sparse | Algorithm_And_Data_Structure/Array/Solved/sort_color.py | omidziaee/DataStructure | train | 0 | |
ea92aca8b46c3388f67c9d72671ba2e698f2ebcf | [
"self.force_admin = kwargs.pop('force_admin', None)\nsuper(NewUserForm, self).__init__(*args, **kwargs)\nself.fields['username'].widget.attrs['class'] = 'form-control'\nself.fields['password1'].widget.attrs['class'] = 'form-control'\nself.fields['password2'].widget.attrs['class'] = 'form-control'\nfor fieldname in ... | <|body_start_0|>
self.force_admin = kwargs.pop('force_admin', None)
super(NewUserForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.at... | Class for creating a new user | NewUserForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|body... | stack_v2_sparse_classes_36k_train_018124 | 30,652 | permissive | [
{
"docstring": "Override init to customise the UserCreationForm widget class appearance",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Override save to make user a superuser",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001124 | Implement the Python class `NewUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a superu... | Implement the Python class `NewUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a superu... | fdff8b8ddc202c53edda2a509a50c4e83013474d | <|skeleton|>
class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
self.force_admin = kwargs.pop('force_admin', None)
super(NewUserForm, self).__init__(*args, **kwargs)
self.fi... | the_stack_v2_python_sparse | rse/forms.py | RSE-Sheffield/RSEAdmin | train | 22 |
3fd3b852acbe5ee3037505e920100f84172b2840 | [
"super(PrenormDecoderLayer, self).__init__(name=name)\nwith tf.compat.v1.variable_scope(name):\n attention_head_size = hidden_size // num_attention_heads\n with tf.compat.v1.variable_scope('attention'):\n with tf.compat.v1.variable_scope('self'):\n self.first_layer_norm = utils.NormLayer(hid... | <|body_start_0|>
super(PrenormDecoderLayer, self).__init__(name=name)
with tf.compat.v1.variable_scope(name):
attention_head_size = hidden_size // num_attention_heads
with tf.compat.v1.variable_scope('attention'):
with tf.compat.v1.variable_scope('self'):
... | Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention. | PrenormDecoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrenormDecoderLayer:
"""Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.... | stack_v2_sparse_classes_36k_train_018125 | 26,836 | permissive | [
{
"docstring": "Constructor of a decoder layer of a transformer in Pegasus style. Args: hidden_size: (optional) int. Size of hidden dimension. intermediate_size: (optional) int. Size of intermediate dimension. intermediate_act_fn: optional) Activation function for intermediate layer. attention_probs_dropout_pro... | 2 | stack_v2_sparse_classes_30k_train_010314 | Implement the Python class `PrenormDecoderLayer` described below.
Class description:
Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention.
Method signatures and docstrings:
- def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=... | Implement the Python class `PrenormDecoderLayer` described below.
Class description:
Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention.
Method signatures and docstrings:
- def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=... | dc64e0aa3661e2f135e02794b979c2f6af4f3c9a | <|skeleton|>
class PrenormDecoderLayer:
"""Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrenormDecoderLayer:
"""Decoder layer of a transformer in Pegasus style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.1, initialize... | the_stack_v2_python_sparse | pretrain/kobigbird/decoder.py | monologg/KoBigBird | train | 208 |
38cfe0f5bda3e41a51628ae02c58ccc004238a8e | [
"self.capacity = capacity\nself.node_map = {}\nself.head = None\nself.tail = None",
"if key not in self.node_map:\n return -1\nnode = self.node_map[key]\nif node.next != None:\n if node.prev == None:\n self.head = self.head.next\n self.head.prev = None\n else:\n node.prev.next = node... | <|body_start_0|>
self.capacity = capacity
self.node_map = {}
self.head = None
self.tail = None
<|end_body_0|>
<|body_start_1|>
if key not in self.node_map:
return -1
node = self.node_map[key]
if node.next != None:
if node.prev == None:
... | LRUCache2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_018126 | 22,676 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache2` described below.
Class description:
Implement the LRUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache2` described below.
Class description:
Implement the LRUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.node_map = {}
self.head = None
self.tail = None
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.node_map:
return -1
... | the_stack_v2_python_sparse | leetcode/leetcode_special.py | Rivarrl/leetcode_python | train | 3 | |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"armors = Armor.objects.all()\nserializer = ArmorSerializer(armors, many=True)\nreturn Response(serializer.data)",
"queryset = Armor.objects.all()\narmor = get_object_or_404(queryset, pk=pk)\nserializer = ArmorSerializer(armor)\nreturn Response(serializer.data)"
] | <|body_start_0|>
armors = Armor.objects.all()
serializer = ArmorSerializer(armors, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = Armor.objects.all()
armor = get_object_or_404(queryset, pk=pk)
serializer = ArmorSerializer(armor)
... | ArmorView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArmorView:
def list(self, request):
"""Получение списка брони"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение брони по идентификатору pk - идентификатор брони"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
armors = Armor.objects.al... | stack_v2_sparse_classes_36k_train_018127 | 12,404 | no_license | [
{
"docstring": "Получение списка брони",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение брони по идентификатору pk - идентификатор брони",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010712 | Implement the Python class `ArmorView` described below.
Class description:
Implement the ArmorView class.
Method signatures and docstrings:
- def list(self, request): Получение списка брони
- def retrieve(self, request, pk=None): Получение брони по идентификатору pk - идентификатор брони | Implement the Python class `ArmorView` described below.
Class description:
Implement the ArmorView class.
Method signatures and docstrings:
- def list(self, request): Получение списка брони
- def retrieve(self, request, pk=None): Получение брони по идентификатору pk - идентификатор брони
<|skeleton|>
class ArmorView... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class ArmorView:
def list(self, request):
"""Получение списка брони"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение брони по идентификатору pk - идентификатор брони"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArmorView:
def list(self, request):
"""Получение списка брони"""
armors = Armor.objects.all()
serializer = ArmorSerializer(armors, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение брони по идентификатору pk - идентифика... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
fbe664acda29fa4f09813d4a03f0baa3fb8597d1 | [
"super().setup(*args, **kwargs)\nif hasattr(self.get_object(), 'events'):\n event_types = models.EventType.objects.filter(events__in=self.get_object().events.all()).distinct()\nelse:\n event_types = models.EventType.objects.filter(event_proposals__in=self.get_object().event_proposals.all()).distinct()\nself.m... | <|body_start_0|>
super().setup(*args, **kwargs)
if hasattr(self.get_object(), 'events'):
event_types = models.EventType.objects.filter(events__in=self.get_object().events.all()).distinct()
else:
event_types = models.EventType.objects.filter(event_proposals__in=self.get_ob... | Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice. | AvailabilityMatrixViewMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_018128 | 7,691 | permissive | [
{
"docstring": "Get the availability matrix",
"name": "setup",
"signature": "def setup(self, *args, **kwargs)"
},
{
"docstring": "Add the matrix to form kwargs, only used if the view has a form",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_004354 | Implement the Python class `AvailabilityMatrixViewMixin` described below.
Class description:
Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice.
Met... | Implement the Python class `AvailabilityMatrixViewMixin` described below.
Class description:
Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice.
Met... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvailabilityMatrixViewMixin:
"""Mixin with shared code between all availability matrix views, meaning all views that show an availability matrix (form or not) for a SpeakerProposal or Speaker object. Used by SpeakerProposal submitters and in backoffice."""
def setup(self, *args, **kwargs):
"""Get... | the_stack_v2_python_sparse | src/program/mixins.py | bornhack/bornhack-website | train | 9 |
6841554449325a7e5ed247c38e9b3ef7792cbd3c | [
"if page_url is None or html_cont is None:\n return\nsoup = BeautifulSoup(html_cont, 'html.parser')\nnew_urls = self._get_new_urls(page_url, soup)\nnew_data = self._get_new_data(page_url, soup)\nreturn (new_urls, new_data)",
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('/item/\\\\w+'))\nfor li... | <|body_start_0|>
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'html.parser')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return (new_urls, new_data)
<|end_body_0|>
<|body_start_1|>
... | HTML解析器 | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
"""HTML解析器"""
def parser(self, page_url, html_cont):
"""parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url"""
<|body_0|>
def _get_new_urls(self, page_... | stack_v2_sparse_classes_36k_train_018129 | 5,667 | no_license | [
{
"docstring": "parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url",
"name": "parser",
"signature": "def parser(self, page_url, html_cont)"
},
{
"docstring": "get some new urls which need... | 3 | stack_v2_sparse_classes_30k_train_014732 | Implement the Python class `HtmlParser` described below.
Class description:
HTML解析器
Method signatures and docstrings:
- def parser(self, page_url, html_cont): parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url... | Implement the Python class `HtmlParser` described below.
Class description:
HTML解析器
Method signatures and docstrings:
- def parser(self, page_url, html_cont): parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url... | 673993d4d197138e89c2952d2be64b95463b19e9 | <|skeleton|>
class HtmlParser:
"""HTML解析器"""
def parser(self, page_url, html_cont):
"""parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url"""
<|body_0|>
def _get_new_urls(self, page_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParser:
"""HTML解析器"""
def parser(self, page_url, html_cont):
"""parse a given html page :param page_url: the url path :param html_cont: the content of this url :return: a turple about new urls and the dictionary of this url"""
if page_url is None or html_cont is None:
retu... | the_stack_v2_python_sparse | spider/baidubaike_spider.py | XiDian-ChenMiao/python-master | train | 0 |
44015d47bc2b45a406c79f31f4742a40242d783c | [
"if root is None:\n return ''\nres = []\nq = deque()\nq.append(root)\ncounter = 1\nwhile len(q) > 0 and counter > 0:\n n = q.popleft()\n if n:\n counter -= 1\n res.append(str(n.val))\n if n.left:\n counter += 1\n if n.right:\n counter += 1\n q.append... | <|body_start_0|>
if root is None:
return ''
res = []
q = deque()
q.append(root)
counter = 1
while len(q) > 0 and counter > 0:
n = q.popleft()
if n:
counter -= 1
res.append(str(n.val))
if n... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_018130 | 1,833 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 87f30b91ff1770871d05b784efacd1656f2246ef | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return ''
res = []
q = deque()
q.append(root)
counter = 1
while len(q) > 0 and counter > 0:
n = q.popleft... | the_stack_v2_python_sparse | leetcode/ser_deser_binary_tree.py | VimanyuAgg/code-morsels | train | 1 | |
dc0e9a7ab602dee118382eeedce4d7bd1ec8f74b | [
"_filename = ConfigManager.fallback_file(filename)\nwith open(_filename) as f:\n self._config = json.loads(f.read())",
"def new_bgm():\n return Bangumi(self._config['bgm']['account'], self._config['bgm']['password'])\n\ndef new_mal():\n return MyAnimeList(self._config['mal']['account'], self._config['mal... | <|body_start_0|>
_filename = ConfigManager.fallback_file(filename)
with open(_filename) as f:
self._config = json.loads(f.read())
<|end_body_0|>
<|body_start_1|>
def new_bgm():
return Bangumi(self._config['bgm']['account'], self._config['bgm']['password'])
def n... | Docstring for ConfigManager. | ConfigManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigManager:
"""Docstring for ConfigManager."""
def __init__(self, filename):
"""TODO :param filename: TODO"""
<|body_0|>
def load_config(self, target):
"""Return the corresponding string representing the websites. :param str target: TODO :returns: an ``AnimeWe... | stack_v2_sparse_classes_36k_train_018131 | 2,533 | permissive | [
{
"docstring": "TODO :param filename: TODO",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Return the corresponding string representing the websites. :param str target: TODO :returns: an ``AnimeWebsite`` object, depending on the input :rtype: AnimeWebsite",
... | 3 | stack_v2_sparse_classes_30k_train_013024 | Implement the Python class `ConfigManager` described below.
Class description:
Docstring for ConfigManager.
Method signatures and docstrings:
- def __init__(self, filename): TODO :param filename: TODO
- def load_config(self, target): Return the corresponding string representing the websites. :param str target: TODO :... | Implement the Python class `ConfigManager` described below.
Class description:
Docstring for ConfigManager.
Method signatures and docstrings:
- def __init__(self, filename): TODO :param filename: TODO
- def load_config(self, target): Return the corresponding string representing the websites. :param str target: TODO :... | 4cc9552411ed8327fdb48ad6f9af110fe2f8657f | <|skeleton|>
class ConfigManager:
"""Docstring for ConfigManager."""
def __init__(self, filename):
"""TODO :param filename: TODO"""
<|body_0|>
def load_config(self, target):
"""Return the corresponding string representing the websites. :param str target: TODO :returns: an ``AnimeWe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigManager:
"""Docstring for ConfigManager."""
def __init__(self, filename):
"""TODO :param filename: TODO"""
_filename = ConfigManager.fallback_file(filename)
with open(_filename) as f:
self._config = json.loads(f.read())
def load_config(self, target):
... | the_stack_v2_python_sparse | src/hiromi/config.py | hiecaq/hiromi | train | 0 |
c94b6162201b3f3ad180d02919b9f005cff7b750 | [
"self.head = ListNode(0)\ndummy = self.head\nfor i in range(1, maxNumbers):\n dummy.next = ListNode(i)\n dummy = dummy.next",
"if self.head:\n val, self.head = (self.head.val, self.head.next)\nelse:\n val = -1\nreturn val",
"dummy = self.head\nwhile dummy:\n if dummy.val == number:\n retur... | <|body_start_0|>
self.head = ListNode(0)
dummy = self.head
for i in range(1, maxNumbers):
dummy.next = ListNode(i)
dummy = dummy.next
<|end_body_0|>
<|body_start_1|>
if self.head:
val, self.head = (self.head.val, self.head.next)
else:
... | PhoneDirectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_36k_train_018132 | 1,715 | no_license | [
{
"docstring": "Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.",
"name": "__init__",
"signature": "def __init__(self, maxNumbers: int)"
},
{
"docstring": "Provide a number which is not assigned to anyone. @return - Return an... | 4 | stack_v2_sparse_classes_30k_train_019868 | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | 00bf9a8164008aa17507b1c87ce72a3374bcb7b9 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
self.head = ListNode(0)
dummy = self.head
for i in range(1, maxNumbers):
dummy.next = Li... | the_stack_v2_python_sparse | solutions/379.design-phone-directory.py | quixoteji/Leetcode | train | 1 | |
7f6a8ad7f9725e6161e4dca0adcb8be22812c87a | [
"def helper(n):\n if n in dp:\n return dp[n]\n if n < 0:\n return float('+inf')\n else:\n tmp = float('+inf')\n for i in ps:\n s = helper(n - i)\n if s < tmp:\n tmp = s\n dp[n] = tmp + 1\n return tmp\nps = []\ndp = {0: 0, 1: 1, ... | <|body_start_0|>
def helper(n):
if n in dp:
return dp[n]
if n < 0:
return float('+inf')
else:
tmp = float('+inf')
for i in ps:
s = helper(n - i)
if s < tmp:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def numSquares(self, n):
""":type n: int :rtype: int 广度优先"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_018133 | 2,548 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int 广度优先",
"name": "numSq... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares(self, n): :type n: int :rtype: int 广度优先 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares(self, n): :type n: int :rtype: int 广度优先
<|skeleton|>
class... | 8853f85214ac88db024d26e228f1848dd5acd933 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def numSquares(self, n):
""":type n: int :rtype: int 广度优先"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
def helper(n):
if n in dp:
return dp[n]
if n < 0:
return float('+inf')
else:
tmp = float('+inf')
for i in ps:
... | the_stack_v2_python_sparse | 279-PerfectSquares/PerfectSquares.py | cqxmzhc/my_leetcode_solutions | train | 2 | |
24b1311596112a082624596d5ec6f9a3c5f8a5e0 | [
"super().__init__()\nself.identity = Identity()\nself.grid_sampler = GridSampler(mode=mode)\nself.ndims = settings.get_ndims()",
"dtype = src.dtype\nif not dtype.is_floating_point:\n src = src.float()\nif self.ndims == 2:\n flow[:, 2] = 0\nif self.ndims == 2:\n flow = flow.expand(-1, -1, -1, -1, 3)\n ... | <|body_start_0|>
super().__init__()
self.identity = Identity()
self.grid_sampler = GridSampler(mode=mode)
self.ndims = settings.get_ndims()
<|end_body_0|>
<|body_start_1|>
dtype = src.dtype
if not dtype.is_floating_point:
src = src.float()
if self.ndi... | N-D Spatial Transformer | SpatialTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialTransformer:
"""N-D Spatial Transformer"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
<|body_0|>
def forwar... | stack_v2_sparse_classes_36k_train_018134 | 8,565 | no_license | [
{
"docstring": "Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode",
"name": "__init__",
"signature": "def __init__(self, mode='bilinear')"
},
{
"docstring": "Transforms the src with the flo... | 2 | null | Implement the Python class `SpatialTransformer` described below.
Class description:
N-D Spatial Transformer
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode:... | Implement the Python class `SpatialTransformer` described below.
Class description:
N-D Spatial Transformer
Method signatures and docstrings:
- def __init__(self, mode='bilinear'): Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode:... | c295ab990c8394a4da8fedee01d1e5a3f63d8f04 | <|skeleton|>
class SpatialTransformer:
"""N-D Spatial Transformer"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
<|body_0|>
def forwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialTransformer:
"""N-D Spatial Transformer"""
def __init__(self, mode='bilinear'):
"""Instantiates the spatial transformer. A spatial transformer transforms a src image with a flow of displacement vectors. Parameters: mode: interpolation mode"""
super().__init__()
self.identit... | the_stack_v2_python_sparse | torchreg/nn/layers.py | SteffenCzolbe/TopologicalChangeDetection | train | 3 |
80e551300d023a8cbe06752f78016cbe4be6e17d | [
"self.func_signature = func_signature\nself.suite = suite\nsuper().__init__(*args, **kwargs)",
"func = is_invalid_type(self.func_signature.check_type(environment))\nfunc_environment = environment.add_child_environment('function', self.func_signature.name)\nfor parameter in self.func_signature.parameter_list:\n ... | <|body_start_0|>
self.func_signature = func_signature
self.suite = suite
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
func = is_invalid_type(self.func_signature.check_type(environment))
func_environment = environment.add_child_environment('function', self.fu... | FuncDefNode AST node. | FuncDefNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuncDefNode:
"""FuncDefNode AST node."""
def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs):
"""Initialise statement list."""
<|body_0|>
def check_type(self, environment: Environment) -> Type:
"""Check type for the function b... | stack_v2_sparse_classes_36k_train_018135 | 1,682 | no_license | [
{
"docstring": "Initialise statement list.",
"name": "__init__",
"signature": "def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs)"
},
{
"docstring": "Check type for the function body.",
"name": "check_type",
"signature": "def check_type(self, environ... | 3 | stack_v2_sparse_classes_30k_val_000152 | Implement the Python class `FuncDefNode` described below.
Class description:
FuncDefNode AST node.
Method signatures and docstrings:
- def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs): Initialise statement list.
- def check_type(self, environment: Environment) -> Type: Check ty... | Implement the Python class `FuncDefNode` described below.
Class description:
FuncDefNode AST node.
Method signatures and docstrings:
- def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs): Initialise statement list.
- def check_type(self, environment: Environment) -> Type: Check ty... | 001ad94aad755c11df7cf6ef8f7f0f828a5ac90e | <|skeleton|>
class FuncDefNode:
"""FuncDefNode AST node."""
def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs):
"""Initialise statement list."""
<|body_0|>
def check_type(self, environment: Environment) -> Type:
"""Check type for the function b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuncDefNode:
"""FuncDefNode AST node."""
def __init__(self, func_signature: FuncSignatureNode, suite: SuiteNode, *args, **kwargs):
"""Initialise statement list."""
self.func_signature = func_signature
self.suite = suite
super().__init__(*args, **kwargs)
def check_type... | the_stack_v2_python_sparse | typt/func_def_node.py | BPHarris/typt | train | 0 |
0bc268e0959ebd52db661aadc09388190f61175c | [
"super(BasicLinker, self).__init__()\nself.config = config\nself.encoder = encoder\nself.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nself.relu = nn.ReLU()",
"context_representation_affined = self.encoder(padded_left_contexts, left_context_lens, padded_right_contexts, righ... | <|body_start_0|>
super(BasicLinker, self).__init__()
self.config = config
self.encoder = encoder
self.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)
self.relu = nn.ReLU()
<|end_body_0|>
<|body_start_1|>
context_representation_affined... | BasicLinker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicLinker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, padded_left_contexts, left_context_lens, padded_right_contexts,... | stack_v2_sparse_classes_36k_train_018136 | 42,719 | permissive | [
{
"docstring": ":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions",
"name": "__init__",
"signature": "def __init__(self, config, encoder)"
},
{
"docstring": ":param mention: A mention object :return: unnormalized log pr... | 2 | stack_v2_sparse_classes_30k_train_008263 | Implement the Python class `BasicLinker` described below.
Class description:
Implement the BasicLinker class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- def fo... | Implement the Python class `BasicLinker` described below.
Class description:
Implement the BasicLinker class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- def fo... | 6a7dcd7d3756327c61ef949e5b4f6af6e2849187 | <|skeleton|>
class BasicLinker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, padded_left_contexts, left_context_lens, padded_right_contexts,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicLinker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
super(BasicLinker, self).__init__()
self.config = config
self.encoder = encoder
self.en... | the_stack_v2_python_sparse | typenet/src/model.py | dhruvdcoder/dl-with-constraints | train | 0 | |
db6b7eb3fcc16cf5bb81a8d4791acaf1751db37a | [
"if self.action in ['list']:\n permission_classes = [IsAuthenticated]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes')\n except AttributeError:\n permission_classes = self.permission_classes\nreturn [permission() for permission in permission_cla... | <|body_start_0|>
if self.action in ['list']:
permission_classes = [IsAuthenticated]
else:
try:
permission_classes = getattr(self, self.action).kwargs.get('permission_classes')
except AttributeError:
permission_classes = self.permission_... | API endpoints for unit memberships. | UnitMembershipViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitMembershipViewSet:
"""API endpoints for unit memberships."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def get_uni... | stack_v2_sparse_classes_36k_train_018137 | 2,178 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Helper: get the related unit, return an ... | 3 | null | Implement the Python class `UnitMembershipViewSet` described below.
Class description:
API endpoints for unit memberships.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's de... | Implement the Python class `UnitMembershipViewSet` described below.
Class description:
API endpoints for unit memberships.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's de... | 22e4afa728a851bb4c2479fbb6f5944a75984b9b | <|skeleton|>
class UnitMembershipViewSet:
"""API endpoints for unit memberships."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def get_uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitMembershipViewSet:
"""API endpoints for unit memberships."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
if self.action in ['list']:
... | the_stack_v2_python_sparse | src/backend/partaj/core/api/unit_membership.py | MTES-MCT/partaj | train | 4 |
a28524f6dbeae83f1a9e2ccab6f5337877b53d81 | [
"truck_sheet = TruckSheet.query.get_sheet_or_404(truck_sheet_id)\norder_sheet = OrderSheet.query.get_sheet_or_404(order_sheet_id)\nreturn Planning.query.get_or_404((truck_sheet.id, order_sheet.id))",
"truck_sheet = TruckSheet.query.get_sheet_or_404(truck_sheet_id)\norder_sheet = OrderSheet.query.get_sheet_or_404(... | <|body_start_0|>
truck_sheet = TruckSheet.query.get_sheet_or_404(truck_sheet_id)
order_sheet = OrderSheet.query.get_sheet_or_404(order_sheet_id)
return Planning.query.get_or_404((truck_sheet.id, order_sheet.id))
<|end_body_0|>
<|body_start_1|>
truck_sheet = TruckSheet.query.get_sheet_or... | PlanningByID | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlanningByID:
def get(self, truck_sheet_id, order_sheet_id):
"""Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use the latest sheet. Roles required: View-only, planner, administrator"""
<|body_0|>
def po... | stack_v2_sparse_classes_36k_train_018138 | 3,651 | permissive | [
{
"docstring": "Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use the latest sheet. Roles required: View-only, planner, administrator",
"name": "get",
"signature": "def get(self, truck_sheet_id, order_sheet_id)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_020609 | Implement the Python class `PlanningByID` described below.
Class description:
Implement the PlanningByID class.
Method signatures and docstrings:
- def get(self, truck_sheet_id, order_sheet_id): Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use ... | Implement the Python class `PlanningByID` described below.
Class description:
Implement the PlanningByID class.
Method signatures and docstrings:
- def get(self, truck_sheet_id, order_sheet_id): Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use ... | a74faa30139a7c32ce2b872544eb2fac588716cd | <|skeleton|>
class PlanningByID:
def get(self, truck_sheet_id, order_sheet_id):
"""Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use the latest sheet. Roles required: View-only, planner, administrator"""
<|body_0|>
def po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlanningByID:
def get(self, truck_sheet_id, order_sheet_id):
"""Get a single planning. `Truck_sheet_id` and `order_sheet_id` can both be the primary key of the sheets, or `latest` to use the latest sheet. Roles required: View-only, planner, administrator"""
truck_sheet = TruckSheet.query.get_s... | the_stack_v2_python_sparse | backend/api/plannings/resources.py | Hori1234/otmdservices | train | 0 | |
4a7fa9df191f2dc6530b9e9f158bf2eeee4d627e | [
"temp_list = []\nwhile head:\n temp_list.append(head.val)\n head = head.next\nl = len(temp_list)\nfor i in range(0, l // 2):\n if temp_list[i] != temp_list[l - 1 - i]:\n return False\nreturn True",
"fast = slow = head\nwhile fast and fast.next:\n fast = fast.next.next\n slow = slow.next\nnod... | <|body_start_0|>
temp_list = []
while head:
temp_list.append(head.val)
head = head.next
l = len(temp_list)
for i in range(0, l // 2):
if temp_list[i] != temp_list[l - 1 - i]:
return False
return True
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
temp_list = []
while head:
... | stack_v2_sparse_classes_36k_train_018139 | 1,482 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindrome(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def isPalindr... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
temp_list = []
while head:
temp_list.append(head.val)
head = head.next
l = len(temp_list)
for i in range(0, l // 2):
if temp_list[i] != temp_list[l - 1 - ... | the_stack_v2_python_sparse | code/234#Palindrome Linked List.py | EachenKuang/LeetCode | train | 28 | |
c0ec68d98fd70e00eae822e988169f7335efb78d | [
"res = []\nif not root:\n return res\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n level = []\n for i in range(len(queue)):\n node = queue.popleft()\n level.append(node.val)\n if node.left:\n queue.append(node.left)\n if node.right:\n que... | <|body_start_0|>
res = []
if not root:
return res
queue = collections.deque()
queue.append(root)
while queue:
level = []
for i in range(len(queue)):
node = queue.popleft()
level.append(node.val)
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def BFS(self, root):
"""利用队列实现树的层次遍历"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
if not root:
return res
que... | stack_v2_sparse_classes_36k_train_018140 | 2,399 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": "利用队列实现树的层次遍历",
"name": "BFS",
"signature": "def BFS(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def BFS(self, root): 利用队列实现树的层次遍历 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def BFS(self, root): 利用队列实现树的层次遍历
<|skeleton|>
class Solution:
def levelOrder(self, root):
... | 1379a6dc2400751ecf79ccd6ed401a1fb0d78046 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def BFS(self, root):
"""利用队列实现树的层次遍历"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
res = []
if not root:
return res
queue = collections.deque()
queue.append(root)
while queue:
level = []
for i in range(len(queue)):
... | the_stack_v2_python_sparse | Python3.6/102-Py3-M-Binary Tree Level Order Traversal.py | Hidenver2016/Leetcode | train | 1 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nmod = adm.get_module_by_id(module_id)\nreturn mod",
"adm = ProjectAdministration()\nmod = adm.get_module_by_id(module_id)\nif mod is not None:\n adm.delete_module(mod)\n return ('gelöscht', 200)\nelse:\n return ('There was some error', 500)"
] | <|body_start_0|>
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
return mod
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
if mod is not None:
adm.delete_module(mod)
return (... | ModuleOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, module_id):
"""Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem ... | stack_v2_sparse_classes_36k_train_018141 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, module_id)"
},
{
"docstring": "Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.",
"name... | 2 | stack_v2_sparse_classes_30k_train_006274 | Implement the Python class `ModuleOperations` described below.
Class description:
Implement the ModuleOperations class.
Method signatures and docstrings:
- def get(self, module_id): Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.
- def delete(self, module_id): Löschen ... | Implement the Python class `ModuleOperations` described below.
Class description:
Implement the ModuleOperations class.
Method signatures and docstrings:
- def get(self, module_id): Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.
- def delete(self, module_id): Löschen ... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, module_id):
"""Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
return mod
def delete(self, module_id):
"""Löschen... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertSelfOutput, self).__init__()\nself.dense = nn.Dense(config.hidden_size, config.hidden_size).to_float(mindspore.float16)\nself.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)\nself.dropout = nn.Dropout(p=config.hidden_dropout_prob)\nself.cast = op... | <|body_start_0|>
super(BertSelfOutput, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)
self.dropout = nn.Dropout(p=co... | bert self output | BertSelfOutput | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertSelfOutput:
"""bert self output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BertSelfOutput, self).__init__(... | stack_v2_sparse_classes_36k_train_018142 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states, input_tensor)"
}
] | 2 | null | Implement the Python class `BertSelfOutput` described below.
Class description:
bert self output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun | Implement the Python class `BertSelfOutput` described below.
Class description:
bert self output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun
<|skeleton|>
class BertSelfOutput:
"""bert self output"""
def __init__(s... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertSelfOutput:
"""bert self output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertSelfOutput:
"""bert self output"""
def __init__(self, config):
"""init fun"""
super(BertSelfOutput, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=c... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
58f65d75ad373949cf0198f5c14d8a296cf06d03 | [
"self._state = True\nself._last_action = time.time()\nself.async_write_ha_state()\nawait self.coordinator.api.set_relay_valve(int(self._item_id[1]), int(self._item_id[3]), int(self._item_id[-1]), 1)",
"self._state = False\nself._last_action = time.time()\nself.async_write_ha_state()\nawait self.coordinator.api.se... | <|body_start_0|>
self._state = True
self._last_action = time.time()
self.async_write_ha_state()
await self.coordinator.api.set_relay_valve(int(self._item_id[1]), int(self._item_id[3]), int(self._item_id[-1]), 1)
<|end_body_0|>
<|body_start_1|>
self._state = False
self._l... | Define the OmniLogic Relay entity. | OmniLogicRelayControl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Turn off the relay."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_018143 | 8,137 | permissive | [
{
"docstring": "Turn on the relay.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs)"
},
{
"docstring": "Turn off the relay.",
"name": "async_turn_off",
"signature": "async def async_turn_off(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005129 | Implement the Python class `OmniLogicRelayControl` described below.
Class description:
Define the OmniLogic Relay entity.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Turn on the relay.
- async def async_turn_off(self, **kwargs): Turn off the relay. | Implement the Python class `OmniLogicRelayControl` described below.
Class description:
Define the OmniLogic Relay entity.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Turn on the relay.
- async def async_turn_off(self, **kwargs): Turn off the relay.
<|skeleton|>
class OmniLogicRelayCo... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Turn off the relay."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
self._state = True
self._last_action = time.time()
self.async_write_ha_state()
await self.coordinator.api.set_relay_valve(int(self._ite... | the_stack_v2_python_sparse | homeassistant/components/omnilogic/switch.py | home-assistant/core | train | 35,501 |
2f6925103574d629206e6f7d9414513a78d10586 | [
"calculator = self.target_config_block\ncalculator_dict = {}\nfor key in calculator:\n if key == 'model_file':\n if calculator[CalculatorInit.kind] in self.schnet_models:\n model = self._load_model_schnetpack(calculator['model_file'], md_initializer.device).to(md_initializer.device)\n el... | <|body_start_0|>
calculator = self.target_config_block
calculator_dict = {}
for key in calculator:
if key == 'model_file':
if calculator[CalculatorInit.kind] in self.schnet_models:
model = self._load_model_schnetpack(calculator['model_file'], md_in... | Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class. | SetupCalculator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetupCalculator:
"""Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class."""
def _setup(self, md_initializer):
"""Main routine for loading the model, prepar... | stack_v2_sparse_classes_36k_train_018144 | 19,441 | permissive | [
{
"docstring": "Main routine for loading the model, preparing it for the calculator and setting up the main :obj:`schnetpack.md.calculator`. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class.",
"name": "_setup",
"signature": "def _setup(self, md_initializer)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_011934 | Implement the Python class `SetupCalculator` described below.
Class description:
Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class.
Method signatures and docstrings:
- def _setup(self, md... | Implement the Python class `SetupCalculator` described below.
Class description:
Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class.
Method signatures and docstrings:
- def _setup(self, md... | dc1257525ab4f0532f5fbc2af60bd99faa3796be | <|skeleton|>
class SetupCalculator:
"""Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class."""
def _setup(self, md_initializer):
"""Main routine for loading the model, prepar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetupCalculator:
"""Parse the calculator block and initialize the calculator for the molecular dynamics simulations. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class."""
def _setup(self, md_initializer):
"""Main routine for loading the model, preparing it for th... | the_stack_v2_python_sparse | schnetpack/md/parsers/md_setup.py | YDS-Med/Transformer3D | train | 1 |
a073e42b383eaf294bcc173e0d30578a1bb5333e | [
"envi.Opcode.__init__(self, va, opcode, mnem, prefixes, size, operands, iflags)\nif prefixes & PREFIX_VEX and (not opcode & INS_VEXNOPREF):\n mnem = 'v' + mnem\nself.mnem = mnem",
"pfx = self.getPrefixName()\nif pfx:\n pfx = '%s: ' % pfx\nreturn pfx + self.mnem + ' ' + ','.join([o.repr(self) for o in self.o... | <|body_start_0|>
envi.Opcode.__init__(self, va, opcode, mnem, prefixes, size, operands, iflags)
if prefixes & PREFIX_VEX and (not opcode & INS_VEXNOPREF):
mnem = 'v' + mnem
self.mnem = mnem
<|end_body_0|>
<|body_start_1|>
pfx = self.getPrefixName()
if pfx:
... | Amd64Opcode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
<... | stack_v2_sparse_classes_36k_train_018145 | 30,851 | permissive | [
{
"docstring": "Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well",
"name": "__init__",
"signature": "def __init__(self, va, opcode, mnem, prefixes, size, operands, ifl... | 3 | stack_v2_sparse_classes_30k_train_001108 | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0): Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically th... | Implement the Python class `Amd64Opcode` described below.
Class description:
Implement the Amd64Opcode class.
Method signatures and docstrings:
- def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0): Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically th... | b07e161cc28b19fdda0d047eefafed22c5b00f15 | <|skeleton|>
class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Amd64Opcode:
def __init__(self, va, opcode, mnem, prefixes, size, operands, iflags=0):
"""Overriding this from envi/__init__.py in order to set the mnem for VEX instructions Technically this should be on the i386 one as well, but we don't yet support VEX for that. So oh well"""
envi.Opcode.__i... | the_stack_v2_python_sparse | envi/archs/amd64/disasm.py | vivisect/vivisect | train | 833 | |
c67580b502f8fd2da6b176fcc5d7fcc192f33a17 | [
"axis = 1\nsigma_scaling = (self.compute_std(F, past_target, axis=axis) / math.sqrt(2)).expand_dims(axis=axis)\namplitude_scaling = sigma_scaling ** 2\nlength_scale_scaling = F.broadcast_mul(F.mean(self.compute_std(F, past_time_feat, axis=axis)), F.ones_like(amplitude_scaling))\nreturn (amplitude_scaling, length_sc... | <|body_start_0|>
axis = 1
sigma_scaling = (self.compute_std(F, past_target, axis=axis) / math.sqrt(2)).expand_dims(axis=axis)
amplitude_scaling = sigma_scaling ** 2
length_scale_scaling = F.broadcast_mul(F.mean(self.compute_std(F, past_time_feat, axis=axis)), F.ones_like(amplitude_scalin... | RBFKernelOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBFKernelOutput:
def gp_params_scaling(self, F, past_target: Tensor, past_time_feat: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
"""This function returns the scales for the GP RBF Kernel hyper-parameters by using the standard deviations of the past_target and past_time_features. Parameters... | stack_v2_sparse_classes_36k_train_018146 | 5,064 | permissive | [
{
"docstring": "This function returns the scales for the GP RBF Kernel hyper-parameters by using the standard deviations of the past_target and past_time_features. Parameters ---------- F A module that can either refer to the Symbol API or the NDArray API in MXNet. past_target Training time series values of sha... | 2 | null | Implement the Python class `RBFKernelOutput` described below.
Class description:
Implement the RBFKernelOutput class.
Method signatures and docstrings:
- def gp_params_scaling(self, F, past_target: Tensor, past_time_feat: Tensor) -> Tuple[Tensor, Tensor, Tensor]: This function returns the scales for the GP RBF Kernel... | Implement the Python class `RBFKernelOutput` described below.
Class description:
Implement the RBFKernelOutput class.
Method signatures and docstrings:
- def gp_params_scaling(self, F, past_target: Tensor, past_time_feat: Tensor) -> Tuple[Tensor, Tensor, Tensor]: This function returns the scales for the GP RBF Kernel... | df4256b0e67120db555c109a1bf6cfa2b3bd3cd8 | <|skeleton|>
class RBFKernelOutput:
def gp_params_scaling(self, F, past_target: Tensor, past_time_feat: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
"""This function returns the scales for the GP RBF Kernel hyper-parameters by using the standard deviations of the past_target and past_time_features. Parameters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RBFKernelOutput:
def gp_params_scaling(self, F, past_target: Tensor, past_time_feat: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
"""This function returns the scales for the GP RBF Kernel hyper-parameters by using the standard deviations of the past_target and past_time_features. Parameters ---------- F ... | the_stack_v2_python_sparse | src/gluonts/mx/kernels/_rbf_kernel.py | mbohlkeschneider/gluon-ts | train | 54 | |
f3c3bcb01f2dbd3316d0cc48eed846e1b6da41bc | [
"while N:\n if self.isMonotone(N):\n return N\n else:\n N -= 1",
"pre_digit = num % 10\nnum = num / 10\nwhile num:\n digit = num % 10\n if digit > pre_digit:\n return False\n num /= 10\n pre_digit = digit\nreturn True"
] | <|body_start_0|>
while N:
if self.isMonotone(N):
return N
else:
N -= 1
<|end_body_0|>
<|body_start_1|>
pre_digit = num % 10
num = num / 10
while num:
digit = num % 10
if digit > pre_digit:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def monotoneIncreasingDigits(self, N):
""":type N: int :rtype: int"""
<|body_0|>
def isMonotone(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while N:
if self.isMonotone(N):
... | stack_v2_sparse_classes_36k_train_018147 | 733 | no_license | [
{
"docstring": ":type N: int :rtype: int",
"name": "monotoneIncreasingDigits",
"signature": "def monotoneIncreasingDigits(self, N)"
},
{
"docstring": ":type num: int :rtype: bool",
"name": "isMonotone",
"signature": "def isMonotone(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def monotoneIncreasingDigits(self, N): :type N: int :rtype: int
- def isMonotone(self, num): :type num: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def monotoneIncreasingDigits(self, N): :type N: int :rtype: int
- def isMonotone(self, num): :type num: int :rtype: bool
<|skeleton|>
class Solution:
def monotoneIncreasing... | f93380721b8383817fe2b0d728deca1321c9ef45 | <|skeleton|>
class Solution:
def monotoneIncreasingDigits(self, N):
""":type N: int :rtype: int"""
<|body_0|>
def isMonotone(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def monotoneIncreasingDigits(self, N):
""":type N: int :rtype: int"""
while N:
if self.isMonotone(N):
return N
else:
N -= 1
def isMonotone(self, num):
""":type num: int :rtype: bool"""
pre_digit = num % 10
... | the_stack_v2_python_sparse | problems/0738.0_Monotone_Increasing_Digits.py | lixiang2017/leetcode | train | 5 | |
e1d1944654d5a67468097988f9bac59c5a133cdd | [
"self.params = {'parseStatus': parseStatus, 'goods_url': goods_url}\nres = self.api_send(self.data['goods'])\nreturn res",
"self.params = {'link': link}\nres = self.api_send(self.data['goods_parse'])\nreturn res"
] | <|body_start_0|>
self.params = {'parseStatus': parseStatus, 'goods_url': goods_url}
res = self.api_send(self.data['goods'])
return res
<|end_body_0|>
<|body_start_1|>
self.params = {'link': link}
res = self.api_send(self.data['goods_parse'])
return res
<|end_body_1|>
| 商品接口集 | Goods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Goods:
"""商品接口集"""
def goods(self, parseStatus, goods_url):
"""新增商品 :param parseStatus: :param url: :return:"""
<|body_0|>
def goods_parse(self, link):
"""解析链接 :param link: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.params = {... | stack_v2_sparse_classes_36k_train_018148 | 680 | no_license | [
{
"docstring": "新增商品 :param parseStatus: :param url: :return:",
"name": "goods",
"signature": "def goods(self, parseStatus, goods_url)"
},
{
"docstring": "解析链接 :param link: :return:",
"name": "goods_parse",
"signature": "def goods_parse(self, link)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009913 | Implement the Python class `Goods` described below.
Class description:
商品接口集
Method signatures and docstrings:
- def goods(self, parseStatus, goods_url): 新增商品 :param parseStatus: :param url: :return:
- def goods_parse(self, link): 解析链接 :param link: :return: | Implement the Python class `Goods` described below.
Class description:
商品接口集
Method signatures and docstrings:
- def goods(self, parseStatus, goods_url): 新增商品 :param parseStatus: :param url: :return:
- def goods_parse(self, link): 解析链接 :param link: :return:
<|skeleton|>
class Goods:
"""商品接口集"""
def goods(se... | 89a18576934822e6294a465e87bdbc9afa29f177 | <|skeleton|>
class Goods:
"""商品接口集"""
def goods(self, parseStatus, goods_url):
"""新增商品 :param parseStatus: :param url: :return:"""
<|body_0|>
def goods_parse(self, link):
"""解析链接 :param link: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Goods:
"""商品接口集"""
def goods(self, parseStatus, goods_url):
"""新增商品 :param parseStatus: :param url: :return:"""
self.params = {'parseStatus': parseStatus, 'goods_url': goods_url}
res = self.api_send(self.data['goods'])
return res
def goods_parse(self, link):
"... | the_stack_v2_python_sparse | api/app_api/goods.py | bigllxx/testframework-api | train | 1 |
c87919dc93fafaa2d8e584a99a9487bedd084d4f | [
"if velocity is None:\n velocity = np.zeros(shape=(dim,))\nif massfractions is None:\n if nspecies > 0:\n massfractions = np.zeros(shape=(nspecies,))\nself._nspecies = nspecies\nself._dim = dim\nself._velocity = velocity\nself._pressure = pressure\nself._temperature = temperature\nself._massfracs = mas... | <|body_start_0|>
if velocity is None:
velocity = np.zeros(shape=(dim,))
if massfractions is None:
if nspecies > 0:
massfractions = np.zeros(shape=(nspecies,))
self._nspecies = nspecies
self._dim = dim
self._velocity = velocity
self.... | Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:: __call__ | MixtureInitializer | [
"X11",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixtureInitializer:
"""Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:: __call__"""
def __init__(self, *... | stack_v2_sparse_classes_36k_train_018149 | 32,800 | permissive | [
{
"docstring": "Initialize mixture parameters. Parameters ---------- dim: int specifies the number of dimensions for the solution nspeces: int specifies the number of mixture species pressure: float specifies the value of :math:`p_0` temperature: float specifies the value of :math:`T_0` massfractions: numpy.nda... | 2 | stack_v2_sparse_classes_30k_train_018091 | Implement the Python class `MixtureInitializer` described below.
Class description:
Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:... | Implement the Python class `MixtureInitializer` described below.
Class description:
Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:... | 47f144782258eae2b1fb39520e96f414ae176ff4 | <|skeleton|>
class MixtureInitializer:
"""Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:: __call__"""
def __init__(self, *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixtureInitializer:
"""Solution initializer for multi-species mixture. This initializer creates a physics-consistent mixture solution given an initial thermal state (pressure, temperature) and a mixture-compatible EOS. .. automethod:: __init__ .. automethod:: __call__"""
def __init__(self, *, dim=3, nspe... | the_stack_v2_python_sparse | mirgecom/initializers.py | kaushikcfd/mirgecom | train | 0 |
4f807ecf4b13c17c3cd9fa1c44495ad70f500af2 | [
"record = (yield self.directoryService().recordWithUID(groupUID))\nif record is None:\n returnValue(None)\ngroup = (yield GroupsRecord.create(self, name=name.encode('utf-8'), groupUID=groupUID.encode('utf-8'), membershipHash=membershipHash))\nyield self.refreshGroup(group, record)\nreturnValue(group)",
"timest... | <|body_start_0|>
record = (yield self.directoryService().recordWithUID(groupUID))
if record is None:
returnValue(None)
group = (yield GroupsRecord.create(self, name=name.encode('utf-8'), groupUID=groupUID.encode('utf-8'), membershipHash=membershipHash))
yield self.refreshGrou... | A mixin for L{CommonStoreTransaction} that covers the groups API. | GroupsAPIMixin | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupsAPIMixin:
"""A mixin for L{CommonStoreTransaction} that covers the groups API."""
def addGroup(self, groupUID, name, membershipHash):
"""@type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}"""
<|body_0|>
def updateGroup(self, groupUID, nam... | stack_v2_sparse_classes_36k_train_018150 | 30,685 | permissive | [
{
"docstring": "@type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}",
"name": "addGroup",
"signature": "def addGroup(self, groupUID, name, membershipHash)"
},
{
"docstring": "@type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str} @type extant: C... | 4 | stack_v2_sparse_classes_30k_train_004017 | Implement the Python class `GroupsAPIMixin` described below.
Class description:
A mixin for L{CommonStoreTransaction} that covers the groups API.
Method signatures and docstrings:
- def addGroup(self, groupUID, name, membershipHash): @type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}
- def... | Implement the Python class `GroupsAPIMixin` described below.
Class description:
A mixin for L{CommonStoreTransaction} that covers the groups API.
Method signatures and docstrings:
- def addGroup(self, groupUID, name, membershipHash): @type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}
- def... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class GroupsAPIMixin:
"""A mixin for L{CommonStoreTransaction} that covers the groups API."""
def addGroup(self, groupUID, name, membershipHash):
"""@type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}"""
<|body_0|>
def updateGroup(self, groupUID, nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupsAPIMixin:
"""A mixin for L{CommonStoreTransaction} that covers the groups API."""
def addGroup(self, groupUID, name, membershipHash):
"""@type groupUID: C{unicode} @type name: C{unicode} @type membershipHash: C{str}"""
record = (yield self.directoryService().recordWithUID(groupUID))... | the_stack_v2_python_sparse | txdav/common/datastore/sql_directory.py | ass-a2s/ccs-calendarserver | train | 2 |
eddfe6e4315f2998f332f0456513a5d5a484ce0f | [
"obj = {'selector': {'type': {'$eq': 'tab'}}}\nresponse = couch_db.post('/jsmm/_find/', obj)\ntab = json.loads(response.body.decode('utf-8'))\nself.write(tab)",
"print(self.request.files)\ntab = json.loads(self.request.body.decode('utf-8'))\ntab['type'] = 'tab'\ntab['_id'] = make_uuid()\ntab['tab_id'] = 'custab_'... | <|body_start_0|>
obj = {'selector': {'type': {'$eq': 'tab'}}}
response = couch_db.post('/jsmm/_find/', obj)
tab = json.loads(response.body.decode('utf-8'))
self.write(tab)
<|end_body_0|>
<|body_start_1|>
print(self.request.files)
tab = json.loads(self.request.body.decode... | TabCollectionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabCollectionHandler:
def get(self):
"""通过find获取对象列表。"""
<|body_0|>
def post(self):
"""创建tab对象。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = {'selector': {'type': {'$eq': 'tab'}}}
response = couch_db.post('/jsmm/_find/', obj)
... | stack_v2_sparse_classes_36k_train_018151 | 3,381 | no_license | [
{
"docstring": "通过find获取对象列表。",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "创建tab对象。",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013430 | Implement the Python class `TabCollectionHandler` described below.
Class description:
Implement the TabCollectionHandler class.
Method signatures and docstrings:
- def get(self): 通过find获取对象列表。
- def post(self): 创建tab对象。 | Implement the Python class `TabCollectionHandler` described below.
Class description:
Implement the TabCollectionHandler class.
Method signatures and docstrings:
- def get(self): 通过find获取对象列表。
- def post(self): 创建tab对象。
<|skeleton|>
class TabCollectionHandler:
def get(self):
"""通过find获取对象列表。"""
... | 731a75b4060578013579247d16c281d00667f8e3 | <|skeleton|>
class TabCollectionHandler:
def get(self):
"""通过find获取对象列表。"""
<|body_0|>
def post(self):
"""创建tab对象。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TabCollectionHandler:
def get(self):
"""通过find获取对象列表。"""
obj = {'selector': {'type': {'$eq': 'tab'}}}
response = couch_db.post('/jsmm/_find/', obj)
tab = json.loads(response.body.decode('utf-8'))
self.write(tab)
def post(self):
"""创建tab对象。"""
print(... | the_stack_v2_python_sparse | app/handlers/tab.py | hsia/jsmm | train | 0 | |
3e2139d3ab760d53aac9b4c0f0467b4583256f50 | [
"data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\ndata_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(data_train)\nself.data_train = data_train.map(self.tf_encode)\nself.d... | <|body_start_0|>
data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
self.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(data_train)
self.data_train... | the dataset class for using with transformers | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""the dataset class for using with transformers"""
def __init__(self, batch_size, max_len):
"""class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers"""
<|body_0|>
def tokenize_dataset(self, data):
"""creates sub... | stack_v2_sparse_classes_36k_train_018152 | 4,260 | no_license | [
{
"docstring": "class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers",
"name": "__init__",
"signature": "def __init__(self, batch_size, max_len)"
},
{
"docstring": "creates sub-word tokenizers for the dataset data: tf.data.Dataset as tuple (pt, en) pt: ... | 4 | stack_v2_sparse_classes_30k_train_019130 | Implement the Python class `Dataset` described below.
Class description:
the dataset class for using with transformers
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers
- def tokenize_dataset(sel... | Implement the Python class `Dataset` described below.
Class description:
the dataset class for using with transformers
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers
- def tokenize_dataset(sel... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class Dataset:
"""the dataset class for using with transformers"""
def __init__(self, batch_size, max_len):
"""class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers"""
<|body_0|>
def tokenize_dataset(self, data):
"""creates sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""the dataset class for using with transformers"""
def __init__(self, batch_size, max_len):
"""class initializer uses ted_hrlr_translate/pt_to_en saves both english and portuguese tokenizers"""
data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=Tr... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/3-dataset.py | mag389/holbertonschool-machine_learning | train | 2 |
8e47dfa41f420d53caedb715885dc89deddbd7e1 | [
"self.sequence = rna_to_dna(sequence.upper())\nself.allthreemers = unique_mers(self.sequence, 3)\nself.exposedsequence = extract_exposed_seqeunces(self.sequence, listofdist, cutofffreq)\nself.exposedthreemers = unique_mers(self.exposedsequence, 3)",
"temp = unique_mers(self.sequence, size)\nif fworrev == 'rev':\n... | <|body_start_0|>
self.sequence = rna_to_dna(sequence.upper())
self.allthreemers = unique_mers(self.sequence, 3)
self.exposedsequence = extract_exposed_seqeunces(self.sequence, listofdist, cutofffreq)
self.exposedthreemers = unique_mers(self.exposedsequence, 3)
<|end_body_0|>
<|body_star... | PartData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartData:
def __init__(self, sequence, listofdist, cutofffreq=0):
"""2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is the frequency cutoff for exposed parts"""
<|body_0|>
def mers(self, fworrev, size):
... | stack_v2_sparse_classes_36k_train_018153 | 12,226 | permissive | [
{
"docstring": "2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is the frequency cutoff for exposed parts",
"name": "__init__",
"signature": "def __init__(self, sequence, listofdist, cutofffreq=0)"
},
{
"docstring": "collects ... | 3 | stack_v2_sparse_classes_30k_test_001195 | Implement the Python class `PartData` described below.
Class description:
Implement the PartData class.
Method signatures and docstrings:
- def __init__(self, sequence, listofdist, cutofffreq=0): 2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is t... | Implement the Python class `PartData` described below.
Class description:
Implement the PartData class.
Method signatures and docstrings:
- def __init__(self, sequence, listofdist, cutofffreq=0): 2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is t... | 1af358bdc06f88227057c92765b748692dd9da11 | <|skeleton|>
class PartData:
def __init__(self, sequence, listofdist, cutofffreq=0):
"""2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is the frequency cutoff for exposed parts"""
<|body_0|>
def mers(self, fworrev, size):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartData:
def __init__(self, sequence, listofdist, cutofffreq=0):
"""2013-12-10 11:56 WEV sequence is the string of bases listofdist is a [float, string] which contains all .()... cutoff is the frequency cutoff for exposed parts"""
self.sequence = rna_to_dna(sequence.upper())
self.allt... | the_stack_v2_python_sparse | pyrfold/design/insulating.py | carothersresearch/pyrfold | train | 1 | |
125bc8cec223ac30d5a5505cb0a1fa8c0c455a0c | [
"self.N = len(nums) + 1\nself.tree = [0] * self.N\nself.nums = nums\nself.init = True\nfor idx, val in enumerate(nums):\n self.update(idx, val * 2)\nself.init = False",
"diff = val - self.nums[i]\nif not self.init:\n self.nums[i] = val\ni += 1\nwhile i < self.N:\n self.tree[i] += diff\n i += i & -i",
... | <|body_start_0|>
self.N = len(nums) + 1
self.tree = [0] * self.N
self.nums = nums
self.init = True
for idx, val in enumerate(nums):
self.update(idx, val * 2)
self.init = False
<|end_body_0|>
<|body_start_1|>
diff = val - self.nums[i]
if not se... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int ... | stack_v2_sparse_classes_36k_train_018154 | 3,945 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int :rtype: void",... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): Input intends to replace the value, not adding the value. However, this function adds the value, not r... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): Input intends to replace the value, not adding the value. However, this function adds the value, not r... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.N = len(nums) + 1
self.tree = [0] * self.N
self.nums = nums
self.init = True
for idx, val in enumerate(nums):
self.update(idx, val * 2)
self.init = False
def update(sel... | the_stack_v2_python_sparse | binary_index_tree/307_Range_Sum_Query.py | vsdrun/lc_public | train | 6 | |
cf911bc53770a904ab10bce7a394875349319bd6 | [
"if not headA or not headB:\n return None\np1 = headA\np2 = headB\nl1 = self.getLen(p1)\nl2 = self.getLen(p2)\nif l1 > l2:\n for i in range(l1 - l2):\n p1 = p1.next\nelse:\n for i in range(l2 - l1):\n p2 = p2.next\nwhile p1 and p2 and (p1.val != p2.val):\n p1 = p1.next\n p2 = p2.next\nr... | <|body_start_0|>
if not headA or not headB:
return None
p1 = headA
p2 = headB
l1 = self.getLen(p1)
l2 = self.getLen(p2)
if l1 > l2:
for i in range(l1 - l2):
p1 = p1.next
else:
for i in range(l2 - l1):
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
<|body_0|>
def getLen(self, head):
"""给定头节点返回链表长度"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not headA or not headB:
retu... | stack_v2_sparse_classes_36k_train_018155 | 2,021 | no_license | [
{
"docstring": ":type headA, headB: ListNode :rtype: ListNode",
"name": "findFirstCommonNode",
"signature": "def findFirstCommonNode(self, headA, headB)"
},
{
"docstring": "给定头节点返回链表长度",
"name": "getLen",
"signature": "def getLen(self, head)"
}
] | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findFirstCommonNode(self, headA, headB): :type headA, headB: ListNode :rtype: ListNode
- def getLen(self, head): 给定头节点返回链表长度 | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def findFirstCommonNode(self, headA, headB): :type headA, headB: ListNode :rtype: ListNode
- def getLen(self, head): 给定头节点返回链表长度
<|skeleton|>
class Solution2:
def findFir... | 1db60502acb208f22d2149a4824e1219d8938225 | <|skeleton|>
class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
<|body_0|>
def getLen(self, head):
"""给定头节点返回链表长度"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
def findFirstCommonNode(self, headA, headB):
""":type headA, headB: ListNode :rtype: ListNode"""
if not headA or not headB:
return None
p1 = headA
p2 = headB
l1 = self.getLen(p1)
l2 = self.getLen(p2)
if l1 > l2:
for i i... | the_stack_v2_python_sparse | code_with_name/test51_prob52_两个链表的第一个公共节点.py | Binjer/jianzhi_offer | train | 2 | |
c76d9801a0f6448dc4e911ae00dd718f4b938522 | [
"if User.objects.filter(username=request.data['username']).exists():\n return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exists'}, status=status.HTTP_409_CONFLICT)\nif User.objects.filter(email=request.data['email']).exists():\n return Response({'error': 'EMAIL', 'message':... | <|body_start_0|>
if User.objects.filter(username=request.data['username']).exists():
return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exists'}, status=status.HTTP_409_CONFLICT)
if User.objects.filter(email=request.data['email']).exists():
retu... | RegistrationAPIView | RegistrationAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
<|body_0|>
def perform_create(self, serializer):
"""rewrite method perform_create"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_018156 | 1,971 | no_license | [
{
"docstring": "rewrite method create",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "rewrite method perform_create",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
}
] | 2 | null | Implement the Python class `RegistrationAPIView` described below.
Class description:
RegistrationAPIView
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): rewrite method create
- def perform_create(self, serializer): rewrite method perform_create | Implement the Python class `RegistrationAPIView` described below.
Class description:
RegistrationAPIView
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): rewrite method create
- def perform_create(self, serializer): rewrite method perform_create
<|skeleton|>
class RegistrationAPIView:
... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
<|body_0|>
def perform_create(self, serializer):
"""rewrite method perform_create"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationAPIView:
"""RegistrationAPIView"""
def create(self, request, *args, **kwargs):
"""rewrite method create"""
if User.objects.filter(username=request.data['username']).exists():
return Response({'error': 'LOGIN', 'message': 'User was NOT created, because LOGIN is exis... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/authorization/api/views/registration_api_view.py | HeCToR74/Python | train | 1 |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"self.a, self.b, self.c = 3 * [-1.0]\nself._func = lambda t, a, b, c: a * np.exp(b * t) + c\nself._fit_func = lambda t: self.a * np.exp(self.b * t) + self.c\nself._fitted = False",
"b_0 = y[-1] / y[-2]\na_0 = 0.1\nc_0 = 0\nguess = np.asarray([a_0, b_0, c_0], dtype=float)\ntry:\n popt = scipy.optimize.curve_fit... | <|body_start_0|>
self.a, self.b, self.c = 3 * [-1.0]
self._func = lambda t, a, b, c: a * np.exp(b * t) + c
self._fit_func = lambda t: self.a * np.exp(self.b * t) + self.c
self._fitted = False
<|end_body_0|>
<|body_start_1|>
b_0 = y[-1] / y[-2]
a_0 = 0.1
c_0 = 0
... | Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data. | TSExp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
<|body_0|>
def fit... | stack_v2_sparse_classes_36k_train_018157 | 12,299 | permissive | [
{
"docstring": "Init an exponential forecasting model.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fit the exponential forecasting model.",
"name": "fit",
"signature": "def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSExp'"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_009256 | Implement the Python class `TSExp` described below.
Class description:
Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data.
Method signatures and docstrings:
- def __init__(self): Init an exponent... | Implement the Python class `TSExp` described below.
Class description:
Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data.
Method signatures and docstrings:
- def __init__(self): Init an exponent... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
<|body_0|>
def fit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TSExp:
"""Exponential forecasting model. The exponential model is in the form by y(t) = a * exp(b * t) + c, where `a`, `b`, and `c` are parameters to be optimized from the fitted data."""
def __init__(self):
"""Init an exponential forecasting model."""
self.a, self.b, self.c = 3 * [-1.0]
... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
fe661f2f2d448500173afc330a038523a5d45ae8 | [
"if self.request.user.is_authenticated:\n if self.request.user.is_superuser:\n self.data_layer = 'admin_layer'\n else:\n self.data_layer = expressive_layer_name(self.request.user)",
"self.__set_layer_name()\ntry:\n unblocked_ids = self.request.session['datasets']\nexcept KeyError:\n unbl... | <|body_start_0|>
if self.request.user.is_authenticated:
if self.request.user.is_superuser:
self.data_layer = 'admin_layer'
else:
self.data_layer = expressive_layer_name(self.request.user)
<|end_body_0|>
<|body_start_1|>
self.__set_layer_name()
... | Template View to bring the necessary variables for the startup to the template | HomeView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
<|body_0|>
def get_context_data(self, **kwargs: object):
"""C... | stack_v2_sparse_classes_36k_train_018158 | 27,241 | permissive | [
{
"docstring": "Set name for layer in geoserver according to username or as admin_layer.",
"name": "__set_layer_name",
"signature": "def __set_layer_name(self)"
},
{
"docstring": "Collect data needed for startup of V-FOR-WaTer Portal home. :param kwargs: :return:",
"name": "get_context_data"... | 2 | stack_v2_sparse_classes_30k_train_002406 | Implement the Python class `HomeView` described below.
Class description:
Template View to bring the necessary variables for the startup to the template
Method signatures and docstrings:
- def __set_layer_name(self): Set name for layer in geoserver according to username or as admin_layer.
- def get_context_data(self,... | Implement the Python class `HomeView` described below.
Class description:
Template View to bring the necessary variables for the startup to the template
Method signatures and docstrings:
- def __set_layer_name(self): Set name for layer in geoserver according to username or as admin_layer.
- def get_context_data(self,... | e245101b5278ee1ee8c55f7dbde2445363c9aa26 | <|skeleton|>
class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
<|body_0|>
def get_context_data(self, **kwargs: object):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomeView:
"""Template View to bring the necessary variables for the startup to the template"""
def __set_layer_name(self):
"""Set name for layer in geoserver according to username or as admin_layer."""
if self.request.user.is_authenticated:
if self.request.user.is_superuser:
... | the_stack_v2_python_sparse | vfwheron/views.py | standardgalactic/vforwater-portal | train | 0 |
e19e224a20070ad32dd5d5b2a249421a3e3cdf25 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsWorkFromAnywhereDevicesSummary()",
"from .user_experience_analytics_autopilot_devices_summary import UserExperienceAnalyticsAutopilotDevicesSummary\nfrom .user_experience_analytics_cloud_identity_devices_summary ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsWorkFromAnywhereDevicesSummary()
<|end_body_0|>
<|body_start_1|>
from .user_experience_analytics_autopilot_devices_summary import UserExperienceAnalyticsAutopilotDevicesSu... | The user experience analytics Work From Anywhere metrics devices summary. | UserExperienceAnalyticsWorkFromAnywhereDevicesSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new ... | stack_v2_sparse_classes_36k_train_018159 | 9,487 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsWorkFromAnywhereDevicesSummary",
"name": "create_from_discriminator_value",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_004893 | Implement the Python class `UserExperienceAnalyticsWorkFromAnywhereDevicesSummary` described below.
Class description:
The user experience analytics Work From Anywhere metrics devices summary.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperien... | Implement the Python class `UserExperienceAnalyticsWorkFromAnywhereDevicesSummary` described below.
Class description:
The user experience analytics Work From Anywhere metrics devices summary.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperien... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""The user experience analytics Work From Anywhere metrics devices summary."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsWorkFromAnywhereDevicesSummary:
"""Creates a new instance of t... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_work_from_anywhere_devices_summary.py | microsoftgraph/msgraph-sdk-python | train | 135 |
5aada8bfc5777eb71ebde95e432353e3ea07ca3e | [
"if N < 2:\n return N\nreturn self.fib(N - 1) + self.fib(N - 2)",
"m = [0] * (N + 1)\nn = N\n\ndef fibr(n, m):\n if n < 2:\n return n\n if m[n] == 0:\n m[n] = fibr(n - 1, m) + fibr(n - 2, m)\n return m[n]\nreturn fibr(n, m)",
"n = N\nif n <= 1:\n return n\na = [0] * (n + 1)\na[0], a... | <|body_start_0|>
if N < 2:
return N
return self.fib(N - 1) + self.fib(N - 2)
<|end_body_0|>
<|body_start_1|>
m = [0] * (N + 1)
n = N
def fibr(n, m):
if n < 2:
return n
if m[n] == 0:
m[n] = fibr(n - 1, m) + fibr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib(self, N):
""":type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N"""
<|body_0|>
def fib(self, N):
"""递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1"""
<|body_1|>
def fib(self, N):
"""动态规划:dp方式优化,时间复杂度n,空间复杂度 n+1"""
<|body_2|>
def fib(... | stack_v2_sparse_classes_36k_train_018160 | 1,262 | no_license | [
{
"docstring": ":type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N",
"name": "fib",
"signature": "def fib(self, N)"
},
{
"docstring": "递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1",
"name": "fib",
"signature": "def fib(self, N)"
},
{
"docstring": "动态规划:dp方式优化,时间复杂度n,空间复杂度 n+1",
"name": "fib... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N): :type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N
- def fib(self, N): 递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1
- def fib(self, N): 动态规划:dp方式优化,时间复杂度n,空间复杂度 n+1
- def fib(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N): :type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N
- def fib(self, N): 递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1
- def fib(self, N): 动态规划:dp方式优化,时间复杂度n,空间复杂度 n+1
- def fib(... | c162817f717b78997197649c084c27af48c3fd6f | <|skeleton|>
class Solution:
def fib(self, N):
""":type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N"""
<|body_0|>
def fib(self, N):
"""递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1"""
<|body_1|>
def fib(self, N):
"""动态规划:dp方式优化,时间复杂度n,空间复杂度 n+1"""
<|body_2|>
def fib(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fib(self, N):
""":type N: int :rtype: int 傻递归方式,无任何优化,复杂度指数级,2**N"""
if N < 2:
return N
return self.fib(N - 1) + self.fib(N - 2)
def fib(self, N):
"""递归:采用缓存结果的方式优化,时间复杂度n,空间复杂度 n+1"""
m = [0] * (N + 1)
n = N
def fibr(n, m... | the_stack_v2_python_sparse | Week_06/509.斐波那契数.py | dream201188/algorithm017 | train | 1 | |
74bce0dbec2c1a92c40a962f3a099097be735c96 | [
"super().__init__()\nself.encoder = TransformerEncoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)\nself.decoder = TransformerDecoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)",
"if src.size(1) != tgt.size(1):\n raise RuntimeError('the batch number ... | <|body_start_0|>
super().__init__()
self.encoder = TransformerEncoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)
self.decoder = TransformerDecoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)
<|end_body_0|>
<|body_start_1|>
if ... | A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural In... | Transformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is... | stack_v2_sparse_classes_36k_train_018161 | 20,460 | permissive | [
{
"docstring": "Initialize the Transformer Model. Parameters ---------- input_size : int, optional dimension of embeddings. If different from d_model, then a linear layer is added to project from input_size to d_model. d_model : int, optional the number of expected features in the encoder/decoder inputs (defaul... | 2 | stack_v2_sparse_classes_30k_train_019712 | Implement the Python class `Transformer` described below.
Class description:
A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, a... | Implement the Python class `Transformer` described below.
Class description:
A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, a... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need... | the_stack_v2_python_sparse | flambe/nn/transformer.py | cle-ros/flambe | train | 1 |
097673aa070bfc33a82922705b908788a97d3d69 | [
"with get_oss_fuzz_repo() as oss_fuzz_repo:\n repo_man = repo_manager.RepoManager(oss_fuzz_repo)\n with mock.patch.object(utils, 'execute', return_value=('test.py\\ndiff.py', None, 0)):\n diff = repo_man.get_git_diff()\n self.assertCountEqual(diff, ['test.py', 'diff.py'])",
"with get_oss_fuzz_... | <|body_start_0|>
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
with mock.patch.object(utils, 'execute', return_value=('test.py\ndiff.py', None, 0)):
diff = repo_man.get_git_diff()
self.assertCountEqual(diff, ... | Tests get_git_diff. | GitDiffTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitDiffTest:
"""Tests get_git_diff."""
def test_diff_exists(self):
"""Tests that a real diff is returned when a valid repo manager exists."""
<|body_0|>
def test_diff_empty(self):
"""Tests that None is returned when there is no difference between repos."""
... | stack_v2_sparse_classes_36k_train_018162 | 8,172 | permissive | [
{
"docstring": "Tests that a real diff is returned when a valid repo manager exists.",
"name": "test_diff_exists",
"signature": "def test_diff_exists(self)"
},
{
"docstring": "Tests that None is returned when there is no difference between repos.",
"name": "test_diff_empty",
"signature":... | 4 | null | Implement the Python class `GitDiffTest` described below.
Class description:
Tests get_git_diff.
Method signatures and docstrings:
- def test_diff_exists(self): Tests that a real diff is returned when a valid repo manager exists.
- def test_diff_empty(self): Tests that None is returned when there is no difference bet... | Implement the Python class `GitDiffTest` described below.
Class description:
Tests get_git_diff.
Method signatures and docstrings:
- def test_diff_exists(self): Tests that a real diff is returned when a valid repo manager exists.
- def test_diff_empty(self): Tests that None is returned when there is no difference bet... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class GitDiffTest:
"""Tests get_git_diff."""
def test_diff_exists(self):
"""Tests that a real diff is returned when a valid repo manager exists."""
<|body_0|>
def test_diff_empty(self):
"""Tests that None is returned when there is no difference between repos."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitDiffTest:
"""Tests get_git_diff."""
def test_diff_exists(self):
"""Tests that a real diff is returned when a valid repo manager exists."""
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
with mock.patch.object(utils,... | the_stack_v2_python_sparse | infra/repo_manager_test.py | google/oss-fuzz | train | 9,438 |
f25df40379a3622a9ae1c44a693fc5d7c7c9b799 | [
"reader = csv.reader(data)\nnext(reader)\nenum = []\nfor item in reader:\n meth = item[0]\n if meth == '*':\n continue\n safe = item[1]\n idem = item[2]\n rfcs = item[3]\n temp = []\n for rfc in filter(None, re.split('\\\\[|\\\\]', rfcs)):\n if 'RFC' in rfc and re.match('\\\\d+', ... | <|body_start_0|>
reader = csv.reader(data)
next(reader)
enum = []
for item in reader:
meth = item[0]
if meth == '*':
continue
safe = item[1]
idem = item[2]
rfcs = item[3]
temp = []
for rfc... | HTTP Method | Method | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Method:
"""HTTP Method"""
def process(self, data: 'list[str]') -> 'list[str]':
"""Process CSV data. Args: data: CSV data. Returns: Enumeration fields."""
<|body_0|>
def context(self, data: 'list[str]') -> 'str':
"""Generate constant context. Args: data: CSV data.... | stack_v2_sparse_classes_36k_train_018163 | 4,612 | permissive | [
{
"docstring": "Process CSV data. Args: data: CSV data. Returns: Enumeration fields.",
"name": "process",
"signature": "def process(self, data: 'list[str]') -> 'list[str]'"
},
{
"docstring": "Generate constant context. Args: data: CSV data. Returns: Constant context.",
"name": "context",
... | 2 | null | Implement the Python class `Method` described below.
Class description:
HTTP Method
Method signatures and docstrings:
- def process(self, data: 'list[str]') -> 'list[str]': Process CSV data. Args: data: CSV data. Returns: Enumeration fields.
- def context(self, data: 'list[str]') -> 'str': Generate constant context. ... | Implement the Python class `Method` described below.
Class description:
HTTP Method
Method signatures and docstrings:
- def process(self, data: 'list[str]') -> 'list[str]': Process CSV data. Args: data: CSV data. Returns: Enumeration fields.
- def context(self, data: 'list[str]') -> 'str': Generate constant context. ... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Method:
"""HTTP Method"""
def process(self, data: 'list[str]') -> 'list[str]':
"""Process CSV data. Args: data: CSV data. Returns: Enumeration fields."""
<|body_0|>
def context(self, data: 'list[str]') -> 'str':
"""Generate constant context. Args: data: CSV data.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Method:
"""HTTP Method"""
def process(self, data: 'list[str]') -> 'list[str]':
"""Process CSV data. Args: data: CSV data. Returns: Enumeration fields."""
reader = csv.reader(data)
next(reader)
enum = []
for item in reader:
meth = item[0]
if ... | the_stack_v2_python_sparse | pcapkit/vendor/http/method.py | JarryShaw/PyPCAPKit | train | 204 |
c32e53468161fbe3f4bbb7580d9b790278b22aeb | [
"super().__init__(name)\nself.reg_seqr = None\nself.adapter = None\nself.model = None\nself.parent_select = LOCAL\nself.upstream_parent = None",
"if self.m_sequencer is None:\n uvm_fatal('NO_SEQR', 'Sequence executing as translation sequence, ' + 'but is not associated with a sequencer (m_sequencer == null)')\... | <|body_start_0|>
super().__init__(name)
self.reg_seqr = None
self.adapter = None
self.model = None
self.parent_select = LOCAL
self.upstream_parent = None
<|end_body_0|>
<|body_start_1|>
if self.m_sequencer is None:
uvm_fatal('NO_SEQR', 'Sequence execu... | UVMRegSequence | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UVMRegSequence:
def __init__(self, name='uvm_reg_sequence_inst'):
"""Function: new Create a new instance, giving it the optional `name`. Args: name:"""
<|body_0|>
async def body(self):
"""Task: body Continually gets a register transaction from the configured upstream... | stack_v2_sparse_classes_36k_train_018164 | 21,775 | permissive | [
{
"docstring": "Function: new Create a new instance, giving it the optional `name`. Args: name:",
"name": "__init__",
"signature": "def __init__(self, name='uvm_reg_sequence_inst')"
},
{
"docstring": "Task: body Continually gets a register transaction from the configured upstream sequencer, `reg... | 3 | stack_v2_sparse_classes_30k_val_000296 | Implement the Python class `UVMRegSequence` described below.
Class description:
Implement the UVMRegSequence class.
Method signatures and docstrings:
- def __init__(self, name='uvm_reg_sequence_inst'): Function: new Create a new instance, giving it the optional `name`. Args: name:
- async def body(self): Task: body C... | Implement the Python class `UVMRegSequence` described below.
Class description:
Implement the UVMRegSequence class.
Method signatures and docstrings:
- def __init__(self, name='uvm_reg_sequence_inst'): Function: new Create a new instance, giving it the optional `name`. Args: name:
- async def body(self): Task: body C... | fc5f955701b2b56c1fddac195c70cb3ebb9139fe | <|skeleton|>
class UVMRegSequence:
def __init__(self, name='uvm_reg_sequence_inst'):
"""Function: new Create a new instance, giving it the optional `name`. Args: name:"""
<|body_0|>
async def body(self):
"""Task: body Continually gets a register transaction from the configured upstream... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UVMRegSequence:
def __init__(self, name='uvm_reg_sequence_inst'):
"""Function: new Create a new instance, giving it the optional `name`. Args: name:"""
super().__init__(name)
self.reg_seqr = None
self.adapter = None
self.model = None
self.parent_select = LOCAL
... | the_stack_v2_python_sparse | src/uvm/reg/uvm_reg_sequence.py | tpoikela/uvm-python | train | 199 | |
84d433b6dc3fd54d5577ab5a26ae6b174090334f | [
"iocs = OrderedDict()\nif os.path.isfile(path):\n root = parse_xml_removing_namespace(path)\n OptionsLoader._options_from_xml(root, iocs)\nelse:\n print_and_log('Cannot find config path: ' + str(path), 'MINOR')\nreturn iocs",
"for ioc in root_xml.findall('./' + TAG_IOC_CONFIG):\n name = ioc.attrib[TAG... | <|body_start_0|>
iocs = OrderedDict()
if os.path.isfile(path):
root = parse_xml_removing_namespace(path)
OptionsLoader._options_from_xml(root, iocs)
else:
print_and_log('Cannot find config path: ' + str(path), 'MINOR')
return iocs
<|end_body_0|>
<|bod... | OptionsLoader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsLoader:
def get_options(path: str) -> OrderedDict:
"""Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded Returns: An ordered dict of IOCs and their associated options"""
<|body_0|>
def _options_f... | stack_v2_sparse_classes_36k_train_018165 | 3,596 | permissive | [
{
"docstring": "Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded Returns: An ordered dict of IOCs and their associated options",
"name": "get_options",
"signature": "def get_options(path: str) -> OrderedDict"
},
{
"docstr... | 2 | null | Implement the Python class `OptionsLoader` described below.
Class description:
Implement the OptionsLoader class.
Method signatures and docstrings:
- def get_options(path: str) -> OrderedDict: Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded R... | Implement the Python class `OptionsLoader` described below.
Class description:
Implement the OptionsLoader class.
Method signatures and docstrings:
- def get_options(path: str) -> OrderedDict: Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded R... | 2e605cbff1cfe071571a64bed61708d8c92dc204 | <|skeleton|>
class OptionsLoader:
def get_options(path: str) -> OrderedDict:
"""Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded Returns: An ordered dict of IOCs and their associated options"""
<|body_0|>
def _options_f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionsLoader:
def get_options(path: str) -> OrderedDict:
"""Loads the IOC options from file and converts them into IocOptions objects Args: path: The path to the xml file to be loaded Returns: An ordered dict of IOCs and their associated options"""
iocs = OrderedDict()
if os.path.isfi... | the_stack_v2_python_sparse | DatabaseServer/options_loader.py | ISISComputingGroup/EPICS-inst_servers | train | 1 | |
cc401479821325564cf8c1e097747e7283e0a81d | [
"prev_node = None\ncurr_node = head\nwhile curr_node:\n next_node = curr_node.next\n curr_node.next = prev_node\n prev_node = curr_node\n curr_node = next_node\nhead = prev_node\nreturn head",
"if not head or not head.next:\n return head\np = self.reverseList(head.next)\nhead.next.next = head\nhead... | <|body_start_0|>
prev_node = None
curr_node = head
while curr_node:
next_node = curr_node.next
curr_node.next = prev_node
prev_node = curr_node
curr_node = next_node
head = prev_node
return head
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList_v1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
prev_node = None
curr_node... | stack_v2_sparse_classes_36k_train_018166 | 804 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList_v1",
"signature": "def reverseList_v1(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021233 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseList_v1(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseList_v1(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def ... | 0706769084d60a397366d41bb87add8d53ba8eb3 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList_v1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
prev_node = None
curr_node = head
while curr_node:
next_node = curr_node.next
curr_node.next = prev_node
prev_node = curr_node
curr_node = next_nod... | the_stack_v2_python_sparse | DataStructure/linked_list/reverse-linkedlist.py | sanjitroy1992/PythonCodingTraining | train | 0 | |
3e3e2cdc88454924841b781b1c40c833c840a6ba | [
"if not s:\n return 0\nn = len(s)\nres = [1] * n\nans = 0\nfor i in range(1, n):\n sub = s[i - res[i - 1]:i]\n if s[i] not in sub:\n res[i] = res[i - 1] + 1\n else:\n res[i] = res[i - 1] - sub.index(s[i])\n ans = max(ans, res[i])\nreturn ans",
"if not s:\n return 0\nans = 0\nn = le... | <|body_start_0|>
if not s:
return 0
n = len(s)
res = [1] * n
ans = 0
for i in range(1, n):
sub = s[i - res[i - 1]:i]
if s[i] not in sub:
res[i] = res[i - 1] + 1
else:
res[i] = res[i - 1] - sub.index(s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring_3(self, s: str) -> int:
"""1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串"""
<|body_0|>
def lengthOfLongestSubstring(self, s: str) -> int:
"""2. 集合+滑动窗口:索引 i~j 为最长子串,lookup 记录子串字母"""
<|body_1|>
def lengthOfLongestSubs... | stack_v2_sparse_classes_36k_train_018167 | 2,720 | no_license | [
{
"docstring": "1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串",
"name": "lengthOfLongestSubstring_3",
"signature": "def lengthOfLongestSubstring_3(self, s: str) -> int"
},
{
"docstring": "2. 集合+滑动窗口:索引 i~j 为最长子串,lookup 记录子串字母",
"name": "lengthOfLongestSubstring",
"signature": "def lengthO... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring_3(self, s: str) -> int: 1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串
- def lengthOfLongestSubstring(self, s: str) -> int: 2. 集合+滑动窗口:索引 i~j 为最长子串,loo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring_3(self, s: str) -> int: 1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串
- def lengthOfLongestSubstring(self, s: str) -> int: 2. 集合+滑动窗口:索引 i~j 为最长子串,loo... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def lengthOfLongestSubstring_3(self, s: str) -> int:
"""1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串"""
<|body_0|>
def lengthOfLongestSubstring(self, s: str) -> int:
"""2. 集合+滑动窗口:索引 i~j 为最长子串,lookup 记录子串字母"""
<|body_1|>
def lengthOfLongestSubs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring_3(self, s: str) -> int:
"""1. 动态规划:O(N^2) res[i] 数组表示以 s[i] 为结尾的最长无重复子串"""
if not s:
return 0
n = len(s)
res = [1] * n
ans = 0
for i in range(1, n):
sub = s[i - res[i - 1]:i]
if s[i] not ... | the_stack_v2_python_sparse | .leetcode/3.无重复字符的最长子串.py | xiaoruijiang/algorithm | train | 0 | |
94f974ef86531298180f8b49834667705da2ae28 | [
"try:\n result = data.DataMaster().create_database(baseid)\n return_data = {'status': '200', 'result': result}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n result = data... | <|body_start_0|>
try:
result = data.DataMaster().create_database(baseid)
return_data = {'status': '200', 'result': result}
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '400', 'result': str(e)}
return ... | 1. POST : 2. PUT : 3. GET : 4. DELETE : | DataFrameSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request):
"""return all ... | stack_v2_sparse_classes_36k_train_018168 | 2,387 | no_license | [
{
"docstring": "create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result",
"name": "post",
"signature": "def post(self, request, baseid)"
},
{
"docstring": "return all databases :param request: Not used :param baseid: schemaId :return: list ... | 4 | stack_v2_sparse_classes_30k_train_005086 | Implement the Python class `DataFrameSchema` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid): create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result
- def get(self, ... | Implement the Python class `DataFrameSchema` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid): create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result
- def get(self, ... | 17216fd58619b56b6a397178d327687c274c238c | <|skeleton|>
class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request):
"""return all ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
try:
result = data.DataMaster().create_database(baseid)
... | the_stack_v2_python_sparse | tfmsarest/views/dataframe_base.py | TensorMSA/tensormsa_server_old | train | 0 |
f2263da1efa2f3c54374278435ca6b894b9a57de | [
"if not root:\n return 0\nnodes = [root.left, root.right]\nif not any(nodes):\n return 1\nmin_depth = float(inf)\nfor node in nodes:\n if node:\n min_depth = min(self.get_depth(node), min_depth)\nreturn min_depth",
"if not root:\n return 0\nelse:\n stack, min_depth = ([(root.left, root.right... | <|body_start_0|>
if not root:
return 0
nodes = [root.left, root.right]
if not any(nodes):
return 1
min_depth = float(inf)
for node in nodes:
if node:
min_depth = min(self.get_depth(node), min_depth)
return min_depth
<|en... | MinimumDepth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimumDepth:
def get_min_depth(self, root: TreeNode) -> int:
"""Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:"""
<|body_0|>
def get_min_depth_(self, root: TreeNode) -> int:
"""Approach: Iterative using DFS Time... | stack_v2_sparse_classes_36k_train_018169 | 1,967 | no_license | [
{
"docstring": "Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:",
"name": "get_min_depth",
"signature": "def get_min_depth(self, root: TreeNode) -> int"
},
{
"docstring": "Approach: Iterative using DFS Time Complexity: O(n) Space Complexity: ... | 3 | null | Implement the Python class `MinimumDepth` described below.
Class description:
Implement the MinimumDepth class.
Method signatures and docstrings:
- def get_min_depth(self, root: TreeNode) -> int: Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:
- def get_min_depth_... | Implement the Python class `MinimumDepth` described below.
Class description:
Implement the MinimumDepth class.
Method signatures and docstrings:
- def get_min_depth(self, root: TreeNode) -> int: Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:
- def get_min_depth_... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class MinimumDepth:
def get_min_depth(self, root: TreeNode) -> int:
"""Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:"""
<|body_0|>
def get_min_depth_(self, root: TreeNode) -> int:
"""Approach: Iterative using DFS Time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinimumDepth:
def get_min_depth(self, root: TreeNode) -> int:
"""Approach: Recursion using DFS. Time Complexity: O(n) Space Complexity: O(log n) :param root: :return:"""
if not root:
return 0
nodes = [root.left, root.right]
if not any(nodes):
return 1
... | the_stack_v2_python_sparse | data_structures/tree_node/min_depth_of_bt.py | Shiv2157k/leet_code | train | 1 | |
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea | [
"os_walk_input_iter = (('a1', ['b1'], ['c1', 'd1']), ('a2', ['b2'], ['c2', 'd2']), ('a3', ['b3'], ['c3', 'd3']))\nos_walk_expected_output = ('a1/c1', 'a1/d1', 'a2/c2', 'a2/d2', 'a3/c3', 'a3/d3')\nos_walk_actual_output = tuple(da.lwc.search._adapt_os_walk_to_filepath(os_walk_input_iter))\nassert os_walk_expected_out... | <|body_start_0|>
os_walk_input_iter = (('a1', ['b1'], ['c1', 'd1']), ('a2', ['b2'], ['c2', 'd2']), ('a3', ['b3'], ['c3', 'd3']))
os_walk_expected_output = ('a1/c1', 'a1/d1', 'a2/c2', 'a2/d2', 'a3/c3', 'a3/d3')
os_walk_actual_output = tuple(da.lwc.search._adapt_os_walk_to_filepath(os_walk_input_i... | Tet cases for the _adapt_os_walk_to_filepath function. | Specify_AdaptOsWalkToFilepath | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Specify_AdaptOsWalkToFilepath:
"""Tet cases for the _adapt_os_walk_to_filepath function."""
def it_serialises_simple_tree(self):
"""Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_filepath should take output in the form provided by os.walk... | stack_v2_sparse_classes_36k_train_018170 | 29,518 | permissive | [
{
"docstring": "Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_filepath should take output in the form provided by os.walk and should adapt it to produce a sequence of \"flat\" file paths.",
"name": "it_serialises_simple_tree",
"signature": "def it_serialise... | 2 | null | Implement the Python class `Specify_AdaptOsWalkToFilepath` described below.
Class description:
Tet cases for the _adapt_os_walk_to_filepath function.
Method signatures and docstrings:
- def it_serialises_simple_tree(self): Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_fi... | Implement the Python class `Specify_AdaptOsWalkToFilepath` described below.
Class description:
Tet cases for the _adapt_os_walk_to_filepath function.
Method signatures and docstrings:
- def it_serialises_simple_tree(self): Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_fi... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class Specify_AdaptOsWalkToFilepath:
"""Tet cases for the _adapt_os_walk_to_filepath function."""
def it_serialises_simple_tree(self):
"""Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_filepath should take output in the form provided by os.walk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Specify_AdaptOsWalkToFilepath:
"""Tet cases for the _adapt_os_walk_to_filepath function."""
def it_serialises_simple_tree(self):
"""Test _adapt_os_walk_to_filepath handles a simple use case as expected. The _adapt_os_walk_to_filepath should take output in the form provided by os.walk and should a... | the_stack_v2_python_sparse | a3_src/h70_internal/da/lwc/spec/spec_search.py | wtpayne/hiai | train | 5 |
6f4e452f24b8ecf87ae069b7dca8d396a1af3a54 | [
"article = Article.objects.filter(id=aid)\nif not article.exists():\n return JsonResponse({'status': False, 'err': '文章不存在'}, status=404)\narticle = article[0]\nif HelpsStarRecord.objects.filter(Q(article=article) & Q(star_man=User_Info.objects.get(email=request.session.get('login')))).exists():\n return JsonR... | <|body_start_0|>
article = Article.objects.filter(id=aid)
if not article.exists():
return JsonResponse({'status': False, 'err': '文章不存在'}, status=404)
article = article[0]
if HelpsStarRecord.objects.filter(Q(article=article) & Q(star_man=User_Info.objects.get(email=request.ses... | StarInfoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarInfoView:
def get(self, request, aid):
"""为文章点赞 :param request: :param aid: :return:"""
<|body_0|>
def delete(self, request, aid):
"""取消文章的点赞 :param request: :param aid: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
article = Article.... | stack_v2_sparse_classes_36k_train_018171 | 2,251 | no_license | [
{
"docstring": "为文章点赞 :param request: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, aid)"
},
{
"docstring": "取消文章的点赞 :param request: :param aid: :return:",
"name": "delete",
"signature": "def delete(self, request, aid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018664 | Implement the Python class `StarInfoView` described below.
Class description:
Implement the StarInfoView class.
Method signatures and docstrings:
- def get(self, request, aid): 为文章点赞 :param request: :param aid: :return:
- def delete(self, request, aid): 取消文章的点赞 :param request: :param aid: :return: | Implement the Python class `StarInfoView` described below.
Class description:
Implement the StarInfoView class.
Method signatures and docstrings:
- def get(self, request, aid): 为文章点赞 :param request: :param aid: :return:
- def delete(self, request, aid): 取消文章的点赞 :param request: :param aid: :return:
<|skeleton|>
class... | 526dea540048fc92260bce611c520c50af744e0b | <|skeleton|>
class StarInfoView:
def get(self, request, aid):
"""为文章点赞 :param request: :param aid: :return:"""
<|body_0|>
def delete(self, request, aid):
"""取消文章的点赞 :param request: :param aid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarInfoView:
def get(self, request, aid):
"""为文章点赞 :param request: :param aid: :return:"""
article = Article.objects.filter(id=aid)
if not article.exists():
return JsonResponse({'status': False, 'err': '文章不存在'}, status=404)
article = article[0]
if HelpsStar... | the_stack_v2_python_sparse | apps/helps/views/star/starInfo.py | DICKQI/ALGYunXS | train | 0 | |
6713abb09de37e0f79ed7dc0233161525f0f5698 | [
"try:\n data = PolicyManager.get_subject_assignments(user_id=user_id, policy_id=uuid, subject_id=perimeter_id, category_id=category_id)\nexcept Exception as e:\n LOG.error(e, exc_info=True)\n return ({'result': False, 'error': str(e)}, 500)\nreturn {'subject_assignments': data}",
"try:\n data_id = req... | <|body_start_0|>
try:
data = PolicyManager.get_subject_assignments(user_id=user_id, policy_id=uuid, subject_id=perimeter_id, category_id=category_id)
except Exception as e:
LOG.error(e, exc_info=True)
return ({'result': False, 'error': str(e)}, 500)
return {'s... | Endpoint for subject assignment requests | SubjectAssignments | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubjectAssignments:
"""Endpoint for subject assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all subject assignments or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: ... | stack_v2_sparse_classes_36k_train_018172 | 14,093 | permissive | [
{
"docstring": "Retrieve all subject assignments or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the subject :param category_id: uuid of the subject category :param data_id: uuid of the subject scope :param user_id: user ID who do the request :return: { \"subjec... | 3 | stack_v2_sparse_classes_30k_train_006899 | Implement the Python class `SubjectAssignments` described below.
Class description:
Endpoint for subject assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all subject assignments or a specific one for a given pol... | Implement the Python class `SubjectAssignments` described below.
Class description:
Endpoint for subject assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all subject assignments or a specific one for a given pol... | daaba34fa2ed4426bc0fde359e54a5e1b872208c | <|skeleton|>
class SubjectAssignments:
"""Endpoint for subject assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all subject assignments or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubjectAssignments:
"""Endpoint for subject assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all subject assignments or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the s... | the_stack_v2_python_sparse | moonv4/moon_manager/moon_manager/api/assignments.py | hashnfv/hashnfv-moon | train | 0 |
567a8c805b4c416561d66d16eba511fd2d23526f | [
"super().__init__()\nself._logger = logging.getLogger(self.__class__.__name__)\nself.weights_dim = weights_dim\nself.prepool = nn.Sequential(nn.Conv1d(4, 64, 1), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv1d(64, ... | <|body_start_0|>
super().__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self.weights_dim = weights_dim
self.prepool = nn.Sequential(nn.Conv1d(4, 64, 1), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.Gr... | ParameterPredictionNet | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterPredictionNet:
def __init__(self, weights_dim):
"""PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should be something like [3], or [64, 3], for 3 types of features"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k_train_018173 | 14,032 | permissive | [
{
"docstring": "PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should be something like [3], or [64, 3], for 3 types of features",
"name": "__init__",
"signature": "def __init__(self, weights_dim)"
},
{
"docstring": "Returns alpha, b... | 2 | null | Implement the Python class `ParameterPredictionNet` described below.
Class description:
Implement the ParameterPredictionNet class.
Method signatures and docstrings:
- def __init__(self, weights_dim): PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should ... | Implement the Python class `ParameterPredictionNet` described below.
Class description:
Implement the ParameterPredictionNet class.
Method signatures and docstrings:
- def __init__(self, weights_dim): PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should ... | 2a5578577ce58786f05bb8701f2329b32ed6bb3a | <|skeleton|>
class ParameterPredictionNet:
def __init__(self, weights_dim):
"""PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should be something like [3], or [64, 3], for 3 types of features"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterPredictionNet:
def __init__(self, weights_dim):
"""PointNet based Parameter prediction network Args: weights_dim: Number of weights to predict (excluding beta), should be something like [3], or [64, 3], for 3 types of features"""
super().__init__()
self._logger = logging.getLo... | the_stack_v2_python_sparse | shapmagn/modules_reg/networks/rpmnet.py | dugushiyu/shapmagn | train | 0 | |
81ca6311d8bfdfc2c75064b7aa6fd5485aa3bec7 | [
"self.variables = np.array([])\nself.cardinality = np.array([], dtype=int)\nself.inhibitor_probability = []\nself.add_variables(variables, cardinality, inhibitor_probability)",
"if len(variables) == 1:\n if not isinstance(inhibitor_probability[0], (list, tuple)):\n inhibitor_probability = [inhibitor_pro... | <|body_start_0|>
self.variables = np.array([])
self.cardinality = np.array([], dtype=int)
self.inhibitor_probability = []
self.add_variables(variables, cardinality, inhibitor_probability)
<|end_body_0|>
<|body_start_1|>
if len(variables) == 1:
if not isinstance(inhib... | Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford.edu/~srinivas/research/6-UAI93-Srinivas-Generalization-of-Noisy-Or.pdf | NoisyOrModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoisyOrModel:
"""Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford.edu/~srinivas/research/6-UAI93-Sriniva... | stack_v2_sparse_classes_36k_train_018174 | 5,683 | permissive | [
{
"docstring": "Init method for NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) array containing names of the variables. cardinality: list, tuple, dict (array like) array containing integers representing the cardinality of the variables. inhibitor_probability: list, tuple, dict (ar... | 3 | stack_v2_sparse_classes_30k_train_021262 | Implement the Python class `NoisyOrModel` described below.
Class description:
Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford... | Implement the Python class `NoisyOrModel` described below.
Class description:
Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford... | 6d66bde4c7f140ba14892174c59370b2b7964e90 | <|skeleton|>
class NoisyOrModel:
"""Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford.edu/~srinivas/research/6-UAI93-Sriniva... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoisyOrModel:
"""Base class for Noisy-Or models. This is an implementation of generalized Noisy-Or models and is not limited to Boolean variables and also any arbitrary function can be used instead of the boolean OR function. Reference: http://xenon.stanford.edu/~srinivas/research/6-UAI93-Srinivas-Generalizat... | the_stack_v2_python_sparse | pgmpy/models/NoisyOrModel.py | pgmpy/pgmpy | train | 2,617 |
f1aa058bb0dcf08d70c2a809f3f21403b2896563 | [
"res = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n queue.append(node.left)\n queue.append(node.right)\n res.append(str(node.val))\n else:\n res.append('#')\nreturn ','.join(res)",
"parts = data.split(',')\nidx = 0\nval = parts[idx]\nif val == ... | <|body_start_0|>
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
queue.append(node.left)
queue.append(node.right)
res.append(str(node.val))
else:
res.append('#')
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_018175 | 1,809 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_018245 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 543e2ce47ea454d355762e6291a65a1cc6f7af71 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
queue.append(node.left)
queue.append(n... | the_stack_v2_python_sparse | algorithms/python/297_serialize_deserialize_binary_tree_2.py | ppd0705/leetcode | train | 1 | |
dc385f17171eb09ed703480a3a4e5256022818b2 | [
"super(Game, self).__init__()\nself._crane_scene = CraneScene()\nself._progress_scene = ProgressScene()\nself.current_scene = self._crane_scene\nself._toggle_press_time = 0",
"super().update(dt)\ncurrent_time = time.time()\nkeys = pygame.key.get_pressed()\nif keys[pygame.K_ESCAPE] and current_time - self._toggle_... | <|body_start_0|>
super(Game, self).__init__()
self._crane_scene = CraneScene()
self._progress_scene = ProgressScene()
self.current_scene = self._crane_scene
self._toggle_press_time = 0
<|end_body_0|>
<|body_start_1|>
super().update(dt)
current_time = time.time()
... | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
def __init__(self):
"""A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene."""
<|body_0|>
def update(self, dt: float):
"""Handles switching between the different scenes, and updates the current scene. Args: dt (... | stack_v2_sparse_classes_36k_train_018176 | 2,474 | no_license | [
{
"docstring": "A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handles switching between the different scenes, and updates the current scene. Args: dt (float): the t... | 3 | stack_v2_sparse_classes_30k_train_013696 | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self): A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene.
- def update(self, dt: float): Handles switching between the di... | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self): A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene.
- def update(self, dt: float): Handles switching between the di... | 115e2ea23e0b7aba41a90ef07d0a239314f1d6cf | <|skeleton|>
class Game:
def __init__(self):
"""A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene."""
<|body_0|>
def update(self, dt: float):
"""Handles switching between the different scenes, and updates the current scene. Args: dt (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
def __init__(self):
"""A scene manager containing two main scenes: the arcade (game) scene, and the progress (pokemon) scene."""
super(Game, self).__init__()
self._crane_scene = CraneScene()
self._progress_scene = ProgressScene()
self.current_scene = self._crane_s... | the_stack_v2_python_sparse | crane/game/scene/game.py | mtmk-ee/crane-game | train | 0 | |
2724f508521b6c3229f5439bf6f09eb476978a02 | [
"self._event = asyncio.Event()\nself._messenger = messenger\nself._response_type = response_type\nself._timeout = timeout\nself._response: Optional[BinaryMessageDefinition] = None",
"if isinstance(message, self._response_type) or isinstance(message, AckFailed):\n self._response = message\n self._event.set()... | <|body_start_0|>
self._event = asyncio.Event()
self._messenger = messenger
self._response_type = response_type
self._timeout = timeout
self._response: Optional[BinaryMessageDefinition] = None
<|end_body_0|>
<|body_start_1|>
if isinstance(message, self._response_type) or ... | Helper class for sending a message and ensuring a response. | SendAndReceiveListener | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendAndReceiveListener:
"""Helper class for sending a message and ensuring a response."""
def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None:
"""Create a new SendAndReceiveListener."""
<|body_0|>
def _... | stack_v2_sparse_classes_36k_train_018177 | 10,794 | permissive | [
{
"docstring": "Create a new SendAndReceiveListener.",
"name": "__init__",
"signature": "def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None"
},
{
"docstring": "When called as a listener, mark the message as received.",
"na... | 3 | null | Implement the Python class `SendAndReceiveListener` described below.
Class description:
Helper class for sending a message and ensuring a response.
Method signatures and docstrings:
- def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None: Create a new... | Implement the Python class `SendAndReceiveListener` described below.
Class description:
Helper class for sending a message and ensuring a response.
Method signatures and docstrings:
- def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None: Create a new... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class SendAndReceiveListener:
"""Helper class for sending a message and ensuring a response."""
def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None:
"""Create a new SendAndReceiveListener."""
<|body_0|>
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendAndReceiveListener:
"""Helper class for sending a message and ensuring a response."""
def __init__(self, messenger: BinaryMessenger, response_type: Type[BinaryMessageDefinition], timeout: float=1.0) -> None:
"""Create a new SendAndReceiveListener."""
self._event = asyncio.Event()
... | the_stack_v2_python_sparse | hardware/opentrons_hardware/drivers/binary_usb/binary_messenger.py | Opentrons/opentrons | train | 326 |
e9026ed6ef1e56b0b6f19169b742fbe6354340b1 | [
"for h in self._all:\n if h is not None:\n h.detach_()",
"for e in self._all:\n a, br, d = e.size()\n sentStates = e.view(a, beam_size, br // beam_size, d)[:, :, idx]\n sentStates.data.copy_(sentStates.data.index_select(1, positions))"
] | <|body_start_0|>
for h in self._all:
if h is not None:
h.detach_()
<|end_body_0|>
<|body_start_1|>
for e in self._all:
a, br, d = e.size()
sentStates = e.view(a, beam_size, br // beam_size, d)[:, :, idx]
sentStates.data.copy_(sentStates.da... | DecoderState is a base class for models, used during translation for storing translation states. | DecoderState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
<|body_0|>
def beam_update(self, idx, positions, beam_siz... | stack_v2_sparse_classes_36k_train_018178 | 39,461 | no_license | [
{
"docstring": "Detaches all Variables from the graph that created it, making it a leaf.",
"name": "detach",
"signature": "def detach(self)"
},
{
"docstring": "Update when beam advances.",
"name": "beam_update",
"signature": "def beam_update(self, idx, positions, beam_size)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009622 | Implement the Python class `DecoderState` described below.
Class description:
DecoderState is a base class for models, used during translation for storing translation states.
Method signatures and docstrings:
- def detach(self): Detaches all Variables from the graph that created it, making it a leaf.
- def beam_updat... | Implement the Python class `DecoderState` described below.
Class description:
DecoderState is a base class for models, used during translation for storing translation states.
Method signatures and docstrings:
- def detach(self): Detaches all Variables from the graph that created it, making it a leaf.
- def beam_updat... | 8b159fcbf1bc9faad5a2ef1c0690090037143899 | <|skeleton|>
class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
<|body_0|>
def beam_update(self, idx, positions, beam_siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
for h in self._all:
if h is not None:
h.detach_... | the_stack_v2_python_sparse | disf_gen_coarse2fine/table/Models.py | JingfengYang/Disfluency-Generation-and-Detection | train | 5 |
0454508f439760a9323726f02344c31e6ffe13ac | [
"self.record = record\nself.action = action\ntemplates = dict(self.DEFAULT_TEMPLATES, **current_app.config['ILS_ILL_NOTIFICATIONS_TEMPLATES'])\nif not action or action not in templates:\n raise KeyError('Invalid action argument `{0}` or not found in templates `{1}`.'.format(action, list(templates.keys())))\ntpl_... | <|body_start_0|>
self.record = record
self.action = action
templates = dict(self.DEFAULT_TEMPLATES, **current_app.config['ILS_ILL_NOTIFICATIONS_TEMPLATES'])
if not action or action not in templates:
raise KeyError('Invalid action argument `{0}` or not found in templates `{1}`... | ILL message class to generate the msg content. | NotificationILLMsg | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationILLMsg:
"""ILL message class to generate the msg content."""
def __init__(self, record, action, msg_ctx, **kwargs):
"""Create message based on the record action."""
<|body_0|>
def to_dict(self):
"""Dump obj."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_018179 | 2,053 | permissive | [
{
"docstring": "Create message based on the record action.",
"name": "__init__",
"signature": "def __init__(self, record, action, msg_ctx, **kwargs)"
},
{
"docstring": "Dump obj.",
"name": "to_dict",
"signature": "def to_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010040 | Implement the Python class `NotificationILLMsg` described below.
Class description:
ILL message class to generate the msg content.
Method signatures and docstrings:
- def __init__(self, record, action, msg_ctx, **kwargs): Create message based on the record action.
- def to_dict(self): Dump obj. | Implement the Python class `NotificationILLMsg` described below.
Class description:
ILL message class to generate the msg content.
Method signatures and docstrings:
- def __init__(self, record, action, msg_ctx, **kwargs): Create message based on the record action.
- def to_dict(self): Dump obj.
<|skeleton|>
class No... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class NotificationILLMsg:
"""ILL message class to generate the msg content."""
def __init__(self, record, action, msg_ctx, **kwargs):
"""Create message based on the record action."""
<|body_0|>
def to_dict(self):
"""Dump obj."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationILLMsg:
"""ILL message class to generate the msg content."""
def __init__(self, record, action, msg_ctx, **kwargs):
"""Create message based on the record action."""
self.record = record
self.action = action
templates = dict(self.DEFAULT_TEMPLATES, **current_app... | the_stack_v2_python_sparse | invenio_app_ils/ill/notifications/messages.py | inveniosoftware/invenio-app-ils | train | 64 |
e38d9c2478e2c4316ab06b7bba7ea5402185db9f | [
"self.molecule = molecule\nself.coords_filename = coords_filename\nself.constraints = constraints\nself.working_dir = working_dir",
"self.molecule.to(filename=os.path.join(self.working_dir, self.coords_filename))\nif self.constraints:\n constrains_string = self.constrains_template(molecule=self.molecule, refer... | <|body_start_0|>
self.molecule = molecule
self.coords_filename = coords_filename
self.constraints = constraints
self.working_dir = working_dir
<|end_body_0|>
<|body_start_1|>
self.molecule.to(filename=os.path.join(self.working_dir, self.coords_filename))
if self.constrai... | An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files. | CRESTInput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRESTInput:
"""An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files."""
def __init__(self, molecule: Molecule, working_dir: str='.', coord... | stack_v2_sparse_classes_36k_train_018180 | 3,987 | permissive | [
{
"docstring": ":param molecule (pymatgen Molecule object): Input molecule, the only required CREST input. :param working_dir (str): Location to write input files, defaults to current directory :param coords_filename (str): Name of input coordinates file :param constraints (Dict): Dictionary of common editable ... | 3 | stack_v2_sparse_classes_30k_train_016674 | Implement the Python class `CRESTInput` described below.
Class description:
An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files.
Method signatures and docstrings:
... | Implement the Python class `CRESTInput` described below.
Class description:
An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files.
Method signatures and docstrings:
... | 6dd3b42f569397fa1a86a16fcfaaa29534abb8ca | <|skeleton|>
class CRESTInput:
"""An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files."""
def __init__(self, molecule: Molecule, working_dir: str='.', coord... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CRESTInput:
"""An object representing CREST input files. Because CREST is controlled through command line flags and external files, the CRESTInput class mainly consists of methods for containing and writing external files."""
def __init__(self, molecule: Molecule, working_dir: str='.', coords_filename: O... | the_stack_v2_python_sparse | pymatgen/io/xtb/inputs.py | Zhuoying/pymatgen | train | 2 |
95ee4f8c418afae3c225433775fb7cea7733698c | [
"self._fcn = fcn\nself._fixed_state = fixed_state\nself._idcs = idcs",
"state = self._fixed_state.clone()\nstate = state.repeat(varying.shape[0], varying.shape[1], 1)\nstate[:, :, self._idcs] = varying\nreturn self._fcn(state)"
] | <|body_start_0|>
self._fcn = fcn
self._fixed_state = fixed_state
self._idcs = idcs
<|end_body_0|>
<|body_start_1|>
state = self._fixed_state.clone()
state = state.repeat(varying.shape[0], varying.shape[1], 1)
state[:, :, self._idcs] = varying
return self._fcn(sta... | Wrap the values function to be able to only pass a subset of the state. | wrap_vfcn | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wrap_vfcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values he... | stack_v2_sparse_classes_36k_train_018181 | 5,789 | permissive | [
{
"docstring": "Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values held constant for the evaluation, dimension matches the Module's input layer :param idcs: indices of the state dimensions where the `fixed_state` is replaced which values from ou... | 2 | stack_v2_sparse_classes_30k_train_011755 | Implement the Python class `wrap_vfcn` described below.
Class description:
Wrap the values function to be able to only pass a subset of the state.
Method signatures and docstrings:
- def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list): Constructor :param fcn: function to wrap with an input dimensio... | Implement the Python class `wrap_vfcn` described below.
Class description:
Wrap the values function to be able to only pass a subset of the state.
Method signatures and docstrings:
- def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list): Constructor :param fcn: function to wrap with an input dimensio... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class wrap_vfcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values he... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wrap_vfcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values held constant f... | the_stack_v2_python_sparse | Pyrado/scripts/plotting/plot_value_fcn.py | 1abner1/SimuRLacra | train | 0 |
0d63ce587e4463078e380c1a4be36de6870278b3 | [
"try:\n cls._run(part, opts or popts.PowerOnOpts(), timeout, synchronous=synchronous)\nexcept pexc.JobRequestTimedOut as error:\n LOG.exception(error)\n raise pexc.VMPowerOnTimeout(lpar_nm=part.name, timeout=timeout)\nexcept pexc.JobRequestFailed as error:\n emsg = six.text_type(error)\n if any((err_... | <|body_start_0|>
try:
cls._run(part, opts or popts.PowerOnOpts(), timeout, synchronous=synchronous)
except pexc.JobRequestTimedOut as error:
LOG.exception(error)
raise pexc.VMPowerOnTimeout(lpar_nm=part.name, timeout=timeout)
except pexc.JobRequestFailed as er... | Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details. | PowerOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
... | stack_v2_sparse_classes_36k_train_018182 | 23,048 | permissive | [
{
"docstring": "Power on a partition. :param part: Partition (LPAR or VIOS) wrapper indicating the partition to power on. :param opts: An instance of power_opts.PowerOnOpts indicating additional options to specify to the PowerOn operation. By default, no additional options are used. :param timeout: value in sec... | 3 | null | Implement the Python class `PowerOp` described below.
Class description:
Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the... | Implement the Python class `PowerOp` described below.
Class description:
Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the... | 68f2b586b4f17489f379534ab52fc56a524b6da5 | <|skeleton|>
class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
def start(... | the_stack_v2_python_sparse | pypowervm/tasks/power.py | powervm/pypowervm | train | 25 |
33793b757adcf19660cee3fdf906e48a60295525 | [
"self.assertEqual(remove_vowels('hello world'), 'hll wrld')\nself.assertEqual(remove_vowels('Aishwariya'), 'shwry')\nself.assertEqual(remove_vowels('Harishjitu'), 'hrshjt')\nself.assertEqual(remove_vowels('Hi1Bye2'), 'h1by2')",
"self.assertTrue(check_pwd('Abcd333'))\nself.assertTrue(check_pwd('AAAABbbcc44'))\nsel... | <|body_start_0|>
self.assertEqual(remove_vowels('hello world'), 'hll wrld')
self.assertEqual(remove_vowels('Aishwariya'), 'shwry')
self.assertEqual(remove_vowels('Harishjitu'), 'hrshjt')
self.assertEqual(remove_vowels('Hi1Bye2'), 'h1by2')
<|end_body_0|>
<|body_start_1|>
self.ass... | RvCpBtIsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RvCpBtIsTest:
def test_remove_vowels(self):
"""Tests for remove_vowels"""
<|body_0|>
def test_check_pwd(self):
"""Tests for check_pwd"""
<|body_1|>
def test_BTree(self):
"""Tests for Binary Tree"""
<|body_2|>
def test_check_insertion... | stack_v2_sparse_classes_36k_train_018183 | 4,004 | no_license | [
{
"docstring": "Tests for remove_vowels",
"name": "test_remove_vowels",
"signature": "def test_remove_vowels(self)"
},
{
"docstring": "Tests for check_pwd",
"name": "test_check_pwd",
"signature": "def test_check_pwd(self)"
},
{
"docstring": "Tests for Binary Tree",
"name": "t... | 4 | stack_v2_sparse_classes_30k_train_015488 | Implement the Python class `RvCpBtIsTest` described below.
Class description:
Implement the RvCpBtIsTest class.
Method signatures and docstrings:
- def test_remove_vowels(self): Tests for remove_vowels
- def test_check_pwd(self): Tests for check_pwd
- def test_BTree(self): Tests for Binary Tree
- def test_check_inser... | Implement the Python class `RvCpBtIsTest` described below.
Class description:
Implement the RvCpBtIsTest class.
Method signatures and docstrings:
- def test_remove_vowels(self): Tests for remove_vowels
- def test_check_pwd(self): Tests for check_pwd
- def test_BTree(self): Tests for Binary Tree
- def test_check_inser... | a26a020ee938c1842efa9eabfd132ee985bbdb50 | <|skeleton|>
class RvCpBtIsTest:
def test_remove_vowels(self):
"""Tests for remove_vowels"""
<|body_0|>
def test_check_pwd(self):
"""Tests for check_pwd"""
<|body_1|>
def test_BTree(self):
"""Tests for Binary Tree"""
<|body_2|>
def test_check_insertion... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RvCpBtIsTest:
def test_remove_vowels(self):
"""Tests for remove_vowels"""
self.assertEqual(remove_vowels('hello world'), 'hll wrld')
self.assertEqual(remove_vowels('Aishwariya'), 'shwry')
self.assertEqual(remove_vowels('Harishjitu'), 'hrshjt')
self.assertEqual(remove_vo... | the_stack_v2_python_sparse | HW06_Aishwariya.py | AishwariyaRajendraprasad/SSW-810 | train | 0 | |
1418ada458120f94cbd72208505b5ddfd9926053 | [
"in_width, out_width = random.sample(range(1, 64), 2)\ninvalid_offset = random.randrange(out_width - in_width + 1, out_width * 2)\nclock = Signal(False)\nsignal_in = Signal(intbv(0)[in_width:])\nsignal_out = Signal(intbv(0)[out_width:])\nself.assertRaisesRegex(ValueError, 'signal_out must be wide enough to accomoda... | <|body_start_0|>
in_width, out_width = random.sample(range(1, 64), 2)
invalid_offset = random.randrange(out_width - in_width + 1, out_width * 2)
clock = Signal(False)
signal_in = Signal(intbv(0)[in_width:])
signal_out = Signal(intbv(0)[out_width:])
self.assertRaisesRegex(... | The signal_assigner should reject incompatible interfaces and arguments. | TestSyncSignalAssignerInterfaceSimulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSyncSignalAssignerInterfaceSimulation:
"""The signal_assigner should reject incompatible interfaces and arguments."""
def test_invalid_widths(self):
"""The signal_assigner should raise a value error if the signal_out is not wide enough to take the signal_in shifted by offset."""
... | stack_v2_sparse_classes_36k_train_018184 | 15,215 | permissive | [
{
"docstring": "The signal_assigner should raise a value error if the signal_out is not wide enough to take the signal_in shifted by offset.",
"name": "test_invalid_widths",
"signature": "def test_invalid_widths(self)"
},
{
"docstring": "The signal_assigner should raise a value error if the sign... | 3 | stack_v2_sparse_classes_30k_train_005334 | Implement the Python class `TestSyncSignalAssignerInterfaceSimulation` described below.
Class description:
The signal_assigner should reject incompatible interfaces and arguments.
Method signatures and docstrings:
- def test_invalid_widths(self): The signal_assigner should raise a value error if the signal_out is not... | Implement the Python class `TestSyncSignalAssignerInterfaceSimulation` described below.
Class description:
The signal_assigner should reject incompatible interfaces and arguments.
Method signatures and docstrings:
- def test_invalid_widths(self): The signal_assigner should raise a value error if the signal_out is not... | 0b5e015cd62ba14d8d8a29b6c23d886044154572 | <|skeleton|>
class TestSyncSignalAssignerInterfaceSimulation:
"""The signal_assigner should reject incompatible interfaces and arguments."""
def test_invalid_widths(self):
"""The signal_assigner should raise a value error if the signal_out is not wide enough to take the signal_in shifted by offset."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSyncSignalAssignerInterfaceSimulation:
"""The signal_assigner should reject incompatible interfaces and arguments."""
def test_invalid_widths(self):
"""The signal_assigner should raise a value error if the signal_out is not wide enough to take the signal_in shifted by offset."""
in_wi... | the_stack_v2_python_sparse | kea/utils/test_synchronous_signal_assigner.py | SmartAcoustics/Kea | train | 5 |
8c7cc6e9bd3ee879e0df00a39731e64c622b1bbc | [
"self.backup_run = backup_run\nself.change_event_id = change_event_id\nself.copy_run = copy_run\nself.job_run_id = job_run_id\nself.protection_job_run_uid = protection_job_run_uid\nself.snapshot_target = snapshot_target\nself.snapshot_target_type = snapshot_target_type\nself.task_status = task_status\nself.uuid = u... | <|body_start_0|>
self.backup_run = backup_run
self.change_event_id = change_event_id
self.copy_run = copy_run
self.job_run_id = job_run_id
self.protection_job_run_uid = protection_job_run_uid
self.snapshot_target = snapshot_target
self.snapshot_target_type = snaps... | Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event_id (long|int): Specifies the event id which ca... | LatestProtectionRun | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event... | stack_v2_sparse_classes_36k_train_018185 | 4,565 | permissive | [
{
"docstring": "Constructor for the LatestProtectionRun class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, change_event_id=None, copy_run=None, job_run_id=None, protection_job_run_uid=None, snapshot_target=None, snapshot_target_type=None, task_status=None, uuid=None)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_011097 | Implement the Python class `LatestProtectionRun` described below.
Class description:
Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local ... | Implement the Python class `LatestProtectionRun` described below.
Class description:
Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event_id (long|int... | the_stack_v2_python_sparse | cohesity_management_sdk/models/latest_protection_run.py | cohesity/management-sdk-python | train | 24 |
5adbfb7b3375c199b043fe81bc6bee173d370c05 | [
"helpers.patch_interpretationlog(session, user.id, log_id, data['message'], allele_id=allele_id)\nsession.commit()\nreturn (None, 200)",
"helpers.delete_interpretationlog(session, user.id, log_id, allele_id=allele_id)\nsession.commit()\nreturn (None, 200)"
] | <|body_start_0|>
helpers.patch_interpretationlog(session, user.id, log_id, data['message'], allele_id=allele_id)
session.commit()
return (None, 200)
<|end_body_0|>
<|body_start_1|>
helpers.delete_interpretationlog(session, user.id, log_id, allele_id=allele_id)
session.commit()
... | AlleleInterpretationLogResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlleleInterpretationLogResource:
def patch(self, session, allele_id, log_id, data=None, user=None):
"""Patch an interpretation log entry. --- summary: Patch interpretation log tags: - Workflow parameters: - name: allele_id in: path type: integer description: Allele id responses: 200: des... | stack_v2_sparse_classes_36k_train_018186 | 16,248 | permissive | [
{
"docstring": "Patch an interpretation log entry. --- summary: Patch interpretation log tags: - Workflow parameters: - name: allele_id in: path type: integer description: Allele id responses: 200: description: Returns null 500: description: Error",
"name": "patch",
"signature": "def patch(self, session... | 2 | null | Implement the Python class `AlleleInterpretationLogResource` described below.
Class description:
Implement the AlleleInterpretationLogResource class.
Method signatures and docstrings:
- def patch(self, session, allele_id, log_id, data=None, user=None): Patch an interpretation log entry. --- summary: Patch interpretat... | Implement the Python class `AlleleInterpretationLogResource` described below.
Class description:
Implement the AlleleInterpretationLogResource class.
Method signatures and docstrings:
- def patch(self, session, allele_id, log_id, data=None, user=None): Patch an interpretation log entry. --- summary: Patch interpretat... | e38631d302611a143c9baaa684bcbd014d9734e4 | <|skeleton|>
class AlleleInterpretationLogResource:
def patch(self, session, allele_id, log_id, data=None, user=None):
"""Patch an interpretation log entry. --- summary: Patch interpretation log tags: - Workflow parameters: - name: allele_id in: path type: integer description: Allele id responses: 200: des... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlleleInterpretationLogResource:
def patch(self, session, allele_id, log_id, data=None, user=None):
"""Patch an interpretation log entry. --- summary: Patch interpretation log tags: - Workflow parameters: - name: allele_id in: path type: integer description: Allele id responses: 200: description: Retu... | the_stack_v2_python_sparse | src/api/v1/resources/workflow/allele.py | dabble-of-devops-consulting/ella | train | 0 | |
e8675ee9f72dfe6ef1da2f92f219492258627fe3 | [
"self.params = NetworkParams()\nself.obs_filter = modules.ObservationFilter()\nn_in = self.obs_filter.get_value_fn_ob_shape(self.observation_space)\nself.embedding = modules.ObservationEmbedding(n_in, self.params.embedding_size)\nself.action_embedding = nn.Sequential(nn.Linear(9, self.params.embedding_size), nn.ReL... | <|body_start_0|>
self.params = NetworkParams()
self.obs_filter = modules.ObservationFilter()
n_in = self.obs_filter.get_value_fn_ob_shape(self.observation_space)
self.embedding = modules.ObservationEmbedding(n_in, self.params.embedding_size)
self.action_embedding = nn.Sequential(... | Q Function. | QNetAppend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNetAppend:
"""Q Function."""
def build(self):
"""Build."""
<|body_0|>
def forward(self, ob, ac):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.params = NetworkParams()
self.obs_filter = modules.ObservationFilter()
... | stack_v2_sparse_classes_36k_train_018187 | 6,326 | permissive | [
{
"docstring": "Build.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, ob, ac)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001049 | Implement the Python class `QNetAppend` described below.
Class description:
Q Function.
Method signatures and docstrings:
- def build(self): Build.
- def forward(self, ob, ac): Forward. | Implement the Python class `QNetAppend` described below.
Class description:
Q Function.
Method signatures and docstrings:
- def build(self): Build.
- def forward(self, ob, ac): Forward.
<|skeleton|>
class QNetAppend:
"""Q Function."""
def build(self):
"""Build."""
<|body_0|>
def forward... | 6fb12eecbaa778c60c5728dba4414330c901b09b | <|skeleton|>
class QNetAppend:
"""Q Function."""
def build(self):
"""Build."""
<|body_0|>
def forward(self, ob, ac):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QNetAppend:
"""Q Function."""
def build(self):
"""Build."""
self.params = NetworkParams()
self.obs_filter = modules.ObservationFilter()
n_in = self.obs_filter.get_value_fn_ob_shape(self.observation_space)
self.embedding = modules.ObservationEmbedding(n_in, self.par... | the_stack_v2_python_sparse | python/residual_learning/networks.py | cbschaff/benchmark-rrc | train | 12 |
e33c1d51dcdd56cec88fb87ea375a93e7bc3b41b | [
"from gui.main_form import MainForm\nself.main_form: MainForm = main_form\nself.menu = None\nself.file_menu = None\nself.report_menu = None\nself.scoring_menu = None",
"self.menu = tkinter.Menu(self.main_form.root)\nself.main_form.root.config(menu=self.menu)\nself.file_menu = tkinter.Menu(self.menu, tearoff=False... | <|body_start_0|>
from gui.main_form import MainForm
self.main_form: MainForm = main_form
self.menu = None
self.file_menu = None
self.report_menu = None
self.scoring_menu = None
<|end_body_0|>
<|body_start_1|>
self.menu = tkinter.Menu(self.main_form.root)
... | Menü-Leiste der MainForm | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menü-Leiste der MainForm"""
def __init__(self, main_form):
"""Konstruktor Args: main_form (MainForm): MainForm"""
<|body_0|>
def create(self):
"""Erstellen des Menüs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from gui.main_form imp... | stack_v2_sparse_classes_36k_train_018188 | 3,055 | no_license | [
{
"docstring": "Konstruktor Args: main_form (MainForm): MainForm",
"name": "__init__",
"signature": "def __init__(self, main_form)"
},
{
"docstring": "Erstellen des Menüs",
"name": "create",
"signature": "def create(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009296 | Implement the Python class `Menu` described below.
Class description:
Menü-Leiste der MainForm
Method signatures and docstrings:
- def __init__(self, main_form): Konstruktor Args: main_form (MainForm): MainForm
- def create(self): Erstellen des Menüs | Implement the Python class `Menu` described below.
Class description:
Menü-Leiste der MainForm
Method signatures and docstrings:
- def __init__(self, main_form): Konstruktor Args: main_form (MainForm): MainForm
- def create(self): Erstellen des Menüs
<|skeleton|>
class Menu:
"""Menü-Leiste der MainForm"""
d... | 349aad3f5a71374f062a7a3b50d827dbf8e99bfe | <|skeleton|>
class Menu:
"""Menü-Leiste der MainForm"""
def __init__(self, main_form):
"""Konstruktor Args: main_form (MainForm): MainForm"""
<|body_0|>
def create(self):
"""Erstellen des Menüs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menü-Leiste der MainForm"""
def __init__(self, main_form):
"""Konstruktor Args: main_form (MainForm): MainForm"""
from gui.main_form import MainForm
self.main_form: MainForm = main_form
self.menu = None
self.file_menu = None
self.report_menu = None... | the_stack_v2_python_sparse | gui/menu.py | RobFro96/Talentiadeverwaltung | train | 0 |
b11cf34f3e206bac1c28092c0e8508e7997fa092 | [
"super(HostActionsAdminTest, cls).setUpClass()\ncls.hosts = cls.admin_hosts_client.list_hosts().entity\ncls.compute_host_name = next((host.host_name for host in cls.hosts if host.service == HostServiceTypes.COMPUTE))",
"host_response = self.admin_hosts_client.update_host(self.compute_host_name, status='disable').... | <|body_start_0|>
super(HostActionsAdminTest, cls).setUpClass()
cls.hosts = cls.admin_hosts_client.list_hosts().entity
cls.compute_host_name = next((host.host_name for host in cls.hosts if host.service == HostServiceTypes.COMPUTE))
<|end_body_0|>
<|body_start_1|>
host_response = self.adm... | HostActionsAdminTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostActionsAdminTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts - The host name of a compute host"""
<|body_0|>
def test_disable_host(self):
"""Test that... | stack_v2_sparse_classes_36k_train_018189 | 2,488 | permissive | [
{
"docstring": "Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts - The host name of a compute host",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Test that an admin user can disable ... | 2 | null | Implement the Python class `HostActionsAdminTest` described below.
Class description:
Implement the HostActionsAdminTest class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts -... | Implement the Python class `HostActionsAdminTest` described below.
Class description:
Implement the HostActionsAdminTest class.
Method signatures and docstrings:
- def setUpClass(cls): Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts -... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class HostActionsAdminTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts - The host name of a compute host"""
<|body_0|>
def test_disable_host(self):
"""Test that... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostActionsAdminTest:
def setUpClass(cls):
"""Perform actions that setup the necessary resources for testing The following data is generated during this setup: - A list of hosts - The host name of a compute host"""
super(HostActionsAdminTest, cls).setUpClass()
cls.hosts = cls.admin_hos... | the_stack_v2_python_sparse | cloudroast/compute/admin_api/hosts/test_host_actions.py | RULCSoft/cloudroast | train | 1 | |
298693e7f10f8cebc2633ce6c24153030e0307eb | [
"device_ids = list()\noutput = run(cmd='idevice_id --list', timeout=60).output\nfor line in output.splitlines():\n command = 'instruments -s | grep {0}'.format(line)\n check_connected = run(cmd=command, timeout=30).output\n if 'null' not in check_connected:\n device_ids.append(line)\n else:\n ... | <|body_start_0|>
device_ids = list()
output = run(cmd='idevice_id --list', timeout=60).output
for line in output.splitlines():
command = 'instruments -s | grep {0}'.format(line)
check_connected = run(cmd=command, timeout=30).output
if 'null' not in check_conne... | IDevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDevice:
def get_devices():
"""Get available iOS devices (only real devices)."""
<|body_0|>
def get_screen(device_id, file_path):
"""Save screen of iOS real device. :param device_id: Device identifier. :param file_path: Path where image will be saved."""
<|bo... | stack_v2_sparse_classes_36k_train_018190 | 1,265 | no_license | [
{
"docstring": "Get available iOS devices (only real devices).",
"name": "get_devices",
"signature": "def get_devices()"
},
{
"docstring": "Save screen of iOS real device. :param device_id: Device identifier. :param file_path: Path where image will be saved.",
"name": "get_screen",
"sign... | 2 | null | Implement the Python class `IDevice` described below.
Class description:
Implement the IDevice class.
Method signatures and docstrings:
- def get_devices(): Get available iOS devices (only real devices).
- def get_screen(device_id, file_path): Save screen of iOS real device. :param device_id: Device identifier. :para... | Implement the Python class `IDevice` described below.
Class description:
Implement the IDevice class.
Method signatures and docstrings:
- def get_devices(): Get available iOS devices (only real devices).
- def get_screen(device_id, file_path): Save screen of iOS real device. :param device_id: Device identifier. :para... | 85e9662ab85c68a472b407e890656bcb73a87e70 | <|skeleton|>
class IDevice:
def get_devices():
"""Get available iOS devices (only real devices)."""
<|body_0|>
def get_screen(device_id, file_path):
"""Save screen of iOS real device. :param device_id: Device identifier. :param file_path: Path where image will be saved."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IDevice:
def get_devices():
"""Get available iOS devices (only real devices)."""
device_ids = list()
output = run(cmd='idevice_id --list', timeout=60).output
for line in output.splitlines():
command = 'instruments -s | grep {0}'.format(line)
check_connec... | the_stack_v2_python_sparse | core/utils/device/idevice.py | NativeScript/nativescript-tooling-qa | train | 5 | |
b2b8b4f88497903768626aee26ab4bb92bafaa5c | [
"info(' # Initializing system object ', verbosity.low)\nself.prefix = prefix\nself.init = init\nself.ensemble = ensemble\nself.motion = motion\nself.beads = beads\nself.cell = cell\nself.nm = nm\nself.fcomp = fcomponents\nself.forces = Forces()\nself.properties = Properties()\nself.trajs = Trajectories()",
"self.... | <|body_start_0|>
info(' # Initializing system object ', verbosity.low)
self.prefix = prefix
self.init = init
self.ensemble = ensemble
self.motion = motion
self.beads = beads
self.cell = cell
self.nm = nm
self.fcomp = fcomponents
self.forces... | Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must act on each replica forces: A Forces object that actually compute energy an... | System | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class System:
"""Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must act on each replica forces: A Forces obje... | stack_v2_sparse_classes_36k_train_018191 | 4,248 | no_license | [
{
"docstring": "Initialises System class. Args: init: A class to deal with initializing the system. beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomponents: A list of force components that are active for each replica of the system. bcomponents: A list of force com... | 2 | null | Implement the Python class `System` described below.
Class description:
Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must ac... | Implement the Python class `System` described below.
Class description:
Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must ac... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class System:
"""Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must act on each replica forces: A Forces obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class System:
"""Physical system object. Contains all the physical information. Also handles stepping and output. Attributes: beads: A beads object giving the atom positions. cell: A cell object giving the system box. fcomp: A list of force components that must act on each replica forces: A Forces object that actua... | the_stack_v2_python_sparse | ipi/engine/system.py | i-pi/i-pi | train | 170 |
6672c7fbec88521b4b10d6036dc0fbca29c310bc | [
"try:\n repository = CompanyRepository(session)\n companies = repository.get_all()\n return web.Response(text=json.dumps([company.to_dict() for company in companies]), status=200)\nexcept Exception as e:\n print(e)\n return web.Response(text='Ocorreu um erro no servidor. Por favor, tente novamente ma... | <|body_start_0|>
try:
repository = CompanyRepository(session)
companies = repository.get_all()
return web.Response(text=json.dumps([company.to_dict() for company in companies]), status=200)
except Exception as e:
print(e)
return web.Response(te... | CompaniesView Handles companies requests according to the situation | CompaniesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompaniesView:
"""CompaniesView Handles companies requests according to the situation"""
async def index(request):
"""Get a list of all companies"""
<|body_0|>
async def show(request):
"""Get company by id"""
<|body_1|>
async def store(request):
... | stack_v2_sparse_classes_36k_train_018192 | 2,812 | no_license | [
{
"docstring": "Get a list of all companies",
"name": "index",
"signature": "async def index(request)"
},
{
"docstring": "Get company by id",
"name": "show",
"signature": "async def show(request)"
},
{
"docstring": "Stores a new company",
"name": "store",
"signature": "as... | 4 | stack_v2_sparse_classes_30k_train_016871 | Implement the Python class `CompaniesView` described below.
Class description:
CompaniesView Handles companies requests according to the situation
Method signatures and docstrings:
- async def index(request): Get a list of all companies
- async def show(request): Get company by id
- async def store(request): Stores a... | Implement the Python class `CompaniesView` described below.
Class description:
CompaniesView Handles companies requests according to the situation
Method signatures and docstrings:
- async def index(request): Get a list of all companies
- async def show(request): Get company by id
- async def store(request): Stores a... | 41331d15a0ca8ca43a524746c7f4673b61affe18 | <|skeleton|>
class CompaniesView:
"""CompaniesView Handles companies requests according to the situation"""
async def index(request):
"""Get a list of all companies"""
<|body_0|>
async def show(request):
"""Get company by id"""
<|body_1|>
async def store(request):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompaniesView:
"""CompaniesView Handles companies requests according to the situation"""
async def index(request):
"""Get a list of all companies"""
try:
repository = CompanyRepository(session)
companies = repository.get_all()
return web.Response(text=j... | the_stack_v2_python_sparse | app/views/companies_view.py | gabriel-yuji-inoue/jeitto-backend-challenge-201901 | train | 0 |
508e9235d66e5f35c593940b775b72f23fe16623 | [
"driver = self.driver\ndriver.get(self.base_url)\nhomepage = HomePage(self.driver)\nhomepage.click_oa()\nhomepage.sleep(0.5)\nhomepage.click_fwgl()\nhomepage.click_cqxmgl()\nhomepage.sleep(0.1)\nhomepage.click_cqxmsq()\nhomepage.switch_frame(driver.find_element_by_xpath(\"//iframe[@src='http://oa2.eascs.com/eaoa/de... | <|body_start_0|>
driver = self.driver
driver.get(self.base_url)
homepage = HomePage(self.driver)
homepage.click_oa()
homepage.sleep(0.5)
homepage.click_fwgl()
homepage.click_cqxmgl()
homepage.sleep(0.1)
homepage.click_cqxmsq()
homepage.swit... | 超期项目管理 | Start | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Start:
"""超期项目管理"""
def test1_cqxmsq(self):
"""超期项目申请"""
<|body_0|>
def test2_lshsq(self):
"""律师函申请"""
<|body_1|>
def test3_sscxsq(self):
"""诉讼程序申请"""
<|body_2|>
def test4_lshtj(self):
"""律师函统计"""
<|body_3|>
<|en... | stack_v2_sparse_classes_36k_train_018193 | 3,738 | no_license | [
{
"docstring": "超期项目申请",
"name": "test1_cqxmsq",
"signature": "def test1_cqxmsq(self)"
},
{
"docstring": "律师函申请",
"name": "test2_lshsq",
"signature": "def test2_lshsq(self)"
},
{
"docstring": "诉讼程序申请",
"name": "test3_sscxsq",
"signature": "def test3_sscxsq(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_005157 | Implement the Python class `Start` described below.
Class description:
超期项目管理
Method signatures and docstrings:
- def test1_cqxmsq(self): 超期项目申请
- def test2_lshsq(self): 律师函申请
- def test3_sscxsq(self): 诉讼程序申请
- def test4_lshtj(self): 律师函统计 | Implement the Python class `Start` described below.
Class description:
超期项目管理
Method signatures and docstrings:
- def test1_cqxmsq(self): 超期项目申请
- def test2_lshsq(self): 律师函申请
- def test3_sscxsq(self): 诉讼程序申请
- def test4_lshtj(self): 律师函统计
<|skeleton|>
class Start:
"""超期项目管理"""
def test1_cqxmsq(self):
... | a90695147681163d45d4951f6a921eda816500bb | <|skeleton|>
class Start:
"""超期项目管理"""
def test1_cqxmsq(self):
"""超期项目申请"""
<|body_0|>
def test2_lshsq(self):
"""律师函申请"""
<|body_1|>
def test3_sscxsq(self):
"""诉讼程序申请"""
<|body_2|>
def test4_lshtj(self):
"""律师函统计"""
<|body_3|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Start:
"""超期项目管理"""
def test1_cqxmsq(self):
"""超期项目申请"""
driver = self.driver
driver.get(self.base_url)
homepage = HomePage(self.driver)
homepage.click_oa()
homepage.sleep(0.5)
homepage.click_fwgl()
homepage.click_cqxmgl()
homepage.s... | the_stack_v2_python_sparse | oa_test_case/oa_cqxmgl.py | shengli520/yyt | train | 0 |
ed46b5406f59f324d2bbeb561840472b956066c8 | [
"transform_or_spec = self._specs.get('transform_or_spec', self.transform_or_spec)\nif hasattr(transform_or_spec, '_batch'):\n transform_or_spec = transform_or_spec._batch(batch_size)\nreturn _DeferredTensorSpec(self._get_batched_input_spec(batch_size), transform_or_spec=transform_or_spec, dtype=self.dtype, shape... | <|body_start_0|>
transform_or_spec = self._specs.get('transform_or_spec', self.transform_or_spec)
if hasattr(transform_or_spec, '_batch'):
transform_or_spec = transform_or_spec._batch(batch_size)
return _DeferredTensorSpec(self._get_batched_input_spec(batch_size), transform_or_spec=t... | `tf.TypeSpec` for `tfp.util.DeferredTensor`. | _DeferredTensorBatchableSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DeferredTensorBatchableSpec:
"""`tf.TypeSpec` for `tfp.util.DeferredTensor`."""
def _batch(self, batch_size):
"""Returns a TypeSpec representing a batch of DeferredTensors."""
<|body_0|>
def _unbatch(self):
"""Returns a TypeSpec representing a single DeferredTen... | stack_v2_sparse_classes_36k_train_018194 | 37,367 | permissive | [
{
"docstring": "Returns a TypeSpec representing a batch of DeferredTensors.",
"name": "_batch",
"signature": "def _batch(self, batch_size)"
},
{
"docstring": "Returns a TypeSpec representing a single DeferredTensor.",
"name": "_unbatch",
"signature": "def _unbatch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021336 | Implement the Python class `_DeferredTensorBatchableSpec` described below.
Class description:
`tf.TypeSpec` for `tfp.util.DeferredTensor`.
Method signatures and docstrings:
- def _batch(self, batch_size): Returns a TypeSpec representing a batch of DeferredTensors.
- def _unbatch(self): Returns a TypeSpec representing... | Implement the Python class `_DeferredTensorBatchableSpec` described below.
Class description:
`tf.TypeSpec` for `tfp.util.DeferredTensor`.
Method signatures and docstrings:
- def _batch(self, batch_size): Returns a TypeSpec representing a batch of DeferredTensors.
- def _unbatch(self): Returns a TypeSpec representing... | 42a64ba0d9e0973b1707fcd9b8bd8d14b2d4e3e5 | <|skeleton|>
class _DeferredTensorBatchableSpec:
"""`tf.TypeSpec` for `tfp.util.DeferredTensor`."""
def _batch(self, batch_size):
"""Returns a TypeSpec representing a batch of DeferredTensors."""
<|body_0|>
def _unbatch(self):
"""Returns a TypeSpec representing a single DeferredTen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _DeferredTensorBatchableSpec:
"""`tf.TypeSpec` for `tfp.util.DeferredTensor`."""
def _batch(self, batch_size):
"""Returns a TypeSpec representing a batch of DeferredTensors."""
transform_or_spec = self._specs.get('transform_or_spec', self.transform_or_spec)
if hasattr(transform_or... | the_stack_v2_python_sparse | tensorflow_probability/python/util/deferred_tensor.py | tensorflow/probability | train | 4,055 |
3107882eb5c0a2f2ee6b84d8252664f5585f72ca | [
"rotation = 0\nfor direction, move in shift:\n if direction == 0:\n rotation += move\n else:\n rotation -= move\nrotation = rotation % len(s)\nprint(rotation)\nreturn s[rotation:] + s[:rotation]",
"s = list(s)\nfor pair in shift:\n side = pair[0]\n number_rotation = pair[1]\n if side ... | <|body_start_0|>
rotation = 0
for direction, move in shift:
if direction == 0:
rotation += move
else:
rotation -= move
rotation = rotation % len(s)
print(rotation)
return s[rotation:] + s[:rotation]
<|end_body_0|>
<|body_st... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def string_shift_optimized(self, s, shift):
"""Optimizing the number of shifting by canceling left and right shifts and perform the rotation once"""
<|body_0|>
def stringShift(self, s, shift):
""":type s: str :type shift: List[List[int]] :rtype: str"""
... | stack_v2_sparse_classes_36k_train_018195 | 2,057 | permissive | [
{
"docstring": "Optimizing the number of shifting by canceling left and right shifts and perform the rotation once",
"name": "string_shift_optimized",
"signature": "def string_shift_optimized(self, s, shift)"
},
{
"docstring": ":type s: str :type shift: List[List[int]] :rtype: str",
"name": ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def string_shift_optimized(self, s, shift): Optimizing the number of shifting by canceling left and right shifts and perform the rotation once
- def stringShift(self, s, shift): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def string_shift_optimized(self, s, shift): Optimizing the number of shifting by canceling left and right shifts and perform the rotation once
- def stringShift(self, s, shift): ... | 547c200b627c774535bc22880b16d5390183aeba | <|skeleton|>
class Solution:
def string_shift_optimized(self, s, shift):
"""Optimizing the number of shifting by canceling left and right shifts and perform the rotation once"""
<|body_0|>
def stringShift(self, s, shift):
""":type s: str :type shift: List[List[int]] :rtype: str"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def string_shift_optimized(self, s, shift):
"""Optimizing the number of shifting by canceling left and right shifts and perform the rotation once"""
rotation = 0
for direction, move in shift:
if direction == 0:
rotation += move
else:
... | the_stack_v2_python_sparse | perform_string_shift.py | Sukhrobjon/leetcode | train | 0 | |
6886fba10bdf115c4faf2c56c6f7f24405dd76dc | [
"self.all_under_hierarchy = all_under_hierarchy\nself.compact_version = compact_version\nself.consecutive_failures = consecutive_failures\nself.environment = environment\nself.exclude_users_within_alert_threshold = exclude_users_within_alert_threshold\nself.group_by = group_by\nself.health_status = health_status\ns... | <|body_start_0|>
self.all_under_hierarchy = all_under_hierarchy
self.compact_version = compact_version
self.consecutive_failures = consecutive_failures
self.environment = environment
self.exclude_users_within_alert_threshold = exclude_users_within_alert_threshold
self.gro... | Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subtenants of the given tenants should be considered for report generation. compact_version (string): Specifies the Cohe... | SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subten... | stack_v2_sparse_classes_36k_train_018196 | 8,990 | permissive | [
{
"docstring": "Constructor for the SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters class",
"name": "__init__",
"signature": "def __init__(self, all_under_hierarchy=None, compact_version=None, consecutive_failures=None, environment=None, exclude_users_within_alert_... | 2 | stack_v2_sparse_classes_30k_train_019662 | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_unde... | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_unde... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subten... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report_Parameters' model. TODO: type description here. Attributes: all_under_hierarchy (bool): Specifies if subtenants of the g... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduler_proto_scheduler_job_schedule_job_parameters_report_job_parameter_report_parameters.py | cohesity/management-sdk-python | train | 24 |
19be791fa0fc0b53c3108d969f07828e69a45ae3 | [
"def reverse(s, e):\n prev = ListNode(None)\n cur = s\n while prev != e:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\n return (e, s)\nif not head or not head.next:\n return head\nret = h = ListNode(None)\nh.next = head\ns = e = head\ncnt = 1\nwhile e:\n ... | <|body_start_0|>
def reverse(s, e):
prev = ListNode(None)
cur = s
while prev != e:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return (e, s)
if not head or not head.next:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""08/04/2018 22:49"""
<|body_0|>
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_018197 | 3,675 | no_license | [
{
"docstring": "08/04/2018 22:49",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(1)",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListN... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): 08/04/2018 22:49
- def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: Time complexity: O(n) Space complexity: O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): 08/04/2018 22:49
- def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: Time complexity: O(n) Space complexity: O(1)... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""08/04/2018 22:49"""
<|body_0|>
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseKGroup(self, head, k):
"""08/04/2018 22:49"""
def reverse(s, e):
prev = ListNode(None)
cur = s
while prev != e:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
... | the_stack_v2_python_sparse | leetcode/solved/25_Reverse_Nodes_in_k-Group/solution.py | sungminoh/algorithms | train | 0 | |
af9c289d7a581a5db9e93bd09144c091e3845e0a | [
"self._max_seq_length = max_seq_length\nself._max_predictions_per_seq = max_predictions_per_seq\nself._tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case=do_lower_case)\nself._label_map = label_map\nself._label_map_inverse = {v: k for k, v in self._label_map.items()}\nif fall_back_mode.lower() == 'ran... | <|body_start_0|>
self._max_seq_length = max_seq_length
self._max_predictions_per_seq = max_predictions_per_seq
self._tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case=do_lower_case)
self._label_map = label_map
self._label_map_inverse = {v: k for k, v in self._label... | Class for creating insertion examples. | InsertionConverter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsertionConverter:
"""Class for creating insertion examples."""
def __init__(self, max_seq_length, max_predictions_per_seq, label_map, vocab_file=None, do_lower_case=True, fall_back_mode='random'):
"""Initializes an instance of InsertionConverter. Args: max_seq_length: Maximum lengt... | stack_v2_sparse_classes_36k_train_018198 | 8,295 | permissive | [
{
"docstring": "Initializes an instance of InsertionConverter. Args: max_seq_length: Maximum length of source sequence. max_predictions_per_seq: Maximum number of MASK tokens. label_map: Dictionary to convert labels_ids to labels. vocab_file: Path to BERT vocabulary file. do_lower_case: text is lowercased. fall... | 3 | null | Implement the Python class `InsertionConverter` described below.
Class description:
Class for creating insertion examples.
Method signatures and docstrings:
- def __init__(self, max_seq_length, max_predictions_per_seq, label_map, vocab_file=None, do_lower_case=True, fall_back_mode='random'): Initializes an instance o... | Implement the Python class `InsertionConverter` described below.
Class description:
Class for creating insertion examples.
Method signatures and docstrings:
- def __init__(self, max_seq_length, max_predictions_per_seq, label_map, vocab_file=None, do_lower_case=True, fall_back_mode='random'): Initializes an instance o... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class InsertionConverter:
"""Class for creating insertion examples."""
def __init__(self, max_seq_length, max_predictions_per_seq, label_map, vocab_file=None, do_lower_case=True, fall_back_mode='random'):
"""Initializes an instance of InsertionConverter. Args: max_seq_length: Maximum lengt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsertionConverter:
"""Class for creating insertion examples."""
def __init__(self, max_seq_length, max_predictions_per_seq, label_map, vocab_file=None, do_lower_case=True, fall_back_mode='random'):
"""Initializes an instance of InsertionConverter. Args: max_seq_length: Maximum length of source s... | the_stack_v2_python_sparse | felix/insertion_converter.py | Jimmy-INL/google-research | train | 1 |
528b582250e00e5b35fa15d50ae99d0af19a14a9 | [
"base_model.BaseModel.__init__(self, name)\nif name in SphericalBody.pykep_bodies:\n self.body = bodies.PyKEPBody('%s' % name)\nelse:\n self.body = bodies.UnKnownBody('%s' % name, SphericalBody.unkown_bodies[name]['mu'], SphericalBody.unkown_bodies[name]['radius'], SphericalBody.unkown_bodies[name]['traj_file... | <|body_start_0|>
base_model.BaseModel.__init__(self, name)
if name in SphericalBody.pykep_bodies:
self.body = bodies.PyKEPBody('%s' % name)
else:
self.body = bodies.UnKnownBody('%s' % name, SphericalBody.unkown_bodies[name]['mu'], SphericalBody.unkown_bodies[name]['radius... | Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acceleration(): method inherits from Super-class. | SphericalBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalBody:
"""Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acceleration(): method inherits from Super-... | stack_v2_sparse_classes_36k_train_018199 | 1,557 | no_license | [
{
"docstring": "Constructor of the class SphericalBody.",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Method computing the potential acceleration of a given body as a perfect sphere. Returns a tensor 3*3.",
"name": "get_acceleration",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_val_000087 | Implement the Python class `SphericalBody` described below.
Class description:
Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acce... | Implement the Python class `SphericalBody` described below.
Class description:
Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acce... | 2dfb7f08d85aff241ca5fa1ae3f70720fdb8621d | <|skeleton|>
class SphericalBody:
"""Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acceleration(): method inherits from Super-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalBody:
"""Class giving the potential acceleration of body as a perfect sphere. This class inherits from class base_model.BaseModel. Attributes defined here: -body: instance of class PyKEPBody and / or class UnKnownBody. Method defined here: -get_acceleration(): method inherits from Super-class."""
... | the_stack_v2_python_sparse | src/model_tensor/gravitational/sphr.py | tobspm/TSX | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.