blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
fe39b800005afdc1ebf100eb9aabeef894f7a93d
[ "if not root:\n return 0\nheight = 0\ncurr_node = root\nwhile curr_node:\n height += 1\n curr_node = curr_node.left\nreturn 2 ** (height - 1) - 1 + self.helper(root, height)", "if not root:\n return 0\nif height == 1:\n return 1\nmid_node = root.left\ncurr_height = 2\nwhile curr_height < height:\n ...
<|body_start_0|> if not root: return 0 height = 0 curr_node = root while curr_node: height += 1 curr_node = curr_node.left return 2 ** (height - 1) - 1 + self.helper(root, height) <|end_body_0|> <|body_start_1|> if not root: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countNodes(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def helper(self, root, height): """count nodes in last level binary-search""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: return 0 ...
stack_v2_sparse_classes_75kplus_train_074700
1,077
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "countNodes", "signature": "def countNodes(self, root)" }, { "docstring": "count nodes in last level binary-search", "name": "helper", "signature": "def helper(self, root, height)" } ]
2
stack_v2_sparse_classes_30k_train_047537
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root): :type root: TreeNode :rtype: int - def helper(self, root, height): count nodes in last level binary-search
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root): :type root: TreeNode :rtype: int - def helper(self, root, height): count nodes in last level binary-search <|skeleton|> class Solution: def coun...
e7b1dcc8b8a33bbe705d9ce348c75ea2474761c4
<|skeleton|> class Solution: def countNodes(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def helper(self, root, height): """count nodes in last level binary-search""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countNodes(self, root): """:type root: TreeNode :rtype: int""" if not root: return 0 height = 0 curr_node = root while curr_node: height += 1 curr_node = curr_node.left return 2 ** (height - 1) - 1 + self.helper(...
the_stack_v2_python_sparse
tree/leetcode_count_complete_tree_nodes.py
psy2013GitHub/dsa
train
0
4e0fce450eef1a9037bdda5aebbd29cbad00a8b2
[ "def dfs(node):\n if node not in visited:\n visited.add(node)\n for i, val in enumerate(M[node]):\n if i != node and val == 1:\n dfs(i)\nvisited = set()\ncnt = 0\nfor i in range(len(M)):\n if i not in visited:\n dfs(i)\n cnt += 1\nreturn cnt", "def dfs(n...
<|body_start_0|> def dfs(node): if node not in visited: visited.add(node) for i, val in enumerate(M[node]): if i != node and val == 1: dfs(i) visited = set() cnt = 0 for i in range(len(M)): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findCircleNum(self, M): """:type M: List[List[int]] :rtype: int""" <|body_0|> def rewrite(self, M): """:type M: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> def dfs(node): if node not in visit...
stack_v2_sparse_classes_75kplus_train_074701
2,471
no_license
[ { "docstring": ":type M: List[List[int]] :rtype: int", "name": "findCircleNum", "signature": "def findCircleNum(self, M)" }, { "docstring": ":type M: List[List[int]] :rtype: int", "name": "rewrite", "signature": "def rewrite(self, M)" } ]
2
stack_v2_sparse_classes_30k_train_030947
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findCircleNum(self, M): :type M: List[List[int]] :rtype: int - def rewrite(self, M): :type M: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findCircleNum(self, M): :type M: List[List[int]] :rtype: int - def rewrite(self, M): :type M: List[List[int]] :rtype: int <|skeleton|> class Solution: def findCircleNum...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def findCircleNum(self, M): """:type M: List[List[int]] :rtype: int""" <|body_0|> def rewrite(self, M): """:type M: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findCircleNum(self, M): """:type M: List[List[int]] :rtype: int""" def dfs(node): if node not in visited: visited.add(node) for i, val in enumerate(M[node]): if i != node and val == 1: dfs(i) ...
the_stack_v2_python_sparse
depth-first-search/547_Friend_Circles.py
vsdrun/lc_public
train
6
c9660ba2502d1607000c9d4834f718f3e4845a60
[ "if not user_id:\n raise ValueError('User ID not informed.')\nself.id = user_id\nfor field in self._fields:\n setattr(self, field, data.get(field))", "fields = self._fields\ndata = {field: getattr(self, field, None) for field in fields}\ndata['id'] = self.id\nreturn data" ]
<|body_start_0|> if not user_id: raise ValueError('User ID not informed.') self.id = user_id for field in self._fields: setattr(self, field, data.get(field)) <|end_body_0|> <|body_start_1|> fields = self._fields data = {field: getattr(self, field, None) f...
User object with basic fields.
BaseUser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseUser: """User object with basic fields.""" def __init__(self, user_id, data): """Initialize object from JWT token using pyramid jwt claims.""" <|body_0|> def to_dict(self) -> dict: """Create a dict representation of current user. :return: dict serializable us...
stack_v2_sparse_classes_75kplus_train_074702
816
no_license
[ { "docstring": "Initialize object from JWT token using pyramid jwt claims.", "name": "__init__", "signature": "def __init__(self, user_id, data)" }, { "docstring": "Create a dict representation of current user. :return: dict serializable user data", "name": "to_dict", "signature": "def t...
2
stack_v2_sparse_classes_30k_test_000481
Implement the Python class `BaseUser` described below. Class description: User object with basic fields. Method signatures and docstrings: - def __init__(self, user_id, data): Initialize object from JWT token using pyramid jwt claims. - def to_dict(self) -> dict: Create a dict representation of current user. :return:...
Implement the Python class `BaseUser` described below. Class description: User object with basic fields. Method signatures and docstrings: - def __init__(self, user_id, data): Initialize object from JWT token using pyramid jwt claims. - def to_dict(self) -> dict: Create a dict representation of current user. :return:...
0f27d5de4b04fe1d0ce2c2c9ccd3f2893b833128
<|skeleton|> class BaseUser: """User object with basic fields.""" def __init__(self, user_id, data): """Initialize object from JWT token using pyramid jwt claims.""" <|body_0|> def to_dict(self) -> dict: """Create a dict representation of current user. :return: dict serializable us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseUser: """User object with basic fields.""" def __init__(self, user_id, data): """Initialize object from JWT token using pyramid jwt claims.""" if not user_id: raise ValueError('User ID not informed.') self.id = user_id for field in self._fields: ...
the_stack_v2_python_sparse
src/briefy/common/types.py
BriefyHQ/briefy.common
train
0
dfe9b194a6a3e2cffe92818259e2122a048825ef
[ "self.category = category\nif self.category.picture != '':\n response = requests.get(self.category.picture)\n self.image = Image.open(BytesIO(response.content))\nelse:\n raise CategoryNoPictureException()\nself.image_name = self.category.name.replace(' ', '-').replace('/', '') + '.' + str(self.image.format...
<|body_start_0|> self.category = category if self.category.picture != '': response = requests.get(self.category.picture) self.image = Image.open(BytesIO(response.content)) else: raise CategoryNoPictureException() self.image_name = self.category.name.re...
CategoryPictureCompressor Class that resizes categories' picture and save them in media directory
CategoryPictureResizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CategoryPictureResizer: """CategoryPictureCompressor Class that resizes categories' picture and save them in media directory""" def __init__(self, category): """Initial class method that gets category instance and downloads its picture from the `picture` URLField, creates a unique na...
stack_v2_sparse_classes_75kplus_train_074703
15,418
no_license
[ { "docstring": "Initial class method that gets category instance and downloads its picture from the `picture` URLField, creates a unique name for the picture and keep it for next operations. :param category: the category which we are going to work with.", "name": "__init__", "signature": "def __init__(s...
4
stack_v2_sparse_classes_30k_test_000309
Implement the Python class `CategoryPictureResizer` described below. Class description: CategoryPictureCompressor Class that resizes categories' picture and save them in media directory Method signatures and docstrings: - def __init__(self, category): Initial class method that gets category instance and downloads its...
Implement the Python class `CategoryPictureResizer` described below. Class description: CategoryPictureCompressor Class that resizes categories' picture and save them in media directory Method signatures and docstrings: - def __init__(self, category): Initial class method that gets category instance and downloads its...
4a63d6b05d12db33e9f3e8da6d9a15815d12f298
<|skeleton|> class CategoryPictureResizer: """CategoryPictureCompressor Class that resizes categories' picture and save them in media directory""" def __init__(self, category): """Initial class method that gets category instance and downloads its picture from the `picture` URLField, creates a unique na...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CategoryPictureResizer: """CategoryPictureCompressor Class that resizes categories' picture and save them in media directory""" def __init__(self, category): """Initial class method that gets category instance and downloads its picture from the `picture` URLField, creates a unique name for the pi...
the_stack_v2_python_sparse
Old_commands/hi.py
webclinic017/DjangoImageSystem
train
0
99a588fd1b3c8e7defae24d01c4ae7e08c5fb5c1
[ "if num_pixels is None and quantile is None:\n raise ValueError('either num_pixels or quantile must be given')\nself.num_pixels: float = num_pixels\n'Number of pixels with highest values to set to one.'\nself.quantile: float = quantile\n'Quantile of pixels to set to one, rest is set to 0;\\n overridden by...
<|body_start_0|> if num_pixels is None and quantile is None: raise ValueError('either num_pixels or quantile must be given') self.num_pixels: float = num_pixels 'Number of pixels with highest values to set to one.' self.quantile: float = quantile 'Quantile of pixels t...
Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.
BinarizeByQuantile
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinarizeByQuantile: """Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.""" def __init__(self, quantile: float=None, num_pixels: int=None): """Init. :param quantile: quantile ...
stack_v2_sparse_classes_75kplus_train_074704
14,707
permissive
[ { "docstring": "Init. :param quantile: quantile of pixels to set to 1, rest is set to 0; overridden by ``num_pixels`` :param num_pixels: number of pixels with highest value to set to one, rest is set to 0", "name": "__init__", "signature": "def __init__(self, quantile: float=None, num_pixels: int=None)"...
3
stack_v2_sparse_classes_30k_train_028477
Implement the Python class `BinarizeByQuantile` described below. Class description: Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel. Method signatures and docstrings: - def __init__(self, quantile: float=None...
Implement the Python class `BinarizeByQuantile` described below. Class description: Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel. Method signatures and docstrings: - def __init__(self, quantile: float=None...
37b9fc83d7b14902dfe92e0c45071c150bcf3779
<|skeleton|> class BinarizeByQuantile: """Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.""" def __init__(self, quantile: float=None, num_pixels: int=None): """Init. :param quantile: quantile ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BinarizeByQuantile: """Set all but the given highest number of pixels / q-th quantile in an image to zero, rest to 1. Mind for RGB images: A pixel here means a pixel in one channel.""" def __init__(self, quantile: float=None, num_pixels: int=None): """Init. :param quantile: quantile of pixels to ...
the_stack_v2_python_sparse
hybrid_learning/datasets/transforms/image_transforms.py
JohnnyZhang917/hybrid_learning
train
0
9eeec201390b6d6f71793315d9ded7b4b81d8aa5
[ "logging.info('========== choose_act ==========')\nWebDriverWait(self.driver, 20).until(lambda x: x.find_element_by_id(self.act_choose_id))\nself.driver.find_element_by_id(self.act_choose_id).click()\nsleep(1)\nacts = self.driver.find_elements_by_class_name(self.check_label_class)\nrandom.choice(acts).click()\nslee...
<|body_start_0|> logging.info('========== choose_act ==========') WebDriverWait(self.driver, 20).until(lambda x: x.find_element_by_id(self.act_choose_id)) self.driver.find_element_by_id(self.act_choose_id).click() sleep(1) acts = self.driver.find_elements_by_class_name(self.check...
活动基类,封装一些公共方法
ActivityCommon
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActivityCommon: """活动基类,封装一些公共方法""" def choose_act(self): """选择活动""" <|body_0|> def choose_expense(self): """选择费用明细""" <|body_1|> def apply_num(self): """赠送数量""" <|body_2|> def apply_amount(self): """赠送金额""" <|bod...
stack_v2_sparse_classes_75kplus_train_074705
17,683
no_license
[ { "docstring": "选择活动", "name": "choose_act", "signature": "def choose_act(self)" }, { "docstring": "选择费用明细", "name": "choose_expense", "signature": "def choose_expense(self)" }, { "docstring": "赠送数量", "name": "apply_num", "signature": "def apply_num(self)" }, { "d...
6
stack_v2_sparse_classes_30k_train_048566
Implement the Python class `ActivityCommon` described below. Class description: 活动基类,封装一些公共方法 Method signatures and docstrings: - def choose_act(self): 选择活动 - def choose_expense(self): 选择费用明细 - def apply_num(self): 赠送数量 - def apply_amount(self): 赠送金额 - def submit(self): 提交活动 - def reconfirm(self): 再次确认
Implement the Python class `ActivityCommon` described below. Class description: 活动基类,封装一些公共方法 Method signatures and docstrings: - def choose_act(self): 选择活动 - def choose_expense(self): 选择费用明细 - def apply_num(self): 赠送数量 - def apply_amount(self): 赠送金额 - def submit(self): 提交活动 - def reconfirm(self): 再次确认 <|skeleton|> ...
05a0430f134c59be968daa6fa60d72aa5a9fbc5e
<|skeleton|> class ActivityCommon: """活动基类,封装一些公共方法""" def choose_act(self): """选择活动""" <|body_0|> def choose_expense(self): """选择费用明细""" <|body_1|> def apply_num(self): """赠送数量""" <|body_2|> def apply_amount(self): """赠送金额""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ActivityCommon: """活动基类,封装一些公共方法""" def choose_act(self): """选择活动""" logging.info('========== choose_act ==========') WebDriverWait(self.driver, 20).until(lambda x: x.find_element_by_id(self.act_choose_id)) self.driver.find_element_by_id(self.act_choose_id).click() ...
the_stack_v2_python_sparse
ccloud/businessView/activity.py
dopqob/Python
train
0
016b9740c041f6f6e232d6857acb5954adc8a8d3
[ "if not rent_item.user:\n return -9999\nweight = 0\nweight += RentAllocationMatrixWeigher._promo_code(rent_item)\nweight += RentAllocationMatrixWeigher._buy_threshold(rent_item)\nweight += RentAllocationMatrixWeigher._trade_threshold(rent_item)\nweight += RentAllocationMatrixWeigher._rental_threshold(rent_item)\...
<|body_start_0|> if not rent_item.user: return -9999 weight = 0 weight += RentAllocationMatrixWeigher._promo_code(rent_item) weight += RentAllocationMatrixWeigher._buy_threshold(rent_item) weight += RentAllocationMatrixWeigher._trade_threshold(rent_item) weigh...
RentAllocationMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RentAllocationMatrix: def calculate_weight(rent_item): """Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_code()``, ``RentAllocationMatrixWeigher._buy_threshold()``) Arguments: - ``rent_item``: ``RentList`` instance"...
stack_v2_sparse_classes_75kplus_train_074706
8,068
no_license
[ { "docstring": "Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_code()``, ``RentAllocationMatrixWeigher._buy_threshold()``) Arguments: - ``rent_item``: ``RentList`` instance", "name": "calculate_weight", "signature": "def calculate_...
2
stack_v2_sparse_classes_30k_train_004288
Implement the Python class `RentAllocationMatrix` described below. Class description: Implement the RentAllocationMatrix class. Method signatures and docstrings: - def calculate_weight(rent_item): Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_c...
Implement the Python class `RentAllocationMatrix` described below. Class description: Implement the RentAllocationMatrix class. Method signatures and docstrings: - def calculate_weight(rent_item): Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_c...
7c3acc39a24c38ae2ee06b71104a24cfbbde8453
<|skeleton|> class RentAllocationMatrix: def calculate_weight(rent_item): """Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_code()``, ``RentAllocationMatrixWeigher._buy_threshold()``) Arguments: - ``rent_item``: ``RentList`` instance"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RentAllocationMatrix: def calculate_weight(rent_item): """Calculates weight for ``RentList`` instance based on rent allocation weights (e.g. ``RentAllocationMatrixWeigher._promo_code()``, ``RentAllocationMatrixWeigher._buy_threshold()``) Arguments: - ``rent_item``: ``RentList`` instance""" if ...
the_stack_v2_python_sparse
project/rent/allocation_matrix.py
chrisblythe812/gamemine
train
1
423af10e0278980c8adb733f71984b51bc72bc44
[ "processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nprint('======', processed_dict)\nalipay = AliPay(appid='2016101100659996', app_notify_url='http://127.0.0.1:8000/api/ailpay/return/', app_private_key_path=APP_PRIVATE_KEY_PATH, ali...
<|body_start_0|> processed_dict = {} for key, value in request.GET.items(): processed_dict[key] = value sign = processed_dict.pop('sign', None) print('======', processed_dict) alipay = AliPay(appid='2016101100659996', app_notify_url='http://127.0.0.1:8000/api/ailpay/r...
AlipayView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlipayView: def get(self, request): """处理支付宝的return_url返回 :param request: :return:""" <|body_0|> def post(self, request): """处理支付宝的notify_url :param request: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> processed_dict = {} for ke...
stack_v2_sparse_classes_75kplus_train_074707
6,333
no_license
[ { "docstring": "处理支付宝的return_url返回 :param request: :return:", "name": "get", "signature": "def get(self, request)" }, { "docstring": "处理支付宝的notify_url :param request: :return:", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_036666
Implement the Python class `AlipayView` described below. Class description: Implement the AlipayView class. Method signatures and docstrings: - def get(self, request): 处理支付宝的return_url返回 :param request: :return: - def post(self, request): 处理支付宝的notify_url :param request: :return:
Implement the Python class `AlipayView` described below. Class description: Implement the AlipayView class. Method signatures and docstrings: - def get(self, request): 处理支付宝的return_url返回 :param request: :return: - def post(self, request): 处理支付宝的notify_url :param request: :return: <|skeleton|> class AlipayView: ...
45f8a57089f5c30ccc1a3cddb03b76dc95355417
<|skeleton|> class AlipayView: def get(self, request): """处理支付宝的return_url返回 :param request: :return:""" <|body_0|> def post(self, request): """处理支付宝的notify_url :param request: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlipayView: def get(self, request): """处理支付宝的return_url返回 :param request: :return:""" processed_dict = {} for key, value in request.GET.items(): processed_dict[key] = value sign = processed_dict.pop('sign', None) print('======', processed_dict) alipa...
the_stack_v2_python_sparse
前后端分离-vue-DRF/Projects-lenongke/LNK/apps/trade/views.py
Suijng/1809_data
train
0
99bbb5b54888792b3aa422bdef310262aff6c8d0
[ "self.__trie = TrieNode()\nself.__cur_node = self.__trie\nself.__search = []\nself.__sentence_to_count = collections.defaultdict(int)\nfor sentence, count in zip(sentences, times):\n self.__sentence_to_count[sentence] = count\n self.__trie.insert(sentence, count)", "result = []\nif c == '#':\n self.__sen...
<|body_start_0|> self.__trie = TrieNode() self.__cur_node = self.__trie self.__search = [] self.__sentence_to_count = collections.defaultdict(int) for sentence, count in zip(sentences, times): self.__sentence_to_count[sentence] = count self.__trie.insert(s...
AutocompleteSystem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutocompleteSystem: def __init__(self, sentences, times): """:type sentences: List[str] :type times: List[int]""" <|body_0|> def input(self, c): """:type c: str :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.__trie = TrieNode...
stack_v2_sparse_classes_75kplus_train_074708
2,083
permissive
[ { "docstring": ":type sentences: List[str] :type times: List[int]", "name": "__init__", "signature": "def __init__(self, sentences, times)" }, { "docstring": ":type c: str :rtype: List[str]", "name": "input", "signature": "def input(self, c)" } ]
2
stack_v2_sparse_classes_30k_train_053492
Implement the Python class `AutocompleteSystem` described below. Class description: Implement the AutocompleteSystem class. Method signatures and docstrings: - def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int] - def input(self, c): :type c: str :rtype: List[str]
Implement the Python class `AutocompleteSystem` described below. Class description: Implement the AutocompleteSystem class. Method signatures and docstrings: - def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int] - def input(self, c): :type c: str :rtype: List[str] <|skeleton|> cla...
4dc4e6642dc92f1983c13564cc0fd99917cab358
<|skeleton|> class AutocompleteSystem: def __init__(self, sentences, times): """:type sentences: List[str] :type times: List[int]""" <|body_0|> def input(self, c): """:type c: str :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AutocompleteSystem: def __init__(self, sentences, times): """:type sentences: List[str] :type times: List[int]""" self.__trie = TrieNode() self.__cur_node = self.__trie self.__search = [] self.__sentence_to_count = collections.defaultdict(int) for sentence, coun...
the_stack_v2_python_sparse
Python/design-search-autocomplete-system.py
kamyu104/LeetCode-Solutions
train
4,549
ff2b2c08c0c5a335685fa5bcc3eaac6ea3c34e30
[ "if len(preorder) == 0 and len(inorder) == 0:\n return None\nif len(preorder) == 1 and len(inorder) == 1:\n return TreeNode(preorder[0])\nroot = TreeNode(preorder[0])\nind = inorder.index(preorder[0])\ninorderleft = inorder[0:ind]\npreorderleft = preorder[1:1 + ind]\nroot.left = self.buildTree(preorderleft, i...
<|body_start_0|> if len(preorder) == 0 and len(inorder) == 0: return None if len(preorder) == 1 and len(inorder) == 1: return TreeNode(preorder[0]) root = TreeNode(preorder[0]) ind = inorder.index(preorder[0]) inorderleft = inorder[0:ind] preorderl...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def minDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if l...
stack_v2_sparse_classes_75kplus_train_074709
6,246
no_license
[ { "docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode", "name": "buildTree", "signature": "def buildTree(self, preorder, inorder)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "minDepth", "signature": "def minDepth(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def minDepth(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def minDepth(self, root): :type root: TreeNode :rtype: int <|skelet...
2a29426be1d690b6f90bc45b437900deee46d832
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def minDepth(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" if len(preorder) == 0 and len(inorder) == 0: return None if len(preorder) == 1 and len(inorder) == 1: return TreeNode(preorder[0]) ...
the_stack_v2_python_sparse
src/leet/111-minimum-depth-of-binary-tree.py
sevenseablue/leetcode
train
0
35df5f74e98e2a08966ea64110cdff11e5680458
[ "if attrs['password'] != attrs['password2']:\n raise serializers.ValidationError('两次输入的密码不一致!')\nif not re.match('^(?:[a-zA-Z0-9]+[_\\\\-\\\\+\\\\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\\\\-]?)*[a-zA-Z0-9]+\\\\.)+([a-zA-Z]{2,})+$', attrs['email']):\n raise serializers.ValidationError('邮箱格式有误!')\nredis_conn = get...
<|body_start_0|> if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次输入的密码不一致!') if not re.match('^(?:[a-zA-Z0-9]+[_\\-\\+\\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\\-]?)*[a-zA-Z0-9]+\\.)+([a-zA-Z]{2,})+$', attrs['email']): raise serializers.ValidationErr...
注册创建用户的序列化器
CreateUserSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateUserSerializer: """注册创建用户的序列化器""" def validate(self, attrs): """检验两次密码是否一致""" <|body_0|> def create(self, validated_data): """创建用户""" <|body_1|> <|end_skeleton|> <|body_start_0|> if attrs['password'] != attrs['password2']: rais...
stack_v2_sparse_classes_75kplus_train_074710
3,137
no_license
[ { "docstring": "检验两次密码是否一致", "name": "validate", "signature": "def validate(self, attrs)" }, { "docstring": "创建用户", "name": "create", "signature": "def create(self, validated_data)" } ]
2
stack_v2_sparse_classes_30k_train_012978
Implement the Python class `CreateUserSerializer` described below. Class description: 注册创建用户的序列化器 Method signatures and docstrings: - def validate(self, attrs): 检验两次密码是否一致 - def create(self, validated_data): 创建用户
Implement the Python class `CreateUserSerializer` described below. Class description: 注册创建用户的序列化器 Method signatures and docstrings: - def validate(self, attrs): 检验两次密码是否一致 - def create(self, validated_data): 创建用户 <|skeleton|> class CreateUserSerializer: """注册创建用户的序列化器""" def validate(self, attrs): "...
0e67ca676b6c25c9e9bff2fa92c1b2932f09856d
<|skeleton|> class CreateUserSerializer: """注册创建用户的序列化器""" def validate(self, attrs): """检验两次密码是否一致""" <|body_0|> def create(self, validated_data): """创建用户""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CreateUserSerializer: """注册创建用户的序列化器""" def validate(self, attrs): """检验两次密码是否一致""" if attrs['password'] != attrs['password2']: raise serializers.ValidationError('两次输入的密码不一致!') if not re.match('^(?:[a-zA-Z0-9]+[_\\-\\+\\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\\-]?)*[a-zA-...
the_stack_v2_python_sparse
personal_blog/apps/users/serializers.py
zizle/PersonalBlog
train
0
05e71eeab763f5e05ae6c5c6fb43f18fd78136c1
[ "super().pre_run(step, level_number)\nL = step.levels[level_number]\nself.add_to_stats(process=0, time=0, level=0, iter=0, sweep=0, type='u0', value=L.u[0])", "super().post_step(step, level_number)\nL = step.levels[level_number]\nself.add_to_stats(process=step.status.slot, time=L.time, level=L.level_index, iter=s...
<|body_start_0|> super().pre_run(step, level_number) L = step.levels[level_number] self.add_to_stats(process=0, time=0, level=0, iter=0, sweep=0, type='u0', value=L.u[0]) <|end_body_0|> <|body_start_1|> super().post_step(step, level_number) L = step.levels[level_number] ...
Record data required for analysis of problems in the resilience project
LogData
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogData: """Record data required for analysis of problems in the resilience project""" def pre_run(self, step, level_number): """Record initial conditions""" <|body_0|> def post_step(self, step, level_number): """Record final solutions as well as step size and er...
stack_v2_sparse_classes_75kplus_train_074711
3,815
permissive
[ { "docstring": "Record initial conditions", "name": "pre_run", "signature": "def pre_run(self, step, level_number)" }, { "docstring": "Record final solutions as well as step size and error estimates", "name": "post_step", "signature": "def post_step(self, step, level_number)" } ]
2
stack_v2_sparse_classes_30k_train_054379
Implement the Python class `LogData` described below. Class description: Record data required for analysis of problems in the resilience project Method signatures and docstrings: - def pre_run(self, step, level_number): Record initial conditions - def post_step(self, step, level_number): Record final solutions as wel...
Implement the Python class `LogData` described below. Class description: Record data required for analysis of problems in the resilience project Method signatures and docstrings: - def pre_run(self, step, level_number): Record initial conditions - def post_step(self, step, level_number): Record final solutions as wel...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class LogData: """Record data required for analysis of problems in the resilience project""" def pre_run(self, step, level_number): """Record initial conditions""" <|body_0|> def post_step(self, step, level_number): """Record final solutions as well as step size and er...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LogData: """Record data required for analysis of problems in the resilience project""" def pre_run(self, step, level_number): """Record initial conditions""" super().pre_run(step, level_number) L = step.levels[level_number] self.add_to_stats(process=0, time=0, level=0, ite...
the_stack_v2_python_sparse
pySDC/projects/Resilience/hook.py
Parallel-in-Time/pySDC
train
30
41e7948a5d4acfeffa0075528b818ee458353a07
[ "self._nums = nums\nself.tree = [0 for _ in range(len(nums) + 1)]\nfor i in range(len(nums)):\n val = nums[i]\n i += 1\n while i < len(self.tree):\n self.tree[i] += val\n i += i & -i\nprint(self.tree)", "val1 = self._nums[i]\nindex = i\ni = i + 1\nwhile i < len(self.tree):\n self.tree[i]...
<|body_start_0|> self._nums = nums self.tree = [0 for _ in range(len(nums) + 1)] for i in range(len(nums)): val = nums[i] i += 1 while i < len(self.tree): self.tree[i] += val i += i & -i print(self.tree) <|end_body_0|> ...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def update(self, i, val): """:type i: int :type val: int :rtype: void""" <|body_1|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_2|...
stack_v2_sparse_classes_75kplus_train_074712
1,364
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type val: int :rtype: void", "name": "update", "signature": "def update(self, i, val)" }, { "docstring": ":type i: int :type j: int :rtype: int", ...
3
stack_v2_sparse_classes_30k_train_020253
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def update(self, i, val): :type i: int :type val: int :rtype: void - def sumRange(self, i, j): :type i: int :type j: int :rtype:...
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def update(self, i, val): :type i: int :type val: int :rtype: void - def sumRange(self, i, j): :type i: int :type j: int :rtype:...
a6d0e392134afe19d1aed2dfe7914b674e05ecc6
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def update(self, i, val): """:type i: int :type val: int :rtype: void""" <|body_1|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_2|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NumArray: def __init__(self, nums): """:type nums: List[int]""" self._nums = nums self.tree = [0 for _ in range(len(nums) + 1)] for i in range(len(nums)): val = nums[i] i += 1 while i < len(self.tree): self.tree[i] += val ...
the_stack_v2_python_sparse
307RangeSumQuery.py
Ting007/leetcodePractice
train
0
633578e6bab6fb5a5c005952d4d510cea714eea3
[ "agg_class = aggregator_manager.AggregatorManager.get_aggregator(aggregator_name)\nfield_lines = []\nfor form_field in agg_class.FORM_FIELDS:\n field = {'name': form_field.get('name', 'N/A'), 'description': form_field.get('label', 'N/A')}\n field_lines.append(field)\nreturn {'name': agg_class.NAME, 'display_n...
<|body_start_0|> agg_class = aggregator_manager.AggregatorManager.get_aggregator(aggregator_name) field_lines = [] for form_field in agg_class.FORM_FIELDS: field = {'name': form_field.get('name', 'N/A'), 'description': form_field.get('label', 'N/A')} field_lines.append(fi...
Resource to get information about an aggregation class.
AggregationInfoResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AggregationInfoResource: """Resource to get information about an aggregation class.""" def _get_info(aggregator_name): """Returns a dict with information about an aggregation.""" <|body_0|> def get(self): """Handles GET request to the resource. Handler for /api/v...
stack_v2_sparse_classes_75kplus_train_074713
27,741
permissive
[ { "docstring": "Returns a dict with information about an aggregation.", "name": "_get_info", "signature": "def _get_info(aggregator_name)" }, { "docstring": "Handles GET request to the resource. Handler for /api/v1/aggregation/info/ Returns: JSON with information about every aggregator.", "n...
3
stack_v2_sparse_classes_30k_val_000171
Implement the Python class `AggregationInfoResource` described below. Class description: Resource to get information about an aggregation class. Method signatures and docstrings: - def _get_info(aggregator_name): Returns a dict with information about an aggregation. - def get(self): Handles GET request to the resourc...
Implement the Python class `AggregationInfoResource` described below. Class description: Resource to get information about an aggregation class. Method signatures and docstrings: - def _get_info(aggregator_name): Returns a dict with information about an aggregation. - def get(self): Handles GET request to the resourc...
24f471b58ca4a87cb053961b5f05c07a544ca7b8
<|skeleton|> class AggregationInfoResource: """Resource to get information about an aggregation class.""" def _get_info(aggregator_name): """Returns a dict with information about an aggregation.""" <|body_0|> def get(self): """Handles GET request to the resource. Handler for /api/v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AggregationInfoResource: """Resource to get information about an aggregation class.""" def _get_info(aggregator_name): """Returns a dict with information about an aggregation.""" agg_class = aggregator_manager.AggregatorManager.get_aggregator(aggregator_name) field_lines = [] ...
the_stack_v2_python_sparse
timesketch/api/v1/resources/aggregation.py
google/timesketch
train
2,263
9a2a69d8c9dc43c3312118a361a02ae166b08b74
[ "self.id = id\nself.insurance_centre_id = insurance_centre_id\nself.article_type = article_type\nself.title = title\nself.summary = summary\nself.article_group = article_group\nself.meta_media_file_id = meta_media_file_id\nself.meta_media_file_url = meta_media_file_url\nself.publish_persian_date = publish_persian_d...
<|body_start_0|> self.id = id self.insurance_centre_id = insurance_centre_id self.article_type = article_type self.title = title self.summary = summary self.article_group = article_group self.meta_media_file_id = meta_media_file_id self.meta_media_file_url...
Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title (string): TODO: type description here. summary (string): TODO: type description...
SummaryNotic
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SummaryNotic: """Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title (string): TODO: type description here. ...
stack_v2_sparse_classes_75kplus_train_074714
3,623
permissive
[ { "docstring": "Constructor for the SummaryNotic class", "name": "__init__", "signature": "def __init__(self, id=None, insurance_centre_id=None, article_type=None, title=None, summary=None, article_group=None, meta_media_file_id=None, meta_media_file_url=None, publish_persian_date=None)" }, { "d...
2
null
Implement the Python class `SummaryNotic` described below. Class description: Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title ...
Implement the Python class `SummaryNotic` described below. Class description: Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title ...
b574a76a8805b306a423229b572c36dae0159def
<|skeleton|> class SummaryNotic: """Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title (string): TODO: type description here. ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SummaryNotic: """Implementation of the 'SummaryNotic' model. TODO: type model description here. Attributes: id (int): TODO: type description here. insurance_centre_id (int): TODO: type description here. article_type (int): TODO: type description here. title (string): TODO: type description here. summary (stri...
the_stack_v2_python_sparse
easybimehlanding/models/summary_notic.py
kmelodi/EasyBimehLanding_Python
train
0
fc04a3afb6a058d44814c8bffe404af229a97fce
[ "self.a = a\nself.b = b\nself.cx = cx\nself.cy = cy\nself.theta = theta", "x = self.a * np.cos(alpha) * np.cos(self.theta) - self.b * np.sin(alpha) * np.sin(self.theta) + self.cx\ny = self.a * np.cos(alpha) * np.sin(self.theta) + self.b * np.sin(alpha) * np.cos(self.theta) + self.cy\nreturn (x, y)" ]
<|body_start_0|> self.a = a self.b = b self.cx = cx self.cy = cy self.theta = theta <|end_body_0|> <|body_start_1|> x = self.a * np.cos(alpha) * np.cos(self.theta) - self.b * np.sin(alpha) * np.sin(self.theta) + self.cx y = self.a * np.cos(alpha) * np.sin(self.th...
Ellipse
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ellipse: def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): """Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated""" <|body_0|> def get_el...
stack_v2_sparse_classes_75kplus_train_074715
12,432
no_license
[ { "docstring": "Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated", "name": "__init__", "signature": "def __init__(self, a=1, b=1, cx=0, cy=0, theta=0)" }, { ...
2
stack_v2_sparse_classes_30k_train_048629
Implement the Python class `Ellipse` described below. Class description: Implement the Ellipse class. Method signatures and docstrings: - def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ell...
Implement the Python class `Ellipse` described below. Class description: Implement the Ellipse class. Method signatures and docstrings: - def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ell...
3be1c0d1a96b7d220c2aba1515af6095712c65bc
<|skeleton|> class Ellipse: def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): """Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated""" <|body_0|> def get_el...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Ellipse: def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): """Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated""" self.a = a self.b = b se...
the_stack_v2_python_sparse
riseq_perception/scripts/ellipse_detector.py
juanmed/riseq_uav
train
3
e57ffe203f84625e7608560a7b34fe8acdd7d7c4
[ "res = self.get(self.INDEX_URN)\nself.assert200(res)\nself.assertEqual(len(res.json['data']), 0)\ntags = [Tag(userId=self.user.id, **item) for item in datasets.index.TAGS]\ndb.session.add_all(tags)\ndb.session.commit()\nres = self.get(self.INDEX_URN)\nself.assert200(res)\nfor index, item in enumerate(res.json['data...
<|body_start_0|> res = self.get(self.INDEX_URN) self.assert200(res) self.assertEqual(len(res.json['data']), 0) tags = [Tag(userId=self.user.id, **item) for item in datasets.index.TAGS] db.session.add_all(tags) db.session.commit() res = self.get(self.INDEX_URN) ...
TagsResourceTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagsResourceTest: def test_index_endpoint(self): """Testing user tag GET index endpoint""" <|body_0|> def test_get_endpoint(self): """Testing user tag GET get endpoint""" <|body_1|> def test_post_endpoint(self): """Testing user tag POST endpoint"...
stack_v2_sparse_classes_75kplus_train_074716
6,179
permissive
[ { "docstring": "Testing user tag GET index endpoint", "name": "test_index_endpoint", "signature": "def test_index_endpoint(self)" }, { "docstring": "Testing user tag GET get endpoint", "name": "test_get_endpoint", "signature": "def test_get_endpoint(self)" }, { "docstring": "Test...
5
stack_v2_sparse_classes_30k_test_001653
Implement the Python class `TagsResourceTest` described below. Class description: Implement the TagsResourceTest class. Method signatures and docstrings: - def test_index_endpoint(self): Testing user tag GET index endpoint - def test_get_endpoint(self): Testing user tag GET get endpoint - def test_post_endpoint(self)...
Implement the Python class `TagsResourceTest` described below. Class description: Implement the TagsResourceTest class. Method signatures and docstrings: - def test_index_endpoint(self): Testing user tag GET index endpoint - def test_get_endpoint(self): Testing user tag GET get endpoint - def test_post_endpoint(self)...
37a3be814fc32ad87eb2a0ecfd93aa46ef46e68d
<|skeleton|> class TagsResourceTest: def test_index_endpoint(self): """Testing user tag GET index endpoint""" <|body_0|> def test_get_endpoint(self): """Testing user tag GET get endpoint""" <|body_1|> def test_post_endpoint(self): """Testing user tag POST endpoint"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TagsResourceTest: def test_index_endpoint(self): """Testing user tag GET index endpoint""" res = self.get(self.INDEX_URN) self.assert200(res) self.assertEqual(len(res.json['data']), 0) tags = [Tag(userId=self.user.id, **item) for item in datasets.index.TAGS] db....
the_stack_v2_python_sparse
smsgw/resources/tags/api_test.py
jajonsraviation/smsgw
train
0
a78c71177f87a4319c2e97a72cc85b64a2c50ed6
[ "cardvalue = 0\nif 0 == cardtype:\n if cardlist[0] != 31:\n cardvalue += cardlist[0] % 10 * 2\n if cardlist[1] != 31:\n cardvalue += cardlist[1] % 10 * 2\n while cardvalue >= 20:\n cardvalue -= 20\n return cardvalue\nelif 1 == cardtype:\n return cardlist[0]\nelse:\n return 0",...
<|body_start_0|> cardvalue = 0 if 0 == cardtype: if cardlist[0] != 31: cardvalue += cardlist[0] % 10 * 2 if cardlist[1] != 31: cardvalue += cardlist[1] % 10 * 2 while cardvalue >= 20: cardvalue -= 20 return c...
:推筒子 :param cardlist:
Tuitongzi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tuitongzi: """:推筒子 :param cardlist:""" def get_card_value(cardlist, cardtype): """:推筒子牌值 :param cardlist:""" <|body_0|> def getCardType(cardlist): """:推筒子牌型 0 单牌 1 豹子 2 二八杠 3 对红中 :param cardlist:""" <|body_1|> def compare(cardlist, cards): ""...
stack_v2_sparse_classes_75kplus_train_074717
2,265
no_license
[ { "docstring": ":推筒子牌值 :param cardlist:", "name": "get_card_value", "signature": "def get_card_value(cardlist, cardtype)" }, { "docstring": ":推筒子牌型 0 单牌 1 豹子 2 二八杠 3 对红中 :param cardlist:", "name": "getCardType", "signature": "def getCardType(cardlist)" }, { "docstring": ":推筒子比牌 :...
3
stack_v2_sparse_classes_30k_train_050940
Implement the Python class `Tuitongzi` described below. Class description: :推筒子 :param cardlist: Method signatures and docstrings: - def get_card_value(cardlist, cardtype): :推筒子牌值 :param cardlist: - def getCardType(cardlist): :推筒子牌型 0 单牌 1 豹子 2 二八杠 3 对红中 :param cardlist: - def compare(cardlist, cards): :推筒子比牌 :param ...
Implement the Python class `Tuitongzi` described below. Class description: :推筒子 :param cardlist: Method signatures and docstrings: - def get_card_value(cardlist, cardtype): :推筒子牌值 :param cardlist: - def getCardType(cardlist): :推筒子牌型 0 单牌 1 豹子 2 二八杠 3 对红中 :param cardlist: - def compare(cardlist, cards): :推筒子比牌 :param ...
383ebca3162734107b1d8af61274a76cb3822684
<|skeleton|> class Tuitongzi: """:推筒子 :param cardlist:""" def get_card_value(cardlist, cardtype): """:推筒子牌值 :param cardlist:""" <|body_0|> def getCardType(cardlist): """:推筒子牌型 0 单牌 1 豹子 2 二八杠 3 对红中 :param cardlist:""" <|body_1|> def compare(cardlist, cards): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Tuitongzi: """:推筒子 :param cardlist:""" def get_card_value(cardlist, cardtype): """:推筒子牌值 :param cardlist:""" cardvalue = 0 if 0 == cardtype: if cardlist[0] != 31: cardvalue += cardlist[0] % 10 * 2 if cardlist[1] != 31: cardva...
the_stack_v2_python_sparse
zhipai/tuitongzi.py
chrinide/phz
train
1
61bda5e7eefde9c18eb5f0a5bf687c45c5830917
[ "N = len(A)\nswap = [0] * N\nno_swap = [0] * N\nswap[0] = 1\nmax_index = N - 1\nfor i in range(1, N):\n prop = []\n if A[max_index - i] < A[max_index - i + 1] and B[max_index - i] < B[max_index - i + 1]:\n prop.append(no_swap[i - 1])\n if A[max_index - i] < B[max_index - i + 1] and B[max_index - i] ...
<|body_start_0|> N = len(A) swap = [0] * N no_swap = [0] * N swap[0] = 1 max_index = N - 1 for i in range(1, N): prop = [] if A[max_index - i] < A[max_index - i + 1] and B[max_index - i] < B[max_index - i + 1]: prop.append(no_swap[i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minSwap(self, A, B): """:type A: List[int] :type B: List[int] :rtype: int 77MS""" <|body_0|> def minSwap_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: int 58ms""" <|body_1|> <|end_skeleton|> <|body_start_0|> N = len(A...
stack_v2_sparse_classes_75kplus_train_074718
2,595
no_license
[ { "docstring": ":type A: List[int] :type B: List[int] :rtype: int 77MS", "name": "minSwap", "signature": "def minSwap(self, A, B)" }, { "docstring": ":type A: List[int] :type B: List[int] :rtype: int 58ms", "name": "minSwap_1", "signature": "def minSwap_1(self, A, B)" } ]
2
stack_v2_sparse_classes_30k_train_017781
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSwap(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 77MS - def minSwap_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 58ms
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSwap(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 77MS - def minSwap_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 58ms <|skeleton|> ...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def minSwap(self, A, B): """:type A: List[int] :type B: List[int] :rtype: int 77MS""" <|body_0|> def minSwap_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: int 58ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minSwap(self, A, B): """:type A: List[int] :type B: List[int] :rtype: int 77MS""" N = len(A) swap = [0] * N no_swap = [0] * N swap[0] = 1 max_index = N - 1 for i in range(1, N): prop = [] if A[max_index - i] < A[max_...
the_stack_v2_python_sparse
MinimumSwapsToMakeSequencesIncreasing_MID_801.py
953250587/leetcode-python
train
2
4bc0b24b8ddf8e3e8b56488c442094d6d2b7449b
[ "expected_prefix = settings.JWT['TOKEN_PREFIX'].lower()\nrequest.user = None\nauth_header = authentication.get_authorization_header(request).split()\nauth_header_len = len(auth_header)\nif not auth_header or auth_header_len != 2:\n return None\nprefix = auth_header[0].decode('utf-8')\ntoken = auth_header[1].deco...
<|body_start_0|> expected_prefix = settings.JWT['TOKEN_PREFIX'].lower() request.user = None auth_header = authentication.get_authorization_header(request).split() auth_header_len = len(auth_header) if not auth_header or auth_header_len != 2: return None prefix...
JWTAuthentication
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JWTAuthentication: def authenticate(self, request): """Determines if the current user making the request isauthenticated""" <|body_0|> def _get_user_credentials_from_token(self, token): """Extracts a user from a JSON web token""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_074719
1,627
permissive
[ { "docstring": "Determines if the current user making the request isauthenticated", "name": "authenticate", "signature": "def authenticate(self, request)" }, { "docstring": "Extracts a user from a JSON web token", "name": "_get_user_credentials_from_token", "signature": "def _get_user_cr...
2
null
Implement the Python class `JWTAuthentication` described below. Class description: Implement the JWTAuthentication class. Method signatures and docstrings: - def authenticate(self, request): Determines if the current user making the request isauthenticated - def _get_user_credentials_from_token(self, token): Extracts...
Implement the Python class `JWTAuthentication` described below. Class description: Implement the JWTAuthentication class. Method signatures and docstrings: - def authenticate(self, request): Determines if the current user making the request isauthenticated - def _get_user_credentials_from_token(self, token): Extracts...
0e9ef1a10c8a3f6736999a5111736f7bd7236689
<|skeleton|> class JWTAuthentication: def authenticate(self, request): """Determines if the current user making the request isauthenticated""" <|body_0|> def _get_user_credentials_from_token(self, token): """Extracts a user from a JSON web token""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JWTAuthentication: def authenticate(self, request): """Determines if the current user making the request isauthenticated""" expected_prefix = settings.JWT['TOKEN_PREFIX'].lower() request.user = None auth_header = authentication.get_authorization_header(request).split() ...
the_stack_v2_python_sparse
authors/apps/authentication/backends.py
andela/ah-backend-odin
train
0
18b112c31fd0e296ea4d961051746ba8d8a7e86f
[ "headers = []\nfor field in self.get_export_fields():\n field_model = AidProject._meta.get_field(field.column_name)\n headers.append(field_model.verbose_name)\nreturn headers", "field_name = self.get_field_name(field)\nmethod = getattr(self, 'dehydrate_%s' % field_name, None)\nif method is not None:\n re...
<|body_start_0|> headers = [] for field in self.get_export_fields(): field_model = AidProject._meta.get_field(field.column_name) headers.append(field_model.verbose_name) return headers <|end_body_0|> <|body_start_1|> field_name = self.get_field_name(field) ...
Resource for Export AidProject.
AidProjectResource
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AidProjectResource: """Resource for Export AidProject.""" def get_export_headers(self): """override get_export_headers() to translate field names.""" <|body_0|> def export_field(self, field, obj): """override export_field() to translate field values.""" <...
stack_v2_sparse_classes_75kplus_train_074720
13,586
permissive
[ { "docstring": "override get_export_headers() to translate field names.", "name": "get_export_headers", "signature": "def get_export_headers(self)" }, { "docstring": "override export_field() to translate field values.", "name": "export_field", "signature": "def export_field(self, field, ...
2
stack_v2_sparse_classes_30k_train_030775
Implement the Python class `AidProjectResource` described below. Class description: Resource for Export AidProject. Method signatures and docstrings: - def get_export_headers(self): override get_export_headers() to translate field names. - def export_field(self, field, obj): override export_field() to translate field...
Implement the Python class `AidProjectResource` described below. Class description: Resource for Export AidProject. Method signatures and docstrings: - def get_export_headers(self): override get_export_headers() to translate field names. - def export_field(self, field, obj): override export_field() to translate field...
af9f6e6e8b1918363793fbf291f3518ef1454169
<|skeleton|> class AidProjectResource: """Resource for Export AidProject.""" def get_export_headers(self): """override get_export_headers() to translate field names.""" <|body_0|> def export_field(self, field, obj): """override export_field() to translate field values.""" <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AidProjectResource: """Resource for Export AidProject.""" def get_export_headers(self): """override get_export_headers() to translate field names.""" headers = [] for field in self.get_export_fields(): field_model = AidProject._meta.get_field(field.column_name) ...
the_stack_v2_python_sparse
src/aids/resources.py
MTES-MCT/aides-territoires
train
21
b5e40a44d65399784477a8c56c045e0d65e2ecb0
[ "async def wrapper(admin: str=Depends(authenticate_admin), *args, **kwargs):\n logger.info('Admin access granted.')\n return await func(*args, **kwargs)\nwrapper.__signature__ = inspect.Signature(parameters=[*inspect.signature(func).parameters.values(), *filter(lambda p: p.kind not in (inspect.Parameter.VAR_P...
<|body_start_0|> async def wrapper(admin: str=Depends(authenticate_admin), *args, **kwargs): logger.info('Admin access granted.') return await func(*args, **kwargs) wrapper.__signature__ = inspect.Signature(parameters=[*inspect.signature(func).parameters.values(), *filter(lambda ...
[Endpoint authentication decorator.]
authentication
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class authentication: """[Endpoint authentication decorator.]""" def admin_required(func): """[Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.]""" <|body_0|> def user_required(func): """[Sets a user authentication requirement....
stack_v2_sparse_classes_75kplus_train_074721
2,466
no_license
[ { "docstring": "[Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.]", "name": "admin_required", "signature": "def admin_required(func)" }, { "docstring": "[Sets a user authentication requirement. User has to exist in the users database and have a 'True' a...
2
stack_v2_sparse_classes_30k_train_012739
Implement the Python class `authentication` described below. Class description: [Endpoint authentication decorator.] Method signatures and docstrings: - def admin_required(func): [Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.] - def user_required(func): [Sets a user authen...
Implement the Python class `authentication` described below. Class description: [Endpoint authentication decorator.] Method signatures and docstrings: - def admin_required(func): [Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.] - def user_required(func): [Sets a user authen...
e17daa214f4bc8394e9bc096aca6a04b0fba04e9
<|skeleton|> class authentication: """[Endpoint authentication decorator.]""" def admin_required(func): """[Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.]""" <|body_0|> def user_required(func): """[Sets a user authentication requirement....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class authentication: """[Endpoint authentication decorator.]""" def admin_required(func): """[Sets an admin authentication requirement.] Args: func ([type]): [Function to be decorated.]""" async def wrapper(admin: str=Depends(authenticate_admin), *args, **kwargs): logger.info('Admi...
the_stack_v2_python_sparse
authentication/decorator.py
pesfahanian/ML_API
train
6
76d61f95b2f041bdddabff067593ee2c7547499a
[ "from torch.nn import LeakyReLU\nfrom torch.nn import Conv2d\nsuper().__init__()\nself.batch_discriminator = MinibatchStdDev()\nself.conv_1 = Conv2d(in_channels + 1, in_channels, (3, 3), padding=1, bias=True)\nself.conv_2 = Conv2d(in_channels, in_channels, (4, 4), bias=True)\nself.conv_3 = Conv2d(in_channels, 1, (1...
<|body_start_0|> from torch.nn import LeakyReLU from torch.nn import Conv2d super().__init__() self.batch_discriminator = MinibatchStdDev() self.conv_1 = Conv2d(in_channels + 1, in_channels, (3, 3), padding=1, bias=True) self.conv_2 = Conv2d(in_channels, in_channels, (4, ...
Final block for the Discriminator
DisFinalBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DisFinalBlock: """Final block for the Discriminator""" def __init__(self, in_channels): """constructor of the class :param in_channels: number of input channels""" <|body_0|> def forward(self, x): """forward pass of the FinalBlock :param x: input :return: y => ou...
stack_v2_sparse_classes_75kplus_train_074722
14,685
no_license
[ { "docstring": "constructor of the class :param in_channels: number of input channels", "name": "__init__", "signature": "def __init__(self, in_channels)" }, { "docstring": "forward pass of the FinalBlock :param x: input :return: y => output", "name": "forward", "signature": "def forward...
2
stack_v2_sparse_classes_30k_train_015220
Implement the Python class `DisFinalBlock` described below. Class description: Final block for the Discriminator Method signatures and docstrings: - def __init__(self, in_channels): constructor of the class :param in_channels: number of input channels - def forward(self, x): forward pass of the FinalBlock :param x: i...
Implement the Python class `DisFinalBlock` described below. Class description: Final block for the Discriminator Method signatures and docstrings: - def __init__(self, in_channels): constructor of the class :param in_channels: number of input channels - def forward(self, x): forward pass of the FinalBlock :param x: i...
428abe1fefe5ea4ef00290155e7e59657bc83444
<|skeleton|> class DisFinalBlock: """Final block for the Discriminator""" def __init__(self, in_channels): """constructor of the class :param in_channels: number of input channels""" <|body_0|> def forward(self, x): """forward pass of the FinalBlock :param x: input :return: y => ou...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DisFinalBlock: """Final block for the Discriminator""" def __init__(self, in_channels): """constructor of the class :param in_channels: number of input channels""" from torch.nn import LeakyReLU from torch.nn import Conv2d super().__init__() self.batch_discriminato...
the_stack_v2_python_sparse
src/msg_stylegan2.py
blakecheng/lafin
train
0
0e53983d2d21a8c62cce830c4398ab12cbe36619
[ "assert ip_address in get_local_ips(), 'At the moment, we want you to start a slurm process only from localhost'\nassert slurm_command in ['srun'], \"At the moment, we only support 'srun' for execution of slurm\"\nsuper(SlurmPythonProcess, self).__init__(function, ip_address, set_up_port_for_structured_back_communi...
<|body_start_0|> assert ip_address in get_local_ips(), 'At the moment, we want you to start a slurm process only from localhost' assert slurm_command in ['srun'], "At the moment, we only support 'srun' for execution of slurm" super(SlurmPythonProcess, self).__init__(function, ip_address, set_up_...
SlurmPythonProcess
[ "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlurmPythonProcess: def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='srun', **kwargs): """:param function: :param ip_address: :param set_up_port_for_structured_back_communication: :param slurm_kwargs: :param kwar...
stack_v2_sparse_classes_75kplus_train_074723
15,481
permissive
[ { "docstring": ":param function: :param ip_address: :param set_up_port_for_structured_back_communication: :param slurm_kwargs: :param kwargs:", "name": "__init__", "signature": "def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='s...
2
null
Implement the Python class `SlurmPythonProcess` described below. Class description: Implement the SlurmPythonProcess class. Method signatures and docstrings: - def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='srun', **kwargs): :param function...
Implement the Python class `SlurmPythonProcess` described below. Class description: Implement the SlurmPythonProcess class. Method signatures and docstrings: - def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='srun', **kwargs): :param function...
84d3b1daf0de363cc823d99f978e2861ed400b5b
<|skeleton|> class SlurmPythonProcess: def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='srun', **kwargs): """:param function: :param ip_address: :param set_up_port_for_structured_back_communication: :param slurm_kwargs: :param kwar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SlurmPythonProcess: def __init__(self, function, ip_address, set_up_port_for_structured_back_communication=True, slurm_kwargs={}, slurm_command='srun', **kwargs): """:param function: :param ip_address: :param set_up_port_for_structured_back_communication: :param slurm_kwargs: :param kwargs:""" ...
the_stack_v2_python_sparse
artemis/remote/child_processes.py
QUVA-Lab/artemis
train
241
4d8412de4fc831bfbb7f9eaba085fe5a1788f24c
[ "if not root:\n return ''\nstack = [root]\nres = ''\nwhile stack:\n childs = []\n for node in stack:\n if not node:\n res += ','\n childs.append(None)\n childs.append(None)\n else:\n res += str(node.val) + ','\n childs.append(node.left)\n...
<|body_start_0|> if not root: return '' stack = [root] res = '' while stack: childs = [] for node in stack: if not node: res += ',' childs.append(None) childs.append(None) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_074724
2,077
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_039893
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
14dcf9029486283b5e4685d95ebfe9979ade03c3
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' stack = [root] res = '' while stack: childs = [] for node in stack: if not node: ...
the_stack_v2_python_sparse
449-SerializeandDeserializeBST.py
dq-code/leetcode
train
0
5b9bfe011757afcb195a85e06598ec11020388e1
[ "n = len(cases) + 1\noutputs = cases_outputs\noutputs.append(default_output)\nif none_keys_output != None:\n outputs.append(none_keys_output)\n n += 1\n self.__ignore_none = False\nelse:\n self.__ignore_none = True\nsuper().__init__(inputs=[inputs], outputs=outputs, input_count=1, output_count=n)\nself....
<|body_start_0|> n = len(cases) + 1 outputs = cases_outputs outputs.append(default_output) if none_keys_output != None: outputs.append(none_keys_output) n += 1 self.__ignore_none = False else: self.__ignore_none = True super...
Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if enabled. Output streams of index 0 to N-1 will be the cases, N will be the defau...
SwitchFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SwitchFilter: """Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if enabled. Output streams of index 0 to N-...
stack_v2_sparse_classes_75kplus_train_074725
7,770
no_license
[ { "docstring": "Parameters: input : str A single stream name. cases_output : str The output streams names that will contain data which data[key] equals to one of the cases. default_output : str The output stream name that will contain data which data[key] doesn't fall into any of the cases. key : Any The key on...
3
stack_v2_sparse_classes_30k_train_004877
Implement the Python class `SwitchFilter` described below. Class description: Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if e...
Implement the Python class `SwitchFilter` described below. Class description: Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if e...
5d1fce470eeb31f5cc75cadfc06d9d2908736052
<|skeleton|> class SwitchFilter: """Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if enabled. Output streams of index 0 to N-...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SwitchFilter: """Splits a Stream based on the value of a field in the atoms. Inputs: A single stream. Outputs: Multiple Streams, as many as the requested cases (N), plus one for the default case, and one for the atoms that do not have the requested key, if enabled. Output streams of index 0 to N-1 will be the...
the_stack_v2_python_sparse
otri/filtering/filters/split_filter.py
OTRI-Unipd/OTRI
train
0
09dff362ed6c7d29acc698a10599708a5b6c87ac
[ "super(Kinect2Camera, self).__init__(configs=configs)\nself.DepthMapFactor = float(self.configs.CAMERA.DEPTH_MAP_FACTOR)\nself.intrinsic_mat = None", "rgb_im, depth_im = self.get_rgb_depth()\ndepth = depth_im.reshape(-1) / self.DepthMapFactor\nrgb = rgb_im.reshape(-1, 3)\nif self.intrinsic_mat is None:\n self....
<|body_start_0|> super(Kinect2Camera, self).__init__(configs=configs) self.DepthMapFactor = float(self.configs.CAMERA.DEPTH_MAP_FACTOR) self.intrinsic_mat = None <|end_body_0|> <|body_start_1|> rgb_im, depth_im = self.get_rgb_depth() depth = depth_im.reshape(-1) / self.DepthMapF...
This is camera class that interfaces with the KinectV2 camera
Kinect2Camera
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Kinect2Camera: """This is camera class that interfaces with the KinectV2 camera""" def __init__(self, configs): """Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YACS CfgNode""" <|body_0|> def get_current_pcd(...
stack_v2_sparse_classes_75kplus_train_074726
4,235
permissive
[ { "docstring": "Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YACS CfgNode", "name": "__init__", "signature": "def __init__(self, configs)" }, { "docstring": "Return the point cloud at current time step (one frame only) :returns: tup...
3
stack_v2_sparse_classes_30k_train_005943
Implement the Python class `Kinect2Camera` described below. Class description: This is camera class that interfaces with the KinectV2 camera Method signatures and docstrings: - def __init__(self, configs): Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YAC...
Implement the Python class `Kinect2Camera` described below. Class description: This is camera class that interfaces with the KinectV2 camera Method signatures and docstrings: - def __init__(self, configs): Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YAC...
b334b60842271d9d8f4ed7a97bc4e5efe8bb72d6
<|skeleton|> class Kinect2Camera: """This is camera class that interfaces with the KinectV2 camera""" def __init__(self, configs): """Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YACS CfgNode""" <|body_0|> def get_current_pcd(...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Kinect2Camera: """This is camera class that interfaces with the KinectV2 camera""" def __init__(self, configs): """Constructor of the KinectV2Camera class. :param configs: Camera specific configuration object :type configs: YACS CfgNode""" super(Kinect2Camera, self).__init__(configs=confi...
the_stack_v2_python_sparse
src/pyrobot/kinect2/camera.py
facebookresearch/pyrobot
train
2,314
b9ba26c2d11a4e93617e48e2f5f5890e7ab0ca8e
[ "options = [joinedload(ObservationPlanRequest.observation_plans).joinedload(EventObservationPlan.planned_observations).joinedload(PlannedObservation.field)]\nobservation_plan_request = ObservationPlanRequest.get_if_accessible_by(observation_plan_request_id, self.current_user, mode='read', raise_if_none=True, option...
<|body_start_0|> options = [joinedload(ObservationPlanRequest.observation_plans).joinedload(EventObservationPlan.planned_observations).joinedload(PlannedObservation.field)] observation_plan_request = ObservationPlanRequest.get_if_accessible_by(observation_plan_request_id, self.current_user, mode='read',...
ObservationPlanSubmitHandler
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObservationPlanSubmitHandler: def post(self, observation_plan_request_id): """--- description: Submit an observation plan. tags: - observation_plan_requests parameters: - in: path name: observation_plan_id required: true schema: type: string responses: 200: content: application/json: sch...
stack_v2_sparse_classes_75kplus_train_074727
26,549
permissive
[ { "docstring": "--- description: Submit an observation plan. tags: - observation_plan_requests parameters: - in: path name: observation_plan_id required: true schema: type: string responses: 200: content: application/json: schema: SingleObservationPlanRequest", "name": "post", "signature": "def post(sel...
2
stack_v2_sparse_classes_30k_train_018320
Implement the Python class `ObservationPlanSubmitHandler` described below. Class description: Implement the ObservationPlanSubmitHandler class. Method signatures and docstrings: - def post(self, observation_plan_request_id): --- description: Submit an observation plan. tags: - observation_plan_requests parameters: - ...
Implement the Python class `ObservationPlanSubmitHandler` described below. Class description: Implement the ObservationPlanSubmitHandler class. Method signatures and docstrings: - def post(self, observation_plan_request_id): --- description: Submit an observation plan. tags: - observation_plan_requests parameters: - ...
2433d5ae0b2f41faac3c76ed4ae8d9a4da5522fb
<|skeleton|> class ObservationPlanSubmitHandler: def post(self, observation_plan_request_id): """--- description: Submit an observation plan. tags: - observation_plan_requests parameters: - in: path name: observation_plan_id required: true schema: type: string responses: 200: content: application/json: sch...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ObservationPlanSubmitHandler: def post(self, observation_plan_request_id): """--- description: Submit an observation plan. tags: - observation_plan_requests parameters: - in: path name: observation_plan_id required: true schema: type: string responses: 200: content: application/json: schema: SingleObs...
the_stack_v2_python_sparse
skyportal/handlers/api/observation_plan.py
dmitryduev/skyportal
train
1
dc855016d94f14786b128973b104d18770d4d27a
[ "if cost_matrix.size == 0:\n return ([], [])\ncost = cost_matrix - cost_matrix.max()\nrow_ind = []\ncol_ind = []\nwhile True:\n row, col = np.unravel_index(cost.argmin(), cost.shape)\n if cost[row, col] < 0.0:\n row_ind.append(row)\n col_ind.append(col)\n cost[row, :] = 0.0\n co...
<|body_start_0|> if cost_matrix.size == 0: return ([], []) cost = cost_matrix - cost_matrix.max() row_ind = [] col_ind = [] while True: row, col = np.unravel_index(cost.argmin(), cost.shape) if cost[row, col] < 0.0: row_ind.appe...
Wrapper for linear_sum_assignment() from scipy to avoid timeouts.
LinearSum
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearSum: """Wrapper for linear_sum_assignment() from scipy to avoid timeouts.""" def simple_assignment(cls, cost_matrix): """Simple heuristic/non-optimal/greedy assignment.""" <|body_0|> def _add_to_cluster(cls, cluster, ship, ships, radius=2): """Add ship to c...
stack_v2_sparse_classes_75kplus_train_074728
25,759
no_license
[ { "docstring": "Simple heuristic/non-optimal/greedy assignment.", "name": "simple_assignment", "signature": "def simple_assignment(cls, cost_matrix)" }, { "docstring": "Add ship to cluster and search other ships for the cluster.", "name": "_add_to_cluster", "signature": "def _add_to_clus...
6
stack_v2_sparse_classes_30k_train_015292
Implement the Python class `LinearSum` described below. Class description: Wrapper for linear_sum_assignment() from scipy to avoid timeouts. Method signatures and docstrings: - def simple_assignment(cls, cost_matrix): Simple heuristic/non-optimal/greedy assignment. - def _add_to_cluster(cls, cluster, ship, ships, rad...
Implement the Python class `LinearSum` described below. Class description: Wrapper for linear_sum_assignment() from scipy to avoid timeouts. Method signatures and docstrings: - def simple_assignment(cls, cost_matrix): Simple heuristic/non-optimal/greedy assignment. - def _add_to_cluster(cls, cluster, ship, ships, rad...
79e006814c20d92cd034d5d80d004a95ff3da11a
<|skeleton|> class LinearSum: """Wrapper for linear_sum_assignment() from scipy to avoid timeouts.""" def simple_assignment(cls, cost_matrix): """Simple heuristic/non-optimal/greedy assignment.""" <|body_0|> def _add_to_cluster(cls, cluster, ship, ships, radius=2): """Add ship to c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinearSum: """Wrapper for linear_sum_assignment() from scipy to avoid timeouts.""" def simple_assignment(cls, cost_matrix): """Simple heuristic/non-optimal/greedy assignment.""" if cost_matrix.size == 0: return ([], []) cost = cost_matrix - cost_matrix.max() ro...
the_stack_v2_python_sparse
mapdata.py
stefank0/halite3
train
5
f4935409ac906de71e81c6bd7e3f1c99bd30bcd2
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Service for providing target systems which can safely be connected to for execution of attacker commands.
TargetSystemProviderServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TargetSystemProviderServicer: """Service for providing target systems which can safely be connected to for execution of attacker commands.""" def AcquireTargetSystem(self, request, context): """Request to be provided a target system Returns error code UNAVAILABLE if no target system ...
stack_v2_sparse_classes_75kplus_train_074729
5,092
no_license
[ { "docstring": "Request to be provided a target system Returns error code UNAVAILABLE if no target system can currently be aqcuired. May be retried.", "name": "AcquireTargetSystem", "signature": "def AcquireTargetSystem(self, request, context)" }, { "docstring": "Request to give back an acquired...
2
stack_v2_sparse_classes_30k_train_053516
Implement the Python class `TargetSystemProviderServicer` described below. Class description: Service for providing target systems which can safely be connected to for execution of attacker commands. Method signatures and docstrings: - def AcquireTargetSystem(self, request, context): Request to be provided a target s...
Implement the Python class `TargetSystemProviderServicer` described below. Class description: Service for providing target systems which can safely be connected to for execution of attacker commands. Method signatures and docstrings: - def AcquireTargetSystem(self, request, context): Request to be provided a target s...
b81b4f35d796b1e34050e1090192f6c808cfb327
<|skeleton|> class TargetSystemProviderServicer: """Service for providing target systems which can safely be connected to for execution of attacker commands.""" def AcquireTargetSystem(self, request, context): """Request to be provided a target system Returns error code UNAVAILABLE if no target system ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TargetSystemProviderServicer: """Service for providing target systems which can safely be connected to for execution of attacker commands.""" def AcquireTargetSystem(self, request, context): """Request to be provided a target system Returns error code UNAVAILABLE if no target system can currently...
the_stack_v2_python_sparse
protocols/target_system_provider/target_system_provider_pb2_grpc.py
Botnet-Honeypot/Honeypot
train
12
2cfaabd4359ce574a32ebd14f6602a5c1e7788a2
[ "if isinstance(key, int):\n return ECDSALowCurve(key)\nif key not in ECDSALowCurve._member_map_:\n extend_enum(ECDSALowCurve, key, default)\nreturn ECDSALowCurve[key]", "if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 2 <= va...
<|body_start_0|> if isinstance(key, int): return ECDSALowCurve(key) if key not in ECDSALowCurve._member_map_: extend_enum(ECDSALowCurve, key, default) return ECDSALowCurve[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 65535...
[ECDSALowCurve] ECDSA_LOW Curve Label
ECDSALowCurve
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ECDSALowCurve: """[ECDSALowCurve] ECDSA_LOW Curve Label""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_074730
1,108
permissive
[ { "docstring": "Backport support for original codes.", "name": "get", "signature": "def get(key, default=-1)" }, { "docstring": "Lookup function used when value is not found.", "name": "_missing_", "signature": "def _missing_(cls, value)" } ]
2
stack_v2_sparse_classes_30k_train_039608
Implement the Python class `ECDSALowCurve` described below. Class description: [ECDSALowCurve] ECDSA_LOW Curve Label Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found.
Implement the Python class `ECDSALowCurve` described below. Class description: [ECDSALowCurve] ECDSA_LOW Curve Label Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found. <|skeleton|> class ECDSALo...
90cd07d67df28d5c5ab0585bc60f467a78d9db33
<|skeleton|> class ECDSALowCurve: """[ECDSALowCurve] ECDSA_LOW Curve Label""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ECDSALowCurve: """[ECDSALowCurve] ECDSA_LOW Curve Label""" def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ECDSALowCurve(key) if key not in ECDSALowCurve._member_map_: extend_enum(ECDSALowCurve, key, defa...
the_stack_v2_python_sparse
pcapkit/const/hip/ecdsa_low_curve.py
stjordanis/PyPCAPKit
train
0
55b919e65b67df40f71934b59d011783e18b5209
[ "mock_resp = mock.Mock()\nmock_resp.raise_for_status = mock.Mock()\nif raise_for_status:\n mock_resp.raise_for_status.side_effect = raise_for_status\nmock_resp.status_code = status\nmock_resp.content = content\nif json_data:\n mock_resp.json = mock.Mock(return_value=json_data)\nreturn mock_resp", "mock_resp...
<|body_start_0|> mock_resp = mock.Mock() mock_resp.raise_for_status = mock.Mock() if raise_for_status: mock_resp.raise_for_status.side_effect = raise_for_status mock_resp.status_code = status mock_resp.content = content if json_data: mock_resp.json...
example text that mocks requests.get and returns a mock Response object
TestRequestsCall
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRequestsCall: """example text that mocks requests.get and returns a mock Response object""" def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None): """since we typically test a bunch of different requests calls for a service, we are going t...
stack_v2_sparse_classes_75kplus_train_074731
2,289
permissive
[ { "docstring": "since we typically test a bunch of different requests calls for a service, we are going to do a lot of mock responses, so its usually a good idea to have a helper function that builds these things", "name": "_mock_response", "signature": "def _mock_response(self, status=200, content='CON...
3
null
Implement the Python class `TestRequestsCall` described below. Class description: example text that mocks requests.get and returns a mock Response object Method signatures and docstrings: - def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None): since we typically test a bunch ...
Implement the Python class `TestRequestsCall` described below. Class description: example text that mocks requests.get and returns a mock Response object Method signatures and docstrings: - def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None): since we typically test a bunch ...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class TestRequestsCall: """example text that mocks requests.get and returns a mock Response object""" def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None): """since we typically test a bunch of different requests calls for a service, we are going t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestRequestsCall: """example text that mocks requests.get and returns a mock Response object""" def _mock_response(self, status=200, content='CONTENT', json_data=None, raise_for_status=None): """since we typically test a bunch of different requests calls for a service, we are going to do a lot of...
the_stack_v2_python_sparse
all-gists/45467f5a7af84d2a2d34f3fcb357449c/snippet.py
gistable/gistable
train
76
52f8bd1436d957b94cf4efae355997514e251c34
[ "super().__init__(env, capacity=capacity)\nself.max_size = max_size\nself._elems = []\nself.cur_elem_nr = 0\nself.diabled_buffer_control = General().diabled_buffer_control", "if self.diabled_buffer_control:\n return 0\ntry:\n a = sum([float(it.msg_length_in_bit) / 8.0 for it in self.items])\nexcept:\n a ...
<|body_start_0|> super().__init__(env, capacity=capacity) self.max_size = max_size self._elems = [] self.cur_elem_nr = 0 self.diabled_buffer_control = General().diabled_buffer_control <|end_body_0|> <|body_start_1|> if self.diabled_buffer_control: return 0 ...
this class is used to wrap the element of the buffer to be able to determine its size in bytes
LogStore
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogStore: """this class is used to wrap the element of the buffer to be able to determine its size in bytes""" def __init__(self, env, capacity, max_size): """Constructor Input: env simpy.Environment environment of this component capacity integer maxmium size of this buffer in elemen...
stack_v2_sparse_classes_75kplus_train_074732
2,559
permissive
[ { "docstring": "Constructor Input: env simpy.Environment environment of this component capacity integer maxmium size of this buffer in elements max_size integer maximum size of this buffer in bytes", "name": "__init__", "signature": "def __init__(self, env, capacity, max_size)" }, { "docstring":...
2
stack_v2_sparse_classes_30k_train_008285
Implement the Python class `LogStore` described below. Class description: this class is used to wrap the element of the buffer to be able to determine its size in bytes Method signatures and docstrings: - def __init__(self, env, capacity, max_size): Constructor Input: env simpy.Environment environment of this compone...
Implement the Python class `LogStore` described below. Class description: this class is used to wrap the element of the buffer to be able to determine its size in bytes Method signatures and docstrings: - def __init__(self, env, capacity, max_size): Constructor Input: env simpy.Environment environment of this compone...
b2e395611e9b5111aeda7ab128f3486354bbbf0d
<|skeleton|> class LogStore: """this class is used to wrap the element of the buffer to be able to determine its size in bytes""" def __init__(self, env, capacity, max_size): """Constructor Input: env simpy.Environment environment of this component capacity integer maxmium size of this buffer in elemen...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LogStore: """this class is used to wrap the element of the buffer to be able to determine its size in bytes""" def __init__(self, env, capacity, max_size): """Constructor Input: env simpy.Environment environment of this component capacity integer maxmium size of this buffer in elements max_size i...
the_stack_v2_python_sparse
ECUSimulation/components/base/ecu/hardware/impl_controller_can_std.py
PhilippMundhenk/IVNS
train
15
b1fdc0363d8cd67fb61b8613debc37b255ded729
[ "from anuga.config import rho_a, rho_w, eta_w\nself.use_coordinates = True\nif len(args) == 1:\n if not callable(args[0]):\n pressure = args[0]\n else:\n vector_function = args[0]\n if len(kwargs) == 1:\n self.use_coordinates = kwargs['use_coordinates']\n else:\n ...
<|body_start_0|> from anuga.config import rho_a, rho_w, eta_w self.use_coordinates = True if len(args) == 1: if not callable(args[0]): pressure = args[0] else: vector_function = args[0] if len(kwargs) == 1: ...
Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set of possibly arbitrarily located nodes at a set o possibly irregular but increasing tim...
Barometric_pressure
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Barometric_pressure: """Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set of possibly arbitrarily located nodes a...
stack_v2_sparse_classes_75kplus_train_074733
48,626
permissive
[ { "docstring": "Initialise barometric pressure field from barometric pressure [hPa] Input p can be either scalars or Python functions, e.g. P = barometric_pressure(1000) Arguments can also be Python functions of t,x,y as in def pressure(t,x,y): ... return p where x and y are vectors. and then pass the functions...
2
stack_v2_sparse_classes_30k_train_029015
Implement the Python class `Barometric_pressure` described below. Class description: Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set ...
Implement the Python class `Barometric_pressure` described below. Class description: Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set ...
6d6d8e22b7e15b601f960c198b521bc20682477c
<|skeleton|> class Barometric_pressure: """Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set of possibly arbitrarily located nodes a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Barometric_pressure: """Apply barometric pressure stress to water momentum in terms of barometric pressure p [hPa]. If the pressure data is stored in a file file_function is used to create a callable function. The data file contains pressure values at a set of possibly arbitrarily located nodes at a set o pos...
the_stack_v2_python_sparse
anuga/shallow_water/forcing.py
stoiver/anuga_core
train
4
0d3eeafc0dbe7e846f5f495a6b42664103882eaf
[ "if not graph.is_directed():\n raise ValueError('the graph is not directed')\nself.graph = graph\nself.positive_weights = all((edge.weight >= 0 for edge in self.graph.iteredges()))\nself.distance = None", "if self.positive_weights:\n self._new_graph = self.graph\nelse:\n self._new_graph = self.graph.__cl...
<|body_start_0|> if not graph.is_directed(): raise ValueError('the graph is not directed') self.graph = graph self.positive_weights = all((edge.weight >= 0 for edge in self.graph.iteredges())) self.distance = None <|end_body_0|> <|body_start_1|> if self.positive_weig...
The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from graphtheory.structures.edges import Edge >...
JohnsonFaster
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JohnsonFaster: """The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from g...
stack_v2_sparse_classes_75kplus_train_074734
6,802
permissive
[ { "docstring": "The algorithm initialization. Parameters ---------- graph : directed weighted graph", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Finding all shortest paths.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_042992
Implement the Python class `JohnsonFaster` described below. Class description: The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instanc...
Implement the Python class `JohnsonFaster` described below. Class description: The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instanc...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class JohnsonFaster: """The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JohnsonFaster: """The Johnson algorithm for the shortest path problem. Attributes ---------- graph : input directed weighted graph distance : dict-of-dict positive_weights : bool _new_node : node, private _new_graph : graph, private _bf : BellmanFord instance, private Examples -------- >>> from graphtheory.st...
the_stack_v2_python_sparse
graphtheory/shortestpaths/johnson.py
kgashok/graphs-dict
train
0
ff04456aa48a678278e658be0dd0258e2f3e2597
[ "super(GCN, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.layers = nn.ModuleList([nn.Linear(self.input_size, self.hidden_size)] + [nn.Linear(self.hidden_size, self.hidden_size) for _ in range(self.num_layers - 1)])", "batch_size = adj_matrix.siz...
<|body_start_0|> super(GCN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.layers = nn.ModuleList([nn.Linear(self.input_size, self.hidden_size)] + [nn.Linear(self.hidden_size, self.hidden_size) for _ in range(self.nu...
@class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks.
GCN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GCN: """@class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks.""" def __init__(self, input_size, hidden_size, num_layers): """Constructor for GCN. @param self The object pointer. @param input_size In...
stack_v2_sparse_classes_75kplus_train_074735
1,819
no_license
[ { "docstring": "Constructor for GCN. @param self The object pointer. @param input_size Integer. Input size(word embedding/hidden state layer before). @param hidden_size Integer. Hidden size of theTreeLSTM unit.", "name": "__init__", "signature": "def __init__(self, input_size, hidden_size, num_layers)" ...
2
null
Implement the Python class `GCN` described below. Class description: @class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks. Method signatures and docstrings: - def __init__(self, input_size, hidden_size, num_layers): Constructor for ...
Implement the Python class `GCN` described below. Class description: @class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks. Method signatures and docstrings: - def __init__(self, input_size, hidden_size, num_layers): Constructor for ...
d2184a4f3f9363b789cbd1f1c5c7fb6e60f05945
<|skeleton|> class GCN: """@class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks.""" def __init__(self, input_size, hidden_size, num_layers): """Constructor for GCN. @param self The object pointer. @param input_size In...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GCN: """@class GCN Implementation of a Graph Convolution Network. > Kipf & Welling. Semi-supervised Classification with Graph Convolution Networks.""" def __init__(self, input_size, hidden_size, num_layers): """Constructor for GCN. @param self The object pointer. @param input_size Integer. Input ...
the_stack_v2_python_sparse
module/gcn.py
jinulee-v/victornlp_utils
train
0
b94449bfa7326332cddc3a150c140205e9cb4461
[ "if not value:\n raise ValueError(f'{value} is an empty string')\nreturn value", "if not re.search('^syn[0-9]+', value):\n raise ValueError(f'{value} is not a valid Synapse id')\nreturn value" ]
<|body_start_0|> if not value: raise ValueError(f'{value} is an empty string') return value <|end_body_0|> <|body_start_1|> if not re.search('^syn[0-9]+', value): raise ValueError(f'{value} is not a valid Synapse id') return value <|end_body_1|>
master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning but allowing the entry on to the sheet. service_acct_creds_synapse_id: The Synapse id o...
GoogleSheetsConfig
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleSheetsConfig: """master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning but allowing the entry on to the sheet. s...
stack_v2_sparse_classes_75kplus_train_074736
5,034
permissive
[ { "docstring": "Check if string is not empty(has at least one char) Args: value (str): A string Raises: ValueError: If the value is zero characters long Returns: (str): The input value", "name": "validate_string_is_not_empty", "signature": "def validate_string_is_not_empty(cls, value: str) -> str" }, ...
2
stack_v2_sparse_classes_30k_train_003280
Implement the Python class `GoogleSheetsConfig` described below. Class description: master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning bu...
Implement the Python class `GoogleSheetsConfig` described below. Class description: master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning bu...
11054993619e7983a76478bb570c73ef8433ae62
<|skeleton|> class GoogleSheetsConfig: """master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning but allowing the entry on to the sheet. s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GoogleSheetsConfig: """master_template_id: The template id of the google sheet. strict_validation: When doing google sheet validation (regex match) with the validation rules. True is alerting the user and not allowing entry of bad values. False is warning but allowing the entry on to the sheet. service_acct_c...
the_stack_v2_python_sparse
schematic/configuration/dataclasses.py
Sage-Bionetworks/schematic
train
11
86b668b54a98b3e401a4b1ba806805e1645b731a
[ "print(nums)\nn = len(nums)\ncnt = []\nres = 0\n\ndef dfs(index, presum, arr):\n nonlocal res\n if index == n:\n if presum == S:\n res += 1\n cnt.append(arr.copy())\n return\n for j in [-1, 1]:\n dfs(index + 1, presum + j * nums[index], arr + [j * nums[index]])\ndfs(0...
<|body_start_0|> print(nums) n = len(nums) cnt = [] res = 0 def dfs(index, presum, arr): nonlocal res if index == n: if presum == S: res += 1 cnt.append(arr.copy()) return for...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findTargetSumWays1(self, nums: List[int], S: int) -> int: """超时""" <|body_0|> def findTargetSumWays2(self, nums: List[int], S: int) -> int: """记忆化递归""" <|body_1|> <|end_skeleton|> <|body_start_0|> print(nums) n = len(nums) ...
stack_v2_sparse_classes_75kplus_train_074737
2,241
no_license
[ { "docstring": "超时", "name": "findTargetSumWays1", "signature": "def findTargetSumWays1(self, nums: List[int], S: int) -> int" }, { "docstring": "记忆化递归", "name": "findTargetSumWays2", "signature": "def findTargetSumWays2(self, nums: List[int], S: int) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays1(self, nums: List[int], S: int) -> int: 超时 - def findTargetSumWays2(self, nums: List[int], S: int) -> int: 记忆化递归
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays1(self, nums: List[int], S: int) -> int: 超时 - def findTargetSumWays2(self, nums: List[int], S: int) -> int: 记忆化递归 <|skeleton|> class Solution: def find...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def findTargetSumWays1(self, nums: List[int], S: int) -> int: """超时""" <|body_0|> def findTargetSumWays2(self, nums: List[int], S: int) -> int: """记忆化递归""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findTargetSumWays1(self, nums: List[int], S: int) -> int: """超时""" print(nums) n = len(nums) cnt = [] res = 0 def dfs(index, presum, arr): nonlocal res if index == n: if presum == S: res ...
the_stack_v2_python_sparse
LeetCode/动态规划法(dp)/背包问题/494. 目标和.py
yiming1012/MyLeetCode
train
2
7c8bf28f7bf5edba90f3777d48c68aacfc897553
[ "d = devicemanage(self.driver)\nd.open_devicemanage()\nself.assertEqual(d.verify(), True)\nd.modify_obj()\nself.assertEqual(d.sub_tagname(), '设备管理-修改')\nd.name_clear()\nd.serial_clear()\nd.version_clear()\nd.add_save()\nself.assertEqual(d.error_name(), '不能为空哦')\nself.assertEqual(d.error_serial(), '不能为空哦')\nself.ass...
<|body_start_0|> d = devicemanage(self.driver) d.open_devicemanage() self.assertEqual(d.verify(), True) d.modify_obj() self.assertEqual(d.sub_tagname(), '设备管理-修改') d.name_clear() d.serial_clear() d.version_clear() d.add_save() self.assertEq...
Test039_Device_Modify_Error
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test039_Device_Modify_Error: def test_device_modify_error1(self): """输入为空""" <|body_0|> def test_device_modify_error2(self): """版本号输入无效""" <|body_1|> <|end_skeleton|> <|body_start_0|> d = devicemanage(self.driver) d.open_devicemanage() ...
stack_v2_sparse_classes_75kplus_train_074738
1,376
no_license
[ { "docstring": "输入为空", "name": "test_device_modify_error1", "signature": "def test_device_modify_error1(self)" }, { "docstring": "版本号输入无效", "name": "test_device_modify_error2", "signature": "def test_device_modify_error2(self)" } ]
2
stack_v2_sparse_classes_30k_train_030647
Implement the Python class `Test039_Device_Modify_Error` described below. Class description: Implement the Test039_Device_Modify_Error class. Method signatures and docstrings: - def test_device_modify_error1(self): 输入为空 - def test_device_modify_error2(self): 版本号输入无效
Implement the Python class `Test039_Device_Modify_Error` described below. Class description: Implement the Test039_Device_Modify_Error class. Method signatures and docstrings: - def test_device_modify_error1(self): 输入为空 - def test_device_modify_error2(self): 版本号输入无效 <|skeleton|> class Test039_Device_Modify_Error: ...
6f42c25249fc642cecc270578a180820988d45b5
<|skeleton|> class Test039_Device_Modify_Error: def test_device_modify_error1(self): """输入为空""" <|body_0|> def test_device_modify_error2(self): """版本号输入无效""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test039_Device_Modify_Error: def test_device_modify_error1(self): """输入为空""" d = devicemanage(self.driver) d.open_devicemanage() self.assertEqual(d.verify(), True) d.modify_obj() self.assertEqual(d.sub_tagname(), '设备管理-修改') d.name_clear() d.seria...
the_stack_v2_python_sparse
GlxssLive_web/TestCase/Manage_Device/Test039_device_modify_error.py
rrmiracle/GlxssLive
train
0
6e520b116798ad3381941019645a525ce31a00aa
[ "try:\n h = httplib2.Http()\n url_create = 'https://www.googleapis.com/urlshortener/v1/url'\n msg = json_encode({'longUrl': url})\n response, content = h.request(url_create, 'POST', msg, headers={'Content-Type': 'application/json'})\n res = DotDict(json_decode(content))\n logging.info('[TINY_URL] ...
<|body_start_0|> try: h = httplib2.Http() url_create = 'https://www.googleapis.com/urlshortener/v1/url' msg = json_encode({'longUrl': url}) response, content = h.request(url_create, 'POST', msg, headers={'Content-Type': 'application/json'}) res = DotDi...
URLHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class URLHelper: def get_tinyurl(url): """Get a tiny url for wap url.""" <|body_0|> def get_tinyid(url): """get a tiny id contains 6 chars""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: h = httplib2.Http() url_create = 'https...
stack_v2_sparse_classes_75kplus_train_074739
2,591
no_license
[ { "docstring": "Get a tiny url for wap url.", "name": "get_tinyurl", "signature": "def get_tinyurl(url)" }, { "docstring": "get a tiny id contains 6 chars", "name": "get_tinyid", "signature": "def get_tinyid(url)" } ]
2
stack_v2_sparse_classes_30k_train_014201
Implement the Python class `URLHelper` described below. Class description: Implement the URLHelper class. Method signatures and docstrings: - def get_tinyurl(url): Get a tiny url for wap url. - def get_tinyid(url): get a tiny id contains 6 chars
Implement the Python class `URLHelper` described below. Class description: Implement the URLHelper class. Method signatures and docstrings: - def get_tinyurl(url): Get a tiny url for wap url. - def get_tinyid(url): get a tiny id contains 6 chars <|skeleton|> class URLHelper: def get_tinyurl(url): """Get...
3b095a325581b1fc48497c234f0ad55e928586a1
<|skeleton|> class URLHelper: def get_tinyurl(url): """Get a tiny url for wap url.""" <|body_0|> def get_tinyid(url): """get a tiny id contains 6 chars""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class URLHelper: def get_tinyurl(url): """Get a tiny url for wap url.""" try: h = httplib2.Http() url_create = 'https://www.googleapis.com/urlshortener/v1/url' msg = json_encode({'longUrl': url}) response, content = h.request(url_create, 'POST', msg, h...
the_stack_v2_python_sparse
libs/helpers/urlhelper.py
jcsy521/ydws
train
0
19e96bf0088491ed3065d948288879c287c4ca85
[ "self._redis = redis_client\nself._store = event_store\nself._pubsub = None", "channel = '{}.{}'.format(self._namespace, event.name)\nkey = '{}:{}'.format(self._namespace, event.id)\nself._redis.publish(channel, key)", "if self._pubsub:\n raise Exception('Already subscribed')\nself._pubsub = self._redis.pubs...
<|body_start_0|> self._redis = redis_client self._store = event_store self._pubsub = None <|end_body_0|> <|body_start_1|> channel = '{}.{}'.format(self._namespace, event.name) key = '{}:{}'.format(self._namespace, event.id) self._redis.publish(channel, key) <|end_body_1|...
RedisEventPubSub
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedisEventPubSub: def __init__(self, redis_client: Redis, event_store: EventStore): """Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTore event_store: the (initialized) event store to use""" <|body_0|> def publish(self, event: ...
stack_v2_sparse_classes_75kplus_train_074740
3,535
permissive
[ { "docstring": "Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTore event_store: the (initialized) event store to use", "name": "__init__", "signature": "def __init__(self, redis_client: Redis, event_store: EventStore)" }, { "docstring": "See superc...
5
stack_v2_sparse_classes_30k_train_048689
Implement the Python class `RedisEventPubSub` described below. Class description: Implement the RedisEventPubSub class. Method signatures and docstrings: - def __init__(self, redis_client: Redis, event_store: EventStore): Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTo...
Implement the Python class `RedisEventPubSub` described below. Class description: Implement the RedisEventPubSub class. Method signatures and docstrings: - def __init__(self, redis_client: Redis, event_store: EventStore): Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTo...
56d808d7836cd15d6c6748cbf704cdea4407fef6
<|skeleton|> class RedisEventPubSub: def __init__(self, redis_client: Redis, event_store: EventStore): """Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTore event_store: the (initialized) event store to use""" <|body_0|> def publish(self, event: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RedisEventPubSub: def __init__(self, redis_client: Redis, event_store: EventStore): """Initialization. :param Redis redis_client: the (initialized) redis client to use :param EventSTore event_store: the (initialized) event store to use""" self._redis = redis_client self._store = event_...
the_stack_v2_python_sparse
src/installer/src/tortuga/events/pubsub.py
UnivaCorporation/tortuga
train
33
d433d513f2b8583146aa8a3ff64c06b3e1e2aa9a
[ "base.Action.__init__(self, self.__loadPlugin)\nself.__frame = frame\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx", "lastDir = fslsettings.read('loadPluginLastDir')\nif lastDir is None:\n lastDir = os.getcwd()\nmsg = strings.messages[self, 'loadPlugin']\ndlg = wx.FileDialog(self.__frame, m...
<|body_start_0|> base.Action.__init__(self, self.__loadPlugin) self.__frame = frame self.__overlayList = overlayList self.__displayCtx = displayCtx <|end_body_0|> <|body_start_1|> lastDir = fslsettings.read('loadPluginLastDir') if lastDir is None: lastDir = o...
The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.
LoadPluginAction
[ "BSD-3-Clause", "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadPluginAction: """The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.""" def __init__(self, overlayList, displayCtx, frame): """Create a ``LoadPluginAction``. :arg overlayList: The :clas...
stack_v2_sparse_classes_75kplus_train_074741
2,921
permissive
[ { "docstring": "Create a ``LoadPluginAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The top-level :class:`.DisplayContext`. :arg overlayList: The :class:`.FSLeyesFrame`.", "name": "__init__", "signature": "def __init__(self, overlayList, displayCtx, frame)" }, { "docstri...
2
stack_v2_sparse_classes_30k_train_049941
Implement the Python class `LoadPluginAction` described below. Class description: The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module. Method signatures and docstrings: - def __init__(self, overlayList, displayCtx, frame): C...
Implement the Python class `LoadPluginAction` described below. Class description: The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module. Method signatures and docstrings: - def __init__(self, overlayList, displayCtx, frame): C...
46ccb4fe2b2346eb57576247f49714032b61307a
<|skeleton|> class LoadPluginAction: """The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.""" def __init__(self, overlayList, displayCtx, frame): """Create a ``LoadPluginAction``. :arg overlayList: The :clas...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoadPluginAction: """The :class:`LoadPluginAction` class is an :class:`.Action` which allows the user to load/install FSLeyes plugins - see the :mod:`.plugins` module.""" def __init__(self, overlayList, displayCtx, frame): """Create a ``LoadPluginAction``. :arg overlayList: The :class:`.OverlayLi...
the_stack_v2_python_sparse
fsleyes/actions/loadplugin.py
sanjayankur31/fsleyes
train
1
28851718890d5678e2cccebb8a9d30ecdead9791
[ "accts = []\nfor account in accounts:\n accts.append(str(account.user_id))\nreturn accts", "locs = []\nfor location in locations:\n polygon = location.bbox\n extent = list(polygon.extent)\n locs.extend(extent)\nreturn locs", "terms = []\nfor searchterm in searchterms:\n if searchterm.is_phrase():...
<|body_start_0|> accts = [] for account in accounts: accts.append(str(account.user_id)) return accts <|end_body_0|> <|body_start_1|> locs = [] for location in locations: polygon = location.bbox extent = list(polygon.extent) locs.ex...
Class for accessing the Twitter Streaming API.
PublicStreamsAPI
[ "MIT", "LicenseRef-scancode-proprietary-license", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-copyleft" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" <|body_0|> def _format...
stack_v2_sparse_classes_75kplus_train_074742
10,023
permissive
[ { "docstring": "Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.", "name": "_format_followees_param", "signature": "def _format_followees_param(accounts)" }, { "docstring": "Takes a list of Location objects and r...
5
stack_v2_sparse_classes_30k_train_034362
Implement the Python class `PublicStreamsAPI` described below. Class description: Class for accessing the Twitter Streaming API. Method signatures and docstrings: - def _format_followees_param(accounts): Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delive...
Implement the Python class `PublicStreamsAPI` described below. Class description: Class for accessing the Twitter Streaming API. Method signatures and docstrings: - def _format_followees_param(accounts): Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delive...
a379a134c0c5af14df4ed2afa066c1626506b754
<|skeleton|> class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" <|body_0|> def _format...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PublicStreamsAPI: """Class for accessing the Twitter Streaming API.""" def _format_followees_param(accounts): """Takes a list of Account objects and returns a list of user IDs, indicating the users whose Tweets should be delivered on the stream.""" accts = [] for account in accoun...
the_stack_v2_python_sparse
Incident-Response/Tools/cyphon/cyphon/platforms/twitter/handlers.py
foss2cyber/Incident-Playbook
train
1
e34e35a7b140e716ff2ce2426ad9ac80bfab38ea
[ "self._servoPin = rospy.get_param('~servoPin')\nself.pwm = pigpio.pi()\nself.pwm.set_mode(self._servoPin, pigpio.OUTPUT)\nself.pwm.set_PWM_frequency(self._servoPin, SERVO_FREQUENCY)\nself.angle_sub = rospy.Subscriber('/motor_control', MotorCommand, self.update_angle)", "if msg.angle > 10:\n self.pwm.set_PWM_du...
<|body_start_0|> self._servoPin = rospy.get_param('~servoPin') self.pwm = pigpio.pi() self.pwm.set_mode(self._servoPin, pigpio.OUTPUT) self.pwm.set_PWM_frequency(self._servoPin, SERVO_FREQUENCY) self.angle_sub = rospy.Subscriber('/motor_control', MotorCommand, self.update_angle) ...
Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor
Servo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Servo: """Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor""" def __init__(self): """Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends PWM signals to the servo pwm: object from the RPi.GPIO l...
stack_v2_sparse_classes_75kplus_train_074743
2,074
permissive
[ { "docstring": "Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends PWM signals to the servo pwm: object from the RPi.GPIO library that handles the servo properties and movement angle_sub: subscriber to the /servo_angle topic, with motor_control::MotorCommand message type and upd...
2
stack_v2_sparse_classes_30k_train_048311
Implement the Python class `Servo` described below. Class description: Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor Method signatures and docstrings: - def __init__(self): Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends...
Implement the Python class `Servo` described below. Class description: Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor Method signatures and docstrings: - def __init__(self): Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends...
da67c53cb7fc7f16c0df862a5cff820e9a0a470f
<|skeleton|> class Servo: """Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor""" def __init__(self): """Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends PWM signals to the servo pwm: object from the RPi.GPIO l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Servo: """Servo class definition, which subscribes to the topic /servo_angle to get angle commands for the servomotor""" def __init__(self): """Servo class default constructor. Its attributes are: _servoPin: GPIO pin that sends PWM signals to the servo pwm: object from the RPi.GPIO library that h...
the_stack_v2_python_sparse
ros_radar_mine/catkin_ws/src/motor_control/src/servo_ros.py
marina-go-al/blimp_snn
train
0
e585d28fa113ea1a7a40b63a4fabc6107d5bdb4a
[ "super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose)\nmodel.apply(has_hooks)\ndebug_level = logger.getEffectiveLevel()\nlogger.debug('Current log level: %s', debug_level)\nself._using_cuda = next(model.parameters()).is_cuda\nif self._in_place is False:\n self._model = copy.deepcopy(model)\n ...
<|body_start_0|> super().__init__(list_of_modules_to_winnow, reshape, in_place, verbose) model.apply(has_hooks) debug_level = logger.getEffectiveLevel() logger.debug('Current log level: %s', debug_level) self._using_cuda = next(model.parameters()).is_cuda if self._in_plac...
The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.
MaskPropagationWinnower
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaskPropagationWinnower: """The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.""" def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch...
stack_v2_sparse_classes_75kplus_train_074744
10,997
permissive
[ { "docstring": "MaskPropagationWinnower object initialization. :param model: The model to be winnowed. :param input_shape: The input shape of the model. :param list_of_modules_to_winnow: A list of Tuples with each Tuple containing a module and a list of channels to be winnowed for that module. :param reshape: I...
5
stack_v2_sparse_classes_30k_test_001803
Implement the Python class `MaskPropagationWinnower` described below. Class description: The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed. Method signatures and docstrings: - def __init__(self, model: torch.nn.Mod...
Implement the Python class `MaskPropagationWinnower` described below. Class description: The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed. Method signatures and docstrings: - def __init__(self, model: torch.nn.Mod...
5a406e657082b6a4f6e4bf48f0e46e085cb1e351
<|skeleton|> class MaskPropagationWinnower: """The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.""" def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MaskPropagationWinnower: """The MaskPropagationWinnower class implements winnowing based on propagating masks corresponding to each module's input channels identified to be winnowed.""" def __init__(self, model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch.nn.Module, L...
the_stack_v2_python_sparse
TrainingExtensions/torch/src/python/aimet_torch/winnow/mask_propagation_winnower.py
quic/aimet
train
1,676
232e095ac99da773819fe664104c323467512b4d
[ "rights = access.Checker(params)\nnew_params = {}\nnew_params['rights'] = rights\nnew_params['logic'] = priority_group_logic\nnew_params['name'] = 'Cron'\nnew_params['django_patterns_defaults'] = [('^%(url_name)s/(?P<access_type>poke)$', 'soc.views.models.%(module_name)s.poke', 'Poke %(name_short)s')]\nparams = dic...
<|body_start_0|> rights = access.Checker(params) new_params = {} new_params['rights'] = rights new_params['logic'] = priority_group_logic new_params['name'] = 'Cron' new_params['django_patterns_defaults'] = [('^%(url_name)s/(?P<access_type>poke)$', 'soc.views.models.%(mod...
View methods for the Cron model.
View
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class View: """View methods for the Cron model.""" def __init__(self, params=None): """Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View""" <|body_0|...
stack_v2_sparse_classes_75kplus_train_074745
3,167
permissive
[ { "docstring": "Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View", "name": "__init__", "signature": "def __init__(self, params=None)" }, { "docstring": "View call...
2
stack_v2_sparse_classes_30k_train_016199
Implement the Python class `View` described below. Class description: View methods for the Cron model. Method signatures and docstrings: - def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para...
Implement the Python class `View` described below. Class description: View methods for the Cron model. Method signatures and docstrings: - def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para...
5c5d50eea89372e967994dac3bd8b06d25b4f0fa
<|skeleton|> class View: """View methods for the Cron model.""" def __init__(self, params=None): """Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View""" <|body_0|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class View: """View methods for the Cron model.""" def __init__(self, params=None): """Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View""" rights = access.Checke...
the_stack_v2_python_sparse
src/melange/src/soc/views/models/cron.py
MatthewWilkes/mw4068-packaging
train
0
1992eb23b533b56f55b836ec901c9851e1f08326
[ "Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()\nstudent = Student.objects.get(id='17373349')\nFeedback(student_id=student, kind='bug', content='ddl有问题').save()\nresponse = self.client.get('/feedback/')\nself.assertEqual(response.status_code, 200)\nresponse = self.client.g...
<|body_start_0|> Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save() student = Student.objects.get(id='17373349') Feedback(student_id=student, kind='bug', content='ddl有问题').save() response = self.client.get('/feedback/') self.assertEqual(resp...
UserLoginTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserLoginTests: def test_get_200(self): """检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈""" <|body_0|> def test_get_400(self): """检测返回状态码位400的get请求 1.参数数量错误 2.参数名称错误 :return:""" <|body_1|> def test_post_200(self): """检测返回状态码为200的post请求 1.成功登录"...
stack_v2_sparse_classes_75kplus_train_074746
3,122
no_license
[ { "docstring": "检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈", "name": "test_get_200", "signature": "def test_get_200(self)" }, { "docstring": "检测返回状态码位400的get请求 1.参数数量错误 2.参数名称错误 :return:", "name": "test_get_400", "signature": "def test_get_400(self)" }, { "docstring": "检测返回...
5
null
Implement the Python class `UserLoginTests` described below. Class description: Implement the UserLoginTests class. Method signatures and docstrings: - def test_get_200(self): 检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈 - def test_get_400(self): 检测返回状态码位400的get请求 1.参数数量错误 2.参数名称错误 :return: - def test_post_200(se...
Implement the Python class `UserLoginTests` described below. Class description: Implement the UserLoginTests class. Method signatures and docstrings: - def test_get_200(self): 检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈 - def test_get_400(self): 检测返回状态码位400的get请求 1.参数数量错误 2.参数名称错误 :return: - def test_post_200(se...
7dfa07283d4130b931a92c80bf4f499f97a33b62
<|skeleton|> class UserLoginTests: def test_get_200(self): """检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈""" <|body_0|> def test_get_400(self): """检测返回状态码位400的get请求 1.参数数量错误 2.参数名称错误 :return:""" <|body_1|> def test_post_200(self): """检测返回状态码为200的post请求 1.成功登录"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserLoginTests: def test_get_200(self): """检测返回状态码为200的get请求 1.获取所有反馈 2.获取某一天的反馈 3。获取某一类的反馈""" Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save() student = Student.objects.get(id='17373349') Feedback(student_id=student, kind='bug', content...
the_stack_v2_python_sparse
user_feedback/tests.py
SE2020-TopUnderstanding/BUAA-Campus-Tools-Backend
train
7
ad6540d6aa8f3ab6497a903a3936e74e8dcb461f
[ "self.qualification_id = qualification_id\nself.manufacturer = manufacturer\nself.qualification_type = qualification_type\nself.qualification_description = qualification_description", "if dictionary is None:\n return None\nqualification_id = dictionary.get('qualificationId')\nmanufacturer = dictionary.get('man...
<|body_start_0|> self.qualification_id = qualification_id self.manufacturer = manufacturer self.qualification_type = qualification_type self.qualification_description = qualification_description <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (string): TODO: type description here. qualification_description (string): TODO: type descripti...
PersonnelQualification
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersonnelQualification: """Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (string): TODO: type description here. qualif...
stack_v2_sparse_classes_75kplus_train_074747
2,400
permissive
[ { "docstring": "Constructor for the PersonnelQualification class", "name": "__init__", "signature": "def __init__(self, qualification_id=None, manufacturer=None, qualification_type=None, qualification_description=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args:...
2
stack_v2_sparse_classes_30k_train_034663
Implement the Python class `PersonnelQualification` described below. Class description: Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (strin...
Implement the Python class `PersonnelQualification` described below. Class description: Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (strin...
6835ee1f6a667b5c7827c5248391081f06b75513
<|skeleton|> class PersonnelQualification: """Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (string): TODO: type description here. qualif...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PersonnelQualification: """Implementation of the 'PersonnelQualification' model. A personnel qualification. Attributes: qualification_id (int): The id of a personnel qualification. manufacturer (string): TODO: type description here. qualification_type (string): TODO: type description here. qualification_descr...
the_stack_v2_python_sparse
greenbyteapi/models/personnel_qualification.py
charlie9578/greenbyte-api-sdk
train
0
0080ec70a09da94da143ff4f2410f38c56f0e384
[ "database = Database()\ntarget = database.get_setting('static', 'root')\nif not target:\n raise CommandError(u'No static root setting. Set static root with:\\nmag.py add_setting static root <directory-name>\\nE.g.\\nmag.py add_setting static root /var/www/static')\napps = database.get_app_list()\nif apps:\n a...
<|body_start_0|> database = Database() target = database.get_setting('static', 'root') if not target: raise CommandError(u'No static root setting. Set static root with:\nmag.py add_setting static root <directory-name>\nE.g.\nmag.py add_setting static root /var/www/static') ap...
Collect static files into the public web directory.
Command
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """Collect static files into the public web directory.""" def handle(self, *args, **options): """Collect the static files of an application.""" <|body_0|> def check_newer(file_tuple): """Check if the source is newer than the target.""" <|body_1|>...
stack_v2_sparse_classes_75kplus_train_074748
4,110
permissive
[ { "docstring": "Collect the static files of an application.", "name": "handle", "signature": "def handle(self, *args, **options)" }, { "docstring": "Check if the source is newer than the target.", "name": "check_newer", "signature": "def check_newer(file_tuple)" }, { "docstring":...
4
stack_v2_sparse_classes_30k_train_001824
Implement the Python class `Command` described below. Class description: Collect static files into the public web directory. Method signatures and docstrings: - def handle(self, *args, **options): Collect the static files of an application. - def check_newer(file_tuple): Check if the source is newer than the target. ...
Implement the Python class `Command` described below. Class description: Collect static files into the public web directory. Method signatures and docstrings: - def handle(self, *args, **options): Collect the static files of an application. - def check_newer(file_tuple): Check if the source is newer than the target. ...
16d3fa3b9a14ce9aa796142396a2db579be06d5e
<|skeleton|> class Command: """Collect static files into the public web directory.""" def handle(self, *args, **options): """Collect the static files of an application.""" <|body_0|> def check_newer(file_tuple): """Check if the source is newer than the target.""" <|body_1|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Command: """Collect static files into the public web directory.""" def handle(self, *args, **options): """Collect the static files of an application.""" database = Database() target = database.get_setting('static', 'root') if not target: raise CommandError(u'No...
the_stack_v2_python_sparse
magpy/management/commands/collectstatic.py
zeth/magpy
train
4
5005814530be9ba2733a4cdea4499a2a09ee6907
[ "self.stdout = sys.stdout\nself.cache = FileCacher()\nset_arguments(arguments)\nself.locals = {'__name__': '__console__', '__doc__': None}", "try:\n sys.stdout = self.cache\n try:\n exec(script, self.locals)\n except SystemExit:\n raise\n except SyntaxError:\n formatted_lines = tr...
<|body_start_0|> self.stdout = sys.stdout self.cache = FileCacher() set_arguments(arguments) self.locals = {'__name__': '__console__', '__doc__': None} <|end_body_0|> <|body_start_1|> try: sys.stdout = self.cache try: exec(script, self.loc...
Class for running a Python script as interactive interpreter.
Shell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Shell: """Class for running a Python script as interactive interpreter.""" def __init__(self, arguments): """Constructor.""" <|body_0|> def run_code(self, script): """Function to run code.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.std...
stack_v2_sparse_classes_75kplus_train_074749
7,287
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, arguments)" }, { "docstring": "Function to run code.", "name": "run_code", "signature": "def run_code(self, script)" } ]
2
stack_v2_sparse_classes_30k_train_051717
Implement the Python class `Shell` described below. Class description: Class for running a Python script as interactive interpreter. Method signatures and docstrings: - def __init__(self, arguments): Constructor. - def run_code(self, script): Function to run code.
Implement the Python class `Shell` described below. Class description: Class for running a Python script as interactive interpreter. Method signatures and docstrings: - def __init__(self, arguments): Constructor. - def run_code(self, script): Function to run code. <|skeleton|> class Shell: """Class for running a...
4648e48f4e290e5a1e5558acaf05431982acb81a
<|skeleton|> class Shell: """Class for running a Python script as interactive interpreter.""" def __init__(self, arguments): """Constructor.""" <|body_0|> def run_code(self, script): """Function to run code.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Shell: """Class for running a Python script as interactive interpreter.""" def __init__(self, arguments): """Constructor.""" self.stdout = sys.stdout self.cache = FileCacher() set_arguments(arguments) self.locals = {'__name__': '__console__', '__doc__': None} ...
the_stack_v2_python_sparse
activities_python/actions/action_run_script.py
mikhail-rozhkov/cicso_lab
train
0
f5583083a3c3cec400b7c5689b140822ca889d5f
[ "result = []\nfor model in cls.model_list:\n result += list(model.objects.filter(*args, **kwargs))\nreturn result", "try:\n ls = cls.filter(*args, **kwargs)\n if len(ls) > 1:\n raise MultipleObjectsReturned()\n return cls.filter(*args, **kwargs)[0]\nexcept IndexError:\n raise ObjectDoesNotEx...
<|body_start_0|> result = [] for model in cls.model_list: result += list(model.objects.filter(*args, **kwargs)) return result <|end_body_0|> <|body_start_1|> try: ls = cls.filter(*args, **kwargs) if len(ls) > 1: raise MultipleObjectsRe...
This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.
AbstractModelQuery
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of a...
stack_v2_sparse_classes_75kplus_train_074750
1,753
permissive
[ { "docstring": "Query all concrete model classes. Iterates over the model list and returns a list of all matching models from the classes given. Filter queries are given here as normal and are passed into the Django ORM for each concrete model", "name": "filter", "signature": "def filter(cls, *args, **k...
2
stack_v2_sparse_classes_30k_train_011836
Implement the Python class `AbstractModelQuery` described below. Class description: This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models. Method signatures and docstrings: - def filter(cls, *args, **kwargs): Query all concrete model clas...
Implement the Python class `AbstractModelQuery` described below. Class description: This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models. Method signatures and docstrings: - def filter(cls, *args, **kwargs): Query all concrete model clas...
886a644432ff53f97babccbae4eee555338caec1
<|skeleton|> class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AbstractModelQuery: """This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.""" def filter(cls, *args, **kwargs): """Query all concrete model classes. Iterates over the model list and returns a list of all matching m...
the_stack_v2_python_sparse
src/dashboard/utils.py
opnfv/laas
train
3
b706d30898495a588cde5f2a2ef7d4601c2d079e
[ "records = {}\nleft, max_length = (0, 0)\nfor i, c in enumerate(s):\n if c in records and left <= records[c]:\n left = records[c] + 1\n else:\n max_length = max(max_length, i - left + 1)\n records[c] = i\nreturn max_length", "if not s:\n return 0\nmax_length = 1\nfor i in range(1, len(s)...
<|body_start_0|> records = {} left, max_length = (0, 0) for i, c in enumerate(s): if c in records and left <= records[c]: left = records[c] + 1 else: max_length = max(max_length, i - left + 1) records[c] = i return max_l...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_0|> def lengthOfLongestSubstring_naive(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> records = {} left, max_length...
stack_v2_sparse_classes_75kplus_train_074751
2,208
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "lengthOfLongestSubstring", "signature": "def lengthOfLongestSubstring(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "lengthOfLongestSubstring_naive", "signature": "def lengthOfLongestSubstring_naive(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_047942
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_naive(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 lengthOfLongestSubstring(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_naive(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def len...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" <|body_0|> def lengthOfLongestSubstring_naive(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lengthOfLongestSubstring(self, s): """:type s: str :rtype: int""" records = {} left, max_length = (0, 0) for i, c in enumerate(s): if c in records and left <= records[c]: left = records[c] + 1 else: max_lengt...
the_stack_v2_python_sparse
src/lt_3.py
oxhead/CodingYourWay
train
0
676a0a53ffa75a783417e24f4a5c660f1b59ecee
[ "try:\n res = urllib.request.urlopen(self.url + '../httpserver.py')\n self.assertNotEqual(res.status, 200)\nexcept urllib.error.HTTPError as error:\n self.assertEqual(error.code, 403)", "try:\n res = urllib.request.urlopen(self.url + '../httpserver.py')\n body = res.read().decode()\n self.assert...
<|body_start_0|> try: res = urllib.request.urlopen(self.url + '../httpserver.py') self.assertNotEqual(res.status, 200) except urllib.error.HTTPError as error: self.assertEqual(error.code, 403) <|end_body_0|> <|body_start_1|> try: res = urllib.requ...
Tests insecure requests to a server.
TestInsecureRequests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInsecureRequests: """Tests insecure requests to a server.""" def test_python_files_status(self): """Server must return 403 for files outside htdocs.""" <|body_0|> def test_python_files_content(self): """Server must return 403 for files outside htdocs.""" ...
stack_v2_sparse_classes_75kplus_train_074752
17,868
no_license
[ { "docstring": "Server must return 403 for files outside htdocs.", "name": "test_python_files_status", "signature": "def test_python_files_status(self)" }, { "docstring": "Server must return 403 for files outside htdocs.", "name": "test_python_files_content", "signature": "def test_pytho...
3
null
Implement the Python class `TestInsecureRequests` described below. Class description: Tests insecure requests to a server. Method signatures and docstrings: - def test_python_files_status(self): Server must return 403 for files outside htdocs. - def test_python_files_content(self): Server must return 403 for files ou...
Implement the Python class `TestInsecureRequests` described below. Class description: Tests insecure requests to a server. Method signatures and docstrings: - def test_python_files_status(self): Server must return 403 for files outside htdocs. - def test_python_files_content(self): Server must return 403 for files ou...
d27b122c87131789178f77e6f693b718dd57c594
<|skeleton|> class TestInsecureRequests: """Tests insecure requests to a server.""" def test_python_files_status(self): """Server must return 403 for files outside htdocs.""" <|body_0|> def test_python_files_content(self): """Server must return 403 for files outside htdocs.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestInsecureRequests: """Tests insecure requests to a server.""" def test_python_files_status(self): """Server must return 403 for files outside htdocs.""" try: res = urllib.request.urlopen(self.url + '../httpserver.py') self.assertNotEqual(res.status, 200) ...
the_stack_v2_python_sparse
2º Ano/2º Semestre/Computação Distribuida/Projectos/tp3-team-alexandrecoelho-sergioverissimo-t3/tests.py
alexmpc98/Engenharia-Informatica-IPS
train
4
5a9bc394abfec97c2ed61fdca423b0a26c146d42
[ "threading.Thread.__init__(self)\nself.taskBuffer = taskBuffer\nif log_stream:\n self.log_stream = log_stream\nelse:\n self.log_stream = _logger\nif hasattr(panda_config, 'CRIC_URL_SCHEDCONFIG'):\n self.CRIC_URL_TAGS = panda_config.CRIC_URL_TAGS\nelse:\n self.CRIC_URL_TAGS = 'https://atlas-cric.cern.ch/...
<|body_start_0|> threading.Thread.__init__(self) self.taskBuffer = taskBuffer if log_stream: self.log_stream = log_stream else: self.log_stream = _logger if hasattr(panda_config, 'CRIC_URL_SCHEDCONFIG'): self.CRIC_URL_TAGS = panda_config.CRIC_U...
Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue
SWTagsDumper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SWTagsDumper: """Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue""" def __init__(self, taskBuffer, log_stream=None): """Initialization and configuration""" <|body_0|> def run(self): """Principal function""" <|body_...
stack_v2_sparse_classes_75kplus_train_074753
38,097
permissive
[ { "docstring": "Initialization and configuration", "name": "__init__", "signature": "def __init__(self, taskBuffer, log_stream=None)" }, { "docstring": "Principal function", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_052089
Implement the Python class `SWTagsDumper` described below. Class description: Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue Method signatures and docstrings: - def __init__(self, taskBuffer, log_stream=None): Initialization and configuration - def run(self): Principal functi...
Implement the Python class `SWTagsDumper` described below. Class description: Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue Method signatures and docstrings: - def __init__(self, taskBuffer, log_stream=None): Initialization and configuration - def run(self): Principal functi...
365a9feb55d493b208e3052428f0b524e63e4178
<|skeleton|> class SWTagsDumper: """Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue""" def __init__(self, taskBuffer, log_stream=None): """Initialization and configuration""" <|body_0|> def run(self): """Principal function""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SWTagsDumper: """Downloads the CRIC tags dump, flattens it out and stores it in the DB, one row per queue""" def __init__(self, taskBuffer, log_stream=None): """Initialization and configuration""" threading.Thread.__init__(self) self.taskBuffer = taskBuffer if log_stream: ...
the_stack_v2_python_sparse
pandaserver/configurator/Configurator.py
PanDAWMS/panda-server
train
8
dc69eff9bb07d104cf822482c048f07af91fc9c9
[ "try:\n return obj.next_item_id\nexcept AttributeError:\n try:\n item = Item.objects.get(branch=obj.branch, lesson=obj.lesson, order=obj.order + 1)\n return {'item_id': item.item_id, 'type': item.type.id, 'category': item.type.category}\n except Item.DoesNotExist:\n return {'item_id': ...
<|body_start_0|> try: return obj.next_item_id except AttributeError: try: item = Item.objects.get(branch=obj.branch, lesson=obj.lesson, order=obj.order + 1) return {'item_id': item.item_id, 'type': item.type.id, 'category': item.type.category} ...
Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. average_grade: The average grade of all students who comp...
AssignmentAnalyticsSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssignmentAnalyticsSerializer: """Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. ...
stack_v2_sparse_classes_75kplus_train_074754
12,166
no_license
[ { "docstring": "Return the next item in the lesson, if any.", "name": "get_next_item", "signature": "def get_next_item(self, obj)" }, { "docstring": "Return the next assignment in the lesson, if any.", "name": "get_next_assignment", "signature": "def get_next_assignment(self, obj)" } ]
2
stack_v2_sparse_classes_30k_train_029571
Implement the Python class `AssignmentAnalyticsSerializer` described below. Class description: Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divid...
Implement the Python class `AssignmentAnalyticsSerializer` described below. Class description: Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divid...
f701eee3e8ced9a839401e268031c2d497252e8a
<|skeleton|> class AssignmentAnalyticsSerializer: """Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AssignmentAnalyticsSerializer: """Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. average_grade...
the_stack_v2_python_sparse
coursera/serializers/items.py
cornytrace/SEP-Autumn-2018-Group2-Coursera
train
0
01c9f97169cc36b84ceb28be27208d19fc3942bb
[ "if not root:\n return 0\nreturn 1 + self.countNodes(root.left) + self.countNodes(root.right)", "if not root:\n return 0\nq = [root]\ncnt = 1\nwhile q:\n tmp = q.pop()\n if tmp.left:\n q.append(tmp.left)\n cnt += 1\n if tmp.right:\n q.append(tmp.right)\n cnt += 1\nreturn...
<|body_start_0|> if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right) <|end_body_0|> <|body_start_1|> if not root: return 0 q = [root] cnt = 1 while q: tmp = q.pop() if tmp.left: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countNodes(self, root): """brute force recursive, TLE :type root: TreeNode :rtype: int""" <|body_0|> def countNodes2(self, root): """brute force iteration, TLE :param root: :return:""" <|body_1|> def countNode3(self, root): """cuz i...
stack_v2_sparse_classes_75kplus_train_074755
1,338
no_license
[ { "docstring": "brute force recursive, TLE :type root: TreeNode :rtype: int", "name": "countNodes", "signature": "def countNodes(self, root)" }, { "docstring": "brute force iteration, TLE :param root: :return:", "name": "countNodes2", "signature": "def countNodes2(self, root)" }, { ...
3
stack_v2_sparse_classes_30k_train_018449
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root): brute force recursive, TLE :type root: TreeNode :rtype: int - def countNodes2(self, root): brute force iteration, TLE :param root: :return: - def coun...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countNodes(self, root): brute force recursive, TLE :type root: TreeNode :rtype: int - def countNodes2(self, root): brute force iteration, TLE :param root: :return: - def coun...
e16702d2b3ec4e5054baad56f4320bc3b31676ad
<|skeleton|> class Solution: def countNodes(self, root): """brute force recursive, TLE :type root: TreeNode :rtype: int""" <|body_0|> def countNodes2(self, root): """brute force iteration, TLE :param root: :return:""" <|body_1|> def countNode3(self, root): """cuz i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countNodes(self, root): """brute force recursive, TLE :type root: TreeNode :rtype: int""" if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right) def countNodes2(self, root): """brute force iteration, TLE :param r...
the_stack_v2_python_sparse
leetcode/medium/count_complete_tree_nodes.py
SuperMartinYang/learning_algorithm
train
0
b2b9968cfa4eee77f384f1af3139cdf8e58b0517
[ "def get_bytes(size):\n return reversed([chr(size >> i * 8 & 255) for i in range(4)])\nres = []\nfor s in strs:\n res.extend(get_bytes(len(s)))\n res.append(s)\nreturn ''.join(res)", "i = 0\nres = []\nwhile i < len(s):\n size = 0\n for c in s[i:i + 4]:\n size = (size << 8) + ord(c)\n i +=...
<|body_start_0|> def get_bytes(size): return reversed([chr(size >> i * 8 & 255) for i in range(4)]) res = [] for s in strs: res.extend(get_bytes(len(s))) res.append(s) return ''.join(res) <|end_body_0|> <|body_start_1|> i = 0 res = [] ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" <|body_0|> def decode(self, s: str) -> [str]: """Decodes a single string to a list of strings.""" <|body_1|> <|end_skeleton|> <|body_start_0|> def get_b...
stack_v2_sparse_classes_75kplus_train_074756
1,610
no_license
[ { "docstring": "Encodes a list of strings to a single string.", "name": "encode", "signature": "def encode(self, strs: [str]) -> str" }, { "docstring": "Decodes a single string to a list of strings.", "name": "decode", "signature": "def decode(self, s: str) -> [str]" } ]
2
stack_v2_sparse_classes_30k_train_009869
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string. - def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string. - def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. <|skeleton|> cla...
84b35ec9a4e4319b29eb5f0f226543c9f3f47630
<|skeleton|> class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" <|body_0|> def decode(self, s: str) -> [str]: """Decodes a single string to a list of strings.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" def get_bytes(size): return reversed([chr(size >> i * 8 & 255) for i in range(4)]) res = [] for s in strs: res.extend(get_bytes(len(s))) res.appe...
the_stack_v2_python_sparse
encode-and-decode-strings.py
maomao905/algo
train
0
064c2df19750ff35d26599156b1aaf1a92a789f0
[ "self.bytes_value = bytes_value\nself.double_value = double_value\nself.int_64_value = int_64_value\nself.string_value = string_value", "if dictionary is None:\n return None\nbytes_value = dictionary.get('bytesValue')\ndouble_value = dictionary.get('doubleValue')\nint_64_value = dictionary.get('int64Value')\ns...
<|body_start_0|> self.bytes_value = bytes_value self.double_value = double_value self.int_64_value = int_64_value self.string_value = string_value <|end_body_0|> <|body_start_1|> if dictionary is None: return None bytes_value = dictionary.get('bytesValue') ...
Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of bytes if the current data type is bytes. Specify a value for this field when...
Value_Data
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Value_Data: """Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of bytes if the current data type is byte...
stack_v2_sparse_classes_75kplus_train_074757
2,688
permissive
[ { "docstring": "Constructor for the Value_Data class", "name": "__init__", "signature": "def __init__(self, bytes_value=None, double_value=None, int_64_value=None, string_value=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona...
2
null
Implement the Python class `Value_Data` described below. Class description: Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of...
Implement the Python class `Value_Data` described below. Class description: Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class Value_Data: """Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of bytes if the current data type is byte...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Value_Data: """Implementation of the 'Value_Data' model. Specifies the fields to store data of a given type. Specify data in the appropriate field for the current data type. Attributes: bytes_value (list of long|int): Specifies the field to store an array of bytes if the current data type is bytes. Specify a ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/value_data.py
cohesity/management-sdk-python
train
24
bf0a30387469fe3617ad31766c28da0c30e6f179
[ "super().__init__(prev_node)\nself.in_dim = prev_node.out_dim\nself.out_dim = np.prod(self.in_dim)\nself.in_var = prev_node.out_var\nself.out_var = Allocation.allocate_var('float', 'x', self.out_dim)", "n = AssignmentNode(self.out_var, self.in_var)\nself.pointer_decls.append(self.out_var)\nself.add_edge('content'...
<|body_start_0|> super().__init__(prev_node) self.in_dim = prev_node.out_dim self.out_dim = np.prod(self.in_dim) self.in_var = prev_node.out_var self.out_var = Allocation.allocate_var('float', 'x', self.out_dim) <|end_body_0|> <|body_start_1|> n = AssignmentNode(self.out...
Node that lowers the dimension.
FlattenNode
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlattenNode: """Node that lowers the dimension.""" def __init__(self, prev_node): """Initialize this node. :param prev_node: The previous node.""" <|body_0|> def lowering(self): """Create the loops required to express this node in ANSI C code without SIMD and rep...
stack_v2_sparse_classes_75kplus_train_074758
20,388
permissive
[ { "docstring": "Initialize this node. :param prev_node: The previous node.", "name": "__init__", "signature": "def __init__(self, prev_node)" }, { "docstring": "Create the loops required to express this node in ANSI C code without SIMD and replace this node. This loop will stay in graph to provi...
2
stack_v2_sparse_classes_30k_train_015095
Implement the Python class `FlattenNode` described below. Class description: Node that lowers the dimension. Method signatures and docstrings: - def __init__(self, prev_node): Initialize this node. :param prev_node: The previous node. - def lowering(self): Create the loops required to express this node in ANSI C code...
Implement the Python class `FlattenNode` described below. Class description: Node that lowers the dimension. Method signatures and docstrings: - def __init__(self, prev_node): Initialize this node. :param prev_node: The previous node. - def lowering(self): Create the loops required to express this node in ANSI C code...
987b0efeb56cd150b3a34b672fd5eba05e6d491f
<|skeleton|> class FlattenNode: """Node that lowers the dimension.""" def __init__(self, prev_node): """Initialize this node. :param prev_node: The previous node.""" <|body_0|> def lowering(self): """Create the loops required to express this node in ANSI C code without SIMD and rep...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FlattenNode: """Node that lowers the dimension.""" def __init__(self, prev_node): """Initialize this node. :param prev_node: The previous node.""" super().__init__(prev_node) self.in_dim = prev_node.out_dim self.out_dim = np.prod(self.in_dim) self.in_var = prev_nod...
the_stack_v2_python_sparse
nncg/nodes/cnn.py
iml130/nncg
train
34
e11d4498884d36c1d2b084335ab055ff94be2d86
[ "Thread.__init__(self)\nself.client = client\nself.transcript = transcript", "self.name = decode(self.client.recv(BUFSIZE), CODE)\nif not self.name:\n print('Client disconnected')\n self.client.close()\nelse:\n print(self.name, 'is connected')\n while True:\n self.client.send(bytes(str(self.tra...
<|body_start_0|> Thread.__init__(self) self.client = client self.transcript = transcript <|end_body_0|> <|body_start_1|> self.name = decode(self.client.recv(BUFSIZE), CODE) if not self.name: print('Client disconnected') self.client.close() else: ...
Handles chatroom requests from a client.
ChatClientHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChatClientHandler: """Handles chatroom requests from a client.""" def __init__(self, client, transcript): """Save references to the client socket and shared transcript.""" <|body_0|> def run(self): """Obtains name from the client, then enters an interative loop t...
stack_v2_sparse_classes_75kplus_train_074759
1,692
no_license
[ { "docstring": "Save references to the client socket and shared transcript.", "name": "__init__", "signature": "def __init__(self, client, transcript)" }, { "docstring": "Obtains name from the client, then enters an interative loop to take and respond to requests.", "name": "run", "signa...
2
stack_v2_sparse_classes_30k_train_044396
Implement the Python class `ChatClientHandler` described below. Class description: Handles chatroom requests from a client. Method signatures and docstrings: - def __init__(self, client, transcript): Save references to the client socket and shared transcript. - def run(self): Obtains name from the client, then enters...
Implement the Python class `ChatClientHandler` described below. Class description: Handles chatroom requests from a client. Method signatures and docstrings: - def __init__(self, client, transcript): Save references to the client socket and shared transcript. - def run(self): Obtains name from the client, then enters...
d0a79d91a51c76cbb75830f7a8d1ce72174ad220
<|skeleton|> class ChatClientHandler: """Handles chatroom requests from a client.""" def __init__(self, client, transcript): """Save references to the client socket and shared transcript.""" <|body_0|> def run(self): """Obtains name from the client, then enters an interative loop t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChatClientHandler: """Handles chatroom requests from a client.""" def __init__(self, client, transcript): """Save references to the client socket and shared transcript.""" Thread.__init__(self) self.client = client self.transcript = transcript def run(self): "...
the_stack_v2_python_sparse
module-06/chatclienthandler.py
tjsaotome65/sec430-python
train
2
d61e244dc98461ad386353ac916b535d7681454e
[ "IO_files = {}\nfile_names = set()\nfor fl in in_dir.files:\n if self.name not in fl.users:\n if utils.splitext(fl.name)[-1] in self.input_types:\n IO_files['-!i'] = os.path.join(in_dir.path, fl.name)\n command_ids = [utils.infer_path_id(IO_files['-!i'])]\n in_dir.use_file...
<|body_start_0|> IO_files = {} file_names = set() for fl in in_dir.files: if self.name not in fl.users: if utils.splitext(fl.name)[-1] in self.input_types: IO_files['-!i'] = os.path.join(in_dir.path, fl.name) command_ids = [util...
Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_type: Input types accepted by t...
psmc_history2ms
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class psmc_history2ms: """Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the func...
stack_v2_sparse_classes_75kplus_train_074760
19,984
permissive
[ { "docstring": "Infers the input and output file paths. This method must keep the directory objects up to date of the file edits! Parameters: in_cmd: A dict containing the command line. in_dir: Input directory (instance of filetypes.Directory). out_dir: Output directory (instance of filetypes.Directory). Return...
2
stack_v2_sparse_classes_30k_train_038684
Implement the Python class `psmc_history2ms` described below. Class description: Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file ed...
Implement the Python class `psmc_history2ms` described below. Class description: Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file ed...
fd83eee4be0bb78c67a111fd1c1c1dff4c16aefe
<|skeleton|> class psmc_history2ms: """Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the func...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class psmc_history2ms: """Class for using history2ms. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the function. input_t...
the_stack_v2_python_sparse
modules/psmc.py
tyrmi/STAPLER
train
4
7f54de7d90a3f0a796d6d63a649548115660925b
[ "if x < 0:\n return False\nxstr = str(x)\nreturn xstr == xstr[::-1]", "if x < 0 or (x % 10 == 0 and x != 0):\n return False\nreverted_x = 0\nwhile x > reverted_x:\n reverted_x = reverted_x * 10 + x % 10\n x /= 10\nreturn x == reverted_x or x == reverted_x / 10" ]
<|body_start_0|> if x < 0: return False xstr = str(x) return xstr == xstr[::-1] <|end_body_0|> <|body_start_1|> if x < 0 or (x % 10 == 0 and x != 0): return False reverted_x = 0 while x > reverted_x: reverted_x = reverted_x * 10 + x % ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindromeStr(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if x < 0: return False xstr = str(x) ...
stack_v2_sparse_classes_75kplus_train_074761
618
no_license
[ { "docstring": ":type x: int :rtype: bool", "name": "isPalindromeStr", "signature": "def isPalindromeStr(self, x)" }, { "docstring": ":type x: int :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, x)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindromeStr(self, x): :type x: int :rtype: bool - def isPalindrome(self, x): :type x: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindromeStr(self, x): :type x: int :rtype: bool - def isPalindrome(self, x): :type x: int :rtype: bool <|skeleton|> class Solution: def isPalindromeStr(self, x): ...
5c2473f859da5efec73120256faad06ab8e0e359
<|skeleton|> class Solution: def isPalindromeStr(self, x): """:type x: int :rtype: bool""" <|body_0|> def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isPalindromeStr(self, x): """:type x: int :rtype: bool""" if x < 0: return False xstr = str(x) return xstr == xstr[::-1] def isPalindrome(self, x): """:type x: int :rtype: bool""" if x < 0 or (x % 10 == 0 and x != 0): r...
the_stack_v2_python_sparse
leetcode/palindrome_number.py
chlos/exercises_in_futility
train
0
baf42b7dc4b506ad175dbf9a2ecf7a4414ff65b3
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['General Boat Fishing Talk', 'Fishing Kayaks']\nURLS = ['https://www.southwestseafishing.co.uk/forum/boat-fishing/general-boat-fishing-talk', 'https://www.southwestseafishing.co.uk/forum/boat-fishing/fishing-kayaks']\nPAGES = [36, 3]\na...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['General Boat Fishing Talk', 'Fishing Kayaks'] URLS = ['https://www.southwestseafishing.co.uk/forum/boat-fishing/general-boat-fishing-talk', 'https://www.southwestseafishing.co.uk/forum/boat-fishing/fi...
scrape reports from angling addicts forum
SouthWestSeaFishingBoatSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SouthWestSeaFishingBoatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, respo...
stack_v2_sparse_classes_75kplus_train_074762
7,237
no_license
[ { "docstring": "generate links to pages in a board", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "crawl", "name": "crawl_board_threads", "signature": "def crawl_board_threads(self, response)" }, { "docstring": "open a report thread and parse first ...
3
stack_v2_sparse_classes_30k_train_033681
Implement the Python class `SouthWestSeaFishingBoatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response)...
Implement the Python class `SouthWestSeaFishingBoatSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board - def crawl_board_threads(self, response): crawl - def parse_thread(self, response)...
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class SouthWestSeaFishingBoatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" <|body_0|> def crawl_board_threads(self, response): """crawl""" <|body_1|> def parse_thread(self, respo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SouthWestSeaFishingBoatSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board""" assert isinstance(response, scrapy.http.response.html.HtmlResponse) BOARDS = ['General Boat Fishing Talk', 'Fishing Kayaks'] U...
the_stack_v2_python_sparse
imgscrape/spiders/southwestseafishing.py
gmonkman/python
train
0
5ca359631eab5a5205457dba67ca43f49785e9c1
[ "if not string:\n return ''\nm, M = (min(string), max(string))\nfor i, letter in enumerate(m):\n if letter != M[i]:\n return m[:i]\nreturn m", "if not string:\n return ''\nm = min(string, key=len)\nleft, right = (0, len(m))\nwhile left <= right:\n pivot = (left + right) // 2\n prefix = strin...
<|body_start_0|> if not string: return '' m, M = (min(string), max(string)) for i, letter in enumerate(m): if letter != M[i]: return m[:i] return m <|end_body_0|> <|body_start_1|> if not string: return '' m = min(string...
LongestCommonPrefix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" <|body_0|> def longest_common_prefix_2(self, string: str) -> str: """Approach: Binary Search :param string: :return:""" ...
stack_v2_sparse_classes_75kplus_train_074763
1,164
no_license
[ { "docstring": "Approach: Using min and max function. :param string: :return:", "name": "longest_common_prefix_1", "signature": "def longest_common_prefix_1(self, string: str) -> str" }, { "docstring": "Approach: Binary Search :param string: :return:", "name": "longest_common_prefix_2", ...
2
stack_v2_sparse_classes_30k_train_021567
Implement the Python class `LongestCommonPrefix` described below. Class description: Implement the LongestCommonPrefix class. Method signatures and docstrings: - def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return: - def longest_common_prefix_2(self, str...
Implement the Python class `LongestCommonPrefix` described below. Class description: Implement the LongestCommonPrefix class. Method signatures and docstrings: - def longest_common_prefix_1(self, string: str) -> str: Approach: Using min and max function. :param string: :return: - def longest_common_prefix_2(self, str...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" <|body_0|> def longest_common_prefix_2(self, string: str) -> str: """Approach: Binary Search :param string: :return:""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LongestCommonPrefix: def longest_common_prefix_1(self, string: str) -> str: """Approach: Using min and max function. :param string: :return:""" if not string: return '' m, M = (min(string), max(string)) for i, letter in enumerate(m): if letter != M[i]: ...
the_stack_v2_python_sparse
math_and_srings/longestcommonprefix.py
Shiv2157k/leet_code
train
1
be792b51708bb811c58226e9b39f341f63d2f480
[ "super(CovarianceTest, self).setUp()\ndata_in = self.get_file('covariance_correlation.csv')\nself.base_frame = self.context.frame.import_csv(data_in)", "sparktk_result = self.base_frame.covariance('C1', 'C4')\nC1_C4_columns_data = self.base_frame.take(self.base_frame.count(), columns=['C1', 'C4']).data\nnumpy_res...
<|body_start_0|> super(CovarianceTest, self).setUp() data_in = self.get_file('covariance_correlation.csv') self.base_frame = self.context.frame.import_csv(data_in) <|end_body_0|> <|body_start_1|> sparktk_result = self.base_frame.covariance('C1', 'C4') C1_C4_columns_data = self.b...
CovarianceTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CovarianceTest: def setUp(self): """Build test frames""" <|body_0|> def test_covar(self): """Test covariance between 2 columns""" <|body_1|> def test_covar_matrix(self): """Verify covariance matrix on all columns""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_75kplus_train_074764
1,805
permissive
[ { "docstring": "Build test frames", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test covariance between 2 columns", "name": "test_covar", "signature": "def test_covar(self)" }, { "docstring": "Verify covariance matrix on all columns", "name": "test_cova...
3
stack_v2_sparse_classes_30k_train_035720
Implement the Python class `CovarianceTest` described below. Class description: Implement the CovarianceTest class. Method signatures and docstrings: - def setUp(self): Build test frames - def test_covar(self): Test covariance between 2 columns - def test_covar_matrix(self): Verify covariance matrix on all columns
Implement the Python class `CovarianceTest` described below. Class description: Implement the CovarianceTest class. Method signatures and docstrings: - def setUp(self): Build test frames - def test_covar(self): Test covariance between 2 columns - def test_covar_matrix(self): Verify covariance matrix on all columns <...
21618500680f2f16ada4cb31684adf3ef3073ce5
<|skeleton|> class CovarianceTest: def setUp(self): """Build test frames""" <|body_0|> def test_covar(self): """Test covariance between 2 columns""" <|body_1|> def test_covar_matrix(self): """Verify covariance matrix on all columns""" <|body_2|> <|end_skel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CovarianceTest: def setUp(self): """Build test frames""" super(CovarianceTest, self).setUp() data_in = self.get_file('covariance_correlation.csv') self.base_frame = self.context.frame.import_csv(data_in) def test_covar(self): """Test covariance between 2 columns"""...
the_stack_v2_python_sparse
regression-tests/sparktkregtests/testcases/frames/covariance_test.py
abhiwand/spark-tk
train
0
946e0fa97dd5b47545f0afb29795f4cb3ef44822
[ "actionAngle.__init__(self, ro=kwargs.get('ro', None), vo=kwargs.get('vo', None))\nif not 'omega' in kwargs:\n raise OSError('Must specify omega= for actionAngleHarmonic')\nself._omega = conversion.parse_frequency(kwargs.get('omega'), ro=self._ro, vo=self._vo)\nreturn None", "if len(args) == 2:\n x, vx = ar...
<|body_start_0|> actionAngle.__init__(self, ro=kwargs.get('ro', None), vo=kwargs.get('vo', None)) if not 'omega' in kwargs: raise OSError('Must specify omega= for actionAngleHarmonic') self._omega = conversion.parse_frequency(kwargs.get('omega'), ro=self._ro, vo=self._vo) ret...
Action-angle formalism for the one-dimensional harmonic oscillator
actionAngleHarmonic
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class actionAngleHarmonic: """Action-angle formalism for the one-dimensional harmonic oscillator""" def __init__(self, *args, **kwargs): """NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (can be Quantity) ro= distance from vantage point to GC (kp...
stack_v2_sparse_classes_75kplus_train_074765
4,113
permissive
[ { "docstring": "NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (can be Quantity) ro= distance from vantage point to GC (kpc; can be Quantity) vo= circular velocity at ro (km/s; can be Quantity) OUTPUT: instance HISTORY: 2018-04-08 - Written - Bovy (Uoft)", "name":...
4
null
Implement the Python class `actionAngleHarmonic` described below. Class description: Action-angle formalism for the one-dimensional harmonic oscillator Method signatures and docstrings: - def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (c...
Implement the Python class `actionAngleHarmonic` described below. Class description: Action-angle formalism for the one-dimensional harmonic oscillator Method signatures and docstrings: - def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (c...
a46619fd4f5979acfccad23f4d57503033f440c5
<|skeleton|> class actionAngleHarmonic: """Action-angle formalism for the one-dimensional harmonic oscillator""" def __init__(self, *args, **kwargs): """NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (can be Quantity) ro= distance from vantage point to GC (kp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class actionAngleHarmonic: """Action-angle formalism for the one-dimensional harmonic oscillator""" def __init__(self, *args, **kwargs): """NAME: __init__ PURPOSE: initialize an actionAngleHarmonic object INPUT: omega= frequencies (can be Quantity) ro= distance from vantage point to GC (kpc; can be Qua...
the_stack_v2_python_sparse
galpy/actionAngle/actionAngleHarmonic.py
jobovy/galpy
train
182
3663a602587ee67b394b718bef084a8c1d7e667c
[ "tag_seq = Seq(seq_len)\nfor type_, start, end in tag_indexes:\n if len(set(tag_seq[start:end])) > 1:\n if not tag_seq.check_clean(type_, start, end):\n continue\n tag_seq[start] = 'B-%s' % type_\n tag_seq[start + 1:end] = ['I-%s' % type_] * (end - start - 1)\nreturn tag_seq.seq", "tag_...
<|body_start_0|> tag_seq = Seq(seq_len) for type_, start, end in tag_indexes: if len(set(tag_seq[start:end])) > 1: if not tag_seq.check_clean(type_, start, end): continue tag_seq[start] = 'B-%s' % type_ tag_seq[start + 1:end] = ['I-...
BIO标注法标注
BioTagger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BioTagger: """BIO标注法标注""" def ind_to_seq(self, seq_len, tag_indexes): """实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序列""" <|body_0|> def seq_to_ind(self, tag_seq...
stack_v2_sparse_classes_75kplus_train_074766
4,361
no_license
[ { "docstring": "实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序列", "name": "ind_to_seq", "signature": "def ind_to_seq(self, seq_len, tag_indexes)" }, { "docstring": "BIO标注序列转换成索引格式 Args ---...
2
null
Implement the Python class `BioTagger` described below. Class description: BIO标注法标注 Method signatures and docstrings: - def ind_to_seq(self, seq_len, tag_indexes): 实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序...
Implement the Python class `BioTagger` described below. Class description: BIO标注法标注 Method signatures and docstrings: - def ind_to_seq(self, seq_len, tag_indexes): 实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序...
359d0c4e2d0daf0121f06469a853260b1a9a3664
<|skeleton|> class BioTagger: """BIO标注法标注""" def ind_to_seq(self, seq_len, tag_indexes): """实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序列""" <|body_0|> def seq_to_ind(self, tag_seq...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BioTagger: """BIO标注法标注""" def ind_to_seq(self, seq_len, tag_indexes): """实体索引转换成BIO标注序列,若两个实体的索引重叠,只取其一 Args ---- seq_len : int, 原始文档的长度 tag_indexes : iterable, 迭代 (实体类型, 实体起始索引, 实体结束索引)元组 Returns ------- tag_seq : list, bio标注序列""" tag_seq = Seq(seq_len) for type_, start, end in t...
the_stack_v2_python_sparse
ruijin/util/tagger.py
VondaZhu/competitions
train
0
5bb716ba3bb943ac75a9c5b450904e7a88e6c0ea
[ "if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects", "if list_dictionaries is None or list_dictionaries == []:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)", "filename = str(cls.__name__) + '.json'\nwith open(filename, mode='w', encodin...
<|body_start_0|> if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects <|end_body_0|> <|body_start_1|> if list_dictionaries is None or list_dictionaries == []: return '[]' else: return json.du...
The Base class
Base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Base: """The Base class""" def __init__(self, id=None): """A Class constructor to initialize id""" <|body_0|> def to_json_string(list_dictionaries): """Returns the JSON string representation of list_dictionaries""" <|body_1|> def save_to_file(cls, li...
stack_v2_sparse_classes_75kplus_train_074767
2,215
no_license
[ { "docstring": "A Class constructor to initialize id", "name": "__init__", "signature": "def __init__(self, id=None)" }, { "docstring": "Returns the JSON string representation of list_dictionaries", "name": "to_json_string", "signature": "def to_json_string(list_dictionaries)" }, { ...
6
stack_v2_sparse_classes_30k_train_047953
Implement the Python class `Base` described below. Class description: The Base class Method signatures and docstrings: - def __init__(self, id=None): A Class constructor to initialize id - def to_json_string(list_dictionaries): Returns the JSON string representation of list_dictionaries - def save_to_file(cls, list_o...
Implement the Python class `Base` described below. Class description: The Base class Method signatures and docstrings: - def __init__(self, id=None): A Class constructor to initialize id - def to_json_string(list_dictionaries): Returns the JSON string representation of list_dictionaries - def save_to_file(cls, list_o...
7a75860b151e8dd0dcf987d27c13522980cf5ccb
<|skeleton|> class Base: """The Base class""" def __init__(self, id=None): """A Class constructor to initialize id""" <|body_0|> def to_json_string(list_dictionaries): """Returns the JSON string representation of list_dictionaries""" <|body_1|> def save_to_file(cls, li...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Base: """The Base class""" def __init__(self, id=None): """A Class constructor to initialize id""" if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects def to_json_string(list_dictionaries): """Re...
the_stack_v2_python_sparse
0x0C-python-almost_a_circle/models/base.py
thenicopixie/holbertonschool-higher_level_programming
train
0
889fc7ca89e5fdbe0c6f7d02c0d38a4f05c54da4
[ "super(EMB, self).__init__()\nif init_emb is None:\n self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim, padding_idx=0)\nelse:\n self.embedding = nn.Embedding.from_pretrained(init_emb)", "mask = Variable((string_lkup > 0).float()).to(device)\nemb = self.embedding(string_lku...
<|body_start_0|> super(EMB, self).__init__() if init_emb is None: self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim, padding_idx=0) else: self.embedding = nn.Embedding.from_pretrained(init_emb) <|end_body_0|> <|body_start_1|> ma...
EMB
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EMB: def __init__(self, vocab_size, embedding_dim, init_emb=None): """param vocab_size: size of vocabulary param emebeding_dim: embedding dimension""" <|body_0|> def forward(self, string_lkup): """Looks up the embedding for the string lookup integers param string_lku...
stack_v2_sparse_classes_75kplus_train_074768
1,017
no_license
[ { "docstring": "param vocab_size: size of vocabulary param emebeding_dim: embedding dimension", "name": "__init__", "signature": "def __init__(self, vocab_size, embedding_dim, init_emb=None)" }, { "docstring": "Looks up the embedding for the string lookup integers param string_lkup: lookup ints ...
2
null
Implement the Python class `EMB` described below. Class description: Implement the EMB class. Method signatures and docstrings: - def __init__(self, vocab_size, embedding_dim, init_emb=None): param vocab_size: size of vocabulary param emebeding_dim: embedding dimension - def forward(self, string_lkup): Looks up the e...
Implement the Python class `EMB` described below. Class description: Implement the EMB class. Method signatures and docstrings: - def __init__(self, vocab_size, embedding_dim, init_emb=None): param vocab_size: size of vocabulary param emebeding_dim: embedding dimension - def forward(self, string_lkup): Looks up the e...
c0b2f83a7d4c0d5fa5effb7584e0e0acc6f877a0
<|skeleton|> class EMB: def __init__(self, vocab_size, embedding_dim, init_emb=None): """param vocab_size: size of vocabulary param emebeding_dim: embedding dimension""" <|body_0|> def forward(self, string_lkup): """Looks up the embedding for the string lookup integers param string_lku...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EMB: def __init__(self, vocab_size, embedding_dim, init_emb=None): """param vocab_size: size of vocabulary param emebeding_dim: embedding dimension""" super(EMB, self).__init__() if init_emb is None: self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=emb...
the_stack_v2_python_sparse
src/main/base_models/architectures/EMB.py
iesl/institution_hierarchies
train
3
bff7b017dfa54596a7b68196d6fdf2e44896c215
[ "super(PendingSponsorshipLevelListView, self).__init__()\nself.project = None\nself.project_slug = None", "context = super(PendingSponsorshipLevelListView, self).get_context_data(**kwargs)\ncontext['num_sponsorshiplevels'] = self.get_queryset().count()\ncontext['unapproved'] = True\ncontext['project_slug'] = self...
<|body_start_0|> super(PendingSponsorshipLevelListView, self).__init__() self.project = None self.project_slug = None <|end_body_0|> <|body_start_1|> context = super(PendingSponsorshipLevelListView, self).get_context_data(**kwargs) context['num_sponsorshiplevels'] = self.get_que...
List view for pending Sponsor.
PendingSponsorshipLevelListView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PendingSponsorshipLevelListView: """List view for pending Sponsor.""" def __init__(self): """We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the valu...
stack_v2_sparse_classes_75kplus_train_074769
17,162
no_license
[ { "docstring": "We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the values in self.get_context_data.", "name": "__init__", "signature": "def __init__(self)" }, { ...
3
stack_v2_sparse_classes_30k_train_017322
Implement the Python class `PendingSponsorshipLevelListView` described below. Class description: List view for pending Sponsor. Method signatures and docstrings: - def __init__(self): We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the f...
Implement the Python class `PendingSponsorshipLevelListView` described below. Class description: List view for pending Sponsor. Method signatures and docstrings: - def __init__(self): We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the f...
ca489c38fdfde29f75c9c1e7f4b4c55d78d91c79
<|skeleton|> class PendingSponsorshipLevelListView: """List view for pending Sponsor.""" def __init__(self): """We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the valu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PendingSponsorshipLevelListView: """List view for pending Sponsor.""" def __init__(self): """We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the values in self.ge...
the_stack_v2_python_sparse
django_project/changes/views/sponsorship_level.py
gitter-badger/projecta
train
0
3890bc3de624292f2203e9910ed70a1b0e1cdf3b
[ "super().__init__(*args, **kwargs)\nself.set_fields_from_dict(['dst_key', 'src_key', 'how_merge'])\nself.fields['how_merge'].required = False", "form_data = super().clean()\nself.store_fields_in_dict([('dst_key', None), ('src_key', None), ('how_merge', None)])\nif self.workflow.has_data_frame:\n if not form_da...
<|body_start_0|> super().__init__(*args, **kwargs) self.set_fields_from_dict(['dst_key', 'src_key', 'how_merge']) self.fields['how_merge'].required = False <|end_body_0|> <|body_start_1|> form_data = super().clean() self.store_fields_in_dict([('dst_key', None), ('src_key', None)...
Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: Left/Right column + merge method
ScheduleSQLUploadForm
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.1-only", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScheduleSQLUploadForm: """Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: Left/Right column + merge method""" ...
stack_v2_sparse_classes_75kplus_train_074770
2,781
permissive
[ { "docstring": "Initialize all the fields", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Store the fields in the Form Payload", "name": "clean", "signature": "def clean(self) -> Dict" } ]
2
stack_v2_sparse_classes_30k_train_026318
Implement the Python class `ScheduleSQLUploadForm` described below. Class description: Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: ...
Implement the Python class `ScheduleSQLUploadForm` described below. Class description: Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: ...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class ScheduleSQLUploadForm: """Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: Left/Right column + merge method""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScheduleSQLUploadForm: """Form to request info for the SQL scheduled upload Three blocks of information are requested: Block 1: Name, description, start -- frequency -- stop times Block 2: Parameters for the SQL connection Block 3: Parameters for the merge: Left/Right column + merge method""" def __init_...
the_stack_v2_python_sparse
ontask/scheduler/forms/sql.py
abelardopardo/ontask_b
train
43
88c54fa14c81e4d2282030add0daa2df4b68a4a2
[ "minprice1, minprice2, maxprofit1, maxprofit2 = (10 ** 9, 10 ** 9, 0, 0)\nfor price in prices:\n minprice1 = min(price, minprice1)\n maxprofit1 = max(maxprofit1, price - minprice1)\n minprice2 = min(minprice2, price - maxprofit1)\n maxprofit2 = max(maxprofit2, price - minprice2)\nprint(maxprofit1, maxpr...
<|body_start_0|> minprice1, minprice2, maxprofit1, maxprofit2 = (10 ** 9, 10 ** 9, 0, 0) for price in prices: minprice1 = min(price, minprice1) maxprofit1 = max(maxprofit1, price - minprice1) minprice2 = min(minprice2, price - maxprofit1) maxprofit2 = max(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_074771
5,624
no_license
[ { "docstring": "贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。", "name": "maxProfit1", "signature": "def maxProfit1(self, prices: List[int]) -> int...
2
stack_v2_sparse_classes_30k_train_023021
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices: List[int]) -> int: 贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices: List[int]) -> int: 贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本...
51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a
<|skeleton|> class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProfit1(self, prices: List[int]) -> int: """贪心算法, 交易一次和交易两次的区别就在于,第二次买的时候,价格其实考虑用第一次赚的钱取补贴一部分 就是minprice1 是第一次作为买卖的成本,就等于第一次买入的股票价格 maxprofit1 是第一次买卖的收益 而minprice2 作为第二次买卖的成本,此时不代表第二次买入股票的价格,而是第二次买入 股票的价格减去第一次的收益 maxprofit2 则不止是第二次买卖的收益,是两次买卖的总收益。""" minprice1, minprice2, maxp...
the_stack_v2_python_sparse
LeetCode_practice/DynamicProgramming/0123.BestTimeToBuyAndSellStock_3.py
LeBron-Jian/BasicAlgorithmPractice
train
13
9f8db057c635cfd71cca0ba84742042284a69128
[ "if g is None:\n g = get_g(E)\nself.g = g\nself.E = E\nself.n = n", "if not isinstance(words, list):\n words = [words]\nreturn np.mean([_pmb(w, self.E, self.g, self.n) for w in words])" ]
<|body_start_0|> if g is None: g = get_g(E) self.g = g self.E = E self.n = n <|end_body_0|> <|body_start_1|> if not isinstance(words, list): words = [words] return np.mean([_pmb(w, self.E, self.g, self.n) for w in words]) <|end_body_1|>
The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word.
PMN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PMN: """The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word.""" def __init__(self, E, g=None, n=100): """Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Gender direction. n (int): Top `n` neighbours according to ...
stack_v2_sparse_classes_75kplus_train_074772
1,538
permissive
[ { "docstring": "Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Gender direction. n (int): Top `n` neighbours according to the cosine similarity.", "name": "__init__", "signature": "def __init__(self, E, g=None, n=100)" }, { "docstring": "Args: words (str or list[str]): ...
2
stack_v2_sparse_classes_30k_train_054460
Implement the Python class `PMN` described below. Class description: The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word. Method signatures and docstrings: - def __init__(self, E, g=None, n=100): Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Ge...
Implement the Python class `PMN` described below. Class description: The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word. Method signatures and docstrings: - def __init__(self, E, g=None, n=100): Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Ge...
013a540069ef433d579e4ea2e5f21aa2a3f86815
<|skeleton|> class PMN: """The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word.""" def __init__(self, E, g=None, n=100): """Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Gender direction. n (int): Top `n` neighbours according to ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PMN: """The class that computes the Percentage of Male Neighbours (PMN) in the top n neighbours for a word.""" def __init__(self, E, g=None, n=100): """Args: E (WE class object): Word embeddings object. kwargs: g (np.array): Gender direction. n (int): Top `n` neighbours according to the cosine si...
the_stack_v2_python_sparse
fee/metrics/pmn.py
FEE-Fair-Embedding-Engine/FEE
train
12
cf7645321f4a3af446b9a6bb063c5285bf85deb7
[ "self.poll_me = poll_me\nself.relation_metric = 'expression_vector_similarity'\nself.recorded_values = []", "node1, node2 = gfunc_edge.nodes\ntry:\n r_val, p_val = sp_stats.pearsonr(node1.data.expression_vector, node2.data.expression_vector)\n return r_val\nexcept AttributeError as err:\n if \"'Bunch' ob...
<|body_start_0|> self.poll_me = poll_me self.relation_metric = 'expression_vector_similarity' self.recorded_values = [] <|end_body_0|> <|body_start_1|> node1, node2 = gfunc_edge.nodes try: r_val, p_val = sp_stats.pearsonr(node1.data.expression_vector, node2.data.expr...
TODO: doc
ExpressionSimilarity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpressionSimilarity: """TODO: doc""" def __init__(self, poll_me=False): """TODO: doc""" <|body_0|> def _calc_metric(self, gfunc_edge): """Does this metric's specific calculations.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.poll_me = p...
stack_v2_sparse_classes_75kplus_train_074773
10,990
no_license
[ { "docstring": "TODO: doc", "name": "__init__", "signature": "def __init__(self, poll_me=False)" }, { "docstring": "Does this metric's specific calculations.", "name": "_calc_metric", "signature": "def _calc_metric(self, gfunc_edge)" } ]
2
stack_v2_sparse_classes_30k_train_042823
Implement the Python class `ExpressionSimilarity` described below. Class description: TODO: doc Method signatures and docstrings: - def __init__(self, poll_me=False): TODO: doc - def _calc_metric(self, gfunc_edge): Does this metric's specific calculations.
Implement the Python class `ExpressionSimilarity` described below. Class description: TODO: doc Method signatures and docstrings: - def __init__(self, poll_me=False): TODO: doc - def _calc_metric(self, gfunc_edge): Does this metric's specific calculations. <|skeleton|> class ExpressionSimilarity: """TODO: doc"""...
0a6c27d281ddc5e7f74cb67bca99e8258e58e2fa
<|skeleton|> class ExpressionSimilarity: """TODO: doc""" def __init__(self, poll_me=False): """TODO: doc""" <|body_0|> def _calc_metric(self, gfunc_edge): """Does this metric's specific calculations.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExpressionSimilarity: """TODO: doc""" def __init__(self, poll_me=False): """TODO: doc""" self.poll_me = poll_me self.relation_metric = 'expression_vector_similarity' self.recorded_values = [] def _calc_metric(self, gfunc_edge): """Does this metric's specific c...
the_stack_v2_python_sparse
src/gfunc/analysis_classes.py
xguse/gfunc
train
0
bdbb3e95204c2bd3f5ca28ae7fb38a2111782372
[ "self.pers = persistence\nself.logger = logging.getLogger('app')\nself.cfg = cfg", "try:\n self.logger.debug('Password Reset attempt %s', user_id)\n password_reset_token = ''\n nosqldb = self.pers.nosql_db\n db_user_record = nosqldb['users'].find_one({'$or': [{'username': user_id}, {'email': user_id}]...
<|body_start_0|> self.pers = persistence self.logger = logging.getLogger('app') self.cfg = cfg <|end_body_0|> <|body_start_1|> try: self.logger.debug('Password Reset attempt %s', user_id) password_reset_token = '' nosqldb = self.pers.nosql_db ...
Web user authentication database helper
PasswordResetDBHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordResetDBHelper: """Web user authentication database helper""" def __init__(self, persistence, cfg): """Class initialization""" <|body_0|> def create_password_reset_token(self, user_id): """Initiate a password reset with a complex token, multi step""" ...
stack_v2_sparse_classes_75kplus_train_074774
4,820
no_license
[ { "docstring": "Class initialization", "name": "__init__", "signature": "def __init__(self, persistence, cfg)" }, { "docstring": "Initiate a password reset with a complex token, multi step", "name": "create_password_reset_token", "signature": "def create_password_reset_token(self, user_i...
4
stack_v2_sparse_classes_30k_train_038680
Implement the Python class `PasswordResetDBHelper` described below. Class description: Web user authentication database helper Method signatures and docstrings: - def __init__(self, persistence, cfg): Class initialization - def create_password_reset_token(self, user_id): Initiate a password reset with a complex token...
Implement the Python class `PasswordResetDBHelper` described below. Class description: Web user authentication database helper Method signatures and docstrings: - def __init__(self, persistence, cfg): Class initialization - def create_password_reset_token(self, user_id): Initiate a password reset with a complex token...
3c774731b054c38a273371450a451c951d73b726
<|skeleton|> class PasswordResetDBHelper: """Web user authentication database helper""" def __init__(self, persistence, cfg): """Class initialization""" <|body_0|> def create_password_reset_token(self, user_id): """Initiate a password reset with a complex token, multi step""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PasswordResetDBHelper: """Web user authentication database helper""" def __init__(self, persistence, cfg): """Class initialization""" self.pers = persistence self.logger = logging.getLogger('app') self.cfg = cfg def create_password_reset_token(self, user_id): ...
the_stack_v2_python_sparse
genesis/passwordresetdbhelper.py
wbmartin/exodus-app
train
0
58483fd26ded2eef48506baf01f41c8d30f8086e
[ "super().__init__(env_spec)\nself.state_des = state_des\nself.limit_rad = 0.5236\nself.kp_servo = 14.0\nself.Kp, self.Kd = (None, None)\nself.init_param(kp, kd)", "th_x, th_y, x, y, _, _, x_dot, y_dot = obs\nerr = to.tensor([self.state_des[0] - x, self.state_des[1] - y])\nerr_dot = to.tensor([0.0 - x_dot, 0.0 - y...
<|body_start_0|> super().__init__(env_spec) self.state_des = state_des self.limit_rad = 0.5236 self.kp_servo = 14.0 self.Kp, self.Kd = (None, None) self.init_param(kp, kd) <|end_body_0|> <|body_start_1|> th_x, th_y, x, y, _, _, x_dot, y_dot = obs err = to...
PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`.
QBallBalancerPDCtrl
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QBallBalancerPDCtrl: """PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`....
stack_v2_sparse_classes_75kplus_train_074775
25,612
permissive
[ { "docstring": "Constructor :param env_spec: environment specification :param state_des: tensor of desired x and y ball position [m] :param kp: 2x2 tensor of constant controller feedback coefficients for error [V/m] :param kd: 2x2 tensor of constant controller feedback coefficients for error time derivative [Vs...
4
stack_v2_sparse_classes_30k_train_011813
Implement the Python class `QBallBalancerPDCtrl` described below. Class description: PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado...
Implement the Python class `QBallBalancerPDCtrl` described below. Class description: PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado...
a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5
<|skeleton|> class QBallBalancerPDCtrl: """PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QBallBalancerPDCtrl: """PD-controller for the Quanser Ball Balancer. The only but significant difference of this controller to the other PD controller is the clipping of the actions. .. note:: This class's desired state specification deviates from the Pyrado policies which interact with a `Task`.""" def ...
the_stack_v2_python_sparse
Pyrado/pyrado/policies/environment_specific.py
jacarvalho/SimuRLacra
train
0
d8b4ee27096f2cfc4517ccab4ba3bd0d62436d73
[ "if use_filemanager is None:\n super().__init__()\nelse:\n super().__init__(use_filemanager)\nself.prefix = prefix", "for key in data_dict:\n with open(self.get_path(f'{self.prefix}_{key}.npy'), 'wb') as file:\n np.save(file, data_dict[key].values)" ]
<|body_start_0|> if use_filemanager is None: super().__init__() else: super().__init__(use_filemanager) self.prefix = prefix <|end_body_0|> <|body_start_1|> for key in data_dict: with open(self.get_path(f'{self.prefix}_{key}.npy'), 'wb') as file: ...
Callback to save the data as npy file.
NPYCallback
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NPYCallback: """Callback to save the data as npy file.""" def __init__(self, prefix: str, use_filemanager: Optional[bool]=None): """Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefix to use for the stored file. :type prefix: str :param us...
stack_v2_sparse_classes_75kplus_train_074776
1,324
permissive
[ { "docstring": "Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefix to use for the stored file. :type prefix: str :param use_filemanager: Flag to denote if the filemanager of the pipeline should be used. :type use_filemanager: Optional[bool]", "name": "__init__",...
2
stack_v2_sparse_classes_30k_train_017224
Implement the Python class `NPYCallback` described below. Class description: Callback to save the data as npy file. Method signatures and docstrings: - def __init__(self, prefix: str, use_filemanager: Optional[bool]=None): Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefi...
Implement the Python class `NPYCallback` described below. Class description: Callback to save the data as npy file. Method signatures and docstrings: - def __init__(self, prefix: str, use_filemanager: Optional[bool]=None): Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefi...
af956f8b1cedf87366259b6010a9f73e6daf5522
<|skeleton|> class NPYCallback: """Callback to save the data as npy file.""" def __init__(self, prefix: str, use_filemanager: Optional[bool]=None): """Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefix to use for the stored file. :type prefix: str :param us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NPYCallback: """Callback to save the data as npy file.""" def __init__(self, prefix: str, use_filemanager: Optional[bool]=None): """Initialise NPYCallback given a filename and optional use_filemanager flag. :param prefix: Prefix to use for the stored file. :type prefix: str :param use_filemanager...
the_stack_v2_python_sparse
pywatts/callbacks/npy_callback.py
KIT-IAI/pyWATTS
train
47
b815d71043a889250f254485da6d8440a9605ffe
[ "if not os.path.isfile(testbed_file):\n raise ValueError('Testbed file {} does not exist.'.format(testbed_file))\nif testbed_pattern:\n testbed_pattern = re.compile(testbed_pattern)\nwith open(testbed_file, 'r') as f:\n raw_testbeds = yaml.safe_load(f)\ntestbeds = {}\nfor raw_testbed in raw_testbeds:\n ...
<|body_start_0|> if not os.path.isfile(testbed_file): raise ValueError('Testbed file {} does not exist.'.format(testbed_file)) if testbed_pattern: testbed_pattern = re.compile(testbed_pattern) with open(testbed_file, 'r') as f: raw_testbeds = yaml.safe_load(f)...
Data model that represents a testbed object.
TestBed
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBed: """Data model that represents a testbed object.""" def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): """Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter te...
stack_v2_sparse_classes_75kplus_train_074777
3,400
permissive
[ { "docstring": "Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter testbeds. hosts (AnsibleHosts): AnsibleHosts object that contains all hosts in the testbed. Returns: dict: Testbed name to testbed object mapping.", "name":...
2
stack_v2_sparse_classes_30k_train_047823
Implement the Python class `TestBed` described below. Class description: Data model that represents a testbed object. Method signatures and docstrings: - def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbe...
Implement the Python class `TestBed` described below. Class description: Data model that represents a testbed object. Method signatures and docstrings: - def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbe...
a86f0e5b1742d01b8d8a28a537f79bf608955695
<|skeleton|> class TestBed: """Data model that represents a testbed object.""" def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): """Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestBed: """Data model that represents a testbed object.""" def from_file(cls, testbed_file='testbed.yaml', testbed_pattern=None, hosts=None): """Load all testbed objects from YAML file. Args: testbed_file (str): Path to testbed file. testbed_pattern (str): Regex pattern to filter testbeds. hosts...
the_stack_v2_python_sparse
ansible/devutil/testbed.py
ramakristipati/sonic-mgmt
train
2
1d764f5a078cf930a51450c5a552033c67aa3a1d
[ "self.sensorname = 'MTK3339'\nself.valname = 'Location'\nglobal gpsc\ntry:\n gpsc = GpsController.GpsController()\n gpsc.start()\nexcept Exception as e:\n print('Unable to start GpsController')\n print('Exception:', e)\n raise", "global gpsc\nif gpsc.fix.speed > 1.0:\n return (gpsc.fix.latitude,...
<|body_start_0|> self.sensorname = 'MTK3339' self.valname = 'Location' global gpsc try: gpsc = GpsController.GpsController() gpsc.start() except Exception as e: print('Unable to start GpsController') print('Exception:', e) ...
serial_gps
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class serial_gps: def __init__(self, data): """Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the parameters to be used during setup.""" <|body_0|> def getval(self): """Get th...
stack_v2_sparse_classes_75kplus_train_074778
2,032
permissive
[ { "docstring": "Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the parameters to be used during setup.", "name": "__init__", "signature": "def __init__(self, data)" }, { "docstring": "Get the curren...
3
stack_v2_sparse_classes_30k_train_004373
Implement the Python class `serial_gps` described below. Class description: Implement the serial_gps class. Method signatures and docstrings: - def __init__(self, data): Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the...
Implement the Python class `serial_gps` described below. Class description: Implement the serial_gps class. Method signatures and docstrings: - def __init__(self, data): Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the...
1f05ea0200d76bd00e0730132d1f5f6e2888a761
<|skeleton|> class serial_gps: def __init__(self, data): """Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the parameters to be used during setup.""" <|body_0|> def getval(self): """Get th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class serial_gps: def __init__(self, data): """Initialise GPS sensor class. Initialise the serial_gps sensor class using parameters passed in 'data'. Args: self: self. data: A dict containing the parameters to be used during setup.""" self.sensorname = 'MTK3339' self.valname = 'Location' ...
the_stack_v2_python_sparse
sensors/serial_gps.py
haydnw/AirPi
train
31
d20c832b13b8556560575c4ff64d23a29a398626
[ "self.to = to\nself.application_id = application_id\nself.scope = scope\nself.expiration_time_in_minutes = expiration_time_in_minutes\nself.code = code", "if dictionary is None:\n return None\nto = dictionary.get('to')\napplication_id = dictionary.get('applicationId')\nexpiration_time_in_minutes = dictionary.g...
<|body_start_0|> self.to = to self.application_id = application_id self.scope = scope self.expiration_time_in_minutes = expiration_time_in_minutes self.code = code <|end_body_0|> <|body_start_1|> if dictionary is None: return None to = dictionary.get(...
Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained from Bandwidth. scope (string): An optional field to denote what scope or action the 2fa code is ...
TwoFactorVerifyRequestSchema
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoFactorVerifyRequestSchema: """Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained from Bandwidth. scope (string): An option...
stack_v2_sparse_classes_75kplus_train_074779
2,920
permissive
[ { "docstring": "Constructor for the TwoFactorVerifyRequestSchema class", "name": "__init__", "signature": "def __init__(self, to=None, application_id=None, expiration_time_in_minutes=None, code=None, scope=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictio...
2
stack_v2_sparse_classes_30k_val_003015
Implement the Python class `TwoFactorVerifyRequestSchema` described below. Class description: Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained fr...
Implement the Python class `TwoFactorVerifyRequestSchema` described below. Class description: Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained fr...
447df3cc8cb7acaf3361d842630c432a9c31ce6e
<|skeleton|> class TwoFactorVerifyRequestSchema: """Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained from Bandwidth. scope (string): An option...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TwoFactorVerifyRequestSchema: """Implementation of the 'TwoFactorVerifyRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. application_id (string): The application unique ID, obtained from Bandwidth. scope (string): An optional field to d...
the_stack_v2_python_sparse
bandwidth/multifactorauth/models/two_factor_verify_request_schema.py
Bandwidth/python-sdk
train
10
f62546fb6ca079571f40f83fb70b31a843a736e3
[ "user_filename = os.path.realpath(user_filename)\nif not os.path.isfile(user_filename):\n raise FileNotFoundError('file does not exist: {}'.format(user_filename))\nwith open(user_filename) as f:\n data = f.read().strip()\nuser_ops = self._simple_string_match(data)\nreturn user_ops", "processed_user_text = u...
<|body_start_0|> user_filename = os.path.realpath(user_filename) if not os.path.isfile(user_filename): raise FileNotFoundError('file does not exist: {}'.format(user_filename)) with open(user_filename) as f: data = f.read().strip() user_ops = self._simple_string_ma...
A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.
SimpleParser
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "OpenSSL", "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause-Open-MPI", "MIT", "MPL-2.0-no-copyleft-exception", "NTP", "BSD-3-Clause", "GPL-1.0-or-later", "0BSD", "MPL-2.0", "LicenseRef-scancode-f...
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleParser: """A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.""" def parse(self, user_filename): """Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file""" ...
stack_v2_sparse_classes_75kplus_train_074780
2,666
permissive
[ { "docstring": "Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file", "name": "parse", "signature": "def parse(self, user_filename)" }, { "docstring": "Find and return ops in the user code (provided as a string). :param use...
2
stack_v2_sparse_classes_30k_train_040492
Implement the Python class `SimpleParser` described below. Class description: A simple parser that works by string matching: Code uses an op if it is found anywhere in the text. Method signatures and docstrings: - def parse(self, user_filename): Find and return ops in the user file. :param user_filename: filename of ...
Implement the Python class `SimpleParser` described below. Class description: A simple parser that works by string matching: Code uses an op if it is found anywhere in the text. Method signatures and docstrings: - def parse(self, user_filename): Find and return ops in the user file. :param user_filename: filename of ...
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
<|skeleton|> class SimpleParser: """A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.""" def parse(self, user_filename): """Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleParser: """A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.""" def parse(self, user_filename): """Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file""" user_f...
the_stack_v2_python_sparse
mindspore/lite/tools/dataset/cropper/parser.py
mindspore-ai/mindspore
train
4,178
25fde73b55ae5d8b870bc3212ad0613fe0f99a8f
[ "import collections\nm = collections.defaultdict(int)\nfor num in nums:\n m[num] += 1\n if m[num] > 1:\n return num\nreturn -1", "i = 0\nwhile i < len(nums):\n if nums[i] == i:\n i += 1\n continue\n if nums[nums[i]] == nums[i]:\n return nums[i]\n nums[nums[i]], nums[i] =...
<|body_start_0|> import collections m = collections.defaultdict(int) for num in nums: m[num] += 1 if m[num] > 1: return num return -1 <|end_body_0|> <|body_start_1|> i = 0 while i < len(nums): if nums[i] == i: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findRepeatNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findRepeatNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> import collections m = coll...
stack_v2_sparse_classes_75kplus_train_074781
964
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findRepeatNumber", "signature": "def findRepeatNumber(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "findRepeatNumber", "signature": "def findRepeatNumber(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_005167
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int - def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int - def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def f...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def findRepeatNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findRepeatNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findRepeatNumber(self, nums): """:type nums: List[int] :rtype: int""" import collections m = collections.defaultdict(int) for num in nums: m[num] += 1 if m[num] > 1: return num return -1 def findRepeatNumber(sel...
the_stack_v2_python_sparse
剑指 Offer 03. 数组中重复的数字.py
yangyuxiang1996/leetcode
train
0
ae2442c4d6ad0fb664be80d134e8bc7feeee63a7
[ "if decay_time <= datetime.timedelta(0):\n raise ValueError('decay_time must have positive duration')\nself.decay_time = decay_time\nself.decay_factor = decay_factor", "timestamp, x = value\nif now is None:\n now = datetime.datetime.utcnow()\ndelta = now - timestamp\nif delta < datetime.timedelta(seconds=0)...
<|body_start_0|> if decay_time <= datetime.timedelta(0): raise ValueError('decay_time must have positive duration') self.decay_time = decay_time self.decay_factor = decay_factor <|end_body_0|> <|body_start_1|> timestamp, x = value if now is None: now = da...
TimeDecay class. Helps to update counters that require a time decay
TimeDecay
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" <|body_0|> def update_value(self, value, now=None): """Computes the updated value for the given ha...
stack_v2_sparse_classes_75kplus_train_074782
1,847
permissive
[ { "docstring": "decay_time is timedelta", "name": "__init__", "signature": "def __init__(self, decay_time, decay_factor=2.0)" }, { "docstring": "Computes the updated value for the given half-life. Args: value (tuple(datetime.datetime, numeric_type)): tuple with the numeric value we wish to updat...
2
stack_v2_sparse_classes_30k_train_012735
Implement the Python class `TimeDecay` described below. Class description: TimeDecay class. Helps to update counters that require a time decay Method signatures and docstrings: - def __init__(self, decay_time, decay_factor=2.0): decay_time is timedelta - def update_value(self, value, now=None): Computes the updated v...
Implement the Python class `TimeDecay` described below. Class description: TimeDecay class. Helps to update counters that require a time decay Method signatures and docstrings: - def __init__(self, decay_time, decay_factor=2.0): decay_time is timedelta - def update_value(self, value, now=None): Computes the updated v...
70280110ec342a6f6db1c102e96756fcc3c3c01b
<|skeleton|> class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" <|body_0|> def update_value(self, value, now=None): """Computes the updated value for the given ha...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TimeDecay: """TimeDecay class. Helps to update counters that require a time decay""" def __init__(self, decay_time, decay_factor=2.0): """decay_time is timedelta""" if decay_time <= datetime.timedelta(0): raise ValueError('decay_time must have positive duration') self....
the_stack_v2_python_sparse
pylib/util/time_decay.py
room77/py77
train
0
7b0847d9aad677cc871f5d2b890469a2f52ae1c8
[ "logger.debug('cleaned_data %s' % self.cleaned_data)\nif self.files:\n self.key = Keypair(string=self.files['key_file'].read())\n self.cert = GID(string=self.files['cert_file'].read())\n cert_pubkey = self.cert.get_pubkey().get_pubkey_string()\n if cert_pubkey != self.key.get_pubkey_string():\n r...
<|body_start_0|> logger.debug('cleaned_data %s' % self.cleaned_data) if self.files: self.key = Keypair(string=self.files['key_file'].read()) self.cert = GID(string=self.files['cert_file'].read()) cert_pubkey = self.cert.get_pubkey().get_pubkey_string() if ...
Form to upload a certificate and its corresponding key.
UploadCertForm
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadCertForm: """Form to upload a certificate and its corresponding key.""" def clean(self): """Check that the cert file is signed by the key file and is trusted.""" <|body_0|> def save(self, user): """Write the key and cert into files. @param user: the user to...
stack_v2_sparse_classes_75kplus_train_074783
6,630
permissive
[ { "docstring": "Check that the cert file is signed by the key file and is trusted.", "name": "clean", "signature": "def clean(self)" }, { "docstring": "Write the key and cert into files. @param user: the user to save the cert and key for. @type user: C{django.contrib.auth.models.User}", "nam...
2
stack_v2_sparse_classes_30k_train_017927
Implement the Python class `UploadCertForm` described below. Class description: Form to upload a certificate and its corresponding key. Method signatures and docstrings: - def clean(self): Check that the cert file is signed by the key file and is trusted. - def save(self, user): Write the key and cert into files. @pa...
Implement the Python class `UploadCertForm` described below. Class description: Form to upload a certificate and its corresponding key. Method signatures and docstrings: - def clean(self): Check that the cert file is signed by the key file and is trusted. - def save(self, user): Write the key and cert into files. @pa...
059ed2b3308bda2af5e1942dc9967e6573dd6a53
<|skeleton|> class UploadCertForm: """Form to upload a certificate and its corresponding key.""" def clean(self): """Check that the cert file is signed by the key file and is trusted.""" <|body_0|> def save(self, user): """Write the key and cert into files. @param user: the user to...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UploadCertForm: """Form to upload a certificate and its corresponding key.""" def clean(self): """Check that the cert file is signed by the key file and is trusted.""" logger.debug('cleaned_data %s' % self.cleaned_data) if self.files: self.key = Keypair(string=self.fil...
the_stack_v2_python_sparse
expedient/src/python/expedient/clearinghouse/geni/forms.py
dana-i2cat/felix
train
4
70a48bbff8040b7574bf27c5d3a333ad7490989e
[ "exc_infos = []\nfor _ in xrange(num):\n exc_infos.extend(failures_lib.CreateExceptInfo(cls(message), traceback))\nreturn exc_infos", "self.assertTrue(failures_lib.CompoundFailure().HasEmptyList())\nexc_infos = self._CreateExceptInfos(KeyError)\nself.assertFalse(failures_lib.CompoundFailure(exc_infos=exc_infos...
<|body_start_0|> exc_infos = [] for _ in xrange(num): exc_infos.extend(failures_lib.CreateExceptInfo(cls(message), traceback)) return exc_infos <|end_body_0|> <|body_start_1|> self.assertTrue(failures_lib.CompoundFailure().HasEmptyList()) exc_infos = self._CreateExce...
Test the CompoundFailure class.
CompoundFailureTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompoundFailureTest: """Test the CompoundFailure class.""" def _CreateExceptInfos(self, cls, message='', traceback='', num=1): """A helper function to create a list of ExceptInfo objects.""" <|body_0|> def testHasEmptyList(self): """Tests the HasEmptyList method....
stack_v2_sparse_classes_75kplus_train_074784
9,373
permissive
[ { "docstring": "A helper function to create a list of ExceptInfo objects.", "name": "_CreateExceptInfos", "signature": "def _CreateExceptInfos(self, cls, message='', traceback='', num=1)" }, { "docstring": "Tests the HasEmptyList method.", "name": "testHasEmptyList", "signature": "def te...
6
stack_v2_sparse_classes_30k_train_032850
Implement the Python class `CompoundFailureTest` described below. Class description: Test the CompoundFailure class. Method signatures and docstrings: - def _CreateExceptInfos(self, cls, message='', traceback='', num=1): A helper function to create a list of ExceptInfo objects. - def testHasEmptyList(self): Tests the...
Implement the Python class `CompoundFailureTest` described below. Class description: Test the CompoundFailure class. Method signatures and docstrings: - def _CreateExceptInfos(self, cls, message='', traceback='', num=1): A helper function to create a list of ExceptInfo objects. - def testHasEmptyList(self): Tests the...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class CompoundFailureTest: """Test the CompoundFailure class.""" def _CreateExceptInfos(self, cls, message='', traceback='', num=1): """A helper function to create a list of ExceptInfo objects.""" <|body_0|> def testHasEmptyList(self): """Tests the HasEmptyList method....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CompoundFailureTest: """Test the CompoundFailure class.""" def _CreateExceptInfos(self, cls, message='', traceback='', num=1): """A helper function to create a list of ExceptInfo objects.""" exc_infos = [] for _ in xrange(num): exc_infos.extend(failures_lib.CreateExcep...
the_stack_v2_python_sparse
third_party/chromite/cbuildbot/failures_lib_unittest.py
metux/chromium-suckless
train
5
2a86d0d7dec4148d31106296884a90efc5efcffd
[ "super().__init__(type='slowdown')\nself.img = pygame.image.load(f'images/{image}.png')\nself.size = size if size else self.img.get_size()\nself.pos = pos.copy()\nself.drawn = False\nself.timer = -10000\nself.clock = Clock()", "if not self.drawn:\n control.window.blit(self.img, self.pos)\n self.drawn = True...
<|body_start_0|> super().__init__(type='slowdown') self.img = pygame.image.load(f'images/{image}.png') self.size = size if size else self.img.get_size() self.pos = pos.copy() self.drawn = False self.timer = -10000 self.clock = Clock() <|end_body_0|> <|body_start_...
Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки
Slowdown
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Slowdown: """Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки""" def __init__(self, image='slowdown', pos=[0, 0], size=None): """Конструктор""" <|body_0|...
stack_v2_sparse_classes_75kplus_train_074785
1,743
no_license
[ { "docstring": "Конструктор", "name": "__init__", "signature": "def __init__(self, image='slowdown', pos=[0, 0], size=None)" }, { "docstring": "Отрисовка и обратный отсчет", "name": "__call__", "signature": "def __call__(self, control)" }, { "docstring": "Удаление со сцены", ...
3
stack_v2_sparse_classes_30k_train_024920
Implement the Python class `Slowdown` described below. Class description: Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки Method signatures and docstrings: - def __init__(self, image='slowdown',...
Implement the Python class `Slowdown` described below. Class description: Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки Method signatures and docstrings: - def __init__(self, image='slowdown',...
65d7aac64bcffec90f4d2976c9d8f67a9b21e41c
<|skeleton|> class Slowdown: """Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки""" def __init__(self, image='slowdown', pos=[0, 0], size=None): """Конструктор""" <|body_0|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Slowdown: """Класс для объектов типа "замедлялка" Конструктор slowdown : str - название изобращения для объекта pos : List[2] - позиция на сцене size : Tuple[2]|None - размер текстурки""" def __init__(self, image='slowdown', pos=[0, 0], size=None): """Конструктор""" super().__init__(type=...
the_stack_v2_python_sparse
slowdown.py
asakhar/snake_programing_game
train
0
35ddd38d6826e00069c13ed51297f8659f19ee58
[ "primary_controller = self.env.primary_controller\nprimary_node = devops_env.get_node_by_fuel_node(primary_controller)\nself.env.warm_shutdown_nodes([primary_node])\nname = 'Test_{}'.format(suffix[:6])\ncmd = 'image-create --name {name} --container-format bare --disk-format qcow2 --file {file}'.format(name=name, fi...
<|body_start_0|> primary_controller = self.env.primary_controller primary_node = devops_env.get_node_by_fuel_node(primary_controller) self.env.warm_shutdown_nodes([primary_node]) name = 'Test_{}'.format(suffix[:6]) cmd = 'image-create --name {name} --container-format bare --disk-...
TestGlanceHA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGlanceHA: def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): """Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image...
stack_v2_sparse_classes_75kplus_train_074786
7,990
no_license
[ { "docstring": "Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image status is `active` 4. Delete created image 5. Check that image deleted", "name": "test_shutdown_primary_controller",...
3
stack_v2_sparse_classes_30k_train_028705
Implement the Python class `TestGlanceHA` described below. Class description: Implement the TestGlanceHA class. Method signatures and docstrings: - def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): Check creating image after shutdown primary controller Steps: 1. Shutdown ...
Implement the Python class `TestGlanceHA` described below. Class description: Implement the TestGlanceHA class. Method signatures and docstrings: - def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): Check creating image after shutdown primary controller Steps: 1. Shutdown ...
8aced2855b78b5f123195d188c80e27b43888a2e
<|skeleton|> class TestGlanceHA: def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): """Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestGlanceHA: def test_shutdown_primary_controller(self, glance, image_file, suffix, devops_env, timeout=60): """Check creating image after shutdown primary controller Steps: 1. Shutdown primary controller 2. Create image from `image_file` 3. Check that image is present in list and image status is `ac...
the_stack_v2_python_sparse
mos_tests/glance/ha_test.py
Mirantis/mos-integration-tests
train
16
d631e55c0a9370ff246000dc6c4859c985c9b2d3
[ "self.model = model\nself.epsilon = epsilon\nself.k = k\nself.a = a\nself.rand = random_start\nif loss_func == 'xent':\n loss = model.xent\nelif loss_func == 'cw':\n label_mask = tf.one_hot(model.y_input, 2, on_value=1.0, off_value=0.0, dtype=tf.float32)\n correct_logit = tf.reduce_sum(label_mask * model.p...
<|body_start_0|> self.model = model self.epsilon = epsilon self.k = k self.a = a self.rand = random_start if loss_func == 'xent': loss = model.xent elif loss_func == 'cw': label_mask = tf.one_hot(model.y_input, 2, on_value=1.0, off_value=0....
LinfPGDAttack
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinfPGDAttack: def __init__(self, model, epsilon, k, a, random_start, loss_func): """Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point.""" <|body_0|> def perturb(self, x_nat, reference, y, sess)...
stack_v2_sparse_classes_75kplus_train_074787
8,800
no_license
[ { "docstring": "Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point.", "name": "__init__", "signature": "def __init__(self, model, epsilon, k, a, random_start, loss_func)" }, { "docstring": "Given a set of examples (x...
2
stack_v2_sparse_classes_30k_train_046179
Implement the Python class `LinfPGDAttack` described below. Class description: Implement the LinfPGDAttack class. Method signatures and docstrings: - def __init__(self, model, epsilon, k, a, random_start, loss_func): Attack parameter initialization. The attack performs k steps of size a, while always staying within e...
Implement the Python class `LinfPGDAttack` described below. Class description: Implement the LinfPGDAttack class. Method signatures and docstrings: - def __init__(self, model, epsilon, k, a, random_start, loss_func): Attack parameter initialization. The attack performs k steps of size a, while always staying within e...
56bcace33b5369be2f9c0d6cae790e3dc2981a7a
<|skeleton|> class LinfPGDAttack: def __init__(self, model, epsilon, k, a, random_start, loss_func): """Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point.""" <|body_0|> def perturb(self, x_nat, reference, y, sess)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinfPGDAttack: def __init__(self, model, epsilon, k, a, random_start, loss_func): """Attack parameter initialization. The attack performs k steps of size a, while always staying within epsilon from the initial point.""" self.model = model self.epsilon = epsilon self.k = k ...
the_stack_v2_python_sparse
adv_generate/facenet+resgn_pgd_attack.py
Liu-1120/adv-alleviation-for-face
train
0
bca6a453a41ba655dafcabc99bc1a5d9f2101500
[ "self.logger = logging.getLogger(__name__)\nself.enabled = enabled\nself.rank = rank\nself.profiler_output_tmp_dir = None\nself.profiler = None", "if self.enabled:\n self.profiler_output_tmp_dir = tempfile.TemporaryDirectory()\n self.logger.info(f'Starting profiler (enabled=True) with tmp dir {self.profiler...
<|body_start_0|> self.logger = logging.getLogger(__name__) self.enabled = enabled self.rank = rank self.profiler_output_tmp_dir = None self.profiler = None <|end_body_0|> <|body_start_1|> if self.enabled: self.profiler_output_tmp_dir = tempfile.TemporaryDirec...
This class handles the initialization and setup of PyTorch profiler
PyTorchProfilerHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow arti...
stack_v2_sparse_classes_75kplus_train_074788
6,804
permissive
[ { "docstring": "Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow artifacts rank (int): rank of the current process/node", "name": "__init__", "signature": "def __init__(self, enabled=False, rank=None)" }, { "docs...
3
stack_v2_sparse_classes_30k_train_030162
Implement the Python class `PyTorchProfilerHandler` described below. Class description: This class handles the initialization and setup of PyTorch profiler Method signatures and docstrings: - def __init__(self, enabled=False, rank=None): Constructor. Args: enabled (bool): is profiling enabled? export_format (str): ge...
Implement the Python class `PyTorchProfilerHandler` described below. Class description: This class handles the initialization and setup of PyTorch profiler Method signatures and docstrings: - def __init__(self, enabled=False, rank=None): Constructor. Args: enabled (bool): is profiling enabled? export_format (str): ge...
e5f7b247d4753f115a8f7da30cbe25294f71f9d7
<|skeleton|> class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow arti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow artifacts rank (i...
the_stack_v2_python_sparse
tutorials/e2e-distributed-pytorch-image/src/pytorch_dl_train/profiling.py
Azure/azureml-examples
train
1,219
70b686f43718901a121eca64e4f7e12b969d0a32
[ "super(GeneratorSimple, self).__init__()\nwith self.init_scope():\n self.e = L.Convolution2D(1025, chs, (4, 1), stride=(4, 1))\n self.c11 = L.Convolution2D(chs, chs, (5, 1))\n self.c12 = L.Convolution2D(chs, chs, (5, 1))\n self.c21 = L.Convolution2D(chs, chs, (5, 1))\n self.c22 = L.Convolution2D(chs,...
<|body_start_0|> super(GeneratorSimple, self).__init__() with self.init_scope(): self.e = L.Convolution2D(1025, chs, (4, 1), stride=(4, 1)) self.c11 = L.Convolution2D(chs, chs, (5, 1)) self.c12 = L.Convolution2D(chs, chs, (5, 1)) self.c21 = L.Convolution2D...
実行用生成側ネットワーク 要 model_convert.py
GeneratorSimple
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeneratorSimple: """実行用生成側ネットワーク 要 model_convert.py""" def __init__(self, chs=256, layers=6): """レイヤー定義""" <|body_0|> def __call__(self, *_x, **kwargs): """実行""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(GeneratorSimple, self).__init__(...
stack_v2_sparse_classes_75kplus_train_074789
7,976
permissive
[ { "docstring": "レイヤー定義", "name": "__init__", "signature": "def __init__(self, chs=256, layers=6)" }, { "docstring": "実行", "name": "__call__", "signature": "def __call__(self, *_x, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_037512
Implement the Python class `GeneratorSimple` described below. Class description: 実行用生成側ネットワーク 要 model_convert.py Method signatures and docstrings: - def __init__(self, chs=256, layers=6): レイヤー定義 - def __call__(self, *_x, **kwargs): 実行
Implement the Python class `GeneratorSimple` described below. Class description: 実行用生成側ネットワーク 要 model_convert.py Method signatures and docstrings: - def __init__(self, chs=256, layers=6): レイヤー定義 - def __call__(self, *_x, **kwargs): 実行 <|skeleton|> class GeneratorSimple: """実行用生成側ネットワーク 要 model_convert.py""" ...
44a1c38c71f67ce32cf64b152c4a87841e819b04
<|skeleton|> class GeneratorSimple: """実行用生成側ネットワーク 要 model_convert.py""" def __init__(self, chs=256, layers=6): """レイヤー定義""" <|body_0|> def __call__(self, *_x, **kwargs): """実行""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GeneratorSimple: """実行用生成側ネットワーク 要 model_convert.py""" def __init__(self, chs=256, layers=6): """レイヤー定義""" super(GeneratorSimple, self).__init__() with self.init_scope(): self.e = L.Convolution2D(1025, chs, (4, 1), stride=(4, 1)) self.c11 = L.Convolution2D(...
the_stack_v2_python_sparse
vrc_project/model.py
toda-necgene/VRC_Project
train
7
4fe98f440cabf06dc0ab60347c1012405a39c6b6
[ "self.offset = offset\nself.length = length\nself.current_byte = current_byte\nself.time = time\nself.source_url = source_url\nself.destination_url = destination_url\nself.component_number = component_number\nself.total_components = total_components\nself.operation_name = operation_name\nself.process_id = process_i...
<|body_start_0|> self.offset = offset self.length = length self.current_byte = current_byte self.time = time self.source_url = source_url self.destination_url = destination_url self.component_number = component_number self.total_components = total_componen...
Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to start operation at. length (int): Total size of file or component in bytes. current_byte (i...
DetailedProgressMessage
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DetailedProgressMessage: """Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to start operation at. length (int): Total ...
stack_v2_sparse_classes_75kplus_train_074790
5,325
permissive
[ { "docstring": "Initializes a ProgressMessage. See attributes docstring for arguments.", "name": "__init__", "signature": "def __init__(self, offset, length, current_byte, time, source_url, destination_url=None, component_number=None, total_components=None, operation_name=None, process_id=None, thread_i...
2
null
Implement the Python class `DetailedProgressMessage` described below. Class description: Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to s...
Implement the Python class `DetailedProgressMessage` described below. Class description: Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to s...
060174026ac068b6442b6c58bedf5adc7bc549cb
<|skeleton|> class DetailedProgressMessage: """Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to start operation at. length (int): Total ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DetailedProgressMessage: """Message class for sending information about operation progress. This class contains specific information on the progress of operating on a file, cloud object, or single component. Attributes: offset (int): Start of byte range to start operation at. length (int): Total size of file ...
the_stack_v2_python_sparse
google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/thread_messages.py
salewski/google-cloud-sdk
train
0
a15f63dd362349fca5197bf65413ea649ea3f6d0
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Quota()", "from .storage_plan_information import StoragePlanInformation\nfrom .storage_plan_information import StoragePlanInformation\nfields: Dict[str, Callable[[Any], None]] = {'deleted': lambda n: setattr(self, 'deleted', n.get_int_...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Quota() <|end_body_0|> <|body_start_1|> from .storage_plan_information import StoragePlanInformation from .storage_plan_information import StoragePlanInformation fields: Dict[str...
Quota
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Quota: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: """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: Quota""" ...
stack_v2_sparse_classes_75kplus_train_074791
3,964
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: Quota", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(parse_n...
3
stack_v2_sparse_classes_30k_train_006428
Implement the Python class `Quota` described below. Class description: Implement the Quota class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
Implement the Python class `Quota` described below. Class description: Implement the Quota class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Quota: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: """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: Quota""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Quota: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Quota: """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: Quota""" if not pars...
the_stack_v2_python_sparse
msgraph/generated/models/quota.py
microsoftgraph/msgraph-sdk-python
train
135
84a1bd59e1807c056aab45edb2c5d1af868b4cfb
[ "super(ResNet18, self).__init__()\nself.conv1 = nn.Sequential(nn.Conv2d(3, 16, kernel_size=3, stride=3, padding=1), nn.BatchNorm2d(16))\nself.blk1 = ResBlk(16, 32, stride=3)\nself.blk2 = ResBlk(32, 64, stride=3)\nself.blk3 = ResBlk(64, 128, stride=2)\nself.blk4 = ResBlk(128, 256, stride=2)\nself.outlayer = nn.Linea...
<|body_start_0|> super(ResNet18, self).__init__() self.conv1 = nn.Sequential(nn.Conv2d(3, 16, kernel_size=3, stride=3, padding=1), nn.BatchNorm2d(16)) self.blk1 = ResBlk(16, 32, stride=3) self.blk2 = ResBlk(32, 64, stride=3) self.blk3 = ResBlk(64, 128, stride=2) self.blk4...
ResNet18
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNet18: def __init__(self, num_class): """:param num_class: :return:""" <|body_0|> def forward(self, x): """:param x: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(ResNet18, self).__init__() self.conv1 = nn.Sequential(nn.C...
stack_v2_sparse_classes_75kplus_train_074792
3,064
no_license
[ { "docstring": ":param num_class: :return:", "name": "__init__", "signature": "def __init__(self, num_class)" }, { "docstring": ":param x: :return:", "name": "forward", "signature": "def forward(self, x)" } ]
2
null
Implement the Python class `ResNet18` described below. Class description: Implement the ResNet18 class. Method signatures and docstrings: - def __init__(self, num_class): :param num_class: :return: - def forward(self, x): :param x: :return:
Implement the Python class `ResNet18` described below. Class description: Implement the ResNet18 class. Method signatures and docstrings: - def __init__(self, num_class): :param num_class: :return: - def forward(self, x): :param x: :return: <|skeleton|> class ResNet18: def __init__(self, num_class): """...
fd491aaee87ae98c617a5530c27073ed650d25e6
<|skeleton|> class ResNet18: def __init__(self, num_class): """:param num_class: :return:""" <|body_0|> def forward(self, x): """:param x: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResNet18: def __init__(self, num_class): """:param num_class: :return:""" super(ResNet18, self).__init__() self.conv1 = nn.Sequential(nn.Conv2d(3, 16, kernel_size=3, stride=3, padding=1), nn.BatchNorm2d(16)) self.blk1 = ResBlk(16, 32, stride=3) self.blk2 = ResBlk(32, 64...
the_stack_v2_python_sparse
resnet.py
RichardoMrMu/image_classification
train
1
a6ba793399f04b64d1ffd43253d331710e82fcf6
[ "self.lambtha = lambtha\nself.π = 3.1415926536\nself.e = 2.7182818285\nλ = float(lambtha)\nif data is None:\n if λ <= 0:\n raise ValueError('lambtha must be a positive value')\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n elif len(data) < 2:\n raise Val...
<|body_start_0|> self.lambtha = lambtha self.π = 3.1415926536 self.e = 2.7182818285 λ = float(lambtha) if data is None: if λ <= 0: raise ValueError('lambtha must be a positive value') else: if type(data) is not list: ...
Class
Poisson
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poisson: """Class""" def __init__(self, data=None, lambtha=1.0): """Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Returns: λ""" <|body_0|> def erf(self, x): ...
stack_v2_sparse_classes_75kplus_train_074793
2,722
no_license
[ { "docstring": "Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Returns: λ", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "is the \"error fu...
5
stack_v2_sparse_classes_30k_train_001061
Implement the Python class `Poisson` described below. Class description: Class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Return...
Implement the Python class `Poisson` described below. Class description: Class Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Return...
eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9
<|skeleton|> class Poisson: """Class""" def __init__(self, data=None, lambtha=1.0): """Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Returns: λ""" <|body_0|> def erf(self, x): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Poisson: """Class""" def __init__(self, data=None, lambtha=1.0): """Initialize Poisson Args: - data (lst): List of the data to be used to estimate the dist - lambtha (int): Expected number of events in a given time frame Returns: λ""" self.lambtha = lambtha self.π = 3.1415926536 ...
the_stack_v2_python_sparse
math/0x03-probability/poisson.py
rodrigocruz13/holbertonschool-machine_learning
train
4
3b3261318f99b609e8cb300d7c6a0d8414d7805b
[ "super().__init__(parent, **kwargs)\nself.active = False\nself.bind('<Button-1>', self.toggle)", "if active is not None:\n self.active = active\nelse:\n self.active = not self.active\nbg = BUTTON_ACTIVE_BG if self.active else BUTTON_ACTIVE_FG\nfg = BUTTON_ACTIVE_FG if self.active else BUTTON_ACTIVE_BG\nself...
<|body_start_0|> super().__init__(parent, **kwargs) self.active = False self.bind('<Button-1>', self.toggle) <|end_body_0|> <|body_start_1|> if active is not None: self.active = active else: self.active = not self.active bg = BUTTON_ACTIVE_BG if s...
ToggleButton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToggleButton: def __init__(self, parent, **kwargs): """Special button to change modes and stay in one state.""" <|body_0|> def toggle(self, event=None, active=None): """Call with no args to toggle or True/False to set button state.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_75kplus_train_074794
18,668
no_license
[ { "docstring": "Special button to change modes and stay in one state.", "name": "__init__", "signature": "def __init__(self, parent, **kwargs)" }, { "docstring": "Call with no args to toggle or True/False to set button state.", "name": "toggle", "signature": "def toggle(self, event=None,...
2
stack_v2_sparse_classes_30k_train_035976
Implement the Python class `ToggleButton` described below. Class description: Implement the ToggleButton class. Method signatures and docstrings: - def __init__(self, parent, **kwargs): Special button to change modes and stay in one state. - def toggle(self, event=None, active=None): Call with no args to toggle or Tr...
Implement the Python class `ToggleButton` described below. Class description: Implement the ToggleButton class. Method signatures and docstrings: - def __init__(self, parent, **kwargs): Special button to change modes and stay in one state. - def toggle(self, event=None, active=None): Call with no args to toggle or Tr...
04df21fce6a8ec3e72530726f85bc88c6f80674a
<|skeleton|> class ToggleButton: def __init__(self, parent, **kwargs): """Special button to change modes and stay in one state.""" <|body_0|> def toggle(self, event=None, active=None): """Call with no args to toggle or True/False to set button state.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ToggleButton: def __init__(self, parent, **kwargs): """Special button to change modes and stay in one state.""" super().__init__(parent, **kwargs) self.active = False self.bind('<Button-1>', self.toggle) def toggle(self, event=None, active=None): """Call with no ar...
the_stack_v2_python_sparse
drawtools/view.py
jeffriesd/dsDraw-python
train
0
c4e747d728a5317e3f5d232b080730bbc6c6c114
[ "dp = [[0] * (n + 1) for _ in range(n + 1)]\nfor i in range(n, 0, -1):\n for j in range(i + 1, n + 1):\n dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j)))\nreturn dp[1][n]", "def search(left, right):\n if left >= right:\n return 0\n if dp[left][right]:\n retu...
<|body_start_0|> dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n, 0, -1): for j in range(i + 1, n + 1): dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j))) return dp[1][n] <|end_body_0|> <|body_start_1|> def search(left, rig...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount_recursive(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> dp = [[0] * (n + 1) for _ in range(n + 1)] fo...
stack_v2_sparse_classes_75kplus_train_074795
2,412
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount", "signature": "def getMoneyAmount(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "getMoneyAmount_recursive", "signature": "def getMoneyAmount_recursive(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_051879
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount_recursive(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMoneyAmount(self, n): :type n: int :rtype: int - def getMoneyAmount_recursive(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def getMoneyAmount(self...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" <|body_0|> def getMoneyAmount_recursive(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getMoneyAmount(self, n): """:type n: int :rtype: int""" dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n, 0, -1): for j in range(i + 1, n + 1): dp[i][j] = min((k + max(dp[i][k - 1], dp[k + 1][j]) for k in range(i, j))) return...
the_stack_v2_python_sparse
src/lt_375.py
oxhead/CodingYourWay
train
0
68574acbaa42c2c9b152ca313489707285fff010
[ "self.location = location\nself.region = region\nself.subnet = subnet\nself.vpn = vpn", "if dictionary is None:\n return None\nlocation = dictionary.get('location')\nregion = cohesity_management_sdk.models.entity_proto.EntityProto.from_dictionary(dictionary.get('region')) if dictionary.get('region') else None\...
<|body_start_0|> self.location = location self.region = region self.subnet = subnet self.vpn = vpn <|end_body_0|> <|body_start_1|> if dictionary is None: return None location = dictionary.get('location') region = cohesity_management_sdk.models.entity_...
Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the virtual network. subnet (EntityProto): Subnet in which we will create a private endpoint. vpn (EntityPro...
DataTransferInfo_PrivateNetworkInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataTransferInfo_PrivateNetworkInfo: """Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the virtual network. subnet (EntityProto): Su...
stack_v2_sparse_classes_75kplus_train_074796
2,435
permissive
[ { "docstring": "Constructor for the DataTransferInfo_PrivateNetworkInfo class", "name": "__init__", "signature": "def __init__(self, location=None, region=None, subnet=None, vpn=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A diction...
2
stack_v2_sparse_classes_30k_train_002875
Implement the Python class `DataTransferInfo_PrivateNetworkInfo` described below. Class description: Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the vi...
Implement the Python class `DataTransferInfo_PrivateNetworkInfo` described below. Class description: Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the vi...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class DataTransferInfo_PrivateNetworkInfo: """Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the virtual network. subnet (EntityProto): Su...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataTransferInfo_PrivateNetworkInfo: """Implementation of the 'DataTransferInfo_PrivateNetworkInfo' model. TODO: type description here. Attributes: location (string): Region/location of the virtual network. region (EntityProto): Proto of the region of the virtual network. subnet (EntityProto): Subnet in which...
the_stack_v2_python_sparse
cohesity_management_sdk/models/data_transfer_info_private_network_info.py
cohesity/management-sdk-python
train
24
bf0a30387469fe3617ad31766c28da0c30e6f179
[ "super().__init__(prev_node)\nself.in_dim = prev_node.out_dim\nself.out_dim = self.in_dim\nself.in_var = prev_node.out_var\nself.out_var = Allocation.allocate_var('float', 'x', self.out_dim)\nself.mean = mean", "out_idx_var = IndexedVariable(self.out_var)\nin_idx_var = IndexedVariable(self.in_var)\nsub_node = Sub...
<|body_start_0|> super().__init__(prev_node) self.in_dim = prev_node.out_dim self.out_dim = self.in_dim self.in_var = prev_node.out_var self.out_var = Allocation.allocate_var('float', 'x', self.out_dim) self.mean = mean <|end_body_0|> <|body_start_1|> out_idx_var...
A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean
MeanNode
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MeanNode: """A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean""" def __init__(self, mean, prev_node): """Initialize the node. :param mean: The mean to be subtracted a...
stack_v2_sparse_classes_75kplus_train_074797
20,388
permissive
[ { "docstring": "Initialize the node. :param mean: The mean to be subtracted as scalar. :param prev_node: The previous node.", "name": "__init__", "signature": "def __init__(self, mean, prev_node)" }, { "docstring": "Create the loops required to express this node in ANSI C code without SIMD and r...
2
stack_v2_sparse_classes_30k_train_038696
Implement the Python class `MeanNode` described below. Class description: A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean Method signatures and docstrings: - def __init__(self, mean, prev_node): Init...
Implement the Python class `MeanNode` described below. Class description: A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean Method signatures and docstrings: - def __init__(self, mean, prev_node): Init...
987b0efeb56cd150b3a34b672fd5eba05e6d491f
<|skeleton|> class MeanNode: """A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean""" def __init__(self, mean, prev_node): """Initialize the node. :param mean: The mean to be subtracted a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MeanNode: """A node to subtract the image mean before the CNN is executed. This kind of layer is not available in Keras but useful to do the preprocessing. out_var = in_var - mean""" def __init__(self, mean, prev_node): """Initialize the node. :param mean: The mean to be subtracted as scalar. :pa...
the_stack_v2_python_sparse
nncg/nodes/cnn.py
iml130/nncg
train
34
03dd5e4d617d1587d96287217541a2f14fb6f3f1
[ "account_data = validated_data.pop('account')\naccount = User(**account_data)\naccount.set_password(account.password)\naccount.save()\nuser_profile = UserProfileModel.objects.create(account=account, **validated_data)\nreturn user_profile", "instance.profile_photo = validated_data.get('profile_photo', instance.pro...
<|body_start_0|> account_data = validated_data.pop('account') account = User(**account_data) account.set_password(account.password) account.save() user_profile = UserProfileModel.objects.create(account=account, **validated_data) return user_profile <|end_body_0|> <|body_...
The serializer for the user profile model
UserProfileSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserProfileSerializer: """The serializer for the user profile model""" def create(self, validated_data): """Creates a new user profile from the request's data""" <|body_0|> def update(self, instance, validated_data): """Updates a certain user profile from the req...
stack_v2_sparse_classes_75kplus_train_074798
3,283
permissive
[ { "docstring": "Creates a new user profile from the request's data", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Updates a certain user profile from the request's data", "name": "update", "signature": "def update(self, instance, validated_data)" ...
2
stack_v2_sparse_classes_30k_train_038780
Implement the Python class `UserProfileSerializer` described below. Class description: The serializer for the user profile model Method signatures and docstrings: - def create(self, validated_data): Creates a new user profile from the request's data - def update(self, instance, validated_data): Updates a certain user...
Implement the Python class `UserProfileSerializer` described below. Class description: The serializer for the user profile model Method signatures and docstrings: - def create(self, validated_data): Creates a new user profile from the request's data - def update(self, instance, validated_data): Updates a certain user...
7c361a31c5225c6ad649fcf92e323bdb10cc4c16
<|skeleton|> class UserProfileSerializer: """The serializer for the user profile model""" def create(self, validated_data): """Creates a new user profile from the request's data""" <|body_0|> def update(self, instance, validated_data): """Updates a certain user profile from the req...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserProfileSerializer: """The serializer for the user profile model""" def create(self, validated_data): """Creates a new user profile from the request's data""" account_data = validated_data.pop('account') account = User(**account_data) account.set_password(account.passwo...
the_stack_v2_python_sparse
users/serializers.py
ahmed-alllam/Koshkie-Server
train
0
d9cf2b4323bf234e810412b1ebd20ab94330dea4
[ "super().__init__(group=None, target=None, name='CheckpointWorker')\nself.notify = notify\nself.patterns = patterns", "while True:\n self.notify.wait(timeout=None)\n self.log.debug('got notification, starting work')\n matched_files = CheckpointWorker.get_matched_filenames(self.patterns)\n CheckpointWo...
<|body_start_0|> super().__init__(group=None, target=None, name='CheckpointWorker') self.notify = notify self.patterns = patterns <|end_body_0|> <|body_start_1|> while True: self.notify.wait(timeout=None) self.log.debug('got notification, starting work') ...
Thread to handle saving and staging out checkpoint files.
CheckpointWorker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param...
stack_v2_sparse_classes_75kplus_train_074799
9,748
permissive
[ { "docstring": "Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param patterns: regex file patterns to match :type patterns: List[str]", "name": "__init__", "signature": "def __init__(self, notify: threading.Event, patterns:...
4
stack_v2_sparse_classes_30k_train_047049
Implement the Python class `CheckpointWorker` described below. Class description: Thread to handle saving and staging out checkpoint files. Method signatures and docstrings: - def __init__(self, notify: threading.Event, patterns: List[str]): Constructor :param notify: event to watch for, which will indicate that this...
Implement the Python class `CheckpointWorker` described below. Class description: Thread to handle saving and staging out checkpoint files. Method signatures and docstrings: - def __init__(self, notify: threading.Event, patterns: List[str]): Constructor :param notify: event to watch for, which will indicate that this...
6b7e41d7ebfacca23d853890937e593a248e6a6a
<|skeleton|> class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param patterns: re...
the_stack_v2_python_sparse
packages/pegasus-worker/src/Pegasus/cli/pegasus-checkpoint.py
pegasus-isi/pegasus
train
156