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
f51e1d097372a31ab33b82037a7d422a477cf4e6
[ "device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)\nif device_class in (cover.CoverDeviceClass.GARAGE, cover.CoverDeviceClass.GATE):\n return [DisplayCategory.GARAGE_DOOR]\nif device_class == cover.CoverDeviceClass.DOOR:\n return [DisplayCategory.DOOR]\nif device_class in (cover.CoverDeviceClass.BL...
<|body_start_0|> device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS) if device_class in (cover.CoverDeviceClass.GARAGE, cover.CoverDeviceClass.GATE): return [DisplayCategory.GARAGE_DOOR] if device_class == cover.CoverDeviceClass.DOOR: return [DisplayCategory.DOOR...
Class to represent Cover capabilities.
CoverCapabilities
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoverCapabilities: """Class to represent Cover capabilities.""" def default_display_categories(self) -> list[str]: """Return the display categories for this entity.""" <|body_0|> def interfaces(self) -> Generator[AlexaCapability, None, None]: """Yield the support...
stack_v2_sparse_classes_36k_train_023700
35,310
permissive
[ { "docstring": "Return the display categories for this entity.", "name": "default_display_categories", "signature": "def default_display_categories(self) -> list[str]" }, { "docstring": "Yield the supported interfaces.", "name": "interfaces", "signature": "def interfaces(self) -> Generat...
2
null
Implement the Python class `CoverCapabilities` described below. Class description: Class to represent Cover capabilities. Method signatures and docstrings: - def default_display_categories(self) -> list[str]: Return the display categories for this entity. - def interfaces(self) -> Generator[AlexaCapability, None, Non...
Implement the Python class `CoverCapabilities` described below. Class description: Class to represent Cover capabilities. Method signatures and docstrings: - def default_display_categories(self) -> list[str]: Return the display categories for this entity. - def interfaces(self) -> Generator[AlexaCapability, None, Non...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class CoverCapabilities: """Class to represent Cover capabilities.""" def default_display_categories(self) -> list[str]: """Return the display categories for this entity.""" <|body_0|> def interfaces(self) -> Generator[AlexaCapability, None, None]: """Yield the support...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CoverCapabilities: """Class to represent Cover capabilities.""" def default_display_categories(self) -> list[str]: """Return the display categories for this entity.""" device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS) if device_class in (cover.CoverDeviceClass.GARAGE, c...
the_stack_v2_python_sparse
homeassistant/components/alexa/entities.py
home-assistant/core
train
35,501
75c114df1443505704857b2feb4f6653eca15132
[ "self.left = left\nself.right = right\nself.key = key\nself.index = index\nself.color = color\nself.p = p", "if self.isnil() == True:\n return None\nreturn str({'key': self.key, 'index': self.index, 'color': self.color})", "if self.key == None and self.color == BLACK:\n return True\nreturn False" ]
<|body_start_0|> self.left = left self.right = right self.key = key self.index = index self.color = color self.p = p <|end_body_0|> <|body_start_1|> if self.isnil() == True: return None return str({'key': self.key, 'index': self.index, 'color'...
红黑树结点
RedBlackTreeNode
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedBlackTreeNode: """红黑树结点""" def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): """红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点""" <|body_0|> def __str__(self): ...
stack_v2_sparse_classes_36k_train_023701
13,604
permissive
[ { "docstring": "红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点", "name": "__init__", "signature": "def __init__(self, key, index=None, color=RED, p=None, left=None, right=None)" }, { "docstring": "str({'key' : self.key,...
3
stack_v2_sparse_classes_30k_train_014916
Implement the Python class `RedBlackTreeNode` described below. Class description: 红黑树结点 Method signatures and docstrings: - def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): 红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `...
Implement the Python class `RedBlackTreeNode` described below. Class description: 红黑树结点 Method signatures and docstrings: - def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): 红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `...
33662f46dc346203b220d7481d1a4439feda05d2
<|skeleton|> class RedBlackTreeNode: """红黑树结点""" def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): """红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点""" <|body_0|> def __str__(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedBlackTreeNode: """红黑树结点""" def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): """红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点""" self.left = left self.right = right ...
the_stack_v2_python_sparse
src/chapter13/redblacktree.py
HideLakitu/IntroductionToAlgorithm.Python
train
1
c5becd72d292bf6cd7634108df65922bbbe38004
[ "super().__init__()\nassert _type in ['poly', 'bernoulli']\nself.type = _type\nself._lambda = _lambda", "if self.type == 'bernoulli':\n train_xs = (train_xs > 0).astype(int)\nn, m = train_xs.shape\nunique_ys, counts = np.unique(train_ys, return_counts=True)\nself.unique_ys = unique_ys\ndenominator = n + self._...
<|body_start_0|> super().__init__() assert _type in ['poly', 'bernoulli'] self.type = _type self._lambda = _lambda <|end_body_0|> <|body_start_1|> if self.type == 'bernoulli': train_xs = (train_xs > 0).astype(int) n, m = train_xs.shape unique_ys, coun...
NaiveBayes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaiveBayes: def __init__(self, _type='poly', _lambda=1) -> None: """_type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子""" <|body_0|> def train(self, train_xs, train_ys): """训练 计算先验概率和似然概率""" <|body_1|> def test(self, test_xs, test_ys): """...
stack_v2_sparse_classes_36k_train_023702
4,232
no_license
[ { "docstring": "_type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子", "name": "__init__", "signature": "def __init__(self, _type='poly', _lambda=1) -> None" }, { "docstring": "训练 计算先验概率和似然概率", "name": "train", "signature": "def train(self, train_xs, train_ys)" }, { "docstri...
4
stack_v2_sparse_classes_30k_train_010884
Implement the Python class `NaiveBayes` described below. Class description: Implement the NaiveBayes class. Method signatures and docstrings: - def __init__(self, _type='poly', _lambda=1) -> None: _type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子 - def train(self, train_xs, train_ys): 训练 计算先验概率和似然概率 - def tes...
Implement the Python class `NaiveBayes` described below. Class description: Implement the NaiveBayes class. Method signatures and docstrings: - def __init__(self, _type='poly', _lambda=1) -> None: _type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子 - def train(self, train_xs, train_ys): 训练 计算先验概率和似然概率 - def tes...
cc9520554682172ba690cbcf517ac8fc5ec180b0
<|skeleton|> class NaiveBayes: def __init__(self, _type='poly', _lambda=1) -> None: """_type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子""" <|body_0|> def train(self, train_xs, train_ys): """训练 计算先验概率和似然概率""" <|body_1|> def test(self, test_xs, test_ys): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NaiveBayes: def __init__(self, _type='poly', _lambda=1) -> None: """_type ['poly','bernoulli'] 多项式朴素贝叶斯、伯努利朴素贝叶斯 _lambda 平滑因子""" super().__init__() assert _type in ['poly', 'bernoulli'] self.type = _type self._lambda = _lambda def train(self, train_xs, train_ys): ...
the_stack_v2_python_sparse
Code/naive_bayes.py
zgood9527/Basic4AI
train
2
6a5213458c196a2b2e09cf6b58f3d8ecd91d6c33
[ "self.degrees = degrees\nself.translate = translate\nself.scale = scale\nself.shear = shear\nself.fillcolor = fillcolor", "center = (image.shape[1] / 2, image.shape[0] / 2)\nangle = np.random.uniform(low=self.degrees[0], high=self.degrees[1])\nscale = np.random.uniform(low=self.scale[0], high=self.scale[1])\nR = ...
<|body_start_0|> self.degrees = degrees self.translate = translate self.scale = scale self.shear = shear self.fillcolor = fillcolor <|end_body_0|> <|body_start_1|> center = (image.shape[1] / 2, image.shape[0] / 2) angle = np.random.uniform(low=self.degrees[0], hi...
RandomAffine
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomAffine: def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127)): """随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平移量采样范围. 该参数为图像宽度和高度的百分比. scale : 缩放系数采样范围. shear : 剪切量采样范围. fillcolor: 无定义区域填充色.""" <|body_0|...
stack_v2_sparse_classes_36k_train_023703
10,684
permissive
[ { "docstring": "随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平移量采样范围. 该参数为图像宽度和高度的百分比. scale : 缩放系数采样范围. shear : 剪切量采样范围. fillcolor: 无定义区域填充色.", "name": "__init__", "signature": "def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127))" ...
2
stack_v2_sparse_classes_30k_train_006138
Implement the Python class `RandomAffine` described below. Class description: Implement the RandomAffine class. Method signatures and docstrings: - def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127)): 随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平...
Implement the Python class `RandomAffine` described below. Class description: Implement the RandomAffine class. Method signatures and docstrings: - def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127)): 随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平...
599bd6de74fc3794694bf1e3baca741d2b517e0e
<|skeleton|> class RandomAffine: def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127)): """随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平移量采样范围. 该参数为图像宽度和高度的百分比. scale : 缩放系数采样范围. shear : 剪切量采样范围. fillcolor: 无定义区域填充色.""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomAffine: def __init__(self, degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-2, 2), fillcolor=(127, 127, 127)): """随机的仿射变换. 参数 ---- degrees : 旋转角度采样范围. translate: 平移量采样范围. 该参数为图像宽度和高度的百分比. scale : 缩放系数采样范围. shear : 剪切量采样范围. fillcolor: 无定义区域填充色.""" self.degrees = degrees ...
the_stack_v2_python_sparse
transforms.py
CnybTseng/JDE
train
29
d989c89a5bbf3509a5868bb52389042b0d0eeeb8
[ "params = get_params(locals())\nraw_result = await self.api_request('getAdCategories', params)\nif return_raw_response:\n return raw_result\nresult = AdswebGetAdCategoriesResponse(**raw_result)\nreturn result", "params = get_params(locals())\nraw_result = await self.api_request('getAdUnitCode', params)\nif ret...
<|body_start_0|> params = get_params(locals()) raw_result = await self.api_request('getAdCategories', params) if return_raw_response: return raw_result result = AdswebGetAdCategoriesResponse(**raw_result) return result <|end_body_0|> <|body_start_1|> params =...
Adsweb
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Adsweb: async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]: """:param office_id: :param return_raw_response: - return result at dict :return:""" <|body_0|> async def get_ad_unit_code(self, r...
stack_v2_sparse_classes_36k_train_023704
4,634
permissive
[ { "docstring": ":param office_id: :param return_raw_response: - return result at dict :return:", "name": "get_ad_categories", "signature": "async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]" }, { "docstring": "...
6
null
Implement the Python class `Adsweb` described below. Class description: Implement the Adsweb class. Method signatures and docstrings: - async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]: :param office_id: :param return_raw_response:...
Implement the Python class `Adsweb` described below. Class description: Implement the Adsweb class. Method signatures and docstrings: - async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]: :param office_id: :param return_raw_response:...
d88311a680e52faf04f3a18f9c5b381ee9e94a8f
<|skeleton|> class Adsweb: async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]: """:param office_id: :param return_raw_response: - return result at dict :return:""" <|body_0|> async def get_ad_unit_code(self, r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Adsweb: async def get_ad_categories(self, office_id: int, return_raw_response: bool=False) -> typing.Union[dict, AdswebGetAdCategoriesResponse]: """:param office_id: :param return_raw_response: - return result at dict :return:""" params = get_params(locals()) raw_result = await self.ap...
the_stack_v2_python_sparse
vkwave/api/methods/adsweb.py
prog1ckg/vkwave
train
0
40e2651d98b08d59fadd5d303eb811d3ac6cb7c7
[ "gap = 0\nsibling = node + 1\nwhile node <= n:\n gap += min(n + 1, sibling) - node\n node *= 10\n sibling *= 10\nreturn gap", "node = 1\nsteps = 1\nwhile steps < k:\n gap = self.getGap(n, node)\n if steps + gap <= k:\n node += 1\n steps += gap\n else:\n node *= 10\n s...
<|body_start_0|> gap = 0 sibling = node + 1 while node <= n: gap += min(n + 1, sibling) - node node *= 10 sibling *= 10 return gap <|end_body_0|> <|body_start_1|> node = 1 steps = 1 while steps < k: gap = self.getGa...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" <|body_0|> def findKthNumber(self, n: int, k: int) -> int: """Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary...
stack_v2_sparse_classes_36k_train_023705
1,647
no_license
[ { "docstring": "Compute how many nodes between node and its next sibling", "name": "getGap", "signature": "def getGap(self, n: int, node: int) -> int" }, { "docstring": "Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary tree", "name": "findKthNumber", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getGap(self, n: int, node: int) -> int: Compute how many nodes between node and its next sibling - def findKthNumber(self, n: int, k: int) -> int: Similar to 386. Lexicograph...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getGap(self, n: int, node: int) -> int: Compute how many nodes between node and its next sibling - def findKthNumber(self, n: int, k: int) -> int: Similar to 386. Lexicograph...
ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653
<|skeleton|> class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" <|body_0|> def findKthNumber(self, n: int, k: int) -> int: """Similar to 386. Lexicographical Numbers This is essentially preorder traversal on 10-ary...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getGap(self, n: int, node: int) -> int: """Compute how many nodes between node and its next sibling""" gap = 0 sibling = node + 1 while node <= n: gap += min(n + 1, sibling) - node node *= 10 sibling *= 10 return gap ...
the_stack_v2_python_sparse
440 K-th Smallest in Lexicographical Order.py
jz33/LeetCodeSolutions
train
8
5c3940226ddcd00390d2a886d80e6c2a945af85e
[ "if len(prices) == 0:\n return 0\nleft = 0\nright = 1\nres = 0\nwhile right < len(prices):\n if prices[left] > prices[right]:\n left = right\n else:\n res += prices[right] - prices[left]\n left += 1\n right += 1\nreturn res", "result = 0\nfor i in range(1, len(prices)):\n if pr...
<|body_start_0|> if len(prices) == 0: return 0 left = 0 right = 1 res = 0 while right < len(prices): if prices[left] > prices[right]: left = right else: res += prices[right] - prices[left] left +=...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" <|body_0|> def maxProfit2(self, prices: List[int]) -> int: """官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(prices) == 0: ...
stack_v2_sparse_classes_36k_train_023706
2,357
no_license
[ { "docstring": "我的解法", "name": "maxProfit", "signature": "def maxProfit(self, prices: List[int]) -> int" }, { "docstring": "官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。", "name": "maxProfit2", "signature": "def maxProfit2(self, prices: List[int]) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 我的解法 - def maxProfit2(self, prices: List[int]) -> int: 官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 我的解法 - def maxProfit2(self, prices: List[int]) -> int: 官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。 <|skeleton|> class Solution: ...
6932d69353b94ec824dd0ddc86a92453f6673232
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" <|body_0|> def maxProfit2(self, prices: List[int]) -> int: """官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" if len(prices) == 0: return 0 left = 0 right = 1 res = 0 while right < len(prices): if prices[left] > prices[right]: left = right else: ...
the_stack_v2_python_sparse
0112_best-time-to-buy-and-sell-stock-ii.py
Nigirimeshi/leetcode
train
0
a8dd04b4a40c8d9a222c29135f0adbc68e2e85a5
[ "def dfs(nodes, comb, ans):\n if not nodes:\n ans.append(comb)\n return\n prev = None\n for i, node in enumerate(nodes):\n if node != prev:\n dfs(nodes[:i] + nodes[i + 1:], comb + [node], ans)\n prev = node\nans = []\nnums = sorted(nums)\ndfs(nums, [], ans)\nretur...
<|body_start_0|> def dfs(nodes, comb, ans): if not nodes: ans.append(comb) return prev = None for i, node in enumerate(nodes): if node != prev: dfs(nodes[:i] + nodes[i + 1:], comb + [node], ans) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def permuteUnique(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def permuteUnique_2(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> def dfs(nodes, ...
stack_v2_sparse_classes_36k_train_023707
1,650
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "permuteUnique", "signature": "def permuteUnique(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "permuteUnique_2", "signature": "def permuteUnique_2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_010325
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]] - def permuteUnique_2(self, nums): :type nums: List[int] :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]] - def permuteUnique_2(self, nums): :type nums: List[int] :rtype: List[List[int]] <|skeleton|> class ...
f2c4f727689567e00ee06560132fca55a6fd9286
<|skeleton|> class Solution: def permuteUnique(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def permuteUnique_2(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def permuteUnique(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" def dfs(nodes, comb, ans): if not nodes: ans.append(comb) return prev = None for i, node in enumerate(nodes): if node...
the_stack_v2_python_sparse
leetcode/47_Permutations_II.py
JianxiangWang/python-journey
train
1
652e099769f8e1bea3745242bb8a264afcda222e
[ "datetime_object = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)\nif not timestamp:\n if raise_error:\n raise ValueError('Missing timestamp value')\n return datetime_object.isoformat()\ntry:\n datetime_object += datetime.timedelta(microseconds=timestamp)\n datetime_object = datetime_...
<|body_start_0|> datetime_object = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC) if not timestamp: if raise_error: raise ValueError('Missing timestamp value') return datetime_object.isoformat() try: datetime_object += datetime.time...
Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.
Timestamp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timestamp: """Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.""" def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):...
stack_v2_sparse_classes_36k_train_023708
3,596
permissive
[ { "docstring": "Copies the timestamp to an ISO 8601 formatted string. Args: timestamp (int): a timestamp containing the number of microseconds since January 1, 1970, 00:00:00 UTC. timezone (Optional[pytz.timezone]): time zone. raise_error (Optional[bool]): True if an OverflowError should be raised if the timest...
2
null
Implement the Python class `Timestamp` described below. Class description: Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC. Method signatures and docstrings: - def Co...
Implement the Python class `Timestamp` described below. Class description: Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC. Method signatures and docstrings: - def Co...
c69b2952b608cfce47ff8fd0d1409d856be35cb1
<|skeleton|> class Timestamp: """Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.""" def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Timestamp: """Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.""" def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False): """C...
the_stack_v2_python_sparse
plaso/lib/timelib.py
cyb3rfox/plaso
train
3
076c85095c3f1a0bf1b0dcdd7f67ea3c7934fe9d
[ "msg = 'DiagnosticHandler.__call__ not '\nmsg += 'implemented for class %s' % self.__class__.__name__\nraise NotImplementedError(msg)", "try:\n executorInstance.report.parse(jobRepXml, executorInstance.stepName)\nexcept FwkJobReportException as ex:\n msg = 'Error reading XML job report file, possibly corrup...
<|body_start_0|> msg = 'DiagnosticHandler.__call__ not ' msg += 'implemented for class %s' % self.__class__.__name__ raise NotImplementedError(msg) <|end_body_0|> <|body_start_1|> try: executorInstance.report.parse(jobRepXml, executorInstance.stepName) except FwkJobR...
_DiagnosticHandler_ Interface definition for handlers for a specific error condition
DiagnosticHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiagnosticHandler: """_DiagnosticHandler_ Interface definition for handlers for a specific error condition""" def __call__(self, errorCode, executorInstance, **args): """_operator(errCode, executor)_ Override to act on a particular error, use the executorInstance to access things lik...
stack_v2_sparse_classes_36k_train_023709
2,313
permissive
[ { "docstring": "_operator(errCode, executor)_ Override to act on a particular error, use the executorInstance to access things like the step, logfiles, and report. Args will be used to provide extra information such as Exception instances etc", "name": "__call__", "signature": "def __call__(self, errorC...
2
null
Implement the Python class `DiagnosticHandler` described below. Class description: _DiagnosticHandler_ Interface definition for handlers for a specific error condition Method signatures and docstrings: - def __call__(self, errorCode, executorInstance, **args): _operator(errCode, executor)_ Override to act on a partic...
Implement the Python class `DiagnosticHandler` described below. Class description: _DiagnosticHandler_ Interface definition for handlers for a specific error condition Method signatures and docstrings: - def __call__(self, errorCode, executorInstance, **args): _operator(errCode, executor)_ Override to act on a partic...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class DiagnosticHandler: """_DiagnosticHandler_ Interface definition for handlers for a specific error condition""" def __call__(self, errorCode, executorInstance, **args): """_operator(errCode, executor)_ Override to act on a particular error, use the executorInstance to access things lik...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiagnosticHandler: """_DiagnosticHandler_ Interface definition for handlers for a specific error condition""" def __call__(self, errorCode, executorInstance, **args): """_operator(errCode, executor)_ Override to act on a particular error, use the executorInstance to access things like the step, l...
the_stack_v2_python_sparse
src/python/WMCore/WMSpec/Steps/Diagnostic.py
vkuznet/WMCore
train
0
0fd4ff92e290d8dddf392d0ed55e56290fb149eb
[ "def pre_search(t):\n if not t:\n self.res += '()'\n return\n elif not t.left and (not t.right):\n self.res += '('\n self.res += str(t.val)\n self.res += ')'\n elif not t.left:\n self.res += '('\n self.res += str(t.val)\n self.res += '()'\n if ...
<|body_start_0|> def pre_search(t): if not t: self.res += '()' return elif not t.left and (not t.right): self.res += '(' self.res += str(t.val) self.res += ')' elif not t.left: sel...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def tree2str(self, t): """:type t: TreeNode :rtype: str""" <|body_0|> def tree2str2(self, t): """:type t: TreeNode :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> def pre_search(t): if not t: self.re...
stack_v2_sparse_classes_36k_train_023710
1,490
no_license
[ { "docstring": ":type t: TreeNode :rtype: str", "name": "tree2str", "signature": "def tree2str(self, t)" }, { "docstring": ":type t: TreeNode :rtype: str", "name": "tree2str2", "signature": "def tree2str2(self, t)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def tree2str(self, t): :type t: TreeNode :rtype: str - def tree2str2(self, t): :type t: TreeNode :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def tree2str(self, t): :type t: TreeNode :rtype: str - def tree2str2(self, t): :type t: TreeNode :rtype: str <|skeleton|> class Solution: def tree2str(self, t): """...
4105e18050b15fc0409c75353ad31be17187dd34
<|skeleton|> class Solution: def tree2str(self, t): """:type t: TreeNode :rtype: str""" <|body_0|> def tree2str2(self, t): """:type t: TreeNode :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def tree2str(self, t): """:type t: TreeNode :rtype: str""" def pre_search(t): if not t: self.res += '()' return elif not t.left and (not t.right): self.res += '(' self.res += str(t.val) ...
the_stack_v2_python_sparse
tree2str.py
NeilWangziyu/Leetcode_py
train
2
162fd1e0c6bcf44241d4c11f077c73c1d1b1a905
[ "if root is None:\n return ''\ndata = []\ndeq = collections.deque([root])\nwhile deq:\n node = deq.popleft()\n data.append(node.val)\n data.append(str(0 if not node.children else len(node.children)))\n if node.children:\n for child in node.children:\n deq.append(child)\nreturn ','.j...
<|body_start_0|> if root is None: return '' data = [] deq = collections.deque([root]) while deq: node = deq.popleft() data.append(node.val) data.append(str(0 if not node.children else len(node.children))) if node.children: ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_36k_train_023711
3,144
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root: 'Node') -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def des...
2
stack_v2_sparse_classes_30k_train_010004
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" if root is None: return '' data = [] deq = collections.deque([root]) while deq: node = deq.popleft() data.append(no...
the_stack_v2_python_sparse
Leetcode 0428. Serialize and Deserialize N-ary Tree.py
Chaoran-sjsu/leetcode
train
0
00101883039da528f46212b989e9a65d29ff0dd1
[ "res = []\ni, j = (1, n)\nwhile i <= j:\n if k > 1:\n if k % 2 > 0:\n res.append(i)\n i += 1\n else:\n res.append(j)\n j -= 1\n k -= 1\n else:\n res.append(i)\n i += 1\nreturn res", "visited = [0] * (n + 1)\ndistinct = {}\nself.r...
<|body_start_0|> res = [] i, j = (1, n) while i <= j: if k > 1: if k % 2 > 0: res.append(i) i += 1 else: res.append(j) j -= 1 k -= 1 else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_0|> def constructArrayTLE(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [] ...
stack_v2_sparse_classes_36k_train_023712
2,816
no_license
[ { "docstring": ":type n: int :type k: int :rtype: List[int]", "name": "constructArray", "signature": "def constructArray(self, n, k)" }, { "docstring": ":type n: int :type k: int :rtype: List[int]", "name": "constructArrayTLE", "signature": "def constructArrayTLE(self, n, k)" } ]
2
stack_v2_sparse_classes_30k_train_015622
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructArray(self, n, k): :type n: int :type k: int :rtype: List[int] - def constructArrayTLE(self, n, k): :type n: int :type k: int :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def constructArray(self, n, k): :type n: int :type k: int :rtype: List[int] - def constructArrayTLE(self, n, k): :type n: int :type k: int :rtype: List[int] <|skeleton|> class S...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_0|> def constructArrayTLE(self, n, k): """:type n: int :type k: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def constructArray(self, n, k): """:type n: int :type k: int :rtype: List[int]""" res = [] i, j = (1, n) while i <= j: if k > 1: if k % 2 > 0: res.append(i) i += 1 else: ...
the_stack_v2_python_sparse
B/BeautifulArrangementII.py
bssrdf/pyleet
train
2
cdc3e1a8e6d8146c6adf7643d8fc722310a18e9a
[ "self.game = game\n\ndef policy(state, valid_actions):\n with torch.no_grad():\n outs = pi(torch.from_numpy(state).to(device).unsqueeze(0))\n value = outs.value.squeeze(0).cpu().numpy()\n logits = outs.dist.logits.squeeze(0)\n probs = F.softmax(logits[valid_actions], dim=0)\n p...
<|body_start_0|> self.game = game def policy(state, valid_actions): with torch.no_grad(): outs = pi(torch.from_numpy(state).to(device).unsqueeze(0)) value = outs.value.squeeze(0).cpu().numpy() logits = outs.dist.logits.squeeze(0) ...
Generate and store self play data.
SelfPlayManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelfPlayManager: """Generate and store self play data.""" def __init__(self, pi, game, game_buffer, device): """Init.""" <|body_0|> def play_game(self, n_sims): """Play a self play game.""" <|body_1|> def sample(self, batch_size): """Sample a...
stack_v2_sparse_classes_36k_train_023713
10,186
no_license
[ { "docstring": "Init.", "name": "__init__", "signature": "def __init__(self, pi, game, game_buffer, device)" }, { "docstring": "Play a self play game.", "name": "play_game", "signature": "def play_game(self, n_sims)" }, { "docstring": "Sample a batch of self play data.", "nam...
3
stack_v2_sparse_classes_30k_train_020385
Implement the Python class `SelfPlayManager` described below. Class description: Generate and store self play data. Method signatures and docstrings: - def __init__(self, pi, game, game_buffer, device): Init. - def play_game(self, n_sims): Play a self play game. - def sample(self, batch_size): Sample a batch of self ...
Implement the Python class `SelfPlayManager` described below. Class description: Generate and store self play data. Method signatures and docstrings: - def __init__(self, pi, game, game_buffer, device): Init. - def play_game(self, n_sims): Play a self play game. - def sample(self, batch_size): Sample a batch of self ...
e71c4b12955b01bfb907aa31c91ded6bcd8aaec8
<|skeleton|> class SelfPlayManager: """Generate and store self play data.""" def __init__(self, pi, game, game_buffer, device): """Init.""" <|body_0|> def play_game(self, n_sims): """Play a self play game.""" <|body_1|> def sample(self, batch_size): """Sample a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SelfPlayManager: """Generate and store self play data.""" def __init__(self, pi, game, game_buffer, device): """Init.""" self.game = game def policy(state, valid_actions): with torch.no_grad(): outs = pi(torch.from_numpy(state).to(device).unsqueeze(0))...
the_stack_v2_python_sparse
dl/rl/mcts/alpha_zero.py
cbschaff/dl
train
1
3d9d2c1496cfbfaf9ad9db461e58aaade6ba1c9a
[ "res = str(num)\nwhile len(res) != 1:\n res = str(sum((int(x) for x in str(res))))\nreturn int(res)", "if num is 0:\n return 0\nelse:\n temp = num % 9\n return 9 if temp is 0 else temp" ]
<|body_start_0|> res = str(num) while len(res) != 1: res = str(sum((int(x) for x in str(res)))) return int(res) <|end_body_0|> <|body_start_1|> if num is 0: return 0 else: temp = num % 9 return 9 if temp is 0 else temp <|end_body_1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def addDigits(self, num): """:type num: int :rtype: int""" <|body_0|> def addDigits2(self, num): """:type num: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = str(num) while len(res) != 1: res = st...
stack_v2_sparse_classes_36k_train_023714
748
no_license
[ { "docstring": ":type num: int :rtype: int", "name": "addDigits", "signature": "def addDigits(self, num)" }, { "docstring": ":type num: int :rtype: int", "name": "addDigits2", "signature": "def addDigits2(self, num)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def addDigits(self, num): :type num: int :rtype: int - def addDigits2(self, num): :type num: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def addDigits(self, num): :type num: int :rtype: int - def addDigits2(self, num): :type num: int :rtype: int <|skeleton|> class Solution: def addDigits(self, num): ...
baa3342ebe2600f365b9348455f6342e19866a44
<|skeleton|> class Solution: def addDigits(self, num): """:type num: int :rtype: int""" <|body_0|> def addDigits2(self, num): """:type num: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def addDigits(self, num): """:type num: int :rtype: int""" res = str(num) while len(res) != 1: res = str(sum((int(x) for x in str(res)))) return int(res) def addDigits2(self, num): """:type num: int :rtype: int""" if num is 0: ...
the_stack_v2_python_sparse
easy/Add_Digits.py
ChrisLiu95/Leetcode
train
0
79d6673f2d1754fc4c18586c7060752192a5b3fb
[ "parkDict = self.getDictBykey(self.__getOperatorParkConfigListView().json(), 'parkName', parkName)\nOldParkConfigDict = self.getOperatorParkConfigInfo(parkName)\nparkConfigDict = self.__setValueByAllkey(OldParkConfigDict, 'parkId', parkDict['parkId'])\nparkConfigDict = self.__setValueByAllkey(parkConfigDict, 'parkC...
<|body_start_0|> parkDict = self.getDictBykey(self.__getOperatorParkConfigListView().json(), 'parkName', parkName) OldParkConfigDict = self.getOperatorParkConfigInfo(parkName) parkConfigDict = self.__setValueByAllkey(OldParkConfigDict, 'parkId', parkDict['parkId']) parkConfigDict = self....
车场配置
ParkingSetting
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParkingSetting: """车场配置""" def updataOperatorParkCofigInfo(self, parkName, key, setValue): """修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return:""" <|body_0|> def getOperatorParkConfigInfo(self, parkName): ...
stack_v2_sparse_classes_36k_train_023715
3,319
no_license
[ { "docstring": "修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return:", "name": "updataOperatorParkCofigInfo", "signature": "def updataOperatorParkCofigInfo(self, parkName, key, setValue)" }, { "docstring": "获取车场配置信息", "name": "getOperat...
4
stack_v2_sparse_classes_30k_train_016490
Implement the Python class `ParkingSetting` described below. Class description: 车场配置 Method signatures and docstrings: - def updataOperatorParkCofigInfo(self, parkName, key, setValue): 修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return: - def getOperatorParkCon...
Implement the Python class `ParkingSetting` described below. Class description: 车场配置 Method signatures and docstrings: - def updataOperatorParkCofigInfo(self, parkName, key, setValue): 修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return: - def getOperatorParkCon...
34c368c109867da26d9256bca85f872b0fac2ea7
<|skeleton|> class ParkingSetting: """车场配置""" def updataOperatorParkCofigInfo(self, parkName, key, setValue): """修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return:""" <|body_0|> def getOperatorParkConfigInfo(self, parkName): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParkingSetting: """车场配置""" def updataOperatorParkCofigInfo(self, parkName, key, setValue): """修改车场配置 :param jsonObject: 车场原来配置 :param key: 需要修改的功能名(车牌强制转换,模糊匹配,...) :param setValue: 1(启用),0(禁用) :return:""" parkDict = self.getDictBykey(self.__getOperatorParkConfigListView().json(), 'parkNa...
the_stack_v2_python_sparse
Api/parkingConfig_service/parkingSetting.py
oyebino/pomp_api
train
1
b8238e555c40600d43782bf6ab249a37bc583b06
[ "class_id = request.POST.get('class_id')\nparams = request.POST.dict()\nparams['body'] = params.pop('content')\ngroup = None\ntry:\n group = Group.objects.get(pk=class_id)\nexcept Group.DoesNotExist:\n return rc.NOT_HERE\nif group and params['body']:\n c = MessageToClass(group=group, user=request.user, con...
<|body_start_0|> class_id = request.POST.get('class_id') params = request.POST.dict() params['body'] = params.pop('content') group = None try: group = Group.objects.get(pk=class_id) except Group.DoesNotExist: return rc.NOT_HERE if group and...
管理瓦片操作.
MessageActionHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageActionHandler: """管理瓦片操作.""" def post_to_class(self, request): """发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内容""" <|body_0|> def post(self, request): ...
stack_v2_sparse_classes_36k_train_023716
13,022
no_license
[ { "docstring": "发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内容", "name": "post_to_class", "signature": "def post_to_class(self, request)" }, { "docstring": "发送一条信息 ``POST`` `messages/crea...
3
null
Implement the Python class `MessageActionHandler` described below. Class description: 管理瓦片操作. Method signatures and docstrings: - def post_to_class(self, request): 发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内...
Implement the Python class `MessageActionHandler` described below. Class description: 管理瓦片操作. Method signatures and docstrings: - def post_to_class(self, request): 发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内...
1b1fbe4c66df731f63f10c57dee20cb0bb4edb4c
<|skeleton|> class MessageActionHandler: """管理瓦片操作.""" def post_to_class(self, request): """发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内容""" <|body_0|> def post(self, request): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageActionHandler: """管理瓦片操作.""" def post_to_class(self, request): """发送一条班级信息(群发) ``POST`` `messages/create_to_class/ <http://192.168.1.222:8080/v1/messages/create_to_class>`_ :param class_id: 接收班级的班级 id :param content: 发送内容""" class_id = request.POST.get('class_id') params = ...
the_stack_v2_python_sparse
apiv2/handlers/message.py
nuannuanwu/weixiao
train
1
5feb3dbf5dd1eb928654efc54b3027f2c7ee8866
[ "self.nums = 0\nself.data = []\nself.dataSet = {}", "if val not in self.dataSet:\n self.data.append(val)\n self.dataSet[val] = val\n self.nums += 1\n return True\nelse:\n return False", "if val in self.dataSet:\n self.data.remove(val)\n del self.dataSet[val]\n self.nums -= 1\n return ...
<|body_start_0|> self.nums = 0 self.data = [] self.dataSet = {} <|end_body_0|> <|body_start_1|> if val not in self.dataSet: self.data.append(val) self.dataSet[val] = val self.nums += 1 return True else: return False <|e...
RandomizedSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomizedSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the specified element.""" <|body_1|> def remove(se...
stack_v2_sparse_classes_36k_train_023717
1,475
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.", "name": "insert", "signature": "def insert(self, val: int) ...
4
stack_v2_sparse_classes_30k_train_003088
Implement the Python class `RandomizedSet` described below. Class description: Implement the RandomizedSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta...
Implement the Python class `RandomizedSet` described below. Class description: Implement the RandomizedSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta...
a42f45213c94d529f69a61f0bda92eddfe5bdfea
<|skeleton|> class RandomizedSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the specified element.""" <|body_1|> def remove(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomizedSet: def __init__(self): """Initialize your data structure here.""" self.nums = 0 self.data = [] self.dataSet = {} def insert(self, val: int) -> bool: """Inserts a value to the set. Returns true if the set did not already contain the specified element."""...
the_stack_v2_python_sparse
chap9/14.设计RamdomPool结构/O(N)_RandomizedSet.py
huang-jingwei/Coding-Interview-Guide
train
6
e37c7a2b403a5ea08a4c4dca7671bbb891921288
[ "super(Output, self).__init__()\nself.connecter = nn.Linear(interm_size, hidden_size)\nself.LayerNorm = LayerNorm(hidden_size)\nself.dropout = nn.Dropout(hidden_dropout_ratio)", "hidden_states = self.connecter(hidden_states)\nhidden_states = self.dropout(hidden_states)\nhidden_states = self.LayerNorm(hidden_state...
<|body_start_0|> super(Output, self).__init__() self.connecter = nn.Linear(interm_size, hidden_size) self.LayerNorm = LayerNorm(hidden_size) self.dropout = nn.Dropout(hidden_dropout_ratio) <|end_body_0|> <|body_start_1|> hidden_states = self.connecter(hidden_states) hidd...
Output Layer
Output
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Output: """Output Layer""" def __init__(self, interm_size, hidden_size, hidden_dropout_ratio): """Initialization""" <|body_0|> def forward(self, hidden_states, input_tensor): """Output block""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(...
stack_v2_sparse_classes_36k_train_023718
12,741
permissive
[ { "docstring": "Initialization", "name": "__init__", "signature": "def __init__(self, interm_size, hidden_size, hidden_dropout_ratio)" }, { "docstring": "Output block", "name": "forward", "signature": "def forward(self, hidden_states, input_tensor)" } ]
2
null
Implement the Python class `Output` described below. Class description: Output Layer Method signatures and docstrings: - def __init__(self, interm_size, hidden_size, hidden_dropout_ratio): Initialization - def forward(self, hidden_states, input_tensor): Output block
Implement the Python class `Output` described below. Class description: Output Layer Method signatures and docstrings: - def __init__(self, interm_size, hidden_size, hidden_dropout_ratio): Initialization - def forward(self, hidden_states, input_tensor): Output block <|skeleton|> class Output: """Output Layer""" ...
e6ab0261eb719c21806bbadfd94001ecfe27de45
<|skeleton|> class Output: """Output Layer""" def __init__(self, interm_size, hidden_size, hidden_dropout_ratio): """Initialization""" <|body_0|> def forward(self, hidden_states, input_tensor): """Output block""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Output: """Output Layer""" def __init__(self, interm_size, hidden_size, hidden_dropout_ratio): """Initialization""" super(Output, self).__init__() self.connecter = nn.Linear(interm_size, hidden_size) self.LayerNorm = LayerNorm(hidden_size) self.dropout = nn.Dropout...
the_stack_v2_python_sparse
apps/drug_target_interaction/moltrans_dti/double_towers.py
PaddlePaddle/PaddleHelix
train
771
7d99a8f2d15085cbb9b8f21f29c5400f4f37a6a0
[ "if sourceSplineObj is None:\n raise TypeError('Expect a spline object got {0}'.format(sourceSplineObj.__class__.__name__))\nif sourceSplineObj.IsInstanceOf(c4d.Onull):\n return None\nif not sourceSplineObj.IsInstanceOf(c4d.Oline) and (not sourceSplineObj.GetInfo() & c4d.OBJECT_ISSPLINE):\n raise TypeError...
<|body_start_0|> if sourceSplineObj is None: raise TypeError('Expect a spline object got {0}'.format(sourceSplineObj.__class__.__name__)) if sourceSplineObj.IsInstanceOf(c4d.Onull): return None if not sourceSplineObj.IsInstanceOf(c4d.Oline) and (not sourceSplineObj.GetInf...
SplineInputGeneratorHelper
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplineInputGeneratorHelper: def FinalSpline(sourceSplineObj): """Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.SplineObject or LineObject): A c4d.BaseObject that can be represented as a Spline. Returns: c4d.SplineObject: The fin...
stack_v2_sparse_classes_36k_train_023719
14,416
permissive
[ { "docstring": "Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.SplineObject or LineObject): A c4d.BaseObject that can be represented as a Spline. Returns: c4d.SplineObject: The final Spline/Line Object, SplineObject should be returned when it's possible...
4
stack_v2_sparse_classes_30k_test_000828
Implement the Python class `SplineInputGeneratorHelper` described below. Class description: Implement the SplineInputGeneratorHelper class. Method signatures and docstrings: - def FinalSpline(sourceSplineObj): Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.Sp...
Implement the Python class `SplineInputGeneratorHelper` described below. Class description: Implement the SplineInputGeneratorHelper class. Method signatures and docstrings: - def FinalSpline(sourceSplineObj): Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.Sp...
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class SplineInputGeneratorHelper: def FinalSpline(sourceSplineObj): """Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.SplineObject or LineObject): A c4d.BaseObject that can be represented as a Spline. Returns: c4d.SplineObject: The fin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SplineInputGeneratorHelper: def FinalSpline(sourceSplineObj): """Retrieves the final (deformed) representation of the spline. Args: sourceSplineObj (c4d.BaseObject or c4d.SplineObject or LineObject): A c4d.BaseObject that can be represented as a Spline. Returns: c4d.SplineObject: The final Spline/Line...
the_stack_v2_python_sparse
plugins/py-osffset_y_spline_r16/py-osffset_y_spline_r16.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
1d0d0fc24cfca0022dbda83b86f6cb95ae3b2a78
[ "self.message_handlers = [[] for i in range(self.NUMBER_OF_MESSAGE_TYPES)]\nself.lock = threading.Lock()\nself.logger = Logger().getLogger('backend.core.MessageBus')", "if isinstance(message_handler, MessageHandler):\n for key in message_priority_list:\n rule = (message_priority_list[key], message_handl...
<|body_start_0|> self.message_handlers = [[] for i in range(self.NUMBER_OF_MESSAGE_TYPES)] self.lock = threading.Lock() self.logger = Logger().getLogger('backend.core.MessageBus') <|end_body_0|> <|body_start_1|> if isinstance(message_handler, MessageHandler): for key in mess...
MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows which MessageHandlers are interested in which type of Messages. MessageBus is a...
MessageBus
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageBus: """MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows which MessageHandlers are interested in w...
stack_v2_sparse_classes_36k_train_023720
4,666
no_license
[ { "docstring": "Create a new MessageBus object.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Register a new MessageHandler to this MessageBus @param message_handler: MessageHandler object @param message_priority_list: Priority list for this MessageHandler", "nam...
4
stack_v2_sparse_classes_30k_train_019539
Implement the Python class `MessageBus` described below. Class description: MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows wh...
Implement the Python class `MessageBus` described below. Class description: MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows wh...
945463032481c3afdef56d0ef9f5be102829eb35
<|skeleton|> class MessageBus: """MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows which MessageHandlers are interested in w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageBus: """MessageBus is the heart of the backend messaging system. Almost all communication between components goes through this MessageBus. Components communicate with Messages, which are delivered to MessageHandlers via MessageBus. MessageBus knows which MessageHandlers are interested in which type of ...
the_stack_v2_python_sparse
entertainerlib/backend/core/message_bus.py
tiwilliam/entertainer
train
0
f218a16813a9351c677fdbc7a6ebe9d0242e2284
[ "QuestionTextsFormRecord._init_map(self)\nQuestionFilesFormRecord._init_map(self)\nsuper(QuestionTextsAndFilesMixin, self)._init_map()", "QuestionTextsFormRecord._init_metadata(self)\nQuestionFilesFormRecord._init_metadata(self)\nsuper(QuestionTextsAndFilesMixin, self)._init_metadata()" ]
<|body_start_0|> QuestionTextsFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextsAndFilesMixin, self)._init_map() <|end_body_0|> <|body_start_1|> QuestionTextsFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) ...
Mixin class to make the two classes compatible with super() for _init_map and _init_metadata
QuestionTextsAndFilesMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuestionTextsAndFilesMixin: """Mixin class to make the two classes compatible with super() for _init_map and _init_metadata""" def _init_map(self): """stub""" <|body_0|> def _init_metadata(self): """stub""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_023721
22,562
permissive
[ { "docstring": "stub", "name": "_init_map", "signature": "def _init_map(self)" }, { "docstring": "stub", "name": "_init_metadata", "signature": "def _init_metadata(self)" } ]
2
stack_v2_sparse_classes_30k_test_000235
Implement the Python class `QuestionTextsAndFilesMixin` described below. Class description: Mixin class to make the two classes compatible with super() for _init_map and _init_metadata Method signatures and docstrings: - def _init_map(self): stub - def _init_metadata(self): stub
Implement the Python class `QuestionTextsAndFilesMixin` described below. Class description: Mixin class to make the two classes compatible with super() for _init_map and _init_metadata Method signatures and docstrings: - def _init_map(self): stub - def _init_metadata(self): stub <|skeleton|> class QuestionTextsAndFi...
445f968a175d61c8d92c0f617a3c17dc1dc7c584
<|skeleton|> class QuestionTextsAndFilesMixin: """Mixin class to make the two classes compatible with super() for _init_map and _init_metadata""" def _init_map(self): """stub""" <|body_0|> def _init_metadata(self): """stub""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuestionTextsAndFilesMixin: """Mixin class to make the two classes compatible with super() for _init_map and _init_metadata""" def _init_map(self): """stub""" QuestionTextsFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextsAndFilesMixin, ...
the_stack_v2_python_sparse
dlkit/records/assessment/basic/simple_records.py
mitsei/dlkit
train
2
4048cbe6be8ba4a4182a4bdfb9b4255a31b77dcb
[ "if inorder_start >= inorder_end:\n return None\nroot = TreeNode(preorder[self.preorder_index])\nroot_index = inorder.index(preorder[self.preorder_index], inorder_start, inorder_end)\nself.preorder_index += 1\nroot.left = self.get_tree(preorder, inorder, inorder_start, root_index)\nroot.right = self.get_tree(pre...
<|body_start_0|> if inorder_start >= inorder_end: return None root = TreeNode(preorder[self.preorder_index]) root_index = inorder.index(preorder[self.preorder_index], inorder_start, inorder_end) self.preorder_index += 1 root.left = self.get_tree(preorder, inorder, ino...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def get_tree(self, preorder, inorder, inorder_start, inorder_end): """Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continues excluding stop index similar to xrange, we always use one index extra as in root.left recursiv...
stack_v2_sparse_classes_36k_train_023722
2,755
no_license
[ { "docstring": "Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continues excluding stop index similar to xrange, we always use one index extra as in root.left recursive call used root_index and not root_index-1 also from buildTree similar thing.", "na...
2
stack_v2_sparse_classes_30k_train_009436
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def get_tree(self, preorder, inorder, inorder_start, inorder_end): Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def get_tree(self, preorder, inorder, inorder_start, inorder_end): Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continu...
57212d700dfba0db4925d9d4896f7f0b9635a5b5
<|skeleton|> class Solution: def get_tree(self, preorder, inorder, inorder_start, inorder_end): """Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continues excluding stop index similar to xrange, we always use one index extra as in root.left recursiv...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def get_tree(self, preorder, inorder, inorder_start, inorder_end): """Note that since L.index(value, [start, [stop]]) -> integer -- return first index of value. where search continues excluding stop index similar to xrange, we always use one index extra as in root.left recursive call used ro...
the_stack_v2_python_sparse
binary_tree_from_inorder_and_preorder.py
baloooo/coding_practice
train
0
d38340b70346da8226d70da54cbc0adcc03b9172
[ "available_resource_types = ProjectType.objects.all().values_list('name', flat=True)\nfor r_type in resource_type:\n if r_type != 'all' and r_type.capitalize() not in available_resource_types:\n return False\nreturn True", "resource_type = self.request.GET.getlist('resource_type', ['all'])\nsearch_term ...
<|body_start_0|> available_resource_types = ProjectType.objects.all().values_list('name', flat=True) for r_type in resource_type: if r_type != 'all' and r_type.capitalize() not in available_resource_types: return False return True <|end_body_0|> <|body_start_1|> ...
Search for a Published Project using the get_content function inside Search Module's views.py
PublishedProjectSearch
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublishedProjectSearch: """Search for a Published Project using the get_content function inside Search Module's views.py""" def check_resource_type(self, resource_type): """Check if the resource_type requested is valid. Returns True if valid, else False""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_023723
4,436
permissive
[ { "docstring": "Check if the resource_type requested is valid. Returns True if valid, else False", "name": "check_resource_type", "signature": "def check_resource_type(self, resource_type)" }, { "docstring": "Modifying the get_queryset method to return the queryset based on the search_term and r...
3
null
Implement the Python class `PublishedProjectSearch` described below. Class description: Search for a Published Project using the get_content function inside Search Module's views.py Method signatures and docstrings: - def check_resource_type(self, resource_type): Check if the resource_type requested is valid. Returns...
Implement the Python class `PublishedProjectSearch` described below. Class description: Search for a Published Project using the get_content function inside Search Module's views.py Method signatures and docstrings: - def check_resource_type(self, resource_type): Check if the resource_type requested is valid. Returns...
304e093dc550da8636552dc601d6545c07ffc771
<|skeleton|> class PublishedProjectSearch: """Search for a Published Project using the get_content function inside Search Module's views.py""" def check_resource_type(self, resource_type): """Check if the resource_type requested is valid. Returns True if valid, else False""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PublishedProjectSearch: """Search for a Published Project using the get_content function inside Search Module's views.py""" def check_resource_type(self, resource_type): """Check if the resource_type requested is valid. Returns True if valid, else False""" available_resource_types = Proje...
the_stack_v2_python_sparse
physionet-django/export/views.py
MIT-LCP/physionet-build
train
50
7ee1314c5b7a024d8d711f298c47a22e3eebe767
[ "super(MySQLProgramsTable, self).__init__(db_dict, dbtype, verbose)\nself.connectdb(db_dict, verbose)\nself._load_table()", "cursor = self.connection.cursor()\nsql = 'INSERT INTO Program (ProgramName, StartDate, EndDate) VALUES (%s, %s, %s)'\ndata = (program_name, start_date, end_date)\ntry:\n cursor.execute(s...
<|body_start_0|> super(MySQLProgramsTable, self).__init__(db_dict, dbtype, verbose) self.connectdb(db_dict, verbose) self._load_table() <|end_body_0|> <|body_start_1|> cursor = self.connection.cursor() sql = 'INSERT INTO Program (ProgramName, StartDate, EndDate) VALUES (%s, %s, ...
Class representing the connection with a mysql database
MySQLProgramsTable
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySQLProgramsTable: """Class representing the connection with a mysql database""" def __init__(self, db_dict, dbtype, verbose): """Read the input file into a dictionary.""" <|body_0|> def insert(self, program_name, start_date, end_date): """Write a new record to ...
stack_v2_sparse_classes_36k_train_023724
9,672
permissive
[ { "docstring": "Read the input file into a dictionary.", "name": "__init__", "signature": "def __init__(self, db_dict, dbtype, verbose)" }, { "docstring": "Write a new record to the programs table of the database at the end of the database. Exceptions: TODO", "name": "insert", "signature...
3
null
Implement the Python class `MySQLProgramsTable` described below. Class description: Class representing the connection with a mysql database Method signatures and docstrings: - def __init__(self, db_dict, dbtype, verbose): Read the input file into a dictionary. - def insert(self, program_name, start_date, end_date): W...
Implement the Python class `MySQLProgramsTable` described below. Class description: Class representing the connection with a mysql database Method signatures and docstrings: - def __init__(self, db_dict, dbtype, verbose): Read the input file into a dictionary. - def insert(self, program_name, start_date, end_date): W...
9c60b3489f02592bd9099b8719ca23ae43a9eaa5
<|skeleton|> class MySQLProgramsTable: """Class representing the connection with a mysql database""" def __init__(self, db_dict, dbtype, verbose): """Read the input file into a dictionary.""" <|body_0|> def insert(self, program_name, start_date, end_date): """Write a new record to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MySQLProgramsTable: """Class representing the connection with a mysql database""" def __init__(self, db_dict, dbtype, verbose): """Read the input file into a dictionary.""" super(MySQLProgramsTable, self).__init__(db_dict, dbtype, verbose) self.connectdb(db_dict, verbose) ...
the_stack_v2_python_sparse
smipyping/_programstable.py
KSchopmeyer/smipyping
train
0
b5343630cc6fab3f7710a3209f3f9736ea9892e0
[ "super(CSVWindowsWriter, self).__init__(filename)\nself.data_file = None\nself.writer = None\nif filename:\n with open(filename, 'wb') as fp:\n fp.write(codecs.BOM_UTF8)\n self.data_file = open(filename, 'a', encoding='utf-8', newline='')\n self.writer = csv.writer(self.data_file, dialect='excel')",...
<|body_start_0|> super(CSVWindowsWriter, self).__init__(filename) self.data_file = None self.writer = None if filename: with open(filename, 'wb') as fp: fp.write(codecs.BOM_UTF8) self.data_file = open(filename, 'a', encoding='utf-8', newline='') ...
CSV file's writer.
CSVWindowsWriter
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CSVWindowsWriter: """CSV file's writer.""" def __init__(self, filename=None): """Args: filename: (String) data file's name. Returns: None""" <|body_0|> def writeln(self, line): """Write data line. Args: line: (List) Line data. Returns: boolean: Write success.""" ...
stack_v2_sparse_classes_36k_train_023725
6,679
permissive
[ { "docstring": "Args: filename: (String) data file's name. Returns: None", "name": "__init__", "signature": "def __init__(self, filename=None)" }, { "docstring": "Write data line. Args: line: (List) Line data. Returns: boolean: Write success.", "name": "writeln", "signature": "def writel...
3
null
Implement the Python class `CSVWindowsWriter` described below. Class description: CSV file's writer. Method signatures and docstrings: - def __init__(self, filename=None): Args: filename: (String) data file's name. Returns: None - def writeln(self, line): Write data line. Args: line: (List) Line data. Returns: boolea...
Implement the Python class `CSVWindowsWriter` described below. Class description: CSV file's writer. Method signatures and docstrings: - def __init__(self, filename=None): Args: filename: (String) data file's name. Returns: None - def writeln(self, line): Write data line. Args: line: (List) Line data. Returns: boolea...
5fa06b29bf800646dc4da5851fdf7a1f299f15a7
<|skeleton|> class CSVWindowsWriter: """CSV file's writer.""" def __init__(self, filename=None): """Args: filename: (String) data file's name. Returns: None""" <|body_0|> def writeln(self, line): """Write data line. Args: line: (List) Line data. Returns: boolean: Write success.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CSVWindowsWriter: """CSV file's writer.""" def __init__(self, filename=None): """Args: filename: (String) data file's name. Returns: None""" super(CSVWindowsWriter, self).__init__(filename) self.data_file = None self.writer = None if filename: with open...
the_stack_v2_python_sparse
muddery/common/utils/writers.py
muddery/muddery
train
139
3fc43052b05e733fc669cfd053336b2825dc65f9
[ "version_url = self._get_base_version_url()\nresp, body = self.raw_request(version_url, 'GET')\nself._error_checker(resp, body)\nself.expected_success(300, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)", "version = 'v%s' % version\nsupported = ['SUPPORTED', 'CURRENT']\nversion...
<|body_start_0|> version_url = self._get_base_version_url() resp, body = self.raw_request(version_url, 'GET') self._error_checker(resp, body) self.expected_success(300, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) <|end_body_0|> <|body...
VersionsClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VersionsClient: def list_versions(self): """List API versions""" <|body_0|> def has_version(self, version): """Return True if a version is supported.""" <|body_1|> <|end_skeleton|> <|body_start_0|> version_url = self._get_base_version_url() ...
stack_v2_sparse_classes_36k_train_023726
1,531
permissive
[ { "docstring": "List API versions", "name": "list_versions", "signature": "def list_versions(self)" }, { "docstring": "Return True if a version is supported.", "name": "has_version", "signature": "def has_version(self, version)" } ]
2
stack_v2_sparse_classes_30k_train_005604
Implement the Python class `VersionsClient` described below. Class description: Implement the VersionsClient class. Method signatures and docstrings: - def list_versions(self): List API versions - def has_version(self, version): Return True if a version is supported.
Implement the Python class `VersionsClient` described below. Class description: Implement the VersionsClient class. Method signatures and docstrings: - def list_versions(self): List API versions - def has_version(self, version): Return True if a version is supported. <|skeleton|> class VersionsClient: def list_...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class VersionsClient: def list_versions(self): """List API versions""" <|body_0|> def has_version(self, version): """Return True if a version is supported.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VersionsClient: def list_versions(self): """List API versions""" version_url = self._get_base_version_url() resp, body = self.raw_request(version_url, 'GET') self._error_checker(resp, body) self.expected_success(300, resp.status) body = json.loads(body) ...
the_stack_v2_python_sparse
tempest/lib/services/image/v2/versions_client.py
openstack/tempest
train
270
fbd1b5d939565c484d46a3d31600f17e87d12b91
[ "person1_instance = User.objects.get(username=person1).id\nperson2_instance = User.objects.get(username=person2).id\ntry:\n instance_1 = Friend.objects.get(sender=person1_instance, receiver=person2_instance)\n return (instance_1, 1)\nexcept Friend.DoesNotExist:\n instance_1 = None\nif instance_1 is None:\n...
<|body_start_0|> person1_instance = User.objects.get(username=person1).id person2_instance = User.objects.get(username=person2).id try: instance_1 = Friend.objects.get(sender=person1_instance, receiver=person2_instance) return (instance_1, 1) except Friend.DoesNot...
FriendManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FriendManager: def get_friend_status(self, person1, person2): """:param person1: :param person2: :return: The resulting row_instance if present in Table or None""" <|body_0|> def add_friend_request(self, sender, receiver): """This function will add the friends Reques...
stack_v2_sparse_classes_36k_train_023727
5,352
no_license
[ { "docstring": ":param person1: :param person2: :return: The resulting row_instance if present in Table or None", "name": "get_friend_status", "signature": "def get_friend_status(self, person1, person2)" }, { "docstring": "This function will add the friends Request for person1 and person2 i.e. i...
2
stack_v2_sparse_classes_30k_train_006740
Implement the Python class `FriendManager` described below. Class description: Implement the FriendManager class. Method signatures and docstrings: - def get_friend_status(self, person1, person2): :param person1: :param person2: :return: The resulting row_instance if present in Table or None - def add_friend_request(...
Implement the Python class `FriendManager` described below. Class description: Implement the FriendManager class. Method signatures and docstrings: - def get_friend_status(self, person1, person2): :param person1: :param person2: :return: The resulting row_instance if present in Table or None - def add_friend_request(...
89e6fae406c33e2c2ef3884be5af68817d2f9413
<|skeleton|> class FriendManager: def get_friend_status(self, person1, person2): """:param person1: :param person2: :return: The resulting row_instance if present in Table or None""" <|body_0|> def add_friend_request(self, sender, receiver): """This function will add the friends Reques...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FriendManager: def get_friend_status(self, person1, person2): """:param person1: :param person2: :return: The resulting row_instance if present in Table or None""" person1_instance = User.objects.get(username=person1).id person2_instance = User.objects.get(username=person2).id ...
the_stack_v2_python_sparse
chitchat/models.py
pranjalpranjal/UNO-Game
train
0
8f448d07e3a4156ac1896bb840000ab5da4bdf17
[ "self.path = path\nif over_write and os.path.exists(path):\n os.remove(path)\n print('删除旧版本的{}'.format(path))\nself.print_flag = print_flag", "with open(self.path, mode='a', encoding='utf8') as f:\n f.write(str + '\\n')\n f.flush()\nif self.print_flag:\n print(str)" ]
<|body_start_0|> self.path = path if over_write and os.path.exists(path): os.remove(path) print('删除旧版本的{}'.format(path)) self.print_flag = print_flag <|end_body_0|> <|body_start_1|> with open(self.path, mode='a', encoding='utf8') as f: f.write(str + '...
Logger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logger: def __init__(self, path, over_write=True, print_flag=False): """Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。""" <|body_0|> def log(self, str): """记录log :param str:log内容。 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_36k_train_023728
977
permissive
[ { "docstring": "Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。", "name": "__init__", "signature": "def __init__(self, path, over_write=True, print_flag=False)" }, { "docstring": "记录log :param str:log内容。 :return:", "name": "log", "signature": "def log(self, str)" } ]
2
stack_v2_sparse_classes_30k_train_016225
Implement the Python class `Logger` described below. Class description: Implement the Logger class. Method signatures and docstrings: - def __init__(self, path, over_write=True, print_flag=False): Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。 - def log(self, str): 记录log :param str:log内容。 :return:
Implement the Python class `Logger` described below. Class description: Implement the Logger class. Method signatures and docstrings: - def __init__(self, path, over_write=True, print_flag=False): Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。 - def log(self, str): 记录log :param str:log内容。 :return: <|skeleto...
b47d05f0bb233ff0b807a0d363d48e43fa29b34a
<|skeleton|> class Logger: def __init__(self, path, over_write=True, print_flag=False): """Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。""" <|body_0|> def log(self, str): """记录log :param str:log内容。 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Logger: def __init__(self, path, over_write=True, print_flag=False): """Logger工具。 :param path:log文件位置。 :param over_write: 是否覆盖。""" self.path = path if over_write and os.path.exists(path): os.remove(path) print('删除旧版本的{}'.format(path)) self.print_flag = p...
the_stack_v2_python_sparse
public_tools/logger.py
iverxin/ml_impl
train
3
f74fffda2e44cd45ecff10231329b6c05d673be2
[ "client = pm.MongoClient(host=os.environ.get('DB_HOSTNAME'), port=int(os.environ.get('DB_PORT')))\ndb_collection = client[mongo_db][mongo_collection]\nself.asset_actions = list(db_collection.find({'networkNodes': asset_id}))", "if len(self.asset_actions) > 0:\n highest_score = 0\n for action in self.asset_a...
<|body_start_0|> client = pm.MongoClient(host=os.environ.get('DB_HOSTNAME'), port=int(os.environ.get('DB_PORT'))) db_collection = client[mongo_db][mongo_collection] self.asset_actions = list(db_collection.find({'networkNodes': asset_id})) <|end_body_0|> <|body_start_1|> if len(self.asse...
GetActionDetails
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetActionDetails: def __init__(self, mongo_db, mongo_collection, asset_id): """Initiate by getting all actions for the given `asset_id`""" <|body_0|> def get_highest_priority_action(self): """Retrieve the Object ID of the action relating to the `asset_id` with the hi...
stack_v2_sparse_classes_36k_train_023729
2,872
no_license
[ { "docstring": "Initiate by getting all actions for the given `asset_id`", "name": "__init__", "signature": "def __init__(self, mongo_db, mongo_collection, asset_id)" }, { "docstring": "Retrieve the Object ID of the action relating to the `asset_id` with the highest `priorityScore`", "name":...
2
stack_v2_sparse_classes_30k_train_008790
Implement the Python class `GetActionDetails` described below. Class description: Implement the GetActionDetails class. Method signatures and docstrings: - def __init__(self, mongo_db, mongo_collection, asset_id): Initiate by getting all actions for the given `asset_id` - def get_highest_priority_action(self): Retrie...
Implement the Python class `GetActionDetails` described below. Class description: Implement the GetActionDetails class. Method signatures and docstrings: - def __init__(self, mongo_db, mongo_collection, asset_id): Initiate by getting all actions for the given `asset_id` - def get_highest_priority_action(self): Retrie...
aee9661c07429697b836f7140c76648eca7fa9d4
<|skeleton|> class GetActionDetails: def __init__(self, mongo_db, mongo_collection, asset_id): """Initiate by getting all actions for the given `asset_id`""" <|body_0|> def get_highest_priority_action(self): """Retrieve the Object ID of the action relating to the `asset_id` with the hi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetActionDetails: def __init__(self, mongo_db, mongo_collection, asset_id): """Initiate by getting all actions for the given `asset_id`""" client = pm.MongoClient(host=os.environ.get('DB_HOSTNAME'), port=int(os.environ.get('DB_PORT'))) db_collection = client[mongo_db][mongo_collection]...
the_stack_v2_python_sparse
src/backend/api/database_options.py
O1sims/Pax
train
4
fe4780221cd30b0dff5637e8a42626e083c616f9
[ "l, r = (0, len(nums) - 1)\nwhile l <= r:\n mid = l + (r - l) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n l = mid + 1\n else:\n r = mid - 1\nreturn -1", "import bisect\nindex = bisect.bisect_left(nums, target)\nreturn index if index < len(nums) and num...
<|body_start_0|> l, r = (0, len(nums) - 1) while l <= r: mid = l + (r - l) // 2 if nums[mid] == target: return mid elif nums[mid] < target: l = mid + 1 else: r = mid - 1 return -1 <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def search_bisect(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_023730
880
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "search", "signature": "def search(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: int", "name": "search_bisect", "signature": "def search_bisect(self, nums, target)" }...
2
stack_v2_sparse_classes_30k_val_000976
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def search_bisect(self, nums, target): :type nums: List[int] :type target: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int - def search_bisect(self, nums, target): :type nums: List[int] :type target: int :rtype: int ...
85f71621c54f6b0029f3a2746f022f89dd7419d9
<|skeleton|> class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_0|> def search_bisect(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def search(self, nums, target): """:type nums: List[int] :type target: int :rtype: int""" l, r = (0, len(nums) - 1) while l <= r: mid = l + (r - l) // 2 if nums[mid] == target: return mid elif nums[mid] < target: ...
the_stack_v2_python_sparse
LeetCode/BinarySearch/704_binary_search.py
XyK0907/for_work
train
0
dd0b014422a05e3a443097c714a452d4d2dd0600
[ "batch_size = 10\nnb_visible = 15\nnb_hidden = 10\nnb_z = 2\nvisible_units = numpy.random.normal(loc=0.0, scale=1.0, size=(batch_size, nb_visible))\nvariational_ae_0 = VariationalAutoencoder(nb_visible, nb_hidden, nb_z, True, 0.3)\nvariational_ae_0.backpropagation(visible_units, is_checking=True, path_to_checking_g...
<|body_start_0|> batch_size = 10 nb_visible = 15 nb_hidden = 10 nb_z = 2 visible_units = numpy.random.normal(loc=0.0, scale=1.0, size=(batch_size, nb_visible)) variational_ae_0 = VariationalAutoencoder(nb_visible, nb_hidden, nb_z, True, 0.3) variational_ae_0.backp...
Class for testing two methods of class `VariationalAutoencoder`.
TesterVariationalAutoencoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TesterVariationalAutoencoder: """Class for testing two methods of class `VariationalAutoencoder`.""" def test_backpropagation(self): """Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via ...
stack_v2_sparse_classes_36k_train_023731
4,566
no_license
[ { "docstring": "Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via gradient checking, see <http://ufldl.stanford.edu/wiki/index.php/Gradient_checking_and_advanced_optimization>. Six histograms are saved in the folde...
2
stack_v2_sparse_classes_30k_train_007205
Implement the Python class `TesterVariationalAutoencoder` described below. Class description: Class for testing two methods of class `VariationalAutoencoder`. Method signatures and docstrings: - def test_backpropagation(self): Tests the method `backpropagation`. The method `backpropagation` computes the gradients of ...
Implement the Python class `TesterVariationalAutoencoder` described below. Class description: Class for testing two methods of class `VariationalAutoencoder`. Method signatures and docstrings: - def test_backpropagation(self): Tests the method `backpropagation`. The method `backpropagation` computes the gradients of ...
17583bbbddeaf40b14bcfe816c061b8fed6bb5df
<|skeleton|> class TesterVariationalAutoencoder: """Class for testing two methods of class `VariationalAutoencoder`.""" def test_backpropagation(self): """Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TesterVariationalAutoencoder: """Class for testing two methods of class `VariationalAutoencoder`.""" def test_backpropagation(self): """Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via gradient chec...
the_stack_v2_python_sparse
svhn/test_vae.py
edmontdants/autoencoder_based_image_compression
train
0
a0ea0cd70639757dd60116262695c773adc246ac
[ "assert self.method in self._allowed_methods\nif sess is None:\n sess = aiohttp.ClientSession()\nelse:\n assert isinstance(sess, aiohttp.ClientSession)\nwith sess:\n if self.content_type == 'multipart/form-data':\n with aiohttp.MultipartWriter('mixed') as mpwriter:\n for file in self._con...
<|body_start_0|> assert self.method in self._allowed_methods if sess is None: sess = aiohttp.ClientSession() else: assert isinstance(sess, aiohttp.ClientSession) with sess: if self.content_type == 'multipart/form-data': with aiohttp.Mul...
AsyncRequestMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsyncRequestMixin: async def asend(self, *, sess=None, timeout=10.0): """Sends the request to the server. This method is a coroutine.""" <|body_0|> async def connect_websocket(self, sess=None): """Creates a WebSocket connection.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_023732
10,302
permissive
[ { "docstring": "Sends the request to the server. This method is a coroutine.", "name": "asend", "signature": "async def asend(self, *, sess=None, timeout=10.0)" }, { "docstring": "Creates a WebSocket connection.", "name": "connect_websocket", "signature": "async def connect_websocket(sel...
2
stack_v2_sparse_classes_30k_train_003319
Implement the Python class `AsyncRequestMixin` described below. Class description: Implement the AsyncRequestMixin class. Method signatures and docstrings: - async def asend(self, *, sess=None, timeout=10.0): Sends the request to the server. This method is a coroutine. - async def connect_websocket(self, sess=None): ...
Implement the Python class `AsyncRequestMixin` described below. Class description: Implement the AsyncRequestMixin class. Method signatures and docstrings: - async def asend(self, *, sess=None, timeout=10.0): Sends the request to the server. This method is a coroutine. - async def connect_websocket(self, sess=None): ...
952690624173b0b46786d9654af7daf29f2bfb05
<|skeleton|> class AsyncRequestMixin: async def asend(self, *, sess=None, timeout=10.0): """Sends the request to the server. This method is a coroutine.""" <|body_0|> async def connect_websocket(self, sess=None): """Creates a WebSocket connection.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AsyncRequestMixin: async def asend(self, *, sess=None, timeout=10.0): """Sends the request to the server. This method is a coroutine.""" assert self.method in self._allowed_methods if sess is None: sess = aiohttp.ClientSession() else: assert isinstance(s...
the_stack_v2_python_sparse
ai/backend/client/request.py
choi-jinil/backend.ai-client-py
train
0
0b3d8c1b6fb3a8c69a41edbb0845b2033244acb9
[ "self.level = level\nself.stateMap = stateMap\nself.default = defState", "if nextState in self.stateMap:\n return nextState\ndefaultNext = 1 and self.default or nextState\nreturn defaultNext" ]
<|body_start_0|> self.level = level self.stateMap = stateMap self.default = defState <|end_body_0|> <|body_start_1|> if nextState in self.stateMap: return nextState defaultNext = 1 and self.default or nextState return defaultNext <|end_body_1|>
State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level.
State
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class State: """State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level.""" def __init__(self, level, stateMap=list(), defState=None): """Constructor. examples: >>> s0 = State( 100 ) >>> s1 = State( 0, [ '...
stack_v2_sparse_classes_36k_train_023733
9,409
no_license
[ { "docstring": "Constructor. examples: >>> s0 = State( 100 ) >>> s1 = State( 0, [ 'StateName1', 'StateName2' ], defState = 'StateName1' ) >>> s2 = State( 0, [ 'StateName1', 'StateName2' ] ) # this example is tricky. The transition rule says that will go to # nextState, e.g. 'StateNext'. But, it is not on the st...
2
stack_v2_sparse_classes_30k_train_012874
Implement the Python class `State` described below. Class description: State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level. Method signatures and docstrings: - def __init__(self, level, stateMap=list(), defState=None): Constructo...
Implement the Python class `State` described below. Class description: State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level. Method signatures and docstrings: - def __init__(self, level, stateMap=list(), defState=None): Constructo...
1a6a337f7049067c0046cfd3c64f35aea987477d
<|skeleton|> class State: """State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level.""" def __init__(self, level, stateMap=list(), defState=None): """Constructor. examples: >>> s0 = State( 100 ) >>> s1 = State( 0, [ '...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class State: """State class that represents a single step on a StateMachine, with all the possible transitions, the default transition and an ordering level.""" def __init__(self, level, stateMap=list(), defState=None): """Constructor. examples: >>> s0 = State( 100 ) >>> s1 = State( 0, [ 'StateName1', ...
the_stack_v2_python_sparse
ResourceStatusSystem/PolicySystem/StateMachine.py
madamFZU/DIRAC
train
0
015bd162295b862ddbf4743fb5fa34370b1aeeac
[ "r = s[::-1]\nfor i in range(len(s)):\n s[i] = r[i]", "length = len(s)\nfor i in range(length / 2):\n s[i], s[length - 1 - i] = (s[length - 1 - i], s[i])", "i = 0\nj = len(s) - 1\nwhile i < j:\n t = s[i]\n s[i] = s[j]\n s[j] = t\n i += 1\n j -= 1" ]
<|body_start_0|> r = s[::-1] for i in range(len(s)): s[i] = r[i] <|end_body_0|> <|body_start_1|> length = len(s) for i in range(length / 2): s[i], s[length - 1 - i] = (s[length - 1 - i], s[i]) <|end_body_1|> <|body_start_2|> i = 0 j = len(s) - 1 ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _reverseString(self, s): """:type s: List[str] :rtype: None Do not return anything, modify s in-place instead.""" <|body_0|> def __reverseString(self, s): """:type s: List[str] :rtype: None Do not return anything, modify s in-place instead.""" <...
stack_v2_sparse_classes_36k_train_023734
1,631
permissive
[ { "docstring": ":type s: List[str] :rtype: None Do not return anything, modify s in-place instead.", "name": "_reverseString", "signature": "def _reverseString(self, s)" }, { "docstring": ":type s: List[str] :rtype: None Do not return anything, modify s in-place instead.", "name": "__reverse...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _reverseString(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. - def __reverseString(self, s): :type s: List[str] :rtype: None Do...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _reverseString(self, s): :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. - def __reverseString(self, s): :type s: List[str] :rtype: None Do...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _reverseString(self, s): """:type s: List[str] :rtype: None Do not return anything, modify s in-place instead.""" <|body_0|> def __reverseString(self, s): """:type s: List[str] :rtype: None Do not return anything, modify s in-place instead.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _reverseString(self, s): """:type s: List[str] :rtype: None Do not return anything, modify s in-place instead.""" r = s[::-1] for i in range(len(s)): s[i] = r[i] def __reverseString(self, s): """:type s: List[str] :rtype: None Do not return anythi...
the_stack_v2_python_sparse
344.reverse-string.py
windard/leeeeee
train
0
226a979165e8ad3415533729e51588f595d2bd0c
[ "raw_df = next(load_data([input_file], shard_size=None))\nself.splits = raw_df[split_field].values\nself.verbose = verbose", "train_inds, valid_inds, test_inds = ([], [], [])\nfor ind, split in enumerate(self.splits):\n split = split.lower()\n if split == 'train':\n train_inds.append(ind)\n elif s...
<|body_start_0|> raw_df = next(load_data([input_file], shard_size=None)) self.splits = raw_df[split_field].values self.verbose = verbose <|end_body_0|> <|body_start_1|> train_inds, valid_inds, test_inds = ([], [], []) for ind, split in enumerate(self.splits): split =...
Class that splits data according to user specification.
SpecifiedSplitter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpecifiedSplitter: """Class that splits data according to user specification.""" def __init__(self, input_file, split_field, verbose=False): """Provide input information for splits.""" <|body_0|> def split(self, dataset, frac_train=0.8, frac_valid=0.1, frac_test=0.1, log...
stack_v2_sparse_classes_36k_train_023735
26,497
permissive
[ { "docstring": "Provide input information for splits.", "name": "__init__", "signature": "def __init__(self, input_file, split_field, verbose=False)" }, { "docstring": "Splits internal compounds into train/validation/test by user-specification.", "name": "split", "signature": "def split(...
2
null
Implement the Python class `SpecifiedSplitter` described below. Class description: Class that splits data according to user specification. Method signatures and docstrings: - def __init__(self, input_file, split_field, verbose=False): Provide input information for splits. - def split(self, dataset, frac_train=0.8, fr...
Implement the Python class `SpecifiedSplitter` described below. Class description: Class that splits data according to user specification. Method signatures and docstrings: - def __init__(self, input_file, split_field, verbose=False): Provide input information for splits. - def split(self, dataset, frac_train=0.8, fr...
ee6e67ebcf7bf04259cf13aff6388e2b791fea3d
<|skeleton|> class SpecifiedSplitter: """Class that splits data according to user specification.""" def __init__(self, input_file, split_field, verbose=False): """Provide input information for splits.""" <|body_0|> def split(self, dataset, frac_train=0.8, frac_valid=0.1, frac_test=0.1, log...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpecifiedSplitter: """Class that splits data according to user specification.""" def __init__(self, input_file, split_field, verbose=False): """Provide input information for splits.""" raw_df = next(load_data([input_file], shard_size=None)) self.splits = raw_df[split_field].values...
the_stack_v2_python_sparse
contrib/atomicconv/splits/splitters.py
deepchem/deepchem
train
4,876
478a11221eb3e26ef4fb53042ae055876d5bc868
[ "self.caps = Capability.NONE\nself.methods: List[Method] = []\nfor method_data in methods:\n try:\n method_cap = Capability._member_map_[method_data.get('type', 'WRONG').upper()]\n except KeyError:\n raise RuntimeError(f'invalid method type for {name}')\n method = Method(self, method_cap, met...
<|body_start_0|> self.caps = Capability.NONE self.methods: List[Method] = [] for method_data in methods: try: method_cap = Capability._member_map_[method_data.get('type', 'WRONG').upper()] except KeyError: raise RuntimeError(f'invalid metho...
Encapsulates a GTFOBin and it's methods for all capabilities
Binary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binary: """Encapsulates a GTFOBin and it's methods for all capabilities""" def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]]): """Create a GTFOBin from the given list of capabilities""" <|body_0|> def iter_methods(self, binary_path: str, caps:...
stack_v2_sparse_classes_36k_train_023736
17,537
permissive
[ { "docstring": "Create a GTFOBin from the given list of capabilities", "name": "__init__", "signature": "def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]])" }, { "docstring": "Iterate over methods in this binary matching the capability and stream masks", "name": "...
2
null
Implement the Python class `Binary` described below. Class description: Encapsulates a GTFOBin and it's methods for all capabilities Method signatures and docstrings: - def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]]): Create a GTFOBin from the given list of capabilities - def iter_metho...
Implement the Python class `Binary` described below. Class description: Encapsulates a GTFOBin and it's methods for all capabilities Method signatures and docstrings: - def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]]): Create a GTFOBin from the given list of capabilities - def iter_metho...
37f04d4e16ff47c7fd70e95162f9fccd327cca7e
<|skeleton|> class Binary: """Encapsulates a GTFOBin and it's methods for all capabilities""" def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]]): """Create a GTFOBin from the given list of capabilities""" <|body_0|> def iter_methods(self, binary_path: str, caps:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binary: """Encapsulates a GTFOBin and it's methods for all capabilities""" def __init__(self, gtfo: 'GTFOBins', name: str, methods: List[Dict[str, Any]]): """Create a GTFOBin from the given list of capabilities""" self.caps = Capability.NONE self.methods: List[Method] = [] ...
the_stack_v2_python_sparse
pwncat/gtfobins.py
calebstewart/pwncat
train
2,177
6347296f455d23b49ed605fb4b9a9a80ba514c66
[ "study_id = filter_params.pop('study_id', None)\nq = Investigator.query.filter_by(**filter_params)\nfrom dataservice.api.study.models import Study\nif study_id:\n q = q.join(Investigator.studies).filter(Study.kf_id == study_id)\nreturn InvestigatorSchema(many=True).jsonify(Pagination(q, after, limit))", "body ...
<|body_start_0|> study_id = filter_params.pop('study_id', None) q = Investigator.query.filter_by(**filter_params) from dataservice.api.study.models import Study if study_id: q = q.join(Investigator.studies).filter(Study.kf_id == study_id) return InvestigatorSchema(man...
Investigator API
InvestigatorListAPI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InvestigatorListAPI: """Investigator API""" def get(self, filter_params, after, limit): """Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator""" <|body_0|> def post(self): """Create a new investigator --- template: p...
stack_v2_sparse_classes_36k_train_023737
4,397
permissive
[ { "docstring": "Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator", "name": "get", "signature": "def get(self, filter_params, after, limit)" }, { "docstring": "Create a new investigator --- template: path: new_resource.yml properties: resource: Inv...
2
null
Implement the Python class `InvestigatorListAPI` described below. Class description: Investigator API Method signatures and docstrings: - def get(self, filter_params, after, limit): Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator - def post(self): Create a new investi...
Implement the Python class `InvestigatorListAPI` described below. Class description: Investigator API Method signatures and docstrings: - def get(self, filter_params, after, limit): Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator - def post(self): Create a new investi...
36ee3fc3d1ba9d1a177274d051fb175c56dd898e
<|skeleton|> class InvestigatorListAPI: """Investigator API""" def get(self, filter_params, after, limit): """Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator""" <|body_0|> def post(self): """Create a new investigator --- template: p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InvestigatorListAPI: """Investigator API""" def get(self, filter_params, after, limit): """Get a paginated investigators --- template: path: get_list.yml properties: resource: Investigator""" study_id = filter_params.pop('study_id', None) q = Investigator.query.filter_by(**filter_...
the_stack_v2_python_sparse
dataservice/api/investigator/resources.py
kids-first/kf-api-dataservice
train
9
9510a83adeb81c80dd396e63d1d809a7368ae555
[ "option_question_numbers = Interview_options.objects.filter(flag=grade).order_by('?')[:option_question_number].values('id')\nshort_question_numbers = Interview_sort_answer.objects.filter(flag=grade).order_by('?')[:short_question_number].values('id')\noption_title_id = [v for i in option_question_numbers for k, v in...
<|body_start_0|> option_question_numbers = Interview_options.objects.filter(flag=grade).order_by('?')[:option_question_number].values('id') short_question_numbers = Interview_sort_answer.objects.filter(flag=grade).order_by('?')[:short_question_number].values('id') option_title_id = [v for i in o...
将用户id和随机题目绑定一起
UserAndTitle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserAndTitle: """将用户id和随机题目绑定一起""" def select_title(cls, grade, option_question_number, short_question_number): """随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号""" <|body_0|> def save_u...
stack_v2_sparse_classes_36k_train_023738
8,285
no_license
[ { "docstring": "随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号", "name": "select_title", "signature": "def select_title(cls, grade, option_question_number, short_question_number)" }, { "docstring": "将用户id和随机题目绑定...
2
null
Implement the Python class `UserAndTitle` described below. Class description: 将用户id和随机题目绑定一起 Method signatures and docstrings: - def select_title(cls, grade, option_question_number, short_question_number): 随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简...
Implement the Python class `UserAndTitle` described below. Class description: 将用户id和随机题目绑定一起 Method signatures and docstrings: - def select_title(cls, grade, option_question_number, short_question_number): 随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简...
4febccac57bfa5f7ef46f5f57e52206c8b0a57ac
<|skeleton|> class UserAndTitle: """将用户id和随机题目绑定一起""" def select_title(cls, grade, option_question_number, short_question_number): """随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号""" <|body_0|> def save_u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserAndTitle: """将用户id和随机题目绑定一起""" def select_title(cls, grade, option_question_number, short_question_number): """随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号""" option_question_numbers = Interview_opt...
the_stack_v2_python_sparse
item/interview/backend/utils.py
soulorman/Python
train
0
5a1d929fbe7760d78228296c93ec42c9708bb274
[ "self.drive_vec = drive_vec\nself.id = id\nself.is_full_channel_restore = is_full_channel_restore\nself.name = name", "if dictionary is None:\n return None\ndrive_vec = None\nif dictionary.get('driveVec') != None:\n drive_vec = list()\n for structure in dictionary.get('driveVec'):\n drive_vec.appe...
<|body_start_0|> self.drive_vec = drive_vec self.id = id self.is_full_channel_restore = is_full_channel_restore self.name = name <|end_body_0|> <|body_start_1|> if dictionary is None: return None drive_vec = None if dictionary.get('driveVec') != None:...
Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_channel_restore is true. id (string): Id of the source channel for re...
RestoreO365TeamsParams_SourceChannel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreO365TeamsParams_SourceChannel: """Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_chann...
stack_v2_sparse_classes_36k_train_023739
2,610
permissive
[ { "docstring": "Constructor for the RestoreO365TeamsParams_SourceChannel class", "name": "__init__", "signature": "def __init__(self, drive_vec=None, id=None, is_full_channel_restore=None, name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio...
2
stack_v2_sparse_classes_30k_train_007420
Implement the Python class `RestoreO365TeamsParams_SourceChannel` described below. Class description: Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restore...
Implement the Python class `RestoreO365TeamsParams_SourceChannel` described below. Class description: Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restore...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestoreO365TeamsParams_SourceChannel: """Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_chann...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestoreO365TeamsParams_SourceChannel: """Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_channel_restore is...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_o_365_teams_params_source_channel.py
cohesity/management-sdk-python
train
24
e3f4f735002d3c56346bb79462ca2e4c58ac2e09
[ "username = ctx.bot.config.get('myanimelist_username')\npassword = ctx.bot.config.get('myanimelist_password')\nif not username or not password:\n await ctx.send('No username and/or password was found in the configuration.')\n return\nresult = await _mal_fetch(ctx.bot.session, 'manga', query, username, passwor...
<|body_start_0|> username = ctx.bot.config.get('myanimelist_username') password = ctx.bot.config.get('myanimelist_password') if not username or not password: await ctx.send('No username and/or password was found in the configuration.') return result = await _mal_f...
MyAnimeList lookup commands.
MyAnimeList
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyAnimeList: """MyAnimeList lookup commands.""" async def manga(self, ctx, *, query): """Search for manga.""" <|body_0|> async def anime(self, ctx, *, query): """Search for anime.""" <|body_1|> <|end_skeleton|> <|body_start_0|> username = ctx.bo...
stack_v2_sparse_classes_36k_train_023740
4,423
permissive
[ { "docstring": "Search for manga.", "name": "manga", "signature": "async def manga(self, ctx, *, query)" }, { "docstring": "Search for anime.", "name": "anime", "signature": "async def anime(self, ctx, *, query)" } ]
2
stack_v2_sparse_classes_30k_train_009026
Implement the Python class `MyAnimeList` described below. Class description: MyAnimeList lookup commands. Method signatures and docstrings: - async def manga(self, ctx, *, query): Search for manga. - async def anime(self, ctx, *, query): Search for anime.
Implement the Python class `MyAnimeList` described below. Class description: MyAnimeList lookup commands. Method signatures and docstrings: - async def manga(self, ctx, *, query): Search for manga. - async def anime(self, ctx, *, query): Search for anime. <|skeleton|> class MyAnimeList: """MyAnimeList lookup com...
9bf3f2125939b66bd1894e509c1b1fa1ab413a6a
<|skeleton|> class MyAnimeList: """MyAnimeList lookup commands.""" async def manga(self, ctx, *, query): """Search for manga.""" <|body_0|> async def anime(self, ctx, *, query): """Search for anime.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyAnimeList: """MyAnimeList lookup commands.""" async def manga(self, ctx, *, query): """Search for manga.""" username = ctx.bot.config.get('myanimelist_username') password = ctx.bot.config.get('myanimelist_password') if not username or not password: await ctx....
the_stack_v2_python_sparse
cogs/lookup/myanimelist.py
DasWolke/kitsuchan-2
train
1
0101cb4e170a8d168a24134fee231c0d44274d44
[ "try:\n self.network_driver.apply_qos_on_port(qos_policy_id, amp_data[constants.VRRP_PORT_ID])\nexcept Exception:\n if not is_revert:\n raise\n LOG.warning('Failed to undo qos policy %(qos_id)s on vrrp port: %(port)s from amphorae: %(amp)s', {'qos_id': request_qos_id, 'port': amp_data[constants.VRRP...
<|body_start_0|> try: self.network_driver.apply_qos_on_port(qos_policy_id, amp_data[constants.VRRP_PORT_ID]) except Exception: if not is_revert: raise LOG.warning('Failed to undo qos policy %(qos_id)s on vrrp port: %(port)s from amphorae: %(amp)s', {'q...
Apply Quality of Services to the VIP
ApplyQosAmphora
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApplyQosAmphora: """Apply Quality of Services to the VIP""" def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): """Call network driver to apply QoS Policy on the vrrp ports.""" <|body_0|> def execute(self, loadb...
stack_v2_sparse_classes_36k_train_023741
44,034
permissive
[ { "docstring": "Call network driver to apply QoS Policy on the vrrp ports.", "name": "_apply_qos_on_vrrp_port", "signature": "def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None)" }, { "docstring": "Apply qos policy on the vrrp ports whic...
3
stack_v2_sparse_classes_30k_train_003310
Implement the Python class `ApplyQosAmphora` described below. Class description: Apply Quality of Services to the VIP Method signatures and docstrings: - def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ...
Implement the Python class `ApplyQosAmphora` described below. Class description: Apply Quality of Services to the VIP Method signatures and docstrings: - def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ...
0426285a41464a5015494584f109eed35a0d44db
<|skeleton|> class ApplyQosAmphora: """Apply Quality of Services to the VIP""" def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): """Call network driver to apply QoS Policy on the vrrp ports.""" <|body_0|> def execute(self, loadb...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApplyQosAmphora: """Apply Quality of Services to the VIP""" def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): """Call network driver to apply QoS Policy on the vrrp ports.""" try: self.network_driver.apply_qos_on_po...
the_stack_v2_python_sparse
octavia/controller/worker/v2/tasks/network_tasks.py
openstack/octavia
train
147
bb316d600504f4ed8419b60c858868d506be842b
[ "url = 'os-keypairs'\nif params:\n url += '?%s' % urllib.urlencode(params)\nresp, body = self.get(url)\nbody = json.loads(body)\nschema = self.get_schema(self.schema_versions_info)\nself.validate_response(schema.list_keypairs, resp, body)\nreturn rest_client.ResponseBody(resp, body)", "url = 'os-keypairs/%s' %...
<|body_start_0|> url = 'os-keypairs' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) schema = self.get_schema(self.schema_versions_info) self.validate_response(schema.list_keypairs, resp, body) retu...
KeyPairsClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyPairsClient: def list_keypairs(self, **params): """Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs""" <|body_0|> def show_ke...
stack_v2_sparse_classes_36k_train_023742
3,699
permissive
[ { "docstring": "Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs", "name": "list_keypairs", "signature": "def list_keypairs(self, **params)" }, { "do...
4
stack_v2_sparse_classes_30k_train_017436
Implement the Python class `KeyPairsClient` described below. Class description: Implement the KeyPairsClient class. Method signatures and docstrings: - def list_keypairs(self, **params): Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API refe...
Implement the Python class `KeyPairsClient` described below. Class description: Implement the KeyPairsClient class. Method signatures and docstrings: - def list_keypairs(self, **params): Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API refe...
0bc47dbdd05b5d12d048c09800515c2bd03a16ce
<|skeleton|> class KeyPairsClient: def list_keypairs(self, **params): """Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs""" <|body_0|> def show_ke...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeyPairsClient: def list_keypairs(self, **params): """Lists keypairs that are associated with the account. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-keypairs""" url = 'os-keypairs' if params: ...
the_stack_v2_python_sparse
tempest/lib/services/compute/keypairs_client.py
cisco-openstack/tempest
train
2
b65d5a1b7e741ea4ad7186f2ab1f644da35f598a
[ "BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder)\nself.fold_frame = fold_frame\nself.rotation = rotation", "s1 = self.fold_frame.features[0].evaluate_value(location)\nr = self.rotation(s1)\nreturn r" ]
<|body_start_0|> BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder) self.fold_frame = fold_frame self.rotation = rotation <|end_body_0|> <|body_start_1|> s1 = self.fold_frame.features[0].evaluate_value(location) r = self.rotation(s1) retu...
FoldRotationAngleFeature
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FoldRotationAngleFeature: def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None): """Parameters ---------- fold_frame rotation""" <|body_0|> def evaluate_value(self, location): """Parameters ---------- lo...
stack_v2_sparse_classes_36k_train_023743
1,260
permissive
[ { "docstring": "Parameters ---------- fold_frame rotation", "name": "__init__", "signature": "def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None)" }, { "docstring": "Parameters ---------- location Returns -------", "name": "ev...
2
stack_v2_sparse_classes_30k_train_002157
Implement the Python class `FoldRotationAngleFeature` described below. Class description: Implement the FoldRotationAngleFeature class. Method signatures and docstrings: - def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None): Parameters ---------- fold_...
Implement the Python class `FoldRotationAngleFeature` described below. Class description: Implement the FoldRotationAngleFeature class. Method signatures and docstrings: - def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None): Parameters ---------- fold_...
c6175623450dbc79ed06ed8d8bbff21b63fc8b4c
<|skeleton|> class FoldRotationAngleFeature: def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None): """Parameters ---------- fold_frame rotation""" <|body_0|> def evaluate_value(self, location): """Parameters ---------- lo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FoldRotationAngleFeature: def __init__(self, fold_frame, rotation, name='fold_rotation_angle', model=None, faults=[], regions=[], builder=None): """Parameters ---------- fold_frame rotation""" BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder) self.fold...
the_stack_v2_python_sparse
LoopStructural/modelling/features/fold/_fold_rotation_angle_feature.py
Loop3D/LoopStructural
train
123
7362bc70d35a5cf0cdeb84ad884fc41a0e1b650f
[ "self.verify_workflow()\nmco = self.create_mco()\nself._initialize_listeners()\nself._deliver_start_event()\ntry:\n mco.run(self.workflow)\nexcept Exception:\n log.exception(\"Method run() of MCO with id '{}' from plugin '{}' raised exception. This might indicate a programming error in the plugin.\".format(mc...
<|body_start_0|> self.verify_workflow() mco = self.create_mco() self._initialize_listeners() self._deliver_start_event() try: mco.run(self.workflow) except Exception: log.exception("Method run() of MCO with id '{}' from plugin '{}' raised exception...
Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run.
OptimizeOperation
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimizeOperation: """Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run.""" def run(self): """Create and run the o...
stack_v2_sparse_classes_36k_train_023744
2,006
permissive
[ { "docstring": "Create and run the optimizer.", "name": "run", "signature": "def run(self)" }, { "docstring": "Create the MCO from the model's factory.", "name": "create_mco", "signature": "def create_mco(self)" } ]
2
stack_v2_sparse_classes_30k_train_007823
Implement the Python class `OptimizeOperation` described below. Class description: Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run. Method signatu...
Implement the Python class `OptimizeOperation` described below. Class description: Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run. Method signatu...
6106bec35d6ad2383138a35205cea44fe529a229
<|skeleton|> class OptimizeOperation: """Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run.""" def run(self): """Create and run the o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OptimizeOperation: """Performs a full MCO run on a system described by a `Workflow` object, based on the format given by a `BaseMCO` class. Contains optional `NotificationListener` classes in order to broadcast information during the MCO run.""" def run(self): """Create and run the optimizer.""" ...
the_stack_v2_python_sparse
force_bdss/app/optimize_operation.py
force-h2020/force-bdss
train
2
0e23729a0b717e5d4401017098a58d28d27fbcec
[ "column = self.defaultcolumn if column is None else column\nidx0, idx1 = self.indices\nret = pd.DataFrame(_symmetric_to_square(self[idx0].values, self[idx1].values, self[column.values]))\nret.index.name = idx0\nret.columns.name = idx1\nreturn ret", "column = 'coef' if column is None else column\nidx0, idx1 = cls(...
<|body_start_0|> column = self.defaultcolumn if column is None else column idx0, idx1 = self.indices ret = pd.DataFrame(_symmetric_to_square(self[idx0].values, self[idx1].values, self[column.values])) ret.index.name = idx0 ret.columns.name = idx1 return ret <|end_body_0|>...
Base class for symmetric matrices.
_Symmetric
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Symmetric: """Base class for symmetric matrices.""" def square(self, column=None): """Return a square DataFrame of the matrix.""" <|body_0|> def from_square(cls, square, column=None): """Create a symmetric matrix DataFrame from a square array.""" <|body_...
stack_v2_sparse_classes_36k_train_023745
7,607
permissive
[ { "docstring": "Return a square DataFrame of the matrix.", "name": "square", "signature": "def square(self, column=None)" }, { "docstring": "Create a symmetric matrix DataFrame from a square array.", "name": "from_square", "signature": "def from_square(cls, square, column=None)" } ]
2
null
Implement the Python class `_Symmetric` described below. Class description: Base class for symmetric matrices. Method signatures and docstrings: - def square(self, column=None): Return a square DataFrame of the matrix. - def from_square(cls, square, column=None): Create a symmetric matrix DataFrame from a square arra...
Implement the Python class `_Symmetric` described below. Class description: Base class for symmetric matrices. Method signatures and docstrings: - def square(self, column=None): Return a square DataFrame of the matrix. - def from_square(cls, square, column=None): Create a symmetric matrix DataFrame from a square arra...
2e87bae3e043e6958129fc823c83ab0b46add8b5
<|skeleton|> class _Symmetric: """Base class for symmetric matrices.""" def square(self, column=None): """Return a square DataFrame of the matrix.""" <|body_0|> def from_square(cls, square, column=None): """Create a symmetric matrix DataFrame from a square array.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Symmetric: """Base class for symmetric matrices.""" def square(self, column=None): """Return a square DataFrame of the matrix.""" column = self.defaultcolumn if column is None else column idx0, idx1 = self.indices ret = pd.DataFrame(_symmetric_to_square(self[idx0].values,...
the_stack_v2_python_sparse
exatomic/core/matrices.py
exa-analytics/exatomic
train
15
3fcc0b2735541cbdcfcf84c9e944b05d218b696c
[ "nintervals = Integer(nintervals)\nif not nintervals > 1:\n raise ValueError('number of intervals must be at least 2')\nself._nintervals = nintervals\nif marked_separatrix is None:\n marked_separatrix = 'out'\nif not marked_separatrix in ['no', 'out', 'in']:\n raise ValueError('marked_separatrix must be no...
<|body_start_0|> nintervals = Integer(nintervals) if not nintervals > 1: raise ValueError('number of intervals must be at least 2') self._nintervals = nintervals if marked_separatrix is None: marked_separatrix = 'out' if not marked_separatrix in ['no', 'ou...
Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in'
AbelianStrata_d
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbelianStrata_d: """Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in'""" def __init__(self, nintervals=None, marked_separatrix=None): """TESTS:: sage: s = AbelianStrata(nintervals=10) sage: s ...
stack_v2_sparse_classes_36k_train_023746
49,724
no_license
[ { "docstring": "TESTS:: sage: s = AbelianStrata(nintervals=10) sage: s == loads(dumps(s)) True sage: AbelianStrata(nintervals=1) Traceback (most recent call last): ... ValueError: number of intervals must be at least 2 sage: AbelianStrata(nintervals=4, marked_separatrix='maybe') Traceback (most recent call last...
3
null
Implement the Python class `AbelianStrata_d` described below. Class description: Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in' Method signatures and docstrings: - def __init__(self, nintervals=None, marked_separatrix=None)...
Implement the Python class `AbelianStrata_d` described below. Class description: Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in' Method signatures and docstrings: - def __init__(self, nintervals=None, marked_separatrix=None)...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class AbelianStrata_d: """Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in'""" def __init__(self, nintervals=None, marked_separatrix=None): """TESTS:: sage: s = AbelianStrata(nintervals=10) sage: s ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AbelianStrata_d: """Strata with constraint number of intervals. INPUT: - ``nintervals`` - an integer greater than 1 - ``marked_separatrix`` - 'no', 'out' or 'in'""" def __init__(self, nintervals=None, marked_separatrix=None): """TESTS:: sage: s = AbelianStrata(nintervals=10) sage: s == loads(dump...
the_stack_v2_python_sparse
sage/src/sage/dynamics/flat_surfaces/strata.py
bopopescu/geosci
train
0
ea23145f386cf178ef629a6f97d1a2bf83b58fb8
[ "self.sum_from_origin = {}\nself.num_rows = len(matrix)\nif self.num_rows == 0:\n return\nself.num_cols = len(matrix[0])\nprint(self.num_rows, self.num_cols)\nfor i in range(self.num_rows):\n for j in range(self.num_cols):\n current_sum = 0\n if i > 0:\n current_sum += self.sum_from_o...
<|body_start_0|> self.sum_from_origin = {} self.num_rows = len(matrix) if self.num_rows == 0: return self.num_cols = len(matrix[0]) print(self.num_rows, self.num_cols) for i in range(self.num_rows): for j in range(self.num_cols): cu...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_023747
2,021
no_license
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int", "name": "sumRegion", "signature": "def sumRegion(self, row1, col1, row2, col2)" ...
2
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:...
afc5a08cd538c45e075fc6c479c255b3596d7ac5
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def sumRegion(self, row1, col1, row2, col2): """:type row1: int :type col1: int :type row2: int :type col2: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" self.sum_from_origin = {} self.num_rows = len(matrix) if self.num_rows == 0: return self.num_cols = len(matrix[0]) print(self.num_rows, self.num_cols) for i in range(s...
the_stack_v2_python_sparse
range_sum_2d_immutable.py
gauravaror/programming
train
0
cefbd0464db5762ad670394baf0502c961302603
[ "self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.user = Employee.objects.create_user(username='admin', passwo...
<|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100') self.user = Employee.objects.cr...
Report tests.
ReportModelTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportModelTest: """Report tests.""" def setUp(self): """Data setup for tests.""" <|body_0|> def test_create(self): """Check creating reports.""" <|body_1|> def test_doubles(self): """Check if two fullproducts with same product are not allowe...
stack_v2_sparse_classes_36k_train_023748
14,711
permissive
[ { "docstring": "Data setup for tests.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Check creating reports.", "name": "test_create", "signature": "def test_create(self)" }, { "docstring": "Check if two fullproducts with same product are not allowed.", "...
4
stack_v2_sparse_classes_30k_test_000883
Implement the Python class `ReportModelTest` described below. Class description: Report tests. Method signatures and docstrings: - def setUp(self): Data setup for tests. - def test_create(self): Check creating reports. - def test_doubles(self): Check if two fullproducts with same product are not allowed. - def test_r...
Implement the Python class `ReportModelTest` described below. Class description: Report tests. Method signatures and docstrings: - def setUp(self): Data setup for tests. - def test_create(self): Check creating reports. - def test_doubles(self): Check if two fullproducts with same product are not allowed. - def test_r...
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class ReportModelTest: """Report tests.""" def setUp(self): """Data setup for tests.""" <|body_0|> def test_create(self): """Check creating reports.""" <|body_1|> def test_doubles(self): """Check if two fullproducts with same product are not allowe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReportModelTest: """Report tests.""" def setUp(self): """Data setup for tests.""" self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='...
the_stack_v2_python_sparse
caffe/reports/test_models.py
VirrageS/io-kawiarnie
train
3
a2f227a6ebc857f96ccb2e45570b7ca7ec431079
[ "super().__init__(productcode, description, marketprice, rentalprice)\nself.productcode = productcode\nself.description = description\nself.marketprice = marketprice\nself.rentalprice = rentalprice\nself.brand = brand\nself.voltage = voltage", "outputdict = {}\noutputdict['productcode'] = self.productcode\noutput...
<|body_start_0|> super().__init__(productcode, description, marketprice, rentalprice) self.productcode = productcode self.description = description self.marketprice = marketprice self.rentalprice = rentalprice self.brand = brand self.voltage = voltage <|end_body_0...
Class docstring
Electricappliances
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Electricappliances: """Class docstring""" def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage): """initializing variables""" <|body_0|> def returnasdictionary(self): """method docstring""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_36k_train_023749
1,134
no_license
[ { "docstring": "initializing variables", "name": "__init__", "signature": "def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage)" }, { "docstring": "method docstring", "name": "returnasdictionary", "signature": "def returnasdictionary(self)" } ]
2
null
Implement the Python class `Electricappliances` described below. Class description: Class docstring Method signatures and docstrings: - def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage): initializing variables - def returnasdictionary(self): method docstring
Implement the Python class `Electricappliances` described below. Class description: Class docstring Method signatures and docstrings: - def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage): initializing variables - def returnasdictionary(self): method docstring <|skeleton|> class El...
ac12beeae8aa57135bbcd03ac7a4f977fa3bdb56
<|skeleton|> class Electricappliances: """Class docstring""" def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage): """initializing variables""" <|body_0|> def returnasdictionary(self): """method docstring""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Electricappliances: """Class docstring""" def __init__(self, productcode, description, marketprice, rentalprice, brand, voltage): """initializing variables""" super().__init__(productcode, description, marketprice, rentalprice) self.productcode = productcode self.descripti...
the_stack_v2_python_sparse
students/Daniel_Carrasco/lesson01/assignment/inventory_management/electricAppliancesClass.py
UWPCE-PythonCert-ClassRepos/py220-online-201904-V2
train
1
dc0fdee6d06d0083a83c86805c1cb2ab61666b71
[ "int_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-']\nres = ''\ni = 0\nlength = len(s)\nif s[0] in int_:\n res += s[0]\n while i < length - 1:\n i += 1\n if s[i] in int_:\n res += s[i]\n else:\n break\n res = int(res)\n if res > 2 ** 31 - 1:\n ...
<|body_start_0|> int_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'] res = '' i = 0 length = len(s) if s[0] in int_: res += s[0] while i < length - 1: i += 1 if s[i] in int_: res += s[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mystoi(self, s): """:type s:str :rtype:int""" <|body_0|> def mystoi_1(self, s): """:type s:str :rtype:int""" <|body_1|> def mystoi_2(self, s): """:type s:str :rtype:int""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_023750
3,713
no_license
[ { "docstring": ":type s:str :rtype:int", "name": "mystoi", "signature": "def mystoi(self, s)" }, { "docstring": ":type s:str :rtype:int", "name": "mystoi_1", "signature": "def mystoi_1(self, s)" }, { "docstring": ":type s:str :rtype:int", "name": "mystoi_2", "signature": ...
3
stack_v2_sparse_classes_30k_train_007195
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mystoi(self, s): :type s:str :rtype:int - def mystoi_1(self, s): :type s:str :rtype:int - def mystoi_2(self, s): :type s:str :rtype:int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mystoi(self, s): :type s:str :rtype:int - def mystoi_1(self, s): :type s:str :rtype:int - def mystoi_2(self, s): :type s:str :rtype:int <|skeleton|> class Solution: def...
4f2802d4773eddd2a2e06e61c51463056886b730
<|skeleton|> class Solution: def mystoi(self, s): """:type s:str :rtype:int""" <|body_0|> def mystoi_1(self, s): """:type s:str :rtype:int""" <|body_1|> def mystoi_2(self, s): """:type s:str :rtype:int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mystoi(self, s): """:type s:str :rtype:int""" int_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'] res = '' i = 0 length = len(s) if s[0] in int_: res += s[0] while i < length - 1: i += 1 ...
the_stack_v2_python_sparse
leetcode/17_myatoi.py
Yara7L/python_algorithm
train
0
360344bffecce399a668c5a77d9d76a15d9dd637
[ "super().__init__(syncthru, name)\nself._name = f'{name} Tray {number}'\nself._number = number\nself._id_suffix = f'_tray_{number}'", "if self.syncthru.is_online():\n self._attributes = self.syncthru.input_tray_status().get(self._number, {})\n self._state = self._attributes.get('newError')\n if self._sta...
<|body_start_0|> super().__init__(syncthru, name) self._name = f'{name} Tray {number}' self._number = number self._id_suffix = f'_tray_{number}' <|end_body_0|> <|body_start_1|> if self.syncthru.is_online(): self._attributes = self.syncthru.input_tray_status().get(sel...
Implementation of a Samsung Printer input tray sensor platform.
SyncThruInputTraySensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SyncThruInputTraySensor: """Implementation of a Samsung Printer input tray sensor platform.""" def __init__(self, syncthru, name, number): """Initialize the sensor.""" <|body_0|> def update(self): """Get the latest data from SyncThru and update the state.""" ...
stack_v2_sparse_classes_36k_train_023751
8,262
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, syncthru, name, number)" }, { "docstring": "Get the latest data from SyncThru and update the state.", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_003639
Implement the Python class `SyncThruInputTraySensor` described below. Class description: Implementation of a Samsung Printer input tray sensor platform. Method signatures and docstrings: - def __init__(self, syncthru, name, number): Initialize the sensor. - def update(self): Get the latest data from SyncThru and upda...
Implement the Python class `SyncThruInputTraySensor` described below. Class description: Implementation of a Samsung Printer input tray sensor platform. Method signatures and docstrings: - def __init__(self, syncthru, name, number): Initialize the sensor. - def update(self): Get the latest data from SyncThru and upda...
ed4ab403deaed9e8c95e0db728477fcb012bf4fa
<|skeleton|> class SyncThruInputTraySensor: """Implementation of a Samsung Printer input tray sensor platform.""" def __init__(self, syncthru, name, number): """Initialize the sensor.""" <|body_0|> def update(self): """Get the latest data from SyncThru and update the state.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SyncThruInputTraySensor: """Implementation of a Samsung Printer input tray sensor platform.""" def __init__(self, syncthru, name, number): """Initialize the sensor.""" super().__init__(syncthru, name) self._name = f'{name} Tray {number}' self._number = number self....
the_stack_v2_python_sparse
homeassistant/components/syncthru/sensor.py
tchellomello/home-assistant
train
8
d61d12d6706488157fd69fd95c2be9ae32c42b9f
[ "for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn []", "cache = {}\nfor key, value in enumerate(nums):\n if value in cache:\n return [cache[value], key]\n cache[target - value] = key\nreturn []" ]
<|body_start_0|> for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] <|end_body_0|> <|body_start_1|> cache = {} for key, value in enumerate(nums): if value in cac...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Time is O(n^2), O(1) space""" <|body_0|> def two_sum(self, nums: List[int], target: int) -> List[int]: """Time is O(n^2), O(1) space""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_023752
1,364
no_license
[ { "docstring": "Time is O(n^2), O(1) space", "name": "twoSum", "signature": "def twoSum(self, nums: List[int], target: int) -> List[int]" }, { "docstring": "Time is O(n^2), O(1) space", "name": "two_sum", "signature": "def two_sum(self, nums: List[int], target: int) -> List[int]" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums: List[int], target: int) -> List[int]: Time is O(n^2), O(1) space - def two_sum(self, nums: List[int], target: int) -> List[int]: Time is O(n^2), O(1) space
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums: List[int], target: int) -> List[int]: Time is O(n^2), O(1) space - def two_sum(self, nums: List[int], target: int) -> List[int]: Time is O(n^2), O(1) space...
0892f41fe055de4361aae950fb60b0e3c2f96505
<|skeleton|> class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Time is O(n^2), O(1) space""" <|body_0|> def two_sum(self, nums: List[int], target: int) -> List[int]: """Time is O(n^2), O(1) space""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Time is O(n^2), O(1) space""" for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] def two_sum(...
the_stack_v2_python_sparse
DataStructures/v1/code/leet/two_sum.py
acemodou/Working-Copy
train
0
9fb86ebe3ca0bc2e40dc831f0a0507f6da6702e6
[ "B, c, m = features.size()\nn = idx.size(1)\nctx.three_interpolate_for_backward = (idx, weight, m)\nreturn _ext.three_interpolate(features, idx, weight)", "idx, weight, m = ctx.three_interpolate_for_backward\ngrad_features = _ext.three_interpolate_grad(grad_out.contiguous(), idx, weight, m)\nreturn (grad_features...
<|body_start_0|> B, c, m = features.size() n = idx.size(1) ctx.three_interpolate_for_backward = (idx, weight, m) return _ext.three_interpolate(features, idx, weight) <|end_body_0|> <|body_start_1|> idx, weight, m = ctx.three_interpolate_for_backward grad_features = _ext....
ThreeInterpolate
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreeInterpolate: def forward(ctx, features, idx, weight): """Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target feature...
stack_v2_sparse_classes_36k_train_023753
15,763
permissive
[ { "docstring": "Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target features in features weight : torch.Tensor (B, n, 3) weights Returns ------- ...
2
stack_v2_sparse_classes_30k_train_021179
Implement the Python class `ThreeInterpolate` described below. Class description: Implement the ThreeInterpolate class. Method signatures and docstrings: - def forward(ctx, features, idx, weight): Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descr...
Implement the Python class `ThreeInterpolate` described below. Class description: Implement the ThreeInterpolate class. Method signatures and docstrings: - def forward(ctx, features, idx, weight): Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descr...
c0eecf2223c3c28d048d816fd239c118b8568dcf
<|skeleton|> class ThreeInterpolate: def forward(ctx, features, idx, weight): """Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target feature...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThreeInterpolate: def forward(ctx, features, idx, weight): """Performs weight linear interpolation on 3 features Parameters ---------- features : torch.Tensor (B, c, m) Features descriptors to be interpolated from idx : torch.Tensor (B, n, 3) three nearest neighbors of the target features in features ...
the_stack_v2_python_sparse
pointcloud/pointnet2/utils/pointnet2_utils.py
WangLi2019Gt/qpu_code
train
0
884007d2bb2edf7b3683053dd508f9c70ebbe306
[ "arguments.AddBackupResourceArg(parser, 'to list backups for')\nparser.display_info.AddFormat('\\n table(\\n name.basename():sort=1:label=NAME,\\n cluster():label=CLUSTER,\\n sourceTable.basename():label=TABLE,\\n expireTime:label=EXPIRE_TIME,\\n state...
<|body_start_0|> arguments.AddBackupResourceArg(parser, 'to list backups for') parser.display_info.AddFormat('\n table(\n name.basename():sort=1:label=NAME,\n cluster():label=CLUSTER,\n sourceTable.basename():label=TABLE,\n expireTime:label=EXPIRE_TIM...
List existing Bigtable backups.
ListBackups
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListBackups: """List existing Bigtable backups.""" def Args(parser): """Register flags for this command.""" <|body_0|> def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were...
stack_v2_sparse_classes_36k_train_023754
3,739
permissive
[ { "docstring": "Register flags for this command.", "name": "Args", "signature": "def Args(parser)" }, { "docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Yields: Some value t...
2
stack_v2_sparse_classes_30k_train_001634
Implement the Python class `ListBackups` described below. Class description: List existing Bigtable backups. Method signatures and docstrings: - def Args(parser): Register flags for this command. - def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All th...
Implement the Python class `ListBackups` described below. Class description: List existing Bigtable backups. Method signatures and docstrings: - def Args(parser): Register flags for this command. - def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All th...
85bb264e273568b5a0408f733b403c56373e2508
<|skeleton|> class ListBackups: """List existing Bigtable backups.""" def Args(parser): """Register flags for this command.""" <|body_0|> def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListBackups: """List existing Bigtable backups.""" def Args(parser): """Register flags for this command.""" arguments.AddBackupResourceArg(parser, 'to list backups for') parser.display_info.AddFormat('\n table(\n name.basename():sort=1:label=NAME,\n ...
the_stack_v2_python_sparse
google-cloud-sdk/lib/surface/bigtable/backups/list.py
bopopescu/socialliteapp
train
0
f663b7b09c1279a915c8d8459a697652870e619a
[ "self.MODULE = MODULE\nself.inserting = True\nself['host'] = None\nself['username'] = None\nself['saveLevel'] = None\nself['saveUri'] = None\nself['otherDirs'] = None\nself['fileName'] = None\nself['sessionStart'] = str(datetime.datetime.now())\nself['sessionType'] = None\nself['XnatIo'] = None\nself['metadata'] = ...
<|body_start_0|> self.MODULE = MODULE self.inserting = True self['host'] = None self['username'] = None self['saveLevel'] = None self['saveUri'] = None self['otherDirs'] = None self['fileName'] = None self['sessionStart'] = str(datetime.datetime.no...
Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys.
XnatSessionArgs
[ "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XnatSessionArgs: """Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys.""" def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=True): """Establish the relevant keys in the Session Manager."...
stack_v2_sparse_classes_36k_train_023755
4,591
permissive
[ { "docstring": "Establish the relevant keys in the Session Manager.", "name": "__init__", "signature": "def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=True)" }, { "docstring": "Assigns a value to a key. User cannot add keys to object.", "name": "__setitem__", "signature...
4
stack_v2_sparse_classes_30k_val_000631
Implement the Python class `XnatSessionArgs` described below. Class description: Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys. Method signatures and docstrings: - def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=Tr...
Implement the Python class `XnatSessionArgs` described below. Class description: Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys. Method signatures and docstrings: - def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=Tr...
06867037842e2a074ae5ed3b0bdf4bf016a231a5
<|skeleton|> class XnatSessionArgs: """Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys.""" def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=True): """Establish the relevant keys in the Session Manager."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XnatSessionArgs: """Inherits the 'dict' type of python. Specifically tailored for XNAT tracking. Keys are immutable, so the user cannot add further keys.""" def __init__(self, MODULE, srcPath=None, useDefaultXnatSaveLevel=True): """Establish the relevant keys in the Session Manager.""" se...
the_stack_v2_python_sparse
XNATSlicer/XnatSlicerLib/utils/SessionManager.py
NrgXnat/XNATSlicer
train
4
67b63e8a8c083f0f36244832536c7ea0ccf1dd5c
[ "super(PerformedRxnForm, self).__init__(*args, **kwargs)\nself.user = user\nlabGroups = user.labgroup_set.all()\nself.fields['labGroup'].queryset = labGroups\nself.fields['recommendation'].queryset = RecommendedReaction.objects.filter(labGroup__in=labGroups)\nself.fields['recommendation'].widget = forms.HiddenInput...
<|body_start_0|> super(PerformedRxnForm, self).__init__(*args, **kwargs) self.user = user labGroups = user.labgroup_set.all() self.fields['labGroup'].queryset = labGroups self.fields['recommendation'].queryset = RecommendedReaction.objects.filter(labGroup__in=labGroups) s...
A form for creating performed reaction instances in teh databases.
PerformedRxnForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PerformedRxnForm: """A form for creating performed reaction instances in teh databases.""" def __init__(self, user, *args, **kwargs): """Overridden __init__ method; requires the user as the first argument so that choice of lab group etc can be validated, as well as to track who enter...
stack_v2_sparse_classes_36k_train_023756
4,205
no_license
[ { "docstring": "Overridden __init__ method; requires the user as the first argument so that choice of lab group etc can be validated, as well as to track who enters what.", "name": "__init__", "signature": "def __init__(self, user, *args, **kwargs)" }, { "docstring": "Overriden save method autom...
2
stack_v2_sparse_classes_30k_train_003577
Implement the Python class `PerformedRxnForm` described below. Class description: A form for creating performed reaction instances in teh databases. Method signatures and docstrings: - def __init__(self, user, *args, **kwargs): Overridden __init__ method; requires the user as the first argument so that choice of lab ...
Implement the Python class `PerformedRxnForm` described below. Class description: A form for creating performed reaction instances in teh databases. Method signatures and docstrings: - def __init__(self, user, *args, **kwargs): Overridden __init__ method; requires the user as the first argument so that choice of lab ...
eae2009eadf87ffd2378233f3e153d385f4654d2
<|skeleton|> class PerformedRxnForm: """A form for creating performed reaction instances in teh databases.""" def __init__(self, user, *args, **kwargs): """Overridden __init__ method; requires the user as the first argument so that choice of lab group etc can be validated, as well as to track who enter...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PerformedRxnForm: """A form for creating performed reaction instances in teh databases.""" def __init__(self, user, *args, **kwargs): """Overridden __init__ method; requires the user as the first argument so that choice of lab group etc can be validated, as well as to track who enters what.""" ...
the_stack_v2_python_sparse
DRP/forms/PerformedReaction.py
zhaojhao/DRP
train
0
5c407886661f9ed0e28ce6b9f6adb1b9c2ff0c99
[ "self.model = model\nself.x_set = x_set\nself.y_set = y_set\nself.args = args\nself.dir = base.INTERPRETABILITY", "preprocess = DataPreprocessing(self.x_set[2:4], self.y_set[2:4], self.args)\nself.x_val, self.y_val, self.label = preprocess.apply_preprocessing()\nclass_index = [0, 1]\nfor idx in class_index:\n ...
<|body_start_0|> self.model = model self.x_set = x_set self.y_set = y_set self.args = args self.dir = base.INTERPRETABILITY <|end_body_0|> <|body_start_1|> preprocess = DataPreprocessing(self.x_set[2:4], self.y_set[2:4], self.args) self.x_val, self.y_val, self.la...
Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results
Interpretability
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interpretability: """Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results""" def __init__(self, model, x_set, y_set, args): """Class initialisation Parameters ---------- model : TensorFlow Keras model model trained test_x, test_y :...
stack_v2_sparse_classes_36k_train_023757
7,791
no_license
[ { "docstring": "Class initialisation Parameters ---------- model : TensorFlow Keras model model trained test_x, test_y : test data (images and label) history : dict history of every training epochs directory : str path to directory where to save outputs args : arguments parser user choices", "name": "__init...
3
stack_v2_sparse_classes_30k_train_014207
Implement the Python class `Interpretability` described below. Class description: Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results Method signatures and docstrings: - def __init__(self, model, x_set, y_set, args): Class initialisation Parameters ---------- mode...
Implement the Python class `Interpretability` described below. Class description: Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results Method signatures and docstrings: - def __init__(self, model, x_set, y_set, args): Class initialisation Parameters ---------- mode...
227641cc02f5c3aef04f3c27cbfc316382041ae0
<|skeleton|> class Interpretability: """Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results""" def __init__(self, model, x_set, y_set, args): """Class initialisation Parameters ---------- model : TensorFlow Keras model model trained test_x, test_y :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Interpretability: """Compute and save tf-explainer and shap interpretability Methods ------- tf_explainer_results shap_results""" def __init__(self, model, x_set, y_set, args): """Class initialisation Parameters ---------- model : TensorFlow Keras model model trained test_x, test_y : test data (i...
the_stack_v2_python_sparse
yotta_p2/bj-computer-vision/masked_face/domain/model_interpretability.py
j-bd/various_exs
train
0
4e85f75a5c5bb9bf3327b2fee1981d30571e5259
[ "if len(money) <= 5:\n return sum(money)\nself.res = 0\nself.dfs(money, 0, len(money) - 1, 0)\nreturn self.res", "if left + len(money) - 1 - right == 5:\n self.res = max(self.res, path)\n return\nself.dfs(money, left + 1, right, path + money[left])\nself.dfs(money, left, right - 1, path + money[right])" ...
<|body_start_0|> if len(money) <= 5: return sum(money) self.res = 0 self.dfs(money, 0, len(money) - 1, 0) return self.res <|end_body_0|> <|body_start_1|> if left + len(money) - 1 - right == 5: self.res = max(self.res, path) return self...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def func(self, money): """回溯 Args: money: list[int] Return: int""" <|body_0|> def dfs(self, money, left, right, path): """Args: money: list[int] left: int right: int path: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(money) <...
stack_v2_sparse_classes_36k_train_023758
993
no_license
[ { "docstring": "回溯 Args: money: list[int] Return: int", "name": "func", "signature": "def func(self, money)" }, { "docstring": "Args: money: list[int] left: int right: int path: int", "name": "dfs", "signature": "def dfs(self, money, left, right, path)" } ]
2
stack_v2_sparse_classes_30k_train_016994
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def func(self, money): 回溯 Args: money: list[int] Return: int - def dfs(self, money, left, right, path): Args: money: list[int] left: int right: int path: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def func(self, money): 回溯 Args: money: list[int] Return: int - def dfs(self, money, left, right, path): Args: money: list[int] left: int right: int path: int <|skeleton|> class ...
101bce2fac8b188a4eb2f5e017293d21ad0ecb21
<|skeleton|> class Solution: def func(self, money): """回溯 Args: money: list[int] Return: int""" <|body_0|> def dfs(self, money, left, right, path): """Args: money: list[int] left: int right: int path: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def func(self, money): """回溯 Args: money: list[int] Return: int""" if len(money) <= 5: return sum(money) self.res = 0 self.dfs(money, 0, len(money) - 1, 0) return self.res def dfs(self, money, left, right, path): """Args: money: list[i...
the_stack_v2_python_sparse
秋招/58/3.py
AiZhanghan/Leetcode
train
0
d99919a5fa8a26a376fe064105d6ffc2f7369eb5
[ "assert isinstance(mc, ModelConfiguration)\nself.mc = mc\nself.conf = mc['conf']", "obj = torch.zeros(1)\nnum_steps = 0\nfor traj in trajectories:\n policy = self.mc.get('policy', False)\n t_states = torch.Tensor(traj.states)\n t_actions = torch.Tensor(traj.actions)\n log_likelihoods = torch.Tensor(tr...
<|body_start_0|> assert isinstance(mc, ModelConfiguration) self.mc = mc self.conf = mc['conf'] <|end_body_0|> <|body_start_1|> obj = torch.zeros(1) num_steps = 0 for traj in trajectories: policy = self.mc.get('policy', False) t_states = torch.Tens...
Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust region policy optimization or proximal policy optimization can be implemented efficiently.
PolicyOptimizationAlgorithm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PolicyOptimizationAlgorithm: """Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust region policy optimization or proximal...
stack_v2_sparse_classes_36k_train_023759
1,950
permissive
[ { "docstring": "Initializes a new policy approximation algorithm. It makes the model config and from that also the running config available to the derived class itself. :param mc: The model configuration, containing all important elements, like env or similar.", "name": "__init__", "signature": "def __i...
2
stack_v2_sparse_classes_30k_train_016174
Implement the Python class `PolicyOptimizationAlgorithm` described below. Class description: Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust...
Implement the Python class `PolicyOptimizationAlgorithm` described below. Class description: Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust...
13038a1a5a93c78374ba869c9e75221c2b73d290
<|skeleton|> class PolicyOptimizationAlgorithm: """Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust region policy optimization or proximal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PolicyOptimizationAlgorithm: """Represents a policy optimization algorithm. It is splitted into two phases for the scheme from the original papers of relative entropy policy search and maximum a posteriori policy optimization. Note that algorithms like trust region policy optimization or proximal policy optim...
the_stack_v2_python_sparse
src/abstract_rl/algorithms/continuous/policy_gradient/policy_optimization_algorithm.py
kosmitive/abstract_rl
train
2
6b73d43ffb767da80c7fb1bf5e897ca1db9ae247
[ "params = self.params()\nresult = await self.cs('shop.service', 'query_info', params)\nself.out(result)", "params = self.params()\nresult = await self.cs('shop.service', 'create_info', params)\nself.out(result)" ]
<|body_start_0|> params = self.params() result = await self.cs('shop.service', 'query_info', params) self.out(result) <|end_body_0|> <|body_start_1|> params = self.params() result = await self.cs('shop.service', 'create_info', params) self.out(result) <|end_body_1|>
Controller
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: async def get(self): """获取指定店铺信息 return data: { "admin_id": "", "account": "", "name": "", }""" <|body_0|> async def post(self): """创建店铺 @return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> params = self.params() result = awa...
stack_v2_sparse_classes_36k_train_023760
773
no_license
[ { "docstring": "获取指定店铺信息 return data: { \"admin_id\": \"\", \"account\": \"\", \"name\": \"\", }", "name": "get", "signature": "async def get(self)" }, { "docstring": "创建店铺 @return:", "name": "post", "signature": "async def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_019904
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - async def get(self): 获取指定店铺信息 return data: { "admin_id": "", "account": "", "name": "", } - async def post(self): 创建店铺 @return:
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - async def get(self): 获取指定店铺信息 return data: { "admin_id": "", "account": "", "name": "", } - async def post(self): 创建店铺 @return: <|skeleton|> class Controller: async def...
9ab7dc87b678fc2a105cf883448cb7aada8494d2
<|skeleton|> class Controller: async def get(self): """获取指定店铺信息 return data: { "admin_id": "", "account": "", "name": "", }""" <|body_0|> async def post(self): """创建店铺 @return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: async def get(self): """获取指定店铺信息 return data: { "admin_id": "", "account": "", "name": "", }""" params = self.params() result = await self.cs('shop.service', 'query_info', params) self.out(result) async def post(self): """创建店铺 @return:""" params...
the_stack_v2_python_sparse
src/module/v1/shop/info.py
yuiitsu/DSSP
train
0
e9dca617c0e57979b1b111606da659fc0847a069
[ "train_dataset = sio.loadmat(path_train)\ntest_dataset = sio.loadmat(path_test)\ntrain_data, train_labels = (train_dataset['X'], train_dataset['y'])\ntest_data, test_labels = (test_dataset['X'], test_dataset['y'])\nprint('Train data:', train_data.shape, ', Train labels:', train_labels.shape)\nprint('Test data:', te...
<|body_start_0|> train_dataset = sio.loadmat(path_train) test_dataset = sio.loadmat(path_test) train_data, train_labels = (train_dataset['X'], train_dataset['y']) test_data, test_labels = (test_dataset['X'], test_dataset['y']) print('Train data:', train_data.shape, ', Train label...
SVHNDataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SVHNDataset: def load_dataset(self, path_train, path_test): """Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array,""" <|body_0|> def convert_to_gray(self, data): """Converts all the images in the dataset i...
stack_v2_sparse_classes_36k_train_023761
3,407
no_license
[ { "docstring": "Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array,", "name": "load_dataset", "signature": "def load_dataset(self, path_train, path_test)" }, { "docstring": "Converts all the images in the dataset into gray scale. Retu...
2
stack_v2_sparse_classes_30k_train_017352
Implement the Python class `SVHNDataset` described below. Class description: Implement the SVHNDataset class. Method signatures and docstrings: - def load_dataset(self, path_train, path_test): Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array, - def conve...
Implement the Python class `SVHNDataset` described below. Class description: Implement the SVHNDataset class. Method signatures and docstrings: - def load_dataset(self, path_train, path_test): Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array, - def conve...
e606f7069bbb14350f167bdd21a8395fb7c46304
<|skeleton|> class SVHNDataset: def load_dataset(self, path_train, path_test): """Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array,""" <|body_0|> def convert_to_gray(self, data): """Converts all the images in the dataset i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SVHNDataset: def load_dataset(self, path_train, path_test): """Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array,""" train_dataset = sio.loadmat(path_train) test_dataset = sio.loadmat(path_test) train_data, train_la...
the_stack_v2_python_sparse
16.video_captures/DigitDetector/SVHN_model_train_local.py
kromerh/phd_python
train
0
ba93d254815acb9421e5145c08b634354a27bf77
[ "hierarchy_mapping_name = os.path.join('..', VG_VisualModule_PICKLES_PATH, hierarchy_mapping_name)\nmodel_path = os.path.join('..', weights_name_dir, WEIGHTS_NAME)\nif not os.path.exists(model_path) or not os.path.exists(hierarchy_mapping_name):\n print('Error: No Weights have been found or No Hierarchy Mapping ...
<|body_start_0|> hierarchy_mapping_name = os.path.join('..', VG_VisualModule_PICKLES_PATH, hierarchy_mapping_name) model_path = os.path.join('..', weights_name_dir, WEIGHTS_NAME) if not os.path.exists(model_path) or not os.path.exists(hierarchy_mapping_name): print('Error: No Weights...
This class is a network visualizer
NetworkVisualizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkVisualizer: """This class is a network visualizer""" def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): """This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hiera...
stack_v2_sparse_classes_36k_train_023762
8,365
no_license
[ { "docstring": "This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping :param gpu_num: 0 (default)", "name": "__init__", "signature": "def __init__(self, weights_name_dir, hierarchy_mapping_name, gp...
5
stack_v2_sparse_classes_30k_train_009041
Implement the Python class `NetworkVisualizer` described below. Class description: This class is a network visualizer Method signatures and docstrings: - def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): This function initializes network visualizer :param weights_name_dir: the path for the weig...
Implement the Python class `NetworkVisualizer` described below. Class description: This class is a network visualizer Method signatures and docstrings: - def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): This function initializes network visualizer :param weights_name_dir: the path for the weig...
1b65b21474f923b799ff486eea9dea5137be6506
<|skeleton|> class NetworkVisualizer: """This class is a network visualizer""" def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): """This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hiera...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkVisualizer: """This class is a network visualizer""" def __init__(self, weights_name_dir, hierarchy_mapping_name, gpu_num=0): """This function initializes network visualizer :param weights_name_dir: the path for the weights :param hierarchy_mapping_name: the path for the hierarchy mapping ...
the_stack_v2_python_sparse
Utils/NetworkVisualizer.py
roeiherz/SceneGrapher
train
0
61a04c4d382f5dfe80c3384ec7277519399addc6
[ "self.load_date = load_date\nself.verbose = verbose\nif isinstance(self.load_date, str):\n self.load_date = pd.to_datetime(self.load_date)\nif isinstance(self.load_date, pd.Timestamp):\n self.doy = int(self.load_date.dayofyear)\nelif isinstance(self.load_date, (datetime, date)):\n self.doy = int(self.load_...
<|body_start_0|> self.load_date = load_date self.verbose = verbose if isinstance(self.load_date, str): self.load_date = pd.to_datetime(self.load_date) if isinstance(self.load_date, pd.Timestamp): self.doy = int(self.load_date.dayofyear) elif isinstance(sel...
Load_SAMPEX_Attitude
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Load_SAMPEX_Attitude: def __init__(self, load_date, verbose=False): """This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time columns into datetime objects""" <|body_0|> def find_matching_attitude_file(self): """Uses pat...
stack_v2_sparse_classes_36k_train_023763
10,167
permissive
[ { "docstring": "This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time columns into datetime objects", "name": "__init__", "signature": "def __init__(self, load_date, verbose=False)" }, { "docstring": "Uses pathlib.rglob to find the attitude file th...
5
stack_v2_sparse_classes_30k_train_019465
Implement the Python class `Load_SAMPEX_Attitude` described below. Class description: Implement the Load_SAMPEX_Attitude class. Method signatures and docstrings: - def __init__(self, load_date, verbose=False): This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time column...
Implement the Python class `Load_SAMPEX_Attitude` described below. Class description: Implement the Load_SAMPEX_Attitude class. Method signatures and docstrings: - def __init__(self, load_date, verbose=False): This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time column...
916a24f072034fea4680ab13f98d967d2ecfcf5d
<|skeleton|> class Load_SAMPEX_Attitude: def __init__(self, load_date, verbose=False): """This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time columns into datetime objects""" <|body_0|> def find_matching_attitude_file(self): """Uses pat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Load_SAMPEX_Attitude: def __init__(self, load_date, verbose=False): """This class loads the appropriate SAMEX attitude file, parses the complex header and converts the time columns into datetime objects""" self.load_date = load_date self.verbose = verbose if isinstance(self.loa...
the_stack_v2_python_sparse
sampex_microburst_widths/misc/load_hilt_data.py
mshumko/sampex_microburst_widths
train
0
6dbefce93d59ca47e7188e8ce3229f0797609d94
[ "arcpy.AddMessage(u'\\t1. Verificando disponibilidad de licencia SPATIAL ANALYST')\nlicense = arcpy.CheckExtension('spatial')\nif license != 'Available':\n raise RuntimeError('\\tError: %s' % license)\narcpy.AddMessage(u'\\t2. Enviando informacion a la GEODATABASE')\narcpy.CheckOutExtension('spatial')\ngeoquimic...
<|body_start_0|> arcpy.AddMessage(u'\t1. Verificando disponibilidad de licencia SPATIAL ANALYST') license = arcpy.CheckExtension('spatial') if license != 'Available': raise RuntimeError('\tError: %s' % license) arcpy.AddMessage(u'\t2. Enviando informacion a la GEODATABASE') ...
Clase que contiene el procesamiento para el tratamiento de la variable geoquimica
Geoquimica
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Geoquimica: """Clase que contiene el procesamiento para el tratamiento de la variable geoquimica""" def process(self): """Enviando el raster ingresado al File Geodatabase :return:""" <|body_0|> def main(self): """Funcion principal del proceso :return:""" ...
stack_v2_sparse_classes_36k_train_023764
1,567
no_license
[ { "docstring": "Enviando el raster ingresado al File Geodatabase :return:", "name": "process", "signature": "def process(self)" }, { "docstring": "Funcion principal del proceso :return:", "name": "main", "signature": "def main(self)" } ]
2
stack_v2_sparse_classes_30k_train_005788
Implement the Python class `Geoquimica` described below. Class description: Clase que contiene el procesamiento para el tratamiento de la variable geoquimica Method signatures and docstrings: - def process(self): Enviando el raster ingresado al File Geodatabase :return: - def main(self): Funcion principal del proceso...
Implement the Python class `Geoquimica` described below. Class description: Clase que contiene el procesamiento para el tratamiento de la variable geoquimica Method signatures and docstrings: - def process(self): Enviando el raster ingresado al File Geodatabase :return: - def main(self): Funcion principal del proceso...
89bcea828bc8720fc1dcf82439b06b1f272bb096
<|skeleton|> class Geoquimica: """Clase que contiene el procesamiento para el tratamiento de la variable geoquimica""" def process(self): """Enviando el raster ingresado al File Geodatabase :return:""" <|body_0|> def main(self): """Funcion principal del proceso :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Geoquimica: """Clase que contiene el procesamiento para el tratamiento de la variable geoquimica""" def process(self): """Enviando el raster ingresado al File Geodatabase :return:""" arcpy.AddMessage(u'\t1. Verificando disponibilidad de licencia SPATIAL ANALYST') license = arcpy.C...
the_stack_v2_python_sparse
Install/dev/scripts/pmmGeoquimica.py
ryali93/addinPotencialMinero
train
0
4367c925479f28c7267c5e760eb081fb2a14776f
[ "o_dict = self.idict.copy()\noutputs = {}\no_dict['Material model']['Model name'] = material_model\nif material_model == 'visco plastic twod':\n material_model_subsection = 'Visco Plastic TwoD'\nelse:\n material_model_subsection = material_model.title()\no_dict['Material model'][material_model_subsection] = {...
<|body_start_0|> o_dict = self.idict.copy() outputs = {} o_dict['Material model']['Model name'] = material_model if material_model == 'visco plastic twod': material_model_subsection = 'Visco Plastic TwoD' else: material_model_subsection = material_model.ti...
class for a case More Attributes:
CASE
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CASE: """class for a case More Attributes:""" def configure_prm(self, if_wb, geometry, material_model, _type): """Configure prm file""" <|body_0|> def configure_wb(self, if_wb, geometry, material_model, _type): """Configure wb file""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_023765
5,403
no_license
[ { "docstring": "Configure prm file", "name": "configure_prm", "signature": "def configure_prm(self, if_wb, geometry, material_model, _type)" }, { "docstring": "Configure wb file", "name": "configure_wb", "signature": "def configure_wb(self, if_wb, geometry, material_model, _type)" } ]
2
stack_v2_sparse_classes_30k_train_013195
Implement the Python class `CASE` described below. Class description: class for a case More Attributes: Method signatures and docstrings: - def configure_prm(self, if_wb, geometry, material_model, _type): Configure prm file - def configure_wb(self, if_wb, geometry, material_model, _type): Configure wb file
Implement the Python class `CASE` described below. Class description: class for a case More Attributes: Method signatures and docstrings: - def configure_prm(self, if_wb, geometry, material_model, _type): Configure prm file - def configure_wb(self, if_wb, geometry, material_model, _type): Configure wb file <|skeleto...
d919cadce2b57811351c0615d94da5c6ebfff800
<|skeleton|> class CASE: """class for a case More Attributes:""" def configure_prm(self, if_wb, geometry, material_model, _type): """Configure prm file""" <|body_0|> def configure_wb(self, if_wb, geometry, material_model, _type): """Configure wb file""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CASE: """class for a case More Attributes:""" def configure_prm(self, if_wb, geometry, material_model, _type): """Configure prm file""" o_dict = self.idict.copy() outputs = {} o_dict['Material model']['Model name'] = material_model if material_model == 'visco plast...
the_stack_v2_python_sparse
files/Project/Cases.py
lhy11009/aspectLib
train
0
650ac55a0733ab868af02f5a3b81fca7c690fe5f
[ "DebugObject.__init__(self, 'AmbientOcclusion')\nself.pipeline = pipeline\nself.create()", "technique = self.pipeline.settings.occlusionTechnique\nif technique not in self.availableTechniques:\n self.error('Unrecognized technique: ' + technique)\n return\nif technique == 'None':\n return\nself.aoPass = A...
<|body_start_0|> DebugObject.__init__(self, 'AmbientOcclusion') self.pipeline = pipeline self.create() <|end_body_0|> <|body_start_1|> technique = self.pipeline.settings.occlusionTechnique if technique not in self.availableTechniques: self.error('Unrecognized techniq...
The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration
AmbientOcclusionManager
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AmbientOcclusionManager: """The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration""" def __init__(self, pipeline): """Creates the manager and directly cr...
stack_v2_sparse_classes_36k_train_023766
3,521
permissive
[ { "docstring": "Creates the manager and directly creates the passes", "name": "__init__", "signature": "def __init__(self, pipeline)" }, { "docstring": "Creates the passes required to compute the occlusion, selecting the appropriate pass for the selected technique", "name": "create", "si...
2
null
Implement the Python class `AmbientOcclusionManager` described below. Class description: The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration Method signatures and docstrings: - def __in...
Implement the Python class `AmbientOcclusionManager` described below. Class description: The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration Method signatures and docstrings: - def __in...
12131b115775f97927633d71832af65b99eebd09
<|skeleton|> class AmbientOcclusionManager: """The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration""" def __init__(self, pipeline): """Creates the manager and directly cr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AmbientOcclusionManager: """The ambient occlusion manager handles the setup of the passes required to compute ambient occlusion. He also registers the configuration defines specified in the pipeline configuration""" def __init__(self, pipeline): """Creates the manager and directly creates the pas...
the_stack_v2_python_sparse
Code/AmbientOcclusionManager.py
2lost4u/RenderPipeline
train
1
ef3b27783bcb0bb800ae68be15b8b2a5062b08ff
[ "self.name = name\nself.bull_points = 0\nself.hand = []\nself.discard = None", "high_card = None\nmax_face = None\nfor card in self.hand:\n if card.face_value > max_face:\n max_face = card.face_value\n high_card = card\nself.hand.remove(high_card)\nreturn high_card", "stacks = dealer.list_of_st...
<|body_start_0|> self.name = name self.bull_points = 0 self.hand = [] self.discard = None <|end_body_0|> <|body_start_1|> high_card = None max_face = None for card in self.hand: if card.face_value > max_face: max_face = card.face_value...
Player
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Player: def __init__(self, name): """Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain so we made assumptions based on the game specifications :param name: the name of the player :re...
stack_v2_sparse_classes_36k_train_023767
3,073
no_license
[ { "docstring": "Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain so we made assumptions based on the game specifications :param name: the name of the player :return: the player object", "name": "__init...
3
null
Implement the Python class `Player` described below. Class description: Implement the Player class. Method signatures and docstrings: - def __init__(self, name): Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain ...
Implement the Python class `Player` described below. Class description: Implement the Player class. Method signatures and docstrings: - def __init__(self, name): Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain ...
c04863a4f01e755988afc5592bfd1f65b4d39a0e
<|skeleton|> class Player: def __init__(self, name): """Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain so we made assumptions based on the game specifications :param name: the name of the player :re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Player: def __init__(self, name): """Purpose Statement: creates a player object Ambiguity: The provided interface did not provide information about what attributes Player object should contain so we made assumptions based on the game specifications :param name: the name of the player :return: the play...
the_stack_v2_python_sparse
2/player.py
campoloj/SoftwareDevelopment2016
train
2
e0b9cd210119845623f2893e4e800322245972e9
[ "User = get_user_model()\nuser = User.objects.create(email='fatemeh@email.com', password='customusertest12345')\nself.assertEqual(user.email, 'fatemeh@email.com')\nself.assertTrue(user.is_active)\nself.assertFalse(user.is_staff)\nself.assertFalse(user.is_superuser)", "User = get_user_model()\nadmin = User.objects...
<|body_start_0|> User = get_user_model() user = User.objects.create(email='fatemeh@email.com', password='customusertest12345') self.assertEqual(user.email, 'fatemeh@email.com') self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superu...
تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر
CustomUserTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserTests: """تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر""" def test_create_user(self): """ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد""" <|body_0|> def test_create_superuser(self)...
stack_v2_sparse_classes_36k_train_023768
1,468
no_license
[ { "docstring": "ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد", "name": "test_create_user", "signature": "def test_create_user(self)" }, { "docstring": "ایجاد ادمین با استفاده از ایمیل و پسورد. چک می کند که فیلد های issuperuse...
2
stack_v2_sparse_classes_30k_train_006354
Implement the Python class `CustomUserTests` described below. Class description: تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر Method signatures and docstrings: - def test_create_user(self): ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد -...
Implement the Python class `CustomUserTests` described below. Class description: تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر Method signatures and docstrings: - def test_create_user(self): ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد -...
1846897db084d72697571900bc41dacbd9b6059b
<|skeleton|> class CustomUserTests: """تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر""" def test_create_user(self): """ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد""" <|body_0|> def test_create_superuser(self)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomUserTests: """تست کیس دو متد ایجاد یوزر و سوپریوزر از مدل کاستوم یوزر""" def test_create_user(self): """ایجاد یوزر تنها با ایمیل و پسورد. چک می کند که فیلدهای: is_active حتما true و issuperuser, is_staff حتما false باشد""" User = get_user_model() user = User.objects.create(e...
the_stack_v2_python_sparse
src/accounts/tests.py
FatemehRahmanzadeh/Book_store_Persian_rtl
train
0
aa6c66914f3fa1fc2daa60e7e3a22322aa190431
[ "self.lctime = update_lc_event(self.lc_events, self.lctime, self.timeind, self.dt)\nfor veh in self.vehicles:\n if veh.in_relax:\n if veh.first_index:\n veh.first_index = False\n else:\n p = veh.cf_parameters\n vtilde = veh.lead.nextspeed * (1 - veh.DeltaN) + veh.le...
<|body_start_0|> self.lctime = update_lc_event(self.lc_events, self.lctime, self.timeind, self.dt) for veh in self.vehicles: if veh.in_relax: if veh.first_index: veh.first_index = False else: p = veh.cf_parameters ...
Does a simulation of a single LLRelaxVehicle, and returns the loss.
LLCalibration
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LLCalibration: """Does a simulation of a single LLRelaxVehicle, and returns the loss.""" def step(self): """Has a different order of updates than Calibration""" <|body_0|> def simulate(self, parameters): """The same, but we need to put it here so it calls the rig...
stack_v2_sparse_classes_36k_train_023769
15,459
permissive
[ { "docstring": "Has a different order of updates than Calibration", "name": "step", "signature": "def step(self)" }, { "docstring": "The same, but we need to put it here so it calls the right event_updates.", "name": "simulate", "signature": "def simulate(self, parameters)" } ]
2
stack_v2_sparse_classes_30k_train_013847
Implement the Python class `LLCalibration` described below. Class description: Does a simulation of a single LLRelaxVehicle, and returns the loss. Method signatures and docstrings: - def step(self): Has a different order of updates than Calibration - def simulate(self, parameters): The same, but we need to put it her...
Implement the Python class `LLCalibration` described below. Class description: Does a simulation of a single LLRelaxVehicle, and returns the loss. Method signatures and docstrings: - def step(self): Has a different order of updates than Calibration - def simulate(self, parameters): The same, but we need to put it her...
0aaf9674e987822ff2dc90c74613d5e68e8ef0ce
<|skeleton|> class LLCalibration: """Does a simulation of a single LLRelaxVehicle, and returns the loss.""" def step(self): """Has a different order of updates than Calibration""" <|body_0|> def simulate(self, parameters): """The same, but we need to put it here so it calls the rig...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LLCalibration: """Does a simulation of a single LLRelaxVehicle, and returns the loss.""" def step(self): """Has a different order of updates than Calibration""" self.lctime = update_lc_event(self.lc_events, self.lctime, self.timeind, self.dt) for veh in self.vehicles: ...
the_stack_v2_python_sparse
scripts/spring 2020/relax results/deprecated/special_newell_model.py
seccode/havsim
train
0
666a8d5dad4efa03db21bd091c7ebbc0e2a46e43
[ "if not user_id:\n return None\nsession_id = super().create_session(user_id)\nif not session_id:\n return None\nsession_data = {'user_id': user_id, 'session_id': session_id}\nobj = UserSession(**session_data)\nobj.save()\nreturn session_id", "if not session_id:\n return None\ntry:\n UserSession.load_f...
<|body_start_0|> if not user_id: return None session_id = super().create_session(user_id) if not session_id: return None session_data = {'user_id': user_id, 'session_id': session_id} obj = UserSession(**session_data) obj.save() return sessi...
SessionDBAuth class
SessionDBAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """returns the User ID by requesting Use...
stack_v2_sparse_classes_36k_train_023770
2,337
no_license
[ { "docstring": "creates and stores new instance of UserSession and returns the Session ID", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "returns the User ID by requesting UserSession in the database based on session_id", "name": "user_id_...
3
stack_v2_sparse_classes_30k_train_012534
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth class Method signatures and docstrings: - def create_session(self, user_id=None): creates and stores new instance of UserSession and returns the Session ID - def user_id_for_session_id(self, session_id=None): returns the User...
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth class Method signatures and docstrings: - def create_session(self, user_id=None): creates and stores new instance of UserSession and returns the Session ID - def user_id_for_session_id(self, session_id=None): returns the User...
2ab609541ff8b45cdc923c24d629f160ddc6f3cf
<|skeleton|> class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """returns the User ID by requesting Use...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """creates and stores new instance of UserSession and returns the Session ID""" if not user_id: return None session_id = super().create_session(user_id) if not session_id: ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_db_auth.py
MatriMariem/holbertonschool-web_back_end
train
0
062b6078e945baae00d4ce62faddc05d7feb7ad0
[ "gtk.VBox.__init__(self)\nself.config = config\nself.set_spacing(8)\nself.set_border_width(8)\nself.useProxy = gtk.CheckButton(_('_Use proxy'))\nself.useProxy.set_active(self.config.glob['useProxy'])\nself.host = gtk.Entry()\nself.host.set_text(self.config.glob['proxyHost'])\nself.port = gtk.Entry()\nself.port.set_...
<|body_start_0|> gtk.VBox.__init__(self) self.config = config self.set_spacing(8) self.set_border_width(8) self.useProxy = gtk.CheckButton(_('_Use proxy')) self.useProxy.set_active(self.config.glob['useProxy']) self.host = gtk.Entry() self.host.set_text(se...
This class represents the panel with the proxy variables in the config file
ProxySettings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProxySettings: """This class represents the panel with the proxy variables in the config file""" def __init__(self, config): """Constructor""" <|body_0|> def save(self): """save the actual setting""" <|body_1|> def useProxyToggled(self, check): ...
stack_v2_sparse_classes_36k_train_023771
25,236
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "save the actual setting", "name": "save", "signature": "def save(self)" }, { "docstring": "callback for the toggled signal", "name": "useProxyToggled", "signatur...
3
null
Implement the Python class `ProxySettings` described below. Class description: This class represents the panel with the proxy variables in the config file Method signatures and docstrings: - def __init__(self, config): Constructor - def save(self): save the actual setting - def useProxyToggled(self, check): callback ...
Implement the Python class `ProxySettings` described below. Class description: This class represents the panel with the proxy variables in the config file Method signatures and docstrings: - def __init__(self, config): Constructor - def save(self): save the actual setting - def useProxyToggled(self, check): callback ...
1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad
<|skeleton|> class ProxySettings: """This class represents the panel with the proxy variables in the config file""" def __init__(self, config): """Constructor""" <|body_0|> def save(self): """save the actual setting""" <|body_1|> def useProxyToggled(self, check): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProxySettings: """This class represents the panel with the proxy variables in the config file""" def __init__(self, config): """Constructor""" gtk.VBox.__init__(self) self.config = config self.set_spacing(8) self.set_border_width(8) self.useProxy = gtk.Chec...
the_stack_v2_python_sparse
emesene/rev1286-1505/left-trunk-1505/PreferenceWindow.py
joliebig/featurehouse_fstmerge_examples
train
3
6523d7d277e52b5227161a8b9f0e22ccdad9828e
[ "self.doc = doc\nself.ecosystem = ecosystem\nself.pkgfile_path = pkgfile_path\nself.cpe2pkg_path = cpe2pkg_path", "result = set()\nfor cpe in utils.get_cpe(self.doc, cpe_type='application'):\n vendor = cpe.get_vendor()[0]\n product = cpe.get_product()[0]\n result.add((vendor, product))\nreturn result", ...
<|body_start_0|> self.doc = doc self.ecosystem = ecosystem self.pkgfile_path = pkgfile_path self.cpe2pkg_path = cpe2pkg_path <|end_body_0|> <|body_start_1|> result = set() for cpe in utils.get_cpe(self.doc, cpe_type='application'): vendor = cpe.get_vendor()[0...
Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words).
NaivePackageNameIdentifier
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaivePackageNameIdentifier: """Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words).""" def __init__(self, doc, ecosystem, pkgfile_path, cpe2pkg_path=Config...
stack_v2_sparse_classes_36k_train_023772
4,239
permissive
[ { "docstring": "Initialize Constructor.", "name": "__init__", "signature": "def __init__(self, doc, ecosystem, pkgfile_path, cpe2pkg_path=Config.cpe2pkg_path)" }, { "docstring": "Get (vendor, product) pairs from the CVE. :return: a set containing (vendor, product) pairs", "name": "_get_vendo...
6
stack_v2_sparse_classes_30k_train_001610
Implement the Python class `NaivePackageNameIdentifier` described below. Class description: Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words). Method signatures and docstrings: - ...
Implement the Python class `NaivePackageNameIdentifier` described below. Class description: Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words). Method signatures and docstrings: - ...
3737d0a267414bd8fb2b626f0255c55620e76477
<|skeleton|> class NaivePackageNameIdentifier: """Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words).""" def __init__(self, doc, ecosystem, pkgfile_path, cpe2pkg_path=Config...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NaivePackageNameIdentifier: """Naive package name identifier. All words from the first sentence of a CVE description that are starting with uppercase letter are considered to be possible package names (minus stop words).""" def __init__(self, doc, ecosystem, pkgfile_path, cpe2pkg_path=Config.cpe2pkg_path...
the_stack_v2_python_sparse
cvejob/identifiers/naive.py
fabric8-analytics/cvejob
train
10
28021ac69c06105417413a442f0e3985354d5fee
[ "parent = self.ancestor.ancestor.ancestor\nif self.relation == self.absolute:\n pqu = PQUModule.PQU(self.value, parent.unit)\n if unit is not None:\n pqu.convertToUnit(unit)\nelse:\n pqu = self.value * parent.pqu(unit)\n if self.relation == self.percent:\n pqu /= 100\nreturn pqu", "if no...
<|body_start_0|> parent = self.ancestor.ancestor.ancestor if self.relation == self.absolute: pqu = PQUModule.PQU(self.value, parent.unit) if unit is not None: pqu.convertToUnit(unit) else: pqu = self.value * parent.pqu(unit) if self...
This is an abstract base class for number quantities. This class adds the pqu and float methods.
Number
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Number: """This is an abstract base class for number quantities. This class adds the pqu and float methods.""" def pqu(self, unit=None): """Returns a PQU instance of self's value in units of unit. If unit is None, self's unit is used.""" <|body_0|> def float(self, unit):...
stack_v2_sparse_classes_36k_train_023773
5,573
permissive
[ { "docstring": "Returns a PQU instance of self's value in units of unit. If unit is None, self's unit is used.", "name": "pqu", "signature": "def pqu(self, unit=None)" }, { "docstring": "Returns a float instance of self's value in units of unit.", "name": "float", "signature": "def float...
2
stack_v2_sparse_classes_30k_train_003205
Implement the Python class `Number` described below. Class description: This is an abstract base class for number quantities. This class adds the pqu and float methods. Method signatures and docstrings: - def pqu(self, unit=None): Returns a PQU instance of self's value in units of unit. If unit is None, self's unit i...
Implement the Python class `Number` described below. Class description: This is an abstract base class for number quantities. This class adds the pqu and float methods. Method signatures and docstrings: - def pqu(self, unit=None): Returns a PQU instance of self's value in units of unit. If unit is None, self's unit i...
6ba80855ae47cb32c37f635d065b228fadb03412
<|skeleton|> class Number: """This is an abstract base class for number quantities. This class adds the pqu and float methods.""" def pqu(self, unit=None): """Returns a PQU instance of self's value in units of unit. If unit is None, self's unit is used.""" <|body_0|> def float(self, unit):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Number: """This is an abstract base class for number quantities. This class adds the pqu and float methods.""" def pqu(self, unit=None): """Returns a PQU instance of self's value in units of unit. If unit is None, self's unit is used.""" parent = self.ancestor.ancestor.ancestor if...
the_stack_v2_python_sparse
xData/uncertainty/physicalQuantity/uncertainty.py
LLNL/fudge
train
21
2c4bb2f28564e7a01ac2030caa2b44d047a4359d
[ "stack = []\nlast_sign = ''\nops = {'+', '-', '*', '/'}\ni = 0\nwhile i < len(s):\n if s[i] in ops:\n last_sign = s[i]\n if s[i] == '*' or s[i] == '/':\n popped = stack.pop()\n op = s[i]\n while i < len(s) and (not s[i].isdigit()):\n i += 1\n char_int = ''\n ...
<|body_start_0|> stack = [] last_sign = '' ops = {'+', '-', '*', '/'} i = 0 while i < len(s): if s[i] in ops: last_sign = s[i] if s[i] == '*' or s[i] == '/': popped = stack.pop() op = s[i] whi...
Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II.
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II.""" def calculate(self, s): """Implement a basic calculator to evaluate a simple expre...
stack_v2_sparse_classes_36k_train_023774
2,510
no_license
[ { "docstring": "Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: \"3+2*2\" Output: 7 Example 2: Input: \" 3/2 \" Output: 1 Ex...
2
null
Implement the Python class `Solution` described below. Class description: Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II. Method signatures and docstrings: - def calculate(self, s)...
Implement the Python class `Solution` described below. Class description: Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II. Method signatures and docstrings: - def calculate(self, s)...
01fe893ba2e37c9bda79e3081c556698f0b6d2f0
<|skeleton|> class Solution: """Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II.""" def calculate(self, s): """Implement a basic calculator to evaluate a simple expre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Runtime: 148 ms, faster than 25.47% of Python3 online submissions for Basic Calculator II. Memory Usage: 15.5 MB, less than 18.91% of Python3 online submissions for Basic Calculator II.""" def calculate(self, s): """Implement a basic calculator to evaluate a simple expression string....
the_stack_v2_python_sparse
LeetCode/227_basic_calculator_II.py
KKosukeee/CodingQuestions
train
1
86ef465c498e6512a8882563a753d6b876e12146
[ "self.num_constraints = num_constraints\nself.population = population\nif population > num_evals:\n raise ValueError('Population size must not be greater than number of evaluations.')\nself.num_evals = num_evals // population * population\nself.seed = seed\nself.crossover_prob = crossover_prob\nself.crossover_et...
<|body_start_0|> self.num_constraints = num_constraints self.population = population if population > num_evals: raise ValueError('Population size must not be greater than number of evaluations.') self.num_evals = num_evals // population * population self.seed = seed ...
Storage class for search parameters.
SearchParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SearchParams: """Storage class for search parameters.""" def __init__(self, num_evals: float, num_constraints: float, population: float, seed: float, crossover_prob: float, crossover_eta: float, mutation_prob: float, mutation_eta: float, acc_delta: float, ref_acc: float): """Initiali...
stack_v2_sparse_classes_36k_train_023775
23,022
permissive
[ { "docstring": "Initializes storage class for search parameters. :param num_evals: Number of evaluations for the search algorithm. :param num_constraints: Number of constraints in search problem :param population: Population size :param seed: Seed used by the search algorithm. :param crossover_prob: Crossover p...
2
null
Implement the Python class `SearchParams` described below. Class description: Storage class for search parameters. Method signatures and docstrings: - def __init__(self, num_evals: float, num_constraints: float, population: float, seed: float, crossover_prob: float, crossover_eta: float, mutation_prob: float, mutatio...
Implement the Python class `SearchParams` described below. Class description: Storage class for search parameters. Method signatures and docstrings: - def __init__(self, num_evals: float, num_constraints: float, population: float, seed: float, crossover_prob: float, crossover_eta: float, mutation_prob: float, mutatio...
c027c8b43c4865d46b8de01d8350dd338ec5a874
<|skeleton|> class SearchParams: """Storage class for search parameters.""" def __init__(self, num_evals: float, num_constraints: float, population: float, seed: float, crossover_prob: float, crossover_eta: float, mutation_prob: float, mutation_eta: float, acc_delta: float, ref_acc: float): """Initiali...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SearchParams: """Storage class for search parameters.""" def __init__(self, num_evals: float, num_constraints: float, population: float, seed: float, crossover_prob: float, crossover_eta: float, mutation_prob: float, mutation_eta: float, acc_delta: float, ref_acc: float): """Initializes storage c...
the_stack_v2_python_sparse
nncf/experimental/torch/nas/bootstrapNAS/search/search.py
openvinotoolkit/nncf
train
558
794b80ae10425635e439c54840b72901b7ec5117
[ "from jizhipy.Basic import Time\nkey = ['PIXTYPE', 'DATECREA', 'ORDERING', 'NSIDE', 'COORDSYS']\nvalue = ['HEALPIX', Time(1), ordering.upper(), nside, coordsys.upper()]\ncomment = ['HEALPIX pixelisation', 'Creation date of this file', 'Pixel ordering scheme, RING or NESTED', 'Healpix resolution parameter', 'Coordin...
<|body_start_0|> from jizhipy.Basic import Time key = ['PIXTYPE', 'DATECREA', 'ORDERING', 'NSIDE', 'COORDSYS'] value = ['HEALPIX', Time(1), ordering.upper(), nside, coordsys.upper()] comment = ['HEALPIX pixelisation', 'Creation date of this file', 'Pixel ordering scheme, RING or NESTED',...
Healpix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Healpix: def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): """nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map ...
stack_v2_sparse_classes_36k_train_023776
16,919
no_license
[ { "docstring": "nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map in arcmin return: [key, value, comment]", "name": "HealpixHeader", "signature": "def HealpixHeader(self, nside, o...
2
stack_v2_sparse_classes_30k_train_014461
Implement the Python class `Healpix` described below. Class description: Implement the Healpix class. Method signatures and docstrings: - def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq:...
Implement the Python class `Healpix` described below. Class description: Implement the Healpix class. Method signatures and docstrings: - def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq:...
b49777105a76b5ae03555a9f93f116454c8245a9
<|skeleton|> class Healpix: def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): """nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Healpix: def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): """nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map in arcmin retu...
the_stack_v2_python_sparse
Astro/Healpix.py
jizhi/jizhipy
train
1
3b3e1b114ca0a4c4562e4d28b4a5aa6f586c7431
[ "if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)):\n for anchor in anchor_list:\n pprint('%s is the achor of %s' % (anchor.name, [feature.name for feature in anchor.features]))\nelse:\n raise TypeError('anchor_list must be FeatureAnchor or List[FeatureAnchor]')", "if isinstance(f...
<|body_start_0|> if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)): for anchor in anchor_list: pprint('%s is the achor of %s' % (anchor.name, [feature.name for feature in anchor.features])) else: raise TypeError('anchor_list must be FeatureAnch...
The class for pretty-printing features
FeaturePrinter
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeaturePrinter: """The class for pretty-printing features""" def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: """Pretty print features Args: feature_list: FeatureAnchor""" <|body_0|> def pretty_print_feature_query(feature_query: FeatureQuery) -> None: ...
stack_v2_sparse_classes_36k_train_023777
1,725
permissive
[ { "docstring": "Pretty print features Args: feature_list: FeatureAnchor", "name": "pretty_print_anchors", "signature": "def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None" }, { "docstring": "Pretty print feature query Args: feature_query: feature query", "name": "pretty_print...
3
stack_v2_sparse_classes_30k_train_001741
Implement the Python class `FeaturePrinter` described below. Class description: The class for pretty-printing features Method signatures and docstrings: - def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: Pretty print features Args: feature_list: FeatureAnchor - def pretty_print_feature_query(featur...
Implement the Python class `FeaturePrinter` described below. Class description: The class for pretty-printing features Method signatures and docstrings: - def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: Pretty print features Args: feature_list: FeatureAnchor - def pretty_print_feature_query(featur...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class FeaturePrinter: """The class for pretty-printing features""" def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: """Pretty print features Args: feature_list: FeatureAnchor""" <|body_0|> def pretty_print_feature_query(feature_query: FeatureQuery) -> None: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeaturePrinter: """The class for pretty-printing features""" def pretty_print_anchors(anchor_list: List[FeatureAnchor]) -> None: """Pretty print features Args: feature_list: FeatureAnchor""" if all((isinstance(anchor, FeatureAnchor) for anchor in anchor_list)): for anchor in a...
the_stack_v2_python_sparse
ai/feathr/feathr_project/feathr/utils/feature_printer.py
alldatacenter/alldata
train
774
94745719ca3ca8d75a9fa780a4d92d2f81263ebe
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Win32LobAppPowerShellScriptRule()", "from .run_as_account_type import RunAsAccountType\nfrom .win32_lob_app_power_shell_script_rule_operation_type import Win32LobAppPowerShellScriptRuleOperationType\nfrom .win32_lob_app_rule import Win...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Win32LobAppPowerShellScriptRule() <|end_body_0|> <|body_start_1|> from .run_as_account_type import RunAsAccountType from .win32_lob_app_power_shell_script_rule_operation_type import Win3...
A complex type to store the PowerShell script rule data for a Win32 LOB app.
Win32LobAppPowerShellScriptRule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Win32LobAppPowerShellScriptRule: """A complex type to store the PowerShell script rule data for a Win32 LOB app.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppPowerShellScriptRule: """Creates a new instance of the appropriate class based o...
stack_v2_sparse_classes_36k_train_023778
5,288
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: Win32LobAppPowerShellScriptRule", "name": "create_from_discriminator_value", "signature": "def create_from_d...
3
null
Implement the Python class `Win32LobAppPowerShellScriptRule` described below. Class description: A complex type to store the PowerShell script rule data for a Win32 LOB app. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppPowerShellScriptRule...
Implement the Python class `Win32LobAppPowerShellScriptRule` described below. Class description: A complex type to store the PowerShell script rule data for a Win32 LOB app. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppPowerShellScriptRule...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Win32LobAppPowerShellScriptRule: """A complex type to store the PowerShell script rule data for a Win32 LOB app.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppPowerShellScriptRule: """Creates a new instance of the appropriate class based o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Win32LobAppPowerShellScriptRule: """A complex type to store the PowerShell script rule data for a Win32 LOB app.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppPowerShellScriptRule: """Creates a new instance of the appropriate class based on discriminat...
the_stack_v2_python_sparse
msgraph/generated/models/win32_lob_app_power_shell_script_rule.py
microsoftgraph/msgraph-sdk-python
train
135
f19c4c637771d24e88293aa9e1654986779bfca3
[ "send = GlobalsatHandler.translateConfigOptions(self, send, options)\nif 'Ri' in options:\n send['freq_mov'] = options['Ri']\nif 'Ra' in options:\n send['freq_idle'] = options['Ra']\nif 'Ro' in options:\n send['send_mov'] = options['Ro']\nif 'S8' in options:\n send['send_by_angle'] = options['S8']\nretu...
<|body_start_0|> send = GlobalsatHandler.translateConfigOptions(self, send, options) if 'Ri' in options: send['freq_mov'] = options['Ri'] if 'Ra' in options: send['freq_idle'] = options['Ra'] if 'Ro' in options: send['send_mov'] = options['Ro'] ...
Globalsat. GTR-128/GTR-129
Handler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Handler: """Globalsat. GTR-128/GTR-129""" def translateConfigOptions(self, send, options): """Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed options""" <|body_0|> def translate(self, data): ...
stack_v2_sparse_classes_36k_train_023779
4,416
no_license
[ { "docstring": "Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed options", "name": "translateConfigOptions", "signature": "def translateConfigOptions(self, send, options)" }, { "docstring": "Translate gps-tracker data ...
3
stack_v2_sparse_classes_30k_train_016643
Implement the Python class `Handler` described below. Class description: Globalsat. GTR-128/GTR-129 Method signatures and docstrings: - def translateConfigOptions(self, send, options): Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed option...
Implement the Python class `Handler` described below. Class description: Globalsat. GTR-128/GTR-129 Method signatures and docstrings: - def translateConfigOptions(self, send, options): Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed option...
4a4bc730252ece695b2773388812e2d59d4947ce
<|skeleton|> class Handler: """Globalsat. GTR-128/GTR-129""" def translateConfigOptions(self, send, options): """Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed options""" <|body_0|> def translate(self, data): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Handler: """Globalsat. GTR-128/GTR-129""" def translateConfigOptions(self, send, options): """Translate gps-tracker parsed options to observer format @param send: {string[]} data to send @param options: {string[]} parsed options""" send = GlobalsatHandler.translateConfigOptions(self, send...
the_stack_v2_python_sparse
lib/handlers/globalsat/gtr128.py
maprox/pipe
train
4
43c1a09496f35dddcb68870869b5d328801517c4
[ "total_sum = sum(nums)\nif total_sum % 2 != 0:\n return False\nsubset_sum = total_sum // 2\ndp = [False] * (subset_sum + 1)\ndp[0] = True\nfor curr in nums:\n for j in range(subset_sum, curr - 1, -1):\n dp[j] = dp[j] or dp[j - curr]\nreturn dp[subset_sum]", "total_sum = sum(nums)\nif total_sum % 2 !=...
<|body_start_0|> total_sum = sum(nums) if total_sum % 2 != 0: return False subset_sum = total_sum // 2 dp = [False] * (subset_sum + 1) dp[0] = True for curr in nums: for j in range(subset_sum, curr - 1, -1): dp[j] = dp[j] or dp[j - ...
Array
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Array: def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool: """Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return:""" <|body_0|> def can_partition_equal_subset_sum_(self, nums: List[int]) -> bool: "...
stack_v2_sparse_classes_36k_train_023780
2,676
no_license
[ { "docstring": "Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return:", "name": "can_partition_equal_subset_sum__", "signature": "def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool" }, { "docstring": "Approach: DP - Bottom Up Ti...
3
stack_v2_sparse_classes_30k_train_014118
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool: Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return: - def can_...
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool: Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return: - def can_...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Array: def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool: """Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return:""" <|body_0|> def can_partition_equal_subset_sum_(self, nums: List[int]) -> bool: "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Array: def can_partition_equal_subset_sum__(self, nums: List[int]) -> bool: """Approach: DP - 1D Array Bottom Up Time Complexity: O(M * N) Space Complexity: O(M) :param nums: :return:""" total_sum = sum(nums) if total_sum % 2 != 0: return False subset_sum = total_su...
the_stack_v2_python_sparse
expedia/partition_equal_subset_sum.py
Shiv2157k/leet_code
train
1
86216350d4e1ac462ac327389b9bb7050ead0c46
[ "guild_id = get_guild_id(guild)\nintegration_id_value = maybe_snowflake(integration_id)\nif integration_id_value is None:\n raise TypeError(f'`integration_id` can be `int`, got {integration_id.__class__.__name__}; {integration_id!r}.')\nif __debug__:\n if not isinstance(type_, str):\n raise AssertionEr...
<|body_start_0|> guild_id = get_guild_id(guild) integration_id_value = maybe_snowflake(integration_id) if integration_id_value is None: raise TypeError(f'`integration_id` can be `int`, got {integration_id.__class__.__name__}; {integration_id!r}.') if __debug__: if...
ClientCompoundIntegrationEndpoints
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientCompoundIntegrationEndpoints: async def integration_create(self, guild, integration_id, type_): """Creates an integration at the given guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild to what the integration will be attached to. integratio...
stack_v2_sparse_classes_36k_train_023781
10,448
permissive
[ { "docstring": "Creates an integration at the given guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild to what the integration will be attached to. integration_id : ``int`` The integration's id. type_ : `str` The integration's type (`'twitch'`, `'youtube'`, etc.). Return...
4
null
Implement the Python class `ClientCompoundIntegrationEndpoints` described below. Class description: Implement the ClientCompoundIntegrationEndpoints class. Method signatures and docstrings: - async def integration_create(self, guild, integration_id, type_): Creates an integration at the given guild. This method is a ...
Implement the Python class `ClientCompoundIntegrationEndpoints` described below. Class description: Implement the ClientCompoundIntegrationEndpoints class. Method signatures and docstrings: - async def integration_create(self, guild, integration_id, type_): Creates an integration at the given guild. This method is a ...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class ClientCompoundIntegrationEndpoints: async def integration_create(self, guild, integration_id, type_): """Creates an integration at the given guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild to what the integration will be attached to. integratio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientCompoundIntegrationEndpoints: async def integration_create(self, guild, integration_id, type_): """Creates an integration at the given guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild to what the integration will be attached to. integration_id : ``int``...
the_stack_v2_python_sparse
hata/discord/client/compounds/integration.py
HuyaneMatsu/hata
train
3
33b6d99c2cf72a6b9793d3d983c6925be6a3ce41
[ "data: List[int] = [109, 19]\nrelative_base: int = 2000\ncomputer = IntcodeComputer(data, relative_base=relative_base)\ncomputer.computation()\nresult = computer.relative_base\nself.assertEqual(result, 2019)\ndata: List[int] = [109, 19] + [0 for _ in range(10000)]\nrelative_base: int = 2019\noutput: int = 1234\ndat...
<|body_start_0|> data: List[int] = [109, 19] relative_base: int = 2000 computer = IntcodeComputer(data, relative_base=relative_base) computer.computation() result = computer.relative_base self.assertEqual(result, 2019) data: List[int] = [109, 19] + [0 for _ in ran...
()
TestAoC09
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAoC09: """()""" def test_computation(self): """Testing computation""" <|body_0|> def test_intcode_computer(self): """Testing intcode_computer""" <|body_1|> <|end_skeleton|> <|body_start_0|> data: List[int] = [109, 19] relative_base: ...
stack_v2_sparse_classes_36k_train_023782
1,820
no_license
[ { "docstring": "Testing computation", "name": "test_computation", "signature": "def test_computation(self)" }, { "docstring": "Testing intcode_computer", "name": "test_intcode_computer", "signature": "def test_intcode_computer(self)" } ]
2
stack_v2_sparse_classes_30k_train_013006
Implement the Python class `TestAoC09` described below. Class description: () Method signatures and docstrings: - def test_computation(self): Testing computation - def test_intcode_computer(self): Testing intcode_computer
Implement the Python class `TestAoC09` described below. Class description: () Method signatures and docstrings: - def test_computation(self): Testing computation - def test_intcode_computer(self): Testing intcode_computer <|skeleton|> class TestAoC09: """()""" def test_computation(self): """Testing ...
4c49273b8f9846ccd2df54c2249a63bb4f8a4ddd
<|skeleton|> class TestAoC09: """()""" def test_computation(self): """Testing computation""" <|body_0|> def test_intcode_computer(self): """Testing intcode_computer""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestAoC09: """()""" def test_computation(self): """Testing computation""" data: List[int] = [109, 19] relative_base: int = 2000 computer = IntcodeComputer(data, relative_base=relative_base) computer.computation() result = computer.relative_base self...
the_stack_v2_python_sparse
test_aoc_09.py
iveL91/Advent-of-Code-2019
train
0
3319686966b089812c235acf94d6491e5bc64b7a
[ "if s[-1] == '1':\n return False\ndiff = defaultdict(int)\nfor i, char in enumerate(s):\n diff[i] += diff[i - 1]\n if char == '0' and (i == 0 or diff[i] > 0):\n diff[i + minJump] += 1\n diff[i + maxJump + 1] -= 1\nreturn diff[len(s) - 1] > 0", "if s[-1] == '1':\n return False\nn = len(s)...
<|body_start_0|> if s[-1] == '1': return False diff = defaultdict(int) for i, char in enumerate(s): diff[i] += diff[i - 1] if char == '0' and (i == 0 or diff[i] > 0): diff[i + minJump] += 1 diff[i + maxJump + 1] -= 1 ret...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: """差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法""" <|body_0|> def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: """差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k_train_023783
1,200
no_license
[ { "docstring": "差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法", "name": "canReach", "signature": "def canReach(self, s: str, minJump: int, maxJump: int) -> bool" }, { "docstring": "差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法", "name": "canReach2", "signature": "def canReach2(self, s: str, minJump: int, m...
2
stack_v2_sparse_classes_30k_train_004935
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canReach(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法 - def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canReach(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法 - def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: 差分数组区间更新,边遍历边还...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: """差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法""" <|body_0|> def canReach2(self, s: str, minJump: int, maxJump: int) -> bool: """差分数组区间更新,边遍历边还原数组值 不修改diff 用 curSum 的写法""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: """差分数组区间更新,边遍历边还原数组值 直接更新diff字典的写法""" if s[-1] == '1': return False diff = defaultdict(int) for i, char in enumerate(s): diff[i] += diff[i - 1] if char == '0' and (i =...
the_stack_v2_python_sparse
22_专题/跳跃游戏/1871. 跳跃游戏-差分范围更新.py
981377660LMT/algorithm-study
train
225
eef03dec285016ce35cceee709d5c2d19daed948
[ "self.tasks = tasks\nself.process_fn = process_fn\nself.result_fn = result_fn\nself.workers = workers\nself.sentinel = object()", "task_queue = queue.Queue(self.workers * 2)\nworker_objs = [_AsyncProcessrWorker(task_queue, self.process_fn, self.result_fn, self.sentinel) for _ in xrange(self.workers)]\nworker_gree...
<|body_start_0|> self.tasks = tasks self.process_fn = process_fn self.result_fn = result_fn self.workers = workers self.sentinel = object() <|end_body_0|> <|body_start_1|> task_queue = queue.Queue(self.workers * 2) worker_objs = [_AsyncProcessrWorker(task_queue, ...
Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the iterator at a time (useful if the task iterator is dynamically generating the tasks). ...
AsyncProcessor
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsyncProcessor: """Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the iterator at a time (useful if the task itera...
stack_v2_sparse_classes_36k_train_023784
8,401
permissive
[ { "docstring": "Args: tasks - Iterator of tasks. process_fn - Callable with the signature fn(task) -> result. Called on every task. result_fn - Callable with the signature fn(result). Called on every task result. workers - Number of parallel worker greenlets.", "name": "__init__", "signature": "def __in...
2
stack_v2_sparse_classes_30k_train_006948
Implement the Python class `AsyncProcessor` described below. Class description: Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the itera...
Implement the Python class `AsyncProcessor` described below. Class description: Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the itera...
0254e76348d247ab957ff547df9662a69cab4c9c
<|skeleton|> class AsyncProcessor: """Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the iterator at a time (useful if the task itera...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AsyncProcessor: """Process a sequence of tasks in parallel. Tasks are pulled from the task iterator and placed in a queue for worker greenlets to pull from. The size of the task queue is limited, so that only a small number of tasks are pulled from the iterator at a time (useful if the task iterator is dynami...
the_stack_v2_python_sparse
src/taba/util/thread_util.py
tellapart/taba
train
9
5c7a4736cbbbd8f71bc1462f2b3e84dc787063ac
[ "guess_str = (str(merkle_root) + str(previous_hash) + str(nonce)).encode('utf8')\nguess_hash = FuncUtil.hashfunc_sha256(guess_str)\nreturn guess_hash[:difficulty] == '0' * difficulty", "last_hash = TypesUtil.hash_json(last_block)\ntx_HMT = MerkleTree(transactions, FuncUtil.hashfunc_sha256)\nif len(tx_HMT) == 0:\n...
<|body_start_0|> guess_str = (str(merkle_root) + str(previous_hash) + str(nonce)).encode('utf8') guess_hash = FuncUtil.hashfunc_sha256(guess_str) return guess_hash[:difficulty] == '0' * difficulty <|end_body_0|> <|body_start_1|> last_hash = TypesUtil.hash_json(last_block) tx_HMT...
Proof-of-Work consenses mechanism
POW
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class POW: """Proof-of-Work consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, difficulty=MINING_DIFFICULTY): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the random number used in Po...
stack_v2_sparse_classes_36k_train_023785
5,661
no_license
[ { "docstring": "Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the random number used in PoW guess @ merkle_root: merkle tree root of transactions in block", "name": "valid_proof", "signature": "def valid_proof(merkle_root, p...
2
null
Implement the Python class `POW` described below. Class description: Proof-of-Work consenses mechanism Method signatures and docstrings: - def valid_proof(merkle_root, previous_hash, nonce, difficulty=MINING_DIFFICULTY): Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The h...
Implement the Python class `POW` described below. Class description: Proof-of-Work consenses mechanism Method signatures and docstrings: - def valid_proof(merkle_root, previous_hash, nonce, difficulty=MINING_DIFFICULTY): Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The h...
03ff57e6fe0114ffd2dd953e79a73a893a6bc0ad
<|skeleton|> class POW: """Proof-of-Work consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, difficulty=MINING_DIFFICULTY): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the random number used in Po...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class POW: """Proof-of-Work consenses mechanism""" def valid_proof(merkle_root, previous_hash, nonce, difficulty=MINING_DIFFICULTY): """Check if a guessing hash value satisfies the mining difficulty conditions. @ previous_hash: The hash of parent block @ nonce: the random number used in PoW guess @ mer...
the_stack_v2_python_sparse
Security/py_dev/ENF_chain/consensus/consensus.py
samuelxu999/Research
train
1
588a089f8352d9052847b1dfb419baa0aadb9132
[ "check_type(session, RestSession, may_be_none=False)\nsuper(RolesAPI, self).__init__()\nself._session = session\nself._object_factory = object_factory", "check_type(max, int)\nparams = dict_from_items_with_values(request_parameters, max=max)\nitems = self._session.get_items(API_ENDPOINT, params=params)\nfor item ...
<|body_start_0|> check_type(session, RestSession, may_be_none=False) super(RolesAPI, self).__init__() self._session = session self._object_factory = object_factory <|end_body_0|> <|body_start_1|> check_type(max, int) params = dict_from_items_with_values(request_parameter...
Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects.
RolesAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RolesAPI: """Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects.""" def __init__(self, session, object_factory): """Initialize a new RolesAPI object with the provided RestSession. Args: session(RestSes...
stack_v2_sparse_classes_36k_train_023786
3,733
permissive
[ { "docstring": "Initialize a new RolesAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Cisco Spark service. Raises: TypeError: If the parameter types are incorrect.", "name": "__init__", "signature": "def __init__(self, sess...
3
null
Implement the Python class `RolesAPI` described below. Class description: Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects. Method signatures and docstrings: - def __init__(self, session, object_factory): Initialize a new RolesAPI ob...
Implement the Python class `RolesAPI` described below. Class description: Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects. Method signatures and docstrings: - def __init__(self, session, object_factory): Initialize a new RolesAPI ob...
e0ab24a99791c3b25422a3208f02919cf98ca084
<|skeleton|> class RolesAPI: """Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects.""" def __init__(self, session, object_factory): """Initialize a new RolesAPI object with the provided RestSession. Args: session(RestSes...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RolesAPI: """Cisco Spark Roles API. Wraps the Cisco Spark Roles API and exposes the API as native Python methods that return native Python objects.""" def __init__(self, session, object_factory): """Initialize a new RolesAPI object with the provided RestSession. Args: session(RestSession): The RE...
the_stack_v2_python_sparse
webex_integration/_trash/_ciscosparkapi/ciscosparkapi/ciscosparkapi/api/roles.py
jurgeon018/snippets
train
0
89b9d7f0f9c993e133cad8229fb5cfe9cd8f04af
[ "context = self.env.context\nif type(context.get('default_location_id')) in (int, long):\n return context.get('default_location_id')\nif isinstance(context.get('default_location_id'), basestring):\n location_ids = self.env.get('stock.location').name_search(name=context['default_location_id'])\n if len(loca...
<|body_start_0|> context = self.env.context if type(context.get('default_location_id')) in (int, long): return context.get('default_location_id') if isinstance(context.get('default_location_id'), basestring): location_ids = self.env.get('stock.location').name_search(name=...
simple_stock_in_line
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class simple_stock_in_line: def _resolve_location_id_from_context(self): """Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team.""" <|body_0|> def _get_default_location_id(self): """Gives default sec...
stack_v2_sparse_classes_36k_train_023787
11,827
no_license
[ { "docstring": "Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team.", "name": "_resolve_location_id_from_context", "signature": "def _resolve_location_id_from_context(self)" }, { "docstring": "Gives default section by che...
2
stack_v2_sparse_classes_30k_train_002754
Implement the Python class `simple_stock_in_line` described below. Class description: Implement the simple_stock_in_line class. Method signatures and docstrings: - def _resolve_location_id_from_context(self): Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a s...
Implement the Python class `simple_stock_in_line` described below. Class description: Implement the simple_stock_in_line class. Method signatures and docstrings: - def _resolve_location_id_from_context(self): Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a s...
46e15330b5d642053da61754247f3fbf9d02717e
<|skeleton|> class simple_stock_in_line: def _resolve_location_id_from_context(self): """Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team.""" <|body_0|> def _get_default_location_id(self): """Gives default sec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class simple_stock_in_line: def _resolve_location_id_from_context(self): """Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team.""" context = self.env.context if type(context.get('default_location_id')) in (int, long):...
the_stack_v2_python_sparse
core/simple_stock2/models/simple_stock_in.py
Muhammad-SF/Test
train
0
4a9ac082e0c734e0f22dd9679562f00b079808ba
[ "table_name = name\nusername = request.user.username\nerror, workspace, dtable = _resource_check(workspace_id, table_name)\nif error:\n return error\nowner = workspace.owner\nerror = _permission_check_for_api_token(username, owner)\nif error:\n return error\ntry:\n api_token_obj = DTableAPIToken.objects.ge...
<|body_start_0|> table_name = name username = request.user.username error, workspace, dtable = _resource_check(workspace_id, table_name) if error: return error owner = workspace.owner error = _permission_check_for_api_token(username, owner) if error: ...
DTableAPITokenView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DTableAPITokenView: def delete(self, request, workspace_id, name, app_name): """delete dtable api token""" <|body_0|> def put(self, request, workspace_id, name, app_name): """update dtable api token""" <|body_1|> <|end_skeleton|> <|body_start_0|> ta...
stack_v2_sparse_classes_36k_train_023788
18,184
no_license
[ { "docstring": "delete dtable api token", "name": "delete", "signature": "def delete(self, request, workspace_id, name, app_name)" }, { "docstring": "update dtable api token", "name": "put", "signature": "def put(self, request, workspace_id, name, app_name)" } ]
2
null
Implement the Python class `DTableAPITokenView` described below. Class description: Implement the DTableAPITokenView class. Method signatures and docstrings: - def delete(self, request, workspace_id, name, app_name): delete dtable api token - def put(self, request, workspace_id, name, app_name): update dtable api tok...
Implement the Python class `DTableAPITokenView` described below. Class description: Implement the DTableAPITokenView class. Method signatures and docstrings: - def delete(self, request, workspace_id, name, app_name): delete dtable api token - def put(self, request, workspace_id, name, app_name): update dtable api tok...
3d08b64bf2a3724326eab9dfa771863bc6743bc2
<|skeleton|> class DTableAPITokenView: def delete(self, request, workspace_id, name, app_name): """delete dtable api token""" <|body_0|> def put(self, request, workspace_id, name, app_name): """update dtable api token""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DTableAPITokenView: def delete(self, request, workspace_id, name, app_name): """delete dtable api token""" table_name = name username = request.user.username error, workspace, dtable = _resource_check(workspace_id, table_name) if error: return error ...
the_stack_v2_python_sparse
seahub/api2/endpoints/dtable_api_token.py
flazx/dtable-web
train
0
bf3d77cfbacf551e2c5dea2ea2d05edf901f1528
[ "with Database() as db:\n if id_county is None and is_active is None:\n data = db.query(Table).all()\n elif id_county is None:\n data = db.query(Table).filter(Table.is_active == is_active).all()\n else:\n data = db.query(Table).get(id_county)\nreturn {'data': data}", "if self.has_per...
<|body_start_0|> with Database() as db: if id_county is None and is_active is None: data = db.query(Table).all() elif id_county is None: data = db.query(Table).filter(Table.is_active == is_active).all() else: data = db.query(Tab...
County
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class County: def get(self, id_county=None, is_active=None): """Return all county information :param id_county: UUID :param id_active: BOOLEAN""" <|body_0|> def create(self, body): """Create a new county :param body: { name: JSON, id_state: UUID, id_region: UUID }""" ...
stack_v2_sparse_classes_36k_train_023789
2,572
no_license
[ { "docstring": "Return all county information :param id_county: UUID :param id_active: BOOLEAN", "name": "get", "signature": "def get(self, id_county=None, is_active=None)" }, { "docstring": "Create a new county :param body: { name: JSON, id_state: UUID, id_region: UUID }", "name": "create",...
4
null
Implement the Python class `County` described below. Class description: Implement the County class. Method signatures and docstrings: - def get(self, id_county=None, is_active=None): Return all county information :param id_county: UUID :param id_active: BOOLEAN - def create(self, body): Create a new county :param bod...
Implement the Python class `County` described below. Class description: Implement the County class. Method signatures and docstrings: - def get(self, id_county=None, is_active=None): Return all county information :param id_county: UUID :param id_active: BOOLEAN - def create(self, body): Create a new county :param bod...
43bd57c466a5cd3b133ddc437cb4a6b9f007d267
<|skeleton|> class County: def get(self, id_county=None, is_active=None): """Return all county information :param id_county: UUID :param id_active: BOOLEAN""" <|body_0|> def create(self, body): """Create a new county :param body: { name: JSON, id_state: UUID, id_region: UUID }""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class County: def get(self, id_county=None, is_active=None): """Return all county information :param id_county: UUID :param id_active: BOOLEAN""" with Database() as db: if id_county is None and is_active is None: data = db.query(Table).all() elif id_county is ...
the_stack_v2_python_sparse
resturls/county.py
CAUCA-9-1-1/survip-api
train
1
beacbe522296fef056837702b3af4917b4b364f0
[ "super().init_weights()\nif self.loss_cls.use_sigmoid:\n bias_init = bias_init_with_prob(0.01)\n nn.init.constant_(self.fc_cls.bias, bias_init)", "references_unsigmoid = inverse_sigmoid(references)\nlayers_bbox_preds = []\nfor layer_id in range(hidden_states.shape[0]):\n tmp_reg_preds = self.fc_reg(self....
<|body_start_0|> super().init_weights() if self.loss_cls.use_sigmoid: bias_init = bias_init_with_prob(0.01) nn.init.constant_(self.fc_cls.bias, bias_init) <|end_body_0|> <|body_start_1|> references_unsigmoid = inverse_sigmoid(references) layers_bbox_preds = [] ...
Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ .
ConditionalDETRHead
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConditionalDETRHead: """Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ .""" def init_weights(self): """Initialize weights of the transformer head.""" <|b...
stack_v2_sparse_classes_36k_train_023790
7,186
permissive
[ { "docstring": "Initialize weights of the transformer head.", "name": "init_weights", "signature": "def init_weights(self)" }, { "docstring": "\"Forward function. Args: hidden_states (Tensor): Features from transformer decoder. If `return_intermediate_dec` is True output has shape (num_decoder_l...
5
stack_v2_sparse_classes_30k_train_008702
Implement the Python class `ConditionalDETRHead` described below. Class description: Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ . Method signatures and docstrings: - def init_weights(self): I...
Implement the Python class `ConditionalDETRHead` described below. Class description: Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ . Method signatures and docstrings: - def init_weights(self): I...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class ConditionalDETRHead: """Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ .""" def init_weights(self): """Initialize weights of the transformer head.""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConditionalDETRHead: """Head of Conditional DETR. Conditional DETR: Conditional DETR for Fast Training Convergence. More details can be found in the `paper. <https://arxiv.org/abs/2108.06152>`_ .""" def init_weights(self): """Initialize weights of the transformer head.""" super().init_wei...
the_stack_v2_python_sparse
ai/mmdetection/mmdet/models/dense_heads/conditional_detr_head.py
alldatacenter/alldata
train
774
4e51e31e4cf653eef361adbe6fda684f3ee0fb42
[ "self.hab = hab\nself.reger = reger if reger is not None else Registry(name=name)\nself.tevers = tevers if tevers is not None else dict()\nself.tvy = eventing.Tevery(tevers=self.tevers, reger=self.reger, db=self.hab.db, regk=None, local=False)\nself.psr = parsing.Parser(framed=True, kvy=self.hab.kvy, tvy=self.tvy)"...
<|body_start_0|> self.hab = hab self.reger = reger if reger is not None else Registry(name=name) self.tevers = tevers if tevers is not None else dict() self.tvy = eventing.Tevery(tevers=self.tevers, reger=self.reger, db=self.hab.db, regk=None, local=False) self.psr = parsing.Pars...
Verifier class accepts and validates TEL events.
Verifier
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Verifier: """Verifier class accepts and validates TEL events.""" def __init__(self, hab, name='test', reger=None, tevers=None): """Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user synonym for this verifier reger is Registry database ins...
stack_v2_sparse_classes_36k_train_023791
3,250
permissive
[ { "docstring": "Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user synonym for this verifier reger is Registry database instance tevers is dict of Tever instances keys by registry identifier", "name": "__init__", "signature": "def __init__(self, hab, name='t...
4
stack_v2_sparse_classes_30k_train_011532
Implement the Python class `Verifier` described below. Class description: Verifier class accepts and validates TEL events. Method signatures and docstrings: - def __init__(self, hab, name='test', reger=None, tevers=None): Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user...
Implement the Python class `Verifier` described below. Class description: Verifier class accepts and validates TEL events. Method signatures and docstrings: - def __init__(self, hab, name='test', reger=None, tevers=None): Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user...
f3f5442ef21127a19b19f584f679c0e7a8e11044
<|skeleton|> class Verifier: """Verifier class accepts and validates TEL events.""" def __init__(self, hab, name='test', reger=None, tevers=None): """Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user synonym for this verifier reger is Registry database ins...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Verifier: """Verifier class accepts and validates TEL events.""" def __init__(self, hab, name='test', reger=None, tevers=None): """Initialize Verifier instance Parameters: hab is Habitat for this verifier's context name is user synonym for this verifier reger is Registry database instance tevers ...
the_stack_v2_python_sparse
src/keri/vdr/verifying.py
SmithSamuelM/keripy-dif
train
0
98ebed895d3d13b48b5ba4d08ea7ca1226cfdabf
[ "text += '\\n\\n'\ntext += f\"*{get_text(user, 'start_button_profile_id')}*\" + str(user.id) + '\\n'\ntext += f\"*{get_text(user, 'start_button_profile_current_course')}*\"\ncur_subs = DataBaseFunc.get_current_subscribe(user)\nif user.is_have_subscription and cur_subs != None:\n info_subscribe = DataBaseFunc.get...
<|body_start_0|> text += '\n\n' text += f"*{get_text(user, 'start_button_profile_id')}*" + str(user.id) + '\n' text += f"*{get_text(user, 'start_button_profile_current_course')}*" cur_subs = DataBaseFunc.get_current_subscribe(user) if user.is_have_subscription and cur_subs != Non...
Класс помогает формировать некоторые функции для обработки User_Handlers
UserHelp
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserHelp: """Класс помогает формировать некоторые функции для обработки User_Handlers""" def get_start_menu_button_profile_text(user: User, text): """Формирует текст для информации профиля.""" <|body_0|> def get_history_menu_profile(user: User): """Формирует исто...
stack_v2_sparse_classes_36k_train_023792
1,835
no_license
[ { "docstring": "Формирует текст для информации профиля.", "name": "get_start_menu_button_profile_text", "signature": "def get_start_menu_button_profile_text(user: User, text)" }, { "docstring": "Формирует историю подписок пользователя.", "name": "get_history_menu_profile", "signature": "...
2
stack_v2_sparse_classes_30k_train_014832
Implement the Python class `UserHelp` described below. Class description: Класс помогает формировать некоторые функции для обработки User_Handlers Method signatures and docstrings: - def get_start_menu_button_profile_text(user: User, text): Формирует текст для информации профиля. - def get_history_menu_profile(user: ...
Implement the Python class `UserHelp` described below. Class description: Класс помогает формировать некоторые функции для обработки User_Handlers Method signatures and docstrings: - def get_start_menu_button_profile_text(user: User, text): Формирует текст для информации профиля. - def get_history_menu_profile(user: ...
3cc6f549e9d6e95c01830a9d9b6d78fb60f4f541
<|skeleton|> class UserHelp: """Класс помогает формировать некоторые функции для обработки User_Handlers""" def get_start_menu_button_profile_text(user: User, text): """Формирует текст для информации профиля.""" <|body_0|> def get_history_menu_profile(user: User): """Формирует исто...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserHelp: """Класс помогает формировать некоторые функции для обработки User_Handlers""" def get_start_menu_button_profile_text(user: User, text): """Формирует текст для информации профиля.""" text += '\n\n' text += f"*{get_text(user, 'start_button_profile_id')}*" + str(user.id) +...
the_stack_v2_python_sparse
handlers/user_handlers/helpers/help.py
cat157/lanamilana_bot_telegram
train
0
936843fd1a1c8006bdcbb87d5a3f1cdc7137f77d
[ "self.input_json_path = input_json_path\nself.template_pattern = template_pattern\nself.templates = []\nself.debug = debug\nif self.debug:\n print('TemplateDiscovery - __init__' + lineno())", "if self.debug:\n print('\\n\\n#######################################')\n print('discover templates' + lineno())...
<|body_start_0|> self.input_json_path = input_json_path self.template_pattern = template_pattern self.templates = [] self.debug = debug if self.debug: print('TemplateDiscovery - __init__' + lineno()) <|end_body_0|> <|body_start_1|> if self.debug: ...
Template discover
TemplateDiscovery
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplateDiscovery: """Template discover""" def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): """Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:""" <|bo...
stack_v2_sparse_classes_36k_train_023793
2,635
permissive
[ { "docstring": "Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:", "name": "__init__", "signature": "def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False)" }, { "docstring": "Di...
4
stack_v2_sparse_classes_30k_train_017396
Implement the Python class `TemplateDiscovery` described below. Class description: Template discover Method signatures and docstrings: - def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): Initialize TemplateDiscovery :param input_json_pat...
Implement the Python class `TemplateDiscovery` described below. Class description: Template discover Method signatures and docstrings: - def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): Initialize TemplateDiscovery :param input_json_pat...
a9d0335a532acdb4070e5537155b03b34915b73e
<|skeleton|> class TemplateDiscovery: """Template discover""" def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): """Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemplateDiscovery: """Template discover""" def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): """Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:""" self.input_json_p...
the_stack_v2_python_sparse
terraform_validator/TemplateDiscovery.py
rubelw/terraform-validator
train
7
52766b63250e46f75fe96371732b49b2efd7345b
[ "kwargs = super().get_form_kwargs()\nif hasattr(self, 'object'):\n kwargs.update({'instance': self.object})\nkwargs.update({'user': self.request.user})\nreturn kwargs", "self.object = form.save()\nself.object.save()\nfor permission in permissions:\n for item in permission['permissions']:\n if item[0]...
<|body_start_0|> kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) kwargs.update({'user': self.request.user}) return kwargs <|end_body_0|> <|body_start_1|> self.object = form.save() self.object.save() ...
Admin user can create a new account user
New
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class New: """Admin user can create a new account user""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" <|body_0|> def form_valid(self, form): """Method for valid form""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_023794
20,739
permissive
[ { "docstring": "Return the keyword arguments for instantiating the form.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }, { "docstring": "Method for valid form", "name": "form_valid", "signature": "def form_valid(self, form)" } ]
2
stack_v2_sparse_classes_30k_train_021688
Implement the Python class `New` described below. Class description: Admin user can create a new account user Method signatures and docstrings: - def get_form_kwargs(self): Return the keyword arguments for instantiating the form. - def form_valid(self, form): Method for valid form
Implement the Python class `New` described below. Class description: Admin user can create a new account user Method signatures and docstrings: - def get_form_kwargs(self): Return the keyword arguments for instantiating the form. - def form_valid(self, form): Method for valid form <|skeleton|> class New: """Admi...
f3f8354bf164fcfe86d597cdbc28b0e3b7b73bd1
<|skeleton|> class New: """Admin user can create a new account user""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" <|body_0|> def form_valid(self, form): """Method for valid form""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class New: """Admin user can create a new account user""" def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) kwargs.update({...
the_stack_v2_python_sparse
seshat/account/views.py
XecusM/SESHAT
train
0
5cb2a47095bcd1a84838323141c695c7e8167725
[ "if isinstance(value, str) and value.replace(' ', '') == '':\n raise InvalidEmptyValue(field_name=field.name)\nreturn value", "ti_utils = ThreatIntelUtil(session_tc=registry.session_tc)\ngroup_types = cls.group_types or ti_utils.group_types\nif value.lower() not in [i.lower() for i in group_types]:\n raise ...
<|body_start_0|> if isinstance(value, str) and value.replace(' ', '') == '': raise InvalidEmptyValue(field_name=field.name) return value <|end_body_0|> <|body_start_1|> ti_utils = ThreatIntelUtil(session_tc=registry.session_tc) group_types = cls.group_types or ti_utils.group...
Group Entity Field (Model) Type
GroupEntity
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupEntity: """Group Entity Field (Model) Type""" def is_empty(cls, value: str, field: ModelField) -> str: """Validate that the value is a non-empty string.""" <|body_0|> def is_type(cls, value: str, field: ModelField) -> str: """Validate that the value is a non...
stack_v2_sparse_classes_36k_train_023795
2,435
permissive
[ { "docstring": "Validate that the value is a non-empty string.", "name": "is_empty", "signature": "def is_empty(cls, value: str, field: ModelField) -> str" }, { "docstring": "Validate that the value is a non-empty string. Without the always and pre args, None values will validated before this va...
2
null
Implement the Python class `GroupEntity` described below. Class description: Group Entity Field (Model) Type Method signatures and docstrings: - def is_empty(cls, value: str, field: ModelField) -> str: Validate that the value is a non-empty string. - def is_type(cls, value: str, field: ModelField) -> str: Validate th...
Implement the Python class `GroupEntity` described below. Class description: Group Entity Field (Model) Type Method signatures and docstrings: - def is_empty(cls, value: str, field: ModelField) -> str: Validate that the value is a non-empty string. - def is_type(cls, value: str, field: ModelField) -> str: Validate th...
30dc147e40d63d1082ec2a5e6c62005b60c29c37
<|skeleton|> class GroupEntity: """Group Entity Field (Model) Type""" def is_empty(cls, value: str, field: ModelField) -> str: """Validate that the value is a non-empty string.""" <|body_0|> def is_type(cls, value: str, field: ModelField) -> str: """Validate that the value is a non...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupEntity: """Group Entity Field (Model) Type""" def is_empty(cls, value: str, field: ModelField) -> str: """Validate that the value is a non-empty string.""" if isinstance(value, str) and value.replace(' ', '') == '': raise InvalidEmptyValue(field_name=field.name) r...
the_stack_v2_python_sparse
tcex/input/field_type/group_entity.py
ThreatConnect-Inc/tcex
train
24
b31aba98df457d00dc052d52d2165d7210986b71
[ "n = words_list.Length()\nint_chunk = BytesUtils.ToInteger(bytes_chunk, endianness=endianness)\nword1_idx = int_chunk % n\nword2_idx = (int_chunk // n + word1_idx) % n\nword3_idx = (int_chunk // n // n + word2_idx) % n\nreturn [words_list.GetWordAtIdx(w) for w in (word1_idx, word2_idx, word3_idx)]", "n = words_li...
<|body_start_0|> n = words_list.Length() int_chunk = BytesUtils.ToInteger(bytes_chunk, endianness=endianness) word1_idx = int_chunk % n word2_idx = (int_chunk // n + word1_idx) % n word3_idx = (int_chunk // n // n + word2_idx) % n return [words_list.GetWordAtIdx(w) for w ...
Class container for mnemonic utility functions.
MnemonicUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MnemonicUtils: """Class container for mnemonic utility functions.""" def BytesChunkToWords(bytes_chunk: bytes, words_list: MnemonicWordsList, endianness: Literal['little', 'big']) -> List[str]: """Get words from a bytes chunk. Args: bytes_chunk (bytes) : Bytes chunk words_list (Mnemo...
stack_v2_sparse_classes_36k_train_023796
10,670
permissive
[ { "docstring": "Get words from a bytes chunk. Args: bytes_chunk (bytes) : Bytes chunk words_list (MnemonicWordsList object): Mnemonic list endianness (\"big\" or \"little\") : Bytes endianness Returns: list[str]: 3 word indexes", "name": "BytesChunkToWords", "signature": "def BytesChunkToWords(bytes_chu...
2
null
Implement the Python class `MnemonicUtils` described below. Class description: Class container for mnemonic utility functions. Method signatures and docstrings: - def BytesChunkToWords(bytes_chunk: bytes, words_list: MnemonicWordsList, endianness: Literal['little', 'big']) -> List[str]: Get words from a bytes chunk. ...
Implement the Python class `MnemonicUtils` described below. Class description: Class container for mnemonic utility functions. Method signatures and docstrings: - def BytesChunkToWords(bytes_chunk: bytes, words_list: MnemonicWordsList, endianness: Literal['little', 'big']) -> List[str]: Get words from a bytes chunk. ...
d15c75ddd74e4838c396a0d036ef6faf11b06a4b
<|skeleton|> class MnemonicUtils: """Class container for mnemonic utility functions.""" def BytesChunkToWords(bytes_chunk: bytes, words_list: MnemonicWordsList, endianness: Literal['little', 'big']) -> List[str]: """Get words from a bytes chunk. Args: bytes_chunk (bytes) : Bytes chunk words_list (Mnemo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MnemonicUtils: """Class container for mnemonic utility functions.""" def BytesChunkToWords(bytes_chunk: bytes, words_list: MnemonicWordsList, endianness: Literal['little', 'big']) -> List[str]: """Get words from a bytes chunk. Args: bytes_chunk (bytes) : Bytes chunk words_list (MnemonicWordsList ...
the_stack_v2_python_sparse
bip_utils/utils/mnemonic/mnemonic_utils.py
ebellocchia/bip_utils
train
244
0ce70d8d6b5dbb413321f983f5a5549843998376
[ "super(SymbolImage, self).__init__(path=path, image=image)\nif getattr(self, 'bin_matrix', None) is None:\n self.bin_matrix = BinaryImage(path=path, image=image).cristian_binarisation().bin_matrix", "m, n = self.bin_matrix.shape\nweight = np.sum(self.bin_matrix) // 255\nnorm_weight = weight / (self.height * se...
<|body_start_0|> super(SymbolImage, self).__init__(path=path, image=image) if getattr(self, 'bin_matrix', None) is None: self.bin_matrix = BinaryImage(path=path, image=image).cristian_binarisation().bin_matrix <|end_body_0|> <|body_start_1|> m, n = self.bin_matrix.shape weig...
Класс осуществляющий выделение символьных признаков для заданного изображения
SymbolImage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SymbolImage: """Класс осуществляющий выделение символьных признаков для заданного изображения""" def __init__(self, path=None, image=None): """Инициализация объекта класса SymbolImage :param path: путь до изображения :type path: str or None :param image: экземпляр класса LabImage :ty...
stack_v2_sparse_classes_36k_train_023797
6,836
no_license
[ { "docstring": "Инициализация объекта класса SymbolImage :param path: путь до изображения :type path: str or None :param image: экземпляр класса LabImage :type image: LabImage or None", "name": "__init__", "signature": "def __init__(self, path=None, image=None)" }, { "docstring": "Функция вычисл...
2
stack_v2_sparse_classes_30k_train_008741
Implement the Python class `SymbolImage` described below. Class description: Класс осуществляющий выделение символьных признаков для заданного изображения Method signatures and docstrings: - def __init__(self, path=None, image=None): Инициализация объекта класса SymbolImage :param path: путь до изображения :type path...
Implement the Python class `SymbolImage` described below. Class description: Класс осуществляющий выделение символьных признаков для заданного изображения Method signatures and docstrings: - def __init__(self, path=None, image=None): Инициализация объекта класса SymbolImage :param path: путь до изображения :type path...
c3a1228f8caf555fb640895b54be25ee8fe87ab2
<|skeleton|> class SymbolImage: """Класс осуществляющий выделение символьных признаков для заданного изображения""" def __init__(self, path=None, image=None): """Инициализация объекта класса SymbolImage :param path: путь до изображения :type path: str or None :param image: экземпляр класса LabImage :ty...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SymbolImage: """Класс осуществляющий выделение символьных признаков для заданного изображения""" def __init__(self, path=None, image=None): """Инициализация объекта класса SymbolImage :param path: путь до изображения :type path: str or None :param image: экземпляр класса LabImage :type image: Lab...
the_stack_v2_python_sparse
library/SymbolImage.py
Myasnikova/OCRLibrary
train
0
cd48a2132311d73612567d65ccd4118da7694dc5
[ "\"\"\"O(n)的时间复杂度\n 但是需要额外的存储空间\n 不好!\"\"\"\nx = str(x)\ni, j = (0, len(x) - 1)\nwhile i < j:\n if x[i] != x[j]:\n return False\n i += 1\n j -= 1\nreturn True", "\"\"\"log10(n)的时间复杂度\n 将数字进行反转,如果是回文肯定和原先数字一样,如果不一样不是回文,但是有溢出的风险。\n 所以可以只反转后裔一半数字\"\"\"\n'如果最后一位是0那么它是回文它必须是...
<|body_start_0|> """O(n)的时间复杂度 但是需要额外的存储空间 不好!""" x = str(x) i, j = (0, len(x) - 1) while i < j: if x[i] != x[j]: return False i += 1 j -= 1 return True <|end_body_0|> <|body_start_1|> ""...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindrome_2(self, x): """:param x: :return:""" <|body_1|> def isPalindrome_3(self, x): """beat 99.64%的人""" <|body_2|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_023798
1,657
no_license
[ { "docstring": ":type x: int :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, x)" }, { "docstring": ":param x: :return:", "name": "isPalindrome_2", "signature": "def isPalindrome_2(self, x)" }, { "docstring": "beat 99.64%的人", "name": "isPalindrome_3...
3
stack_v2_sparse_classes_30k_train_006128
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def isPalindrome_2(self, x): :param x: :return: - def isPalindrome_3(self, x): beat 99.64%的人
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def isPalindrome_2(self, x): :param x: :return: - def isPalindrome_3(self, x): beat 99.64%的人 <|skeleton|> class Solution: ...
09b7121628df824f432b8cdd25c55f045b013c0b
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindrome_2(self, x): """:param x: :return:""" <|body_1|> def isPalindrome_3(self, x): """beat 99.64%的人""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" """O(n)的时间复杂度 但是需要额外的存储空间 不好!""" x = str(x) i, j = (0, len(x) - 1) while i < j: if x[i] != x[j]: return False i += 1 ...
the_stack_v2_python_sparse
tuter_start/9_int.py
cainingning/leetcode
train
1
f010861e2989a19675cd54f6022fdac4b29ec0ff
[ "Parametre.__init__(self, 'renommer', 'rename')\nself.tronquer = True\nself.schema = '<ancien:nom_familier> <nouveau:nom_familier>'\nself.aide_courte = \"change le nom d'un familier\"\nself.aide_longue = \"Cette commande permet de changer le nom d'un familer. Ce nom est important, puisqu'il s'agit du nom que vous u...
<|body_start_0|> Parametre.__init__(self, 'renommer', 'rename') self.tronquer = True self.schema = '<ancien:nom_familier> <nouveau:nom_familier>' self.aide_courte = "change le nom d'un familier" self.aide_longue = "Cette commande permet de changer le nom d'un familer. Ce nom est ...
Commande 'familier renommer'.
PrmRenommer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmRenommer: """Commande 'familier renommer'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def ajouter(self): """Méthode appelée lors de l'ajout de la commande à l'interpréteur""" <|body_1|> def interpreter(self, personnage, dic_...
stack_v2_sparse_classes_36k_train_023799
3,553
permissive
[ { "docstring": "Constructeur du paramètre", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Méthode appelée lors de l'ajout de la commande à l'interpréteur", "name": "ajouter", "signature": "def ajouter(self)" }, { "docstring": "Interprétation du paramètr...
3
stack_v2_sparse_classes_30k_train_015101
Implement the Python class `PrmRenommer` described below. Class description: Commande 'familier renommer'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur - def interpreter(self, personnage, dic_masq...
Implement the Python class `PrmRenommer` described below. Class description: Commande 'familier renommer'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur - def interpreter(self, personnage, dic_masq...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmRenommer: """Commande 'familier renommer'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def ajouter(self): """Méthode appelée lors de l'ajout de la commande à l'interpréteur""" <|body_1|> def interpreter(self, personnage, dic_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrmRenommer: """Commande 'familier renommer'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'renommer', 'rename') self.tronquer = True self.schema = '<ancien:nom_familier> <nouveau:nom_familier>' self.aide_courte = "change le nom d...
the_stack_v2_python_sparse
src/secondaires/familier/commandes/familier/renommer.py
vincent-lg/tsunami
train
5