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
0ad1674af08cd5adbeb25bf78a127cefd04d437a
[ "global saccList, fixList\nsaccList = []\nfixList = []\nglobal trialId\nself.waitForSacc = False\nself.saccOnset = None\nself.stimTime = None\ntrialDict['saccLat'] = trialDict['xCoG'] = trialDict['xCoGMask'] = trialDict['yCoG'] = trialDict['yCoGMask'] = trialDict['rtFromStim'] = trialDict['endX'] = trialDict['endXC...
<|body_start_0|> global saccList, fixList saccList = [] fixList = [] global trialId self.waitForSacc = False self.saccOnset = None self.stimTime = None trialDict['saccLat'] = trialDict['xCoG'] = trialDict['xCoGMask'] = trialDict['yCoG'] = trialDict['yCoGMa...
MyReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyReader: def initTrial(self, trialDict): """Initialize a trial: Arguments: trialDict -- a trial dictionary""" <|body_0|> def finishTrial(self, trialDict): """Finalizes the trial. Arguments: trialDict -- a trial dictionary""" <|body_1|> def parseLine(sel...
stack_v2_sparse_classes_75kplus_train_003700
9,558
no_license
[ { "docstring": "Initialize a trial: Arguments: trialDict -- a trial dictionary", "name": "initTrial", "signature": "def initTrial(self, trialDict)" }, { "docstring": "Finalizes the trial. Arguments: trialDict -- a trial dictionary", "name": "finishTrial", "signature": "def finishTrial(se...
4
stack_v2_sparse_classes_30k_train_015731
Implement the Python class `MyReader` described below. Class description: Implement the MyReader class. Method signatures and docstrings: - def initTrial(self, trialDict): Initialize a trial: Arguments: trialDict -- a trial dictionary - def finishTrial(self, trialDict): Finalizes the trial. Arguments: trialDict -- a ...
Implement the Python class `MyReader` described below. Class description: Implement the MyReader class. Method signatures and docstrings: - def initTrial(self, trialDict): Initialize a trial: Arguments: trialDict -- a trial dictionary - def finishTrial(self, trialDict): Finalizes the trial. Arguments: trialDict -- a ...
a114d422756f926c3a1256dc796c8f39d34d8078
<|skeleton|> class MyReader: def initTrial(self, trialDict): """Initialize a trial: Arguments: trialDict -- a trial dictionary""" <|body_0|> def finishTrial(self, trialDict): """Finalizes the trial. Arguments: trialDict -- a trial dictionary""" <|body_1|> def parseLine(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyReader: def initTrial(self, trialDict): """Initialize a trial: Arguments: trialDict -- a trial dictionary""" global saccList, fixList saccList = [] fixList = [] global trialId self.waitForSacc = False self.saccOnset = None self.stimTime = None ...
the_stack_v2_python_sparse
004B/bckp/backup .⁄studies._004/parseAsc.py
lvanderlinden/004
train
0
d061b12a13f2a806e449cd905b398586931d73d6
[ "h = hashlib.sha256()\nwith open(file_path, 'rb') as f:\n for chunk in iter(lambda: f.read(2048 * h.block_size), b''):\n h.update(chunk)\nchecksum = h.hexdigest()\nk = klass(checksum=checksum, corpus_file_id=file_path.name)\nLOGGER.info(k)\nreturn k", "with file_path.open() as f:\n for line in iter(f...
<|body_start_0|> h = hashlib.sha256() with open(file_path, 'rb') as f: for chunk in iter(lambda: f.read(2048 * h.block_size), b''): h.update(chunk) checksum = h.hexdigest() k = klass(checksum=checksum, corpus_file_id=file_path.name) LOGGER.info(k) ...
BaseCorpusFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseCorpusFile: def create(klass, file_path): """Args: file_path(pathlib.Path): File path""" <|body_0|> def _readline(self, file_path): """Args: file_path[pathlib.Path]: File path""" <|body_1|> <|end_skeleton|> <|body_start_0|> h = hashlib.sha256() ...
stack_v2_sparse_classes_75kplus_train_003701
791
no_license
[ { "docstring": "Args: file_path(pathlib.Path): File path", "name": "create", "signature": "def create(klass, file_path)" }, { "docstring": "Args: file_path[pathlib.Path]: File path", "name": "_readline", "signature": "def _readline(self, file_path)" } ]
2
null
Implement the Python class `BaseCorpusFile` described below. Class description: Implement the BaseCorpusFile class. Method signatures and docstrings: - def create(klass, file_path): Args: file_path(pathlib.Path): File path - def _readline(self, file_path): Args: file_path[pathlib.Path]: File path
Implement the Python class `BaseCorpusFile` described below. Class description: Implement the BaseCorpusFile class. Method signatures and docstrings: - def create(klass, file_path): Args: file_path(pathlib.Path): File path - def _readline(self, file_path): Args: file_path[pathlib.Path]: File path <|skeleton|> class ...
2a0c2b6bb42b6244afcca2601f126e7f3c7d1504
<|skeleton|> class BaseCorpusFile: def create(klass, file_path): """Args: file_path(pathlib.Path): File path""" <|body_0|> def _readline(self, file_path): """Args: file_path[pathlib.Path]: File path""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseCorpusFile: def create(klass, file_path): """Args: file_path(pathlib.Path): File path""" h = hashlib.sha256() with open(file_path, 'rb') as f: for chunk in iter(lambda: f.read(2048 * h.block_size), b''): h.update(chunk) checksum = h.hexdigest() ...
the_stack_v2_python_sparse
sanakin-keep/corpus_file/base_corpus_file.py
wbydo/sanascan
train
0
e61ae8eef6835a580c4beed41fb29db68dc72cc5
[ "temp = dict(*args, **kwargs)\nif 'Refs' in temp:\n refs = temp['Refs']\n if not isinstance(refs, DbRefs):\n refs = DbRefs(refs)\nelse:\n refs = DbRefs()\nfor key, val in temp.items():\n if key in KnownDatabases:\n refs[key] = val\n del temp[key]\nDelegator.__init__(self, refs)\nsel...
<|body_start_0|> temp = dict(*args, **kwargs) if 'Refs' in temp: refs = temp['Refs'] if not isinstance(refs, DbRefs): refs = DbRefs(refs) else: refs = DbRefs() for key, val in temp.items(): if key in KnownDatabases: ...
Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs.
Info
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Info: """Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs.""" def __init__(self, *args, **kwargs): """Returns new Info object. Creates DbRefs if necessary.""" <|body_0|> def __getattr__(self, attr): """Checks for attr i...
stack_v2_sparse_classes_75kplus_train_003702
4,625
permissive
[ { "docstring": "Returns new Info object. Creates DbRefs if necessary.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Checks for attr in Refs first.", "name": "__getattr__", "signature": "def __getattr__(self, attr)" }, { "docstring": "...
6
stack_v2_sparse_classes_30k_train_048327
Implement the Python class `Info` described below. Class description: Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Returns new Info object. Creates DbRefs if necessary. - def __getattr__(self, att...
Implement the Python class `Info` described below. Class description: Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Returns new Info object. Creates DbRefs if necessary. - def __getattr__(self, att...
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
<|skeleton|> class Info: """Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs.""" def __init__(self, *args, **kwargs): """Returns new Info object. Creates DbRefs if necessary.""" <|body_0|> def __getattr__(self, attr): """Checks for attr i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Info: """Dictionary that stores attributes for Sequence objects. Delegates to DbRefs for database IDs.""" def __init__(self, *args, **kwargs): """Returns new Info object. Creates DbRefs if necessary.""" temp = dict(*args, **kwargs) if 'Refs' in temp: refs = temp['Refs'...
the_stack_v2_python_sparse
scripts/venv/lib/python2.7/site-packages/cogent/core/info.py
sauloal/cnidaria
train
3
e2f6d390618541d22d65239e8053040e8137885a
[ "email = request.data['email']\nuser = User.objects.get(email=email)\nif user.withdrawal_status:\n return Response(data={'탈퇴 회원'}, status=status.HTTP_400_BAD_REQUEST)\nLENGTH = 8\nstring_pool = string.ascii_letters + string.digits\nauth_num = ''\nfor i in range(LENGTH):\n auth_num += random.choice(string_pool...
<|body_start_0|> email = request.data['email'] user = User.objects.get(email=email) if user.withdrawal_status: return Response(data={'탈퇴 회원'}, status=status.HTTP_400_BAD_REQUEST) LENGTH = 8 string_pool = string.ascii_letters + string.digits auth_num = '' ...
ForgetPWDViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForgetPWDViewSet: def email_auth_num(self, request): """비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송""" <|body_0|> def is_pwd_token(self, request): """토큰값이 유효한 값인지 확인""" <|body_1|> def password_reset(self, request): """USE...
stack_v2_sparse_classes_75kplus_train_003703
30,076
no_license
[ { "docstring": "비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송", "name": "email_auth_num", "signature": "def email_auth_num(self, request)" }, { "docstring": "토큰값이 유효한 값인지 확인", "name": "is_pwd_token", "signature": "def is_pwd_token(self, request)" }, { "docs...
3
stack_v2_sparse_classes_30k_train_046040
Implement the Python class `ForgetPWDViewSet` described below. Class description: Implement the ForgetPWDViewSet class. Method signatures and docstrings: - def email_auth_num(self, request): 비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송 - def is_pwd_token(self, request): 토큰값이 유효한 값인지 확인 - def p...
Implement the Python class `ForgetPWDViewSet` described below. Class description: Implement the ForgetPWDViewSet class. Method signatures and docstrings: - def email_auth_num(self, request): 비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송 - def is_pwd_token(self, request): 토큰값이 유효한 값인지 확인 - def p...
bcc955bddd9941f2bc54f7577c26c1ddc6b36a48
<|skeleton|> class ForgetPWDViewSet: def email_auth_num(self, request): """비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송""" <|body_0|> def is_pwd_token(self, request): """토큰값이 유효한 값인지 확인""" <|body_1|> def password_reset(self, request): """USE...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ForgetPWDViewSet: def email_auth_num(self, request): """비밀번호 변경 토큰 생성 -> 토큰 생성 후 User 테이블 forget_pwd_token에 저장 -> 이메일로 토큰 전송""" email = request.data['email'] user = User.objects.get(email=email) if user.withdrawal_status: return Response(data={'탈퇴 회원'}, status=statu...
the_stack_v2_python_sparse
users/views.py
bgy1060/Daily_Project
train
1
238010d82051af9c51dec23b7d97ce6cc2aa1788
[ "cursor = None\nwhile head:\n node = head.next\n head.next = cursor\n cursor = head\n head = node\nreturn cursor", "if not head:\n return None\nif not head.next:\n return head\nnode = self.reverseList_v2(head.next)\nhead.next.next = head\nhead.next = None\nreturn node" ]
<|body_start_0|> cursor = None while head: node = head.next head.next = cursor cursor = head head = node return cursor <|end_body_0|> <|body_start_1|> if not head: return None if not head.next: return head ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList_v1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList_v2(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> cursor = None while hea...
stack_v2_sparse_classes_75kplus_train_003704
1,081
permissive
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList_v1", "signature": "def reverseList_v1(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList_v2", "signature": "def reverseList_v2(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_016370
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList_v1(self, head): :type head: ListNode :rtype: ListNode - def reverseList_v2(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList_v1(self, head): :type head: ListNode :rtype: ListNode - def reverseList_v2(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: d...
0fd165afa2ec339a6f194bc57f8810e66cd2822b
<|skeleton|> class Solution: def reverseList_v1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList_v2(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList_v1(self, head): """:type head: ListNode :rtype: ListNode""" cursor = None while head: node = head.next head.next = cursor cursor = head head = node return cursor def reverseList_v2(self, head): ...
the_stack_v2_python_sparse
LinkedList/206_ReverseLinkedList.py
wanggalex/leetcode
train
0
a29b6337bae4aa48d4e15ad98a7a6f0d939ca986
[ "if len(payload) == 2 + 4 and payload[:2] == b'\\x00\\x01':\n return socket.inet_ntop(socket.AF_INET, bytes(payload[2:]))\nelif len(payload) == 2 + 16 and payload[:2] == b'\\x00\\x02':\n return socket.inet_ntop(socket.AF_INET6, bytes(payload[2:]))\nraise exception.CodecException('Invalid Address payload')", ...
<|body_start_0|> if len(payload) == 2 + 4 and payload[:2] == b'\x00\x01': return socket.inet_ntop(socket.AF_INET, bytes(payload[2:])) elif len(payload) == 2 + 16 and payload[:2] == b'\x00\x02': return socket.inet_ntop(socket.AF_INET6, bytes(payload[2:])) raise exception.C...
AddressAVP
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddressAVP: def decode_payload(payload): """Decode the payload as IPV4 or IPV6 string""" <|body_0|> def encode_value(value): """Encode the payload given IPV4 or IPV6 string""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(payload) == 2 + 4 and...
stack_v2_sparse_classes_75kplus_train_003705
21,908
permissive
[ { "docstring": "Decode the payload as IPV4 or IPV6 string", "name": "decode_payload", "signature": "def decode_payload(payload)" }, { "docstring": "Encode the payload given IPV4 or IPV6 string", "name": "encode_value", "signature": "def encode_value(value)" } ]
2
stack_v2_sparse_classes_30k_test_001265
Implement the Python class `AddressAVP` described below. Class description: Implement the AddressAVP class. Method signatures and docstrings: - def decode_payload(payload): Decode the payload as IPV4 or IPV6 string - def encode_value(value): Encode the payload given IPV4 or IPV6 string
Implement the Python class `AddressAVP` described below. Class description: Implement the AddressAVP class. Method signatures and docstrings: - def decode_payload(payload): Decode the payload as IPV4 or IPV6 string - def encode_value(value): Encode the payload given IPV4 or IPV6 string <|skeleton|> class AddressAVP:...
0e1d895dfe625681229e181fbc2dbad83e13c5cb
<|skeleton|> class AddressAVP: def decode_payload(payload): """Decode the payload as IPV4 or IPV6 string""" <|body_0|> def encode_value(value): """Encode the payload given IPV4 or IPV6 string""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AddressAVP: def decode_payload(payload): """Decode the payload as IPV4 or IPV6 string""" if len(payload) == 2 + 4 and payload[:2] == b'\x00\x01': return socket.inet_ntop(socket.AF_INET, bytes(payload[2:])) elif len(payload) == 2 + 16 and payload[:2] == b'\x00\x02': ...
the_stack_v2_python_sparse
lte/gateway/python/magma/subscriberdb/protocols/diameter/avp.py
magma/magma
train
1,219
9c3ea8f510a9346e1770aabd724aee8c2932c884
[ "self.comment = get_object_or_404(Comment, pk=kwargs.get('pk'))\nself.userProfile = get_object_or_404(Profile, user=self.request.user)\ntry:\n CommentLike.objects.get(liked_by=self.userProfile, comment_id=self.comment)\nexcept CommentLike.DoesNotExist:\n serializer = self.serializer_class(data={})\n serial...
<|body_start_0|> self.comment = get_object_or_404(Comment, pk=kwargs.get('pk')) self.userProfile = get_object_or_404(Profile, user=self.request.user) try: CommentLike.objects.get(liked_by=self.userProfile, comment_id=self.comment) except CommentLike.DoesNotExist: ...
CommentLikeView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentLikeView: def put(self, *args, **kwargs): """like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if complete else 404 if comment is not found""" <|body_0|> def get(self, *args, **kwargs): "...
stack_v2_sparse_classes_75kplus_train_003706
7,652
permissive
[ { "docstring": "like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if complete else 404 if comment is not found", "name": "put", "signature": "def put(self, *args, **kwargs)" }, { "docstring": "get all likes of a comment Ret...
3
stack_v2_sparse_classes_30k_train_046120
Implement the Python class `CommentLikeView` described below. Class description: Implement the CommentLikeView class. Method signatures and docstrings: - def put(self, *args, **kwargs): like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if comple...
Implement the Python class `CommentLikeView` described below. Class description: Implement the CommentLikeView class. Method signatures and docstrings: - def put(self, *args, **kwargs): like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if comple...
60c830977fa39a7eea9ab978a9ba0c3beb0c4d88
<|skeleton|> class CommentLikeView: def put(self, *args, **kwargs): """like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if complete else 404 if comment is not found""" <|body_0|> def get(self, *args, **kwargs): "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CommentLikeView: def put(self, *args, **kwargs): """like or unlike a specific comment Args: pk[integer]:primary key for a specific comment Returns: success message and 200 ok if complete else 404 if comment is not found""" self.comment = get_object_or_404(Comment, pk=kwargs.get('pk')) ...
the_stack_v2_python_sparse
authors/apps/comments/views.py
andela/Ah-backend-xmen
train
4
ada8ccf58df8e113b632e5dda96b142d18234d1e
[ "self.k = k\nself.nums = nums\nheapq.heapify(self.nums)\nwhile len(self.nums) > k:\n heapq.heappop(self.nums)", "if len(self.nums) < self.k:\n heapq.heappush(self.nums, val)\nelif val > self.nums[0]:\n heapq.heapreplace(self.nums, val)\nreturn self.nums[0]" ]
<|body_start_0|> self.k = k self.nums = nums heapq.heapify(self.nums) while len(self.nums) > k: heapq.heappop(self.nums) <|end_body_0|> <|body_start_1|> if len(self.nums) < self.k: heapq.heappush(self.nums, val) elif val > self.nums[0]: ...
KthLargest1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.k = k self.nums = nums heapq.heapify...
stack_v2_sparse_classes_75kplus_train_003707
1,362
no_license
[ { "docstring": ":type k: int :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, k, nums)" }, { "docstring": ":type val: int :rtype: int", "name": "add", "signature": "def add(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_045183
Implement the Python class `KthLargest1` described below. Class description: Implement the KthLargest1 class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int
Implement the Python class `KthLargest1` described below. Class description: Implement the KthLargest1 class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int <|skeleton|> class KthLargest1: def __init__(self, k,...
d4a33dc28a6d3f99d5179fdb6a83b2ab8c5a0beb
<|skeleton|> class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KthLargest1: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" self.k = k self.nums = nums heapq.heapify(self.nums) while len(self.nums) > k: heapq.heappop(self.nums) def add(self, val): """:type val: int :rtype: int""" ...
the_stack_v2_python_sparse
leetcode/703_kth_largest_num.py
294150302hxq/python_learn
train
0
b9ff1d46ae3c554191dbefca37085bd0d8db7ccd
[ "self.input_directory = Path(input_directory)\nself.output_directory = Path(output_directory)\nself.output_directory.mkdir(parents=True, exist_ok=False)", "dataset_gdf = pd.concat(dataset)\ndataset_gdf['original_file'] = dataset_gdf['original_file'].astype(str)\ndataset_gdf.to_file(str(self.output_directory / f'f...
<|body_start_0|> self.input_directory = Path(input_directory) self.output_directory = Path(output_directory) self.output_directory.mkdir(parents=True, exist_ok=False) <|end_body_0|> <|body_start_1|> dataset_gdf = pd.concat(dataset) dataset_gdf['original_file'] = dataset_gdf['ori...
The GeoDataFrame generator class that turns txt files into geojson.
GeoDataGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeoDataGenerator: """The GeoDataFrame generator class that turns txt files into geojson.""" def __init__(self, input_directory, output_directory): """Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geoj...
stack_v2_sparse_classes_75kplus_train_003708
5,325
no_license
[ { "docstring": "Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geojson files.", "name": "__init__", "signature": "def __init__(self, input_directory, output_directory)" }, { "docstring": "Save a block of images. A...
5
stack_v2_sparse_classes_30k_val_000867
Implement the Python class `GeoDataGenerator` described below. Class description: The GeoDataFrame generator class that turns txt files into geojson. Method signatures and docstrings: - def __init__(self, input_directory, output_directory): Initialize the GeoDataGenerator. Args: input_directory (str): Directory with ...
Implement the Python class `GeoDataGenerator` described below. Class description: The GeoDataFrame generator class that turns txt files into geojson. Method signatures and docstrings: - def __init__(self, input_directory, output_directory): Initialize the GeoDataGenerator. Args: input_directory (str): Directory with ...
1b953d87968dac46ebbc9b1d5c254ea9493ee328
<|skeleton|> class GeoDataGenerator: """The GeoDataFrame generator class that turns txt files into geojson.""" def __init__(self, input_directory, output_directory): """Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geoj...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GeoDataGenerator: """The GeoDataFrame generator class that turns txt files into geojson.""" def __init__(self, input_directory, output_directory): """Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geojson files."""...
the_stack_v2_python_sparse
fmlwright/dataset_builder/GeoDataGenerator.py
rgresia-umd/fml-wright
train
0
595cb31dca5acbe571ac64480c620e916df9724a
[ "self.pick = pick\nif self.pick != 3:\n raise NotImplementedError(\"Haven't implemented pick 4\")\nself.bet_type = bet_type\nself.amount = amount\nself.chosen = chosen", "if self.bet_type == BetType.THREE_WAY_BOX:\n if not self.chosen.has_double():\n raise TypeError('Three way box demands a bet with ...
<|body_start_0|> self.pick = pick if self.pick != 3: raise NotImplementedError("Haven't implemented pick 4") self.bet_type = bet_type self.amount = amount self.chosen = chosen <|end_body_0|> <|body_start_1|> if self.bet_type == BetType.THREE_WAY_BOX: ...
Represents a bet type and an amount. Can only represent a simple bet.
Bet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bet: """Represents a bet type and an amount. Can only represent a simple bet.""" def __init__(self, pick, bet_type, amount, chosen): """:type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits""" <|body_0|> def validate(self): """Is th...
stack_v2_sparse_classes_75kplus_train_003709
9,444
permissive
[ { "docstring": ":type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits", "name": "__init__", "signature": "def __init__(self, pick, bet_type, amount, chosen)" }, { "docstring": "Is this an screwed up bet? :return:", "name": "validate", "signature": "def vali...
3
stack_v2_sparse_classes_30k_val_002415
Implement the Python class `Bet` described below. Class description: Represents a bet type and an amount. Can only represent a simple bet. Method signatures and docstrings: - def __init__(self, pick, bet_type, amount, chosen): :type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits - def ...
Implement the Python class `Bet` described below. Class description: Represents a bet type and an amount. Can only represent a simple bet. Method signatures and docstrings: - def __init__(self, pick, bet_type, amount, chosen): :type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits - def ...
9551cf89c55974ec51eec1daeacad1a5e4c7d8c3
<|skeleton|> class Bet: """Represents a bet type and an amount. Can only represent a simple bet.""" def __init__(self, pick, bet_type, amount, chosen): """:type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits""" <|body_0|> def validate(self): """Is th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Bet: """Represents a bet type and an amount. Can only represent a simple bet.""" def __init__(self, pick, bet_type, amount, chosen): """:type pick: int :type bet_type: BetType :type amount: int|float :type chosen: Digits""" self.pick = pick if self.pick != 3: raise Not...
the_stack_v2_python_sparse
pick_three/ticket.py
matthewdeanmartin/pick_three
train
1
c8d19c19599c89744eb69083827f33e14ea43c10
[ "self._base_path = base_path\nself._tokenizer = tokenization.FullTokenizer(vocab_path)\nwith open(config_path) as f:\n self._conf = json.loads(f.read())\nconfig = modeling.BertConfig(**self._conf)\nself._inputs = tf.placeholder(shape=[None, None], dtype=tf.int32)\nself._mask = tf.placeholder(shape=[None, None], ...
<|body_start_0|> self._base_path = base_path self._tokenizer = tokenization.FullTokenizer(vocab_path) with open(config_path) as f: self._conf = json.loads(f.read()) config = modeling.BertConfig(**self._conf) self._inputs = tf.placeholder(shape=[None, None], dtype=tf.i...
a class for encoding paragraphs
BERT_encoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BERT_encoder: """a class for encoding paragraphs""" def __init__(self, config_path, vocab_path, base_path): """making instance of encoder and bert model""" <|body_0|> def encode(self, batch): """:param batch: a list of sequences to be encoded :return: - a numpy a...
stack_v2_sparse_classes_75kplus_train_003710
4,242
no_license
[ { "docstring": "making instance of encoder and bert model", "name": "__init__", "signature": "def __init__(self, config_path, vocab_path, base_path)" }, { "docstring": ":param batch: a list of sequences to be encoded :return: - a numpy array of shape [batch_size,embedding(768)]", "name": "en...
2
stack_v2_sparse_classes_30k_train_019697
Implement the Python class `BERT_encoder` described below. Class description: a class for encoding paragraphs Method signatures and docstrings: - def __init__(self, config_path, vocab_path, base_path): making instance of encoder and bert model - def encode(self, batch): :param batch: a list of sequences to be encoded...
Implement the Python class `BERT_encoder` described below. Class description: a class for encoding paragraphs Method signatures and docstrings: - def __init__(self, config_path, vocab_path, base_path): making instance of encoder and bert model - def encode(self, batch): :param batch: a list of sequences to be encoded...
612b34e7a8cd3854b96c39065b0136885ecbd10d
<|skeleton|> class BERT_encoder: """a class for encoding paragraphs""" def __init__(self, config_path, vocab_path, base_path): """making instance of encoder and bert model""" <|body_0|> def encode(self, batch): """:param batch: a list of sequences to be encoded :return: - a numpy a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BERT_encoder: """a class for encoding paragraphs""" def __init__(self, config_path, vocab_path, base_path): """making instance of encoder and bert model""" self._base_path = base_path self._tokenizer = tokenization.FullTokenizer(vocab_path) with open(config_path) as f: ...
the_stack_v2_python_sparse
BERT/make_dataset_from_indices.py
ShenakhtPajouh/transposition-simple
train
0
62e58a03fb05165bd94ded54580f64e3d31edae2
[ "def easyEnqueue(queue, num, k):\n if len(queue) == k:\n queue.popleft()\n maxValue, maxIndex = (num, len(queue))\n for index, v in enumerate(queue):\n if v > maxValue:\n maxValue = v\n maxIndex = index\n for index in range(maxIndex):\n ...
<|body_start_0|> def easyEnqueue(queue, num, k): if len(queue) == k: queue.popleft() maxValue, maxIndex = (num, len(queue)) for index, v in enumerate(queue): if v > maxValue: maxValue = v ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """(knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,进行若干次出队,把当前队列的最大值排到队首; - 然后将队首元素与预入队元素比对,如果小于等于将要入队的元素,则出队; - 循环执行上一步骤,直到队列为空或者队首元素大于将要入队的元素; - 最...
stack_v2_sparse_classes_75kplus_train_003711
6,702
no_license
[ { "docstring": "(knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,进行若干次出队,把当前队列的最大值排到队首; - 然后将队首元素与预入队元素比对,如果小于等于将要入队的元素,则出队; - 循环执行上一步骤,直到队列为空或者队首元素大于将要入队的元素; - 最后将要入队的元素入队。 3. 初始时,先用步骤2的方法,入队k-1个元素,从第k个元素开始,每次入队完,队首的元素即...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): (knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSlidingWindow(self, nums, k): (knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,...
19ea28c38762c65318275007932786e648a8b415
<|skeleton|> class Solution: def maxSlidingWindow(self, nums, k): """(knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,进行若干次出队,把当前队列的最大值排到队首; - 然后将队首元素与预入队元素比对,如果小于等于将要入队的元素,则出队; - 循环执行上一步骤,直到队列为空或者队首元素大于将要入队的元素; - 最...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxSlidingWindow(self, nums, k): """(knowledge) 思路: 1. 用一个队列记录当前处于窗口内的值,这个队列有如下性质: - 队列中的元素不会超过窗口大小k; - 保证队头的元素总是队列里面最大的; 2. 每次有数据入队时都执行如下流程: - 判断当前队列长度是否为k,如果是则首先pop一个元素,并依次比对,进行若干次出队,把当前队列的最大值排到队首; - 然后将队首元素与预入队元素比对,如果小于等于将要入队的元素,则出队; - 循环执行上一步骤,直到队列为空或者队首元素大于将要入队的元素; - 最后将要入队的元素入队。 3....
the_stack_v2_python_sparse
chapter3/13_sliding-window-maximum.py
SunnyQjm/algorithm-review
train
2
337b757021637c1ea01c47410999d9f0d4ff125c
[ "from math import e, log\nleft = int(e ** (0.5 * log(val)))\nright = left + 1\nreturn left if right * right > val else right", "if val <= 2:\n return val\nleft, right = (2, val // 2)\nwhile left <= right:\n pivot = left + (right - left) // 2\n res = pivot * pivot\n if res < val:\n left = pivot ...
<|body_start_0|> from math import e, log left = int(e ** (0.5 * log(val))) right = left + 1 return left if right * right > val else right <|end_body_0|> <|body_start_1|> if val <= 2: return val left, right = (2, val // 2) while left <= right: ...
SquareRoot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SquareRoot: def get_square_root_(self, val: int) -> int: """Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return:""" <|body_0|> def get_square_root__(self, val: int) -> int: """Approach: Bin...
stack_v2_sparse_classes_75kplus_train_003712
1,738
no_license
[ { "docstring": "Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return:", "name": "get_square_root_", "signature": "def get_square_root_(self, val: int) -> int" }, { "docstring": "Approach: Binary Search input: val, outpu...
3
stack_v2_sparse_classes_30k_train_011270
Implement the Python class `SquareRoot` described below. Class description: Implement the SquareRoot class. Method signatures and docstrings: - def get_square_root_(self, val: int) -> int: Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return...
Implement the Python class `SquareRoot` described below. Class description: Implement the SquareRoot class. Method signatures and docstrings: - def get_square_root_(self, val: int) -> int: Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class SquareRoot: def get_square_root_(self, val: int) -> int: """Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return:""" <|body_0|> def get_square_root__(self, val: int) -> int: """Approach: Bin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SquareRoot: def get_square_root_(self, val: int) -> int: """Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return:""" from math import e, log left = int(e ** (0.5 * log(val))) right = left + 1 r...
the_stack_v2_python_sparse
math_and_srings/square_root_x.py
Shiv2157k/leet_code
train
1
a8d25053d0ed335df10d853fd0cef4679774bd62
[ "if 'id' not in kwargs and ('name' not in kwargs or 'version' not in kwargs) and ('registered_name' not in kwargs or ('pipeline' not in kwargs and 'pipeline_kwargs' not in kwargs)):\n raise TrainingError('Need to pass at least one of: `id`, `name, version`, `registered_name, pipeline`, `registered_name, pipeline...
<|body_start_0|> if 'id' not in kwargs and ('name' not in kwargs or 'version' not in kwargs) and ('registered_name' not in kwargs or ('pipeline' not in kwargs and 'pipeline_kwargs' not in kwargs)): raise TrainingError('Need to pass at least one of: `id`, `name, version`, `registered_name, pipeline`,...
ModelCreator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelCreator: def determine_filters(cls, strict: bool=False, **kwargs) -> Tuple[Model, Dict[str, Any]]: """stateless method to determine which filters to apply when looking for existing persistable Returns: database class, filter dictionary :param registered_name: Class name registered i...
stack_v2_sparse_classes_75kplus_train_003713
17,135
permissive
[ { "docstring": "stateless method to determine which filters to apply when looking for existing persistable Returns: database class, filter dictionary :param registered_name: Class name registered in SimpleML :param strict: whether to fit objects first before assuming they are identical In theory if all inputs a...
2
stack_v2_sparse_classes_30k_train_030210
Implement the Python class `ModelCreator` described below. Class description: Implement the ModelCreator class. Method signatures and docstrings: - def determine_filters(cls, strict: bool=False, **kwargs) -> Tuple[Model, Dict[str, Any]]: stateless method to determine which filters to apply when looking for existing p...
Implement the Python class `ModelCreator` described below. Class description: Implement the ModelCreator class. Method signatures and docstrings: - def determine_filters(cls, strict: bool=False, **kwargs) -> Tuple[Model, Dict[str, Any]]: stateless method to determine which filters to apply when looking for existing p...
c7cdf1fa90b373025da48aa85bf9f0d3792ce494
<|skeleton|> class ModelCreator: def determine_filters(cls, strict: bool=False, **kwargs) -> Tuple[Model, Dict[str, Any]]: """stateless method to determine which filters to apply when looking for existing persistable Returns: database class, filter dictionary :param registered_name: Class name registered i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ModelCreator: def determine_filters(cls, strict: bool=False, **kwargs) -> Tuple[Model, Dict[str, Any]]: """stateless method to determine which filters to apply when looking for existing persistable Returns: database class, filter dictionary :param registered_name: Class name registered in SimpleML :pa...
the_stack_v2_python_sparse
simpleml/utils/training/create_persistable.py
eyadgaran/SimpleML
train
15
b54dee2d24e8182ed9f7d8475f85b3db7750cdd1
[ "self.catg = syms.getSyntaxTypeIndexNumber(category)\nself.synf = None\nself.semf = None\nself.hpnc = {}\nbrkg = _FS(syms, '[' + sID + sBRK + ']', True)\nzero = ellyBits.EllyBits()\nfor sky in smfs.keys():\n smfs[sky] = _FS(syms, smfs[sky], True)\nfor defn in defns:\n pc = defn[0]\n if len(defn) > 1:\n ...
<|body_start_0|> self.catg = syms.getSyntaxTypeIndexNumber(category) self.synf = None self.semf = None self.hpnc = {} brkg = _FS(syms, '[' + sID + sBRK + ']', True) zero = ellyBits.EllyBits() for sky in smfs.keys(): smfs[sky] = _FS(syms, smfs[sky], Tru...
recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars
PunctuationRecognizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PunctuationRecognizer: """recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars""" def __init__(self, syms): """initialization arguments: self - syms -...
stack_v2_sparse_classes_75kplus_train_003714
7,773
no_license
[ { "docstring": "initialization arguments: self - syms - Elly symbol table exceptions: FormatFailure on error", "name": "__init__", "signature": "def __init__(self, syms)" }, { "docstring": "check whether list of chars corresponds to punctuation arguments: self - s - list or string of chars to ch...
2
stack_v2_sparse_classes_30k_train_027995
Implement the Python class `PunctuationRecognizer` described below. Class description: recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars Method signatures and docstrings: - def __in...
Implement the Python class `PunctuationRecognizer` described below. Class description: recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars Method signatures and docstrings: - def __in...
bb6e4aef283229f1dbf6397112a7f5772d4020e5
<|skeleton|> class PunctuationRecognizer: """recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars""" def __init__(self, syms): """initialization arguments: self - syms -...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PunctuationRecognizer: """recognizer to support parsing attributes: catg - syntactic category for recognized punctuation synf - syntactic features semf - semantic features hpnc - hash lookup for punctuation chars""" def __init__(self, syms): """initialization arguments: self - syms - Elly symbol ...
the_stack_v2_python_sparse
punctuationRecognizer.py
prohippo/pyellytoo
train
0
a37c02a80373a12f9bf9c3db57155b7b974f2f49
[ "super().__init__(name)\nself.model = model\nself.alphabet = alphabet", "one_hots = np.array([s_utils.string_to_one_hot(seq, self.alphabet) for seq in sequences])\nflattened = one_hots.reshape(one_hots.shape[0], one_hots.shape[1] * one_hots.shape[2])\nself.model.fit(flattened, labels)" ]
<|body_start_0|> super().__init__(name) self.model = model self.alphabet = alphabet <|end_body_0|> <|body_start_1|> one_hots = np.array([s_utils.string_to_one_hot(seq, self.alphabet) for seq in sequences]) flattened = one_hots.reshape(one_hots.shape[0], one_hots.shape[1] * one_h...
Base sklearn model wrapper.
SklearnModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" <|body_0|> def train(self, sequences, labels): ...
stack_v2_sparse_classes_75kplus_train_003715
2,860
permissive
[ { "docstring": "Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).", "name": "__init__", "signature": "def __init__(self, model, alphabet, name)" }, { "docstring": "Flatten one-hot sequences and train model using `model.fit...
2
stack_v2_sparse_classes_30k_train_009294
Implement the Python class `SklearnModel` described below. Class description: Base sklearn model wrapper. Method signatures and docstrings: - def __init__(self, model, alphabet, name): Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging). - def tra...
Implement the Python class `SklearnModel` described below. Class description: Base sklearn model wrapper. Method signatures and docstrings: - def __init__(self, model, alphabet, name): Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging). - def tra...
744e792456d93e8c48fc58220689c0b4cff6ded9
<|skeleton|> class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" <|body_0|> def train(self, sequences, labels): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" super().__init__(name) self.model = model self.alpha...
the_stack_v2_python_sparse
flexs/baselines/models/sklearn_models.py
jonshao/FLEXS
train
0
5e9a1244d481fb9db0b1459f04676a1ec401c08b
[ "maximallyOverlapObjects, overlappingAreas = self.findMaximallyOverlapObjects(segm, gold)\ngoldAreas = self.findAreas(gold)\nsegmentedNo = overlappingAreas.shape[0]\ngoldNo = goldAreas.shape[0]\nTP, FP, FN = (0, 0, 0)\nfor i in range(segmentedNo):\n if int(maximallyOverlapObjects[i]) >= 0 and overlappingAreas[i]...
<|body_start_0|> maximallyOverlapObjects, overlappingAreas = self.findMaximallyOverlapObjects(segm, gold) goldAreas = self.findAreas(gold) segmentedNo = overlappingAreas.shape[0] goldNo = goldAreas.shape[0] TP, FP, FN = (0, 0, 0) for i in range(segmentedNo): i...
ObjectBasedMetrics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectBasedMetrics: def calculate4Detection(self, segm, gold): """Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components of annotation Returns: TP (int) : true positives FP (int) : false positives FN (int) : false negatives""" ...
stack_v2_sparse_classes_75kplus_train_003716
44,704
no_license
[ { "docstring": "Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components of annotation Returns: TP (int) : true positives FP (int) : false positives FN (int) : false negatives", "name": "calculate4Detection", "signature": "def calculate4Detectio...
2
null
Implement the Python class `ObjectBasedMetrics` described below. Class description: Implement the ObjectBasedMetrics class. Method signatures and docstrings: - def calculate4Detection(self, segm, gold): Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components...
Implement the Python class `ObjectBasedMetrics` described below. Class description: Implement the ObjectBasedMetrics class. Method signatures and docstrings: - def calculate4Detection(self, segm, gold): Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components...
193fc372d8cd5c9c465996b594ec0993af1d5a2e
<|skeleton|> class ObjectBasedMetrics: def calculate4Detection(self, segm, gold): """Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components of annotation Returns: TP (int) : true positives FP (int) : false positives FN (int) : false negatives""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ObjectBasedMetrics: def calculate4Detection(self, segm, gold): """Args: segm (np.ndarray) : (H,W) connected components of segmentation gold (np.ndarray) : (H,W) connected components of annotation Returns: TP (int) : true positives FP (int) : false positives FN (int) : false negatives""" maxima...
the_stack_v2_python_sparse
src/metrics.py
furkanh/image-segmentation-with-shape-preserving-loss
train
2
058183e67a72dd972209650d1cb57f9176262df5
[ "if target == 0:\n res.append(tem_res)\n return\nif target < candidates[index]:\n return\nfor i in range(index, len(candidates)):\n if target < candidates[i]:\n break\n self.curSum(candidates, i, target - candidates[i], tem_res + [candidates[i]], res)", "res = []\ncandidates.sort()\nself.cur...
<|body_start_0|> if target == 0: res.append(tem_res) return if target < candidates[index]: return for i in range(index, len(candidates)): if target < candidates[i]: break self.curSum(candidates, i, target - candidates[i]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def curSum(self, candidates, index, target, tem_res, res): """:param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果""" <|body_0|> def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: ...
stack_v2_sparse_classes_75kplus_train_003717
1,067
no_license
[ { "docstring": ":param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果", "name": "curSum", "signature": "def curSum(self, candidates, index, target, tem_res, res)" }, { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]] :组合相加", ...
2
stack_v2_sparse_classes_30k_train_003973
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def curSum(self, candidates, index, target, tem_res, res): :param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果 - def combinationSum(self, ca...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def curSum(self, candidates, index, target, tem_res, res): :param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果 - def combinationSum(self, ca...
45fafcc5dd8f3a9dd26984dc6e82441cc2e8f8d7
<|skeleton|> class Solution: def curSum(self, candidates, index, target, tem_res, res): """:param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果""" <|body_0|> def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def curSum(self, candidates, index, target, tem_res, res): """:param candidates: :param target: :param tem_res: 当前的结果 :param res: 全局的结果 :return:当前搜索的结果""" if target == 0: res.append(tem_res) return if target < candidates[index]: return ...
the_stack_v2_python_sparse
T39.py
zhanggyang/leedcode
train
0
66239f0d2abc00f54748886bbc94f68419ad962a
[ "super(FileManager, self).__init__(parent)\nself.parent = parent\nself.ctaEngine = ctaEngine\nself.eventEngine = eventEngine\nself.setFixedWidth(420)\nself.widgetDict = {}\nself.initUi()", "self.setWindowTitle(u'策略管理')\nQtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName('utf-8'))\nhbox = QtGui.QHBoxLa...
<|body_start_0|> super(FileManager, self).__init__(parent) self.parent = parent self.ctaEngine = ctaEngine self.eventEngine = eventEngine self.setFixedWidth(420) self.widgetDict = {} self.initUi() <|end_body_0|> <|body_start_1|> self.setWindowTitle(u'策略管理...
文件管理
FileManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileManager: """文件管理""" def __init__(self, ctaEngine, eventEngine, parent=None): """Constructor""" <|body_0|> def initUi(self): """初始化界面""" <|body_1|> def addStrategy(self, index): """显示策略""" <|body_2|> def add(self, filename): ...
stack_v2_sparse_classes_75kplus_train_003718
27,775
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, ctaEngine, eventEngine, parent=None)" }, { "docstring": "初始化界面", "name": "initUi", "signature": "def initUi(self)" }, { "docstring": "显示策略", "name": "addStrategy", "signature": "def addStra...
5
stack_v2_sparse_classes_30k_train_047875
Implement the Python class `FileManager` described below. Class description: 文件管理 Method signatures and docstrings: - def __init__(self, ctaEngine, eventEngine, parent=None): Constructor - def initUi(self): 初始化界面 - def addStrategy(self, index): 显示策略 - def add(self, filename): 新增回测组合 - def data(self): 加载数据
Implement the Python class `FileManager` described below. Class description: 文件管理 Method signatures and docstrings: - def __init__(self, ctaEngine, eventEngine, parent=None): Constructor - def initUi(self): 初始化界面 - def addStrategy(self, index): 显示策略 - def add(self, filename): 新增回测组合 - def data(self): 加载数据 <|skeleton...
97707a403c3300753d988167beb6759e7ee729dc
<|skeleton|> class FileManager: """文件管理""" def __init__(self, ctaEngine, eventEngine, parent=None): """Constructor""" <|body_0|> def initUi(self): """初始化界面""" <|body_1|> def addStrategy(self, index): """显示策略""" <|body_2|> def add(self, filename): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileManager: """文件管理""" def __init__(self, ctaEngine, eventEngine, parent=None): """Constructor""" super(FileManager, self).__init__(parent) self.parent = parent self.ctaEngine = ctaEngine self.eventEngine = eventEngine self.setFixedWidth(420) self....
the_stack_v2_python_sparse
uiCtaWidget.py
rlcjj/PythonLab
train
1
35a54e0fb129c33ad1aeb5a68fa1648a213625e9
[ "self.id = id\nself.amount = amount\nself.posted_date = posted_date\nself.description = description\nself.normalized_payee = normalized_payee\nself.institution_transaction_id = institution_transaction_id\nself.category = category\nself.memo = memo\nself.additional_properties = additional_properties", "if dictiona...
<|body_start_0|> self.id = id self.amount = amount self.posted_date = posted_date self.description = description self.normalized_payee = normalized_payee self.institution_transaction_id = institution_transaction_id self.category = category self.memo = memo...
Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transactions for deposits are positive values, and withdrawals and d...
TransactionsReportTransaction
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransactionsReportTransaction: """Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transaction...
stack_v2_sparse_classes_75kplus_train_003719
4,376
permissive
[ { "docstring": "Constructor for the TransactionsReportTransaction class", "name": "__init__", "signature": "def __init__(self, id=None, amount=None, posted_date=None, description=None, normalized_payee=None, institution_transaction_id=None, category=None, memo=None, additional_properties={})" }, { ...
2
stack_v2_sparse_classes_30k_train_001376
Implement the Python class `TransactionsReportTransaction` described below. Class description: Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total...
Implement the Python class `TransactionsReportTransaction` described below. Class description: Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class TransactionsReportTransaction: """Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transaction...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TransactionsReportTransaction: """Implementation of the 'Transactions Report Transaction' model. The fields used in the Transactions Report Transactions record Attributes: id (long|int): The Finicity ID of the financial transaction. amount (float): The total amount of the transaction. Transactions for deposit...
the_stack_v2_python_sparse
finicityapi/models/transactions_report_transaction.py
monarchmoney/finicity-python
train
0
55d64fe317bd1244c5f485df7ba11465887ac780
[ "session = None\nsession_store_class = get_session_class()\nif app_settings.COOKIE_NAME in request.COOKIES:\n session = session_store_class(key=request.COOKIES[app_settings.COOKIE_NAME].value, request=request)\nif not session:\n session = session_store_class(request=request)\nrequest.session = session", "re...
<|body_start_0|> session = None session_store_class = get_session_class() if app_settings.COOKIE_NAME in request.COOKIES: session = session_store_class(key=request.COOKIES[app_settings.COOKIE_NAME].value, request=request) if not session: session = session_store_cl...
SessionMiddleware
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionMiddleware: def process_request(self, request): """Creates a session instance for the current user.""" <|body_0|> def process_response(self, request, response): """Sets the session cookie with its key""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_003720
984
no_license
[ { "docstring": "Creates a session instance for the current user.", "name": "process_request", "signature": "def process_request(self, request)" }, { "docstring": "Sets the session cookie with its key", "name": "process_response", "signature": "def process_response(self, request, response...
2
stack_v2_sparse_classes_30k_train_011165
Implement the Python class `SessionMiddleware` described below. Class description: Implement the SessionMiddleware class. Method signatures and docstrings: - def process_request(self, request): Creates a session instance for the current user. - def process_response(self, request, response): Sets the session cookie wi...
Implement the Python class `SessionMiddleware` described below. Class description: Implement the SessionMiddleware class. Method signatures and docstrings: - def process_request(self, request): Creates a session instance for the current user. - def process_response(self, request, response): Sets the session cookie wi...
875ac157b207fee80be6841f9b17c41b7069e15d
<|skeleton|> class SessionMiddleware: def process_request(self, request): """Creates a session instance for the current user.""" <|body_0|> def process_response(self, request, response): """Sets the session cookie with its key""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionMiddleware: def process_request(self, request): """Creates a session instance for the current user.""" session = None session_store_class = get_session_class() if app_settings.COOKIE_NAME in request.COOKIES: session = session_store_class(key=request.COOKIES[a...
the_stack_v2_python_sparse
london/apps/sessions/middleware.py
avelino/votacao_paredao_bbb
train
0
44098b9b12434929a8f5852271bf2b0e1f3be349
[ "prev_u_next = u_next\nwhile True:\n g = self.system.evaluate(t + dt, tslices.TimeSlice(prev_u_next, domain, time=t)).data\n dg, TOL = self.system.implicit_method_jacobian(t + dt, tslices.TimeSlice(prev_u_next, domain, time=t))\n dg = dg.data\n f = prev_u_next - u_start - dt * g\n df = 1.0 - dt * dg\...
<|body_start_0|> prev_u_next = u_next while True: g = self.system.evaluate(t + dt, tslices.TimeSlice(prev_u_next, domain, time=t)).data dg, TOL = self.system.implicit_method_jacobian(t + dt, tslices.TimeSlice(prev_u_next, domain, time=t)) dg = dg.data f = ...
An implementation of the first order implicit Euler method.
ImplicitEuler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImplicitEuler: """An implementation of the first order implicit Euler method.""" def _NR(self, u_start, u_next, t, dt, domain): """A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Parameters ---------- u_start: numpy.ndarray Initial values of t...
stack_v2_sparse_classes_75kplus_train_003721
8,908
no_license
[ { "docstring": "A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Parameters ---------- u_start: numpy.ndarray Initial values of the function. u_next: numpy.ndarray The first guess at the next values of the function. t: float Current time. dt: float Current time step. doma...
2
stack_v2_sparse_classes_30k_train_004558
Implement the Python class `ImplicitEuler` described below. Class description: An implementation of the first order implicit Euler method. Method signatures and docstrings: - def _NR(self, u_start, u_next, t, dt, domain): A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Paramet...
Implement the Python class `ImplicitEuler` described below. Class description: An implementation of the first order implicit Euler method. Method signatures and docstrings: - def _NR(self, u_start, u_next, t, dt, domain): A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Paramet...
2ce16d776448553e2ae5c45f3cf973c8271aefbf
<|skeleton|> class ImplicitEuler: """An implementation of the first order implicit Euler method.""" def _NR(self, u_start, u_next, t, dt, domain): """A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Parameters ---------- u_start: numpy.ndarray Initial values of t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImplicitEuler: """An implementation of the first order implicit Euler method.""" def _NR(self, u_start, u_next, t, dt, domain): """A Newton-Raphson auxilliary routine for the implementation of the implicit Euler scheme. Parameters ---------- u_start: numpy.ndarray Initial values of the function. ...
the_stack_v2_python_sparse
Code/packages/coffee/solvers/solvers.py
mfuphi/SOFTX_2019_93
train
0
162778e4c689076cff8013dabdf418f09fc7ca6e
[ "super(PreprocessImage, self).__init__(env)\nself.img_size = (height, width)\nself.grayscale = grayscale\nself.crop = crop\nn_colors = 1 if self.grayscale else 3\nself.observation_space = Box(0.0, 1.0, [n_colors, height, width])", "img = self.crop(img)\nimg = imresize(img, self.img_size)\nif self.grayscale:\n ...
<|body_start_0|> super(PreprocessImage, self).__init__(env) self.img_size = (height, width) self.grayscale = grayscale self.crop = crop n_colors = 1 if self.grayscale else 3 self.observation_space = Box(0.0, 1.0, [n_colors, height, width]) <|end_body_0|> <|body_start_1|>...
PreprocessImage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreprocessImage: def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img): """A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.""" <|body_0|> def _observation(self, img): """what happens to the obse...
stack_v2_sparse_classes_75kplus_train_003722
1,713
no_license
[ { "docstring": "A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.", "name": "__init__", "signature": "def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img)" }, { "docstring": "what happens to the observation", "name": "_...
2
stack_v2_sparse_classes_30k_train_047198
Implement the Python class `PreprocessImage` described below. Class description: Implement the PreprocessImage class. Method signatures and docstrings: - def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img): A gym wrapper that crops, scales image into the desired shapes and optionally gr...
Implement the Python class `PreprocessImage` described below. Class description: Implement the PreprocessImage class. Method signatures and docstrings: - def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img): A gym wrapper that crops, scales image into the desired shapes and optionally gr...
4c145470dfc7b594d479bf60857b6db5c1505eb7
<|skeleton|> class PreprocessImage: def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img): """A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.""" <|body_0|> def _observation(self, img): """what happens to the obse...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreprocessImage: def __init__(self, env, height=64, width=64, grayscale=True, crop=lambda img: img): """A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.""" super(PreprocessImage, self).__init__(env) self.img_size = (height, width) sel...
the_stack_v2_python_sparse
atari_experiments/src/envs/doom.py
neurips2019submission/Formal-Language-Constraints-for-Markov-Decision-Processes
train
0
e6a56d67a61e25fb70232eddd9d7590453b19e94
[ "assert stride is None and size is None or (stride is not None and size is not None), 'Either both or neither stride and size should be None'\nself.cnn_network_dir = cnn_network_dir\nself.batch_size = batch_size\nself.config = config\nself.compare_labels = compare_labels\nself.stride = stride\nself.size = size\nsup...
<|body_start_0|> assert stride is None and size is None or (stride is not None and size is not None), 'Either both or neither stride and size should be None' self.cnn_network_dir = cnn_network_dir self.batch_size = batch_size self.config = config self.compare_labels = compare_lab...
Train a CNN
ClassifyCNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassifyCNN: """Train a CNN""" def __init__(self, str_description, cnn_network_dir, batch_size=2000, config=None, compare_labels=False, stride=None, size=None): """Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the ...
stack_v2_sparse_classes_75kplus_train_003723
4,216
permissive
[ { "docstring": "Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory where the CNN is stored @param batch_size: Batch size to use when classifying with Tensorflow @param config: Additional session configuration dictionary @param compa...
2
stack_v2_sparse_classes_30k_train_047302
Implement the Python class `ClassifyCNN` described below. Class description: Train a CNN Method signatures and docstrings: - def __init__(self, str_description, cnn_network_dir, batch_size=2000, config=None, compare_labels=False, stride=None, size=None): Initialize TrainCNN item @param str_description: String describ...
Implement the Python class `ClassifyCNN` described below. Class description: Train a CNN Method signatures and docstrings: - def __init__(self, str_description, cnn_network_dir, batch_size=2000, config=None, compare_labels=False, stride=None, size=None): Initialize TrainCNN item @param str_description: String describ...
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
<|skeleton|> class ClassifyCNN: """Train a CNN""" def __init__(self, str_description, cnn_network_dir, batch_size=2000, config=None, compare_labels=False, stride=None, size=None): """Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ClassifyCNN: """Train a CNN""" def __init__(self, str_description, cnn_network_dir, batch_size=2000, config=None, compare_labels=False, stride=None, size=None): """Initialize TrainCNN item @param str_description: String describing item @param cnn_network_dir: Strining containing the directiory wh...
the_stack_v2_python_sparse
pyinsar/processing/discovery/classify_cnn.py
MITeaps/pyinsar
train
11
7039c828a334b8c8837ad6c9ff0d89af7173df4f
[ "if not strs:\n return ''\nif len(strs) == 1:\n return strs[0]\nfor i, j in zip(strs[0], strs[-1]):\n print(str(i) + ' -> ' + str(j))\nprint(strs.sort())\nstrs.sort()\np = ''\nfor x, y in zip(strs[0], strs[-1]):\n if x == y:\n p += x\n else:\n break\nreturn p", "output = ''\nif strs i...
<|body_start_0|> if not strs: return '' if len(strs) == 1: return strs[0] for i, j in zip(strs[0], strs[-1]): print(str(i) + ' -> ' + str(j)) print(strs.sort()) strs.sort() p = '' for x, y in zip(strs[0], strs[-1]): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix_2(self, strs): """:type strs: List[str] :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not strs: re...
stack_v2_sparse_classes_75kplus_train_003724
1,058
no_license
[ { "docstring": ":type strs: List[str] :rtype: str", "name": "longestCommonPrefix", "signature": "def longestCommonPrefix(self, strs)" }, { "docstring": ":type strs: List[str] :rtype: str", "name": "longestCommonPrefix_2", "signature": "def longestCommonPrefix_2(self, strs)" } ]
2
stack_v2_sparse_classes_30k_train_030026
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix_2(self, strs): :type strs: List[str] :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str - def longestCommonPrefix_2(self, strs): :type strs: List[str] :rtype: str <|skeleton|> class Solution: ...
15ebd6b76dd1f26bd14ee911e5eb08d6e37db8fd
<|skeleton|> class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" <|body_0|> def longestCommonPrefix_2(self, strs): """:type strs: List[str] :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def longestCommonPrefix(self, strs): """:type strs: List[str] :rtype: str""" if not strs: return '' if len(strs) == 1: return strs[0] for i, j in zip(strs[0], strs[-1]): print(str(i) + ' -> ' + str(j)) print(strs.sort()) ...
the_stack_v2_python_sparse
LongestCommonPrefix.py
manishkumar2k9/GitRepository-LeedCodeSolutions
train
0
b91ee64dc7ee589c7c29bce5a64d50805a82521a
[ "if 'SF' in user_id:\n res = assoc_db.read_one_associate_by_query({'salesforce_id': user_id})\nelse:\n res = assoc_db.read_one_associate_by_query({'email': user_id})\nif res['swot']:\n for swot in res['swot']:\n swot['date_created'] = converter(swot['date_created'])\nelse:\n res['swot'] = [{'auth...
<|body_start_0|> if 'SF' in user_id: res = assoc_db.read_one_associate_by_query({'salesforce_id': user_id}) else: res = assoc_db.read_one_associate_by_query({'email': user_id}) if res['swot']: for swot in res['swot']: swot['date_created'] = con...
Class for routing employee/user_id requests
EmployeeIdRoute
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmployeeIdRoute: """Class for routing employee/user_id requests""" def get(self, user_id): """Retrieves associate information for a designated associate vai salesforce id or email""" <|body_0|> def post(self, user_id): """Adds a SWOT to a designated associate via...
stack_v2_sparse_classes_75kplus_train_003725
4,872
no_license
[ { "docstring": "Retrieves associate information for a designated associate vai salesforce id or email", "name": "get", "signature": "def get(self, user_id)" }, { "docstring": "Adds a SWOT to a designated associate via their salesforce id or email", "name": "post", "signature": "def post(...
2
stack_v2_sparse_classes_30k_train_044207
Implement the Python class `EmployeeIdRoute` described below. Class description: Class for routing employee/user_id requests Method signatures and docstrings: - def get(self, user_id): Retrieves associate information for a designated associate vai salesforce id or email - def post(self, user_id): Adds a SWOT to a des...
Implement the Python class `EmployeeIdRoute` described below. Class description: Class for routing employee/user_id requests Method signatures and docstrings: - def get(self, user_id): Retrieves associate information for a designated associate vai salesforce id or email - def post(self, user_id): Adds a SWOT to a des...
d376039c1d08f573fde536978ffce0e44a05922c
<|skeleton|> class EmployeeIdRoute: """Class for routing employee/user_id requests""" def get(self, user_id): """Retrieves associate information for a designated associate vai salesforce id or email""" <|body_0|> def post(self, user_id): """Adds a SWOT to a designated associate via...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EmployeeIdRoute: """Class for routing employee/user_id requests""" def get(self, user_id): """Retrieves associate information for a designated associate vai salesforce id or email""" if 'SF' in user_id: res = assoc_db.read_one_associate_by_query({'salesforce_id': user_id}) ...
the_stack_v2_python_sparse
src/router/employees.py
revaturelabs/csm-backend
train
2
c3c6e7ab2388b58853ec08f4401f4c30dee6078f
[ "from collections import defaultdict\nself.prefixes = defaultdict(set)\nself.suffixes = defaultdict(set)\nself.weights = {}\nfor index, word in enumerate(words):\n prefix, suffix = ('', '')\n for char in [''] + list(word):\n prefix += char\n self.prefixes[prefix].add(word)\n for char in [''] ...
<|body_start_0|> from collections import defaultdict self.prefixes = defaultdict(set) self.suffixes = defaultdict(set) self.weights = {} for index, word in enumerate(words): prefix, suffix = ('', '') for char in [''] + list(word): prefix +=...
WordFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> from collections import defaultdict ...
stack_v2_sparse_classes_75kplus_train_003726
1,282
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type prefix: str :type suffix: str :rtype: int", "name": "f", "signature": "def f(self, prefix, suffix)" } ]
2
stack_v2_sparse_classes_30k_train_053595
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int <|skeleton|> class WordFilter: def __in...
e4c02084f26384cedbd87c4c60e9bdfbf77228cc
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WordFilter: def __init__(self, words): """:type words: List[str]""" from collections import defaultdict self.prefixes = defaultdict(set) self.suffixes = defaultdict(set) self.weights = {} for index, word in enumerate(words): prefix, suffix = ('', '')...
the_stack_v2_python_sparse
Advanced/745. Prefix and Suffix Search Hard.py
dongbo910220/leetcode_
train
0
f0ed1edd2753d76cd111be5e8587f15c612a224b
[ "super().__init__(**kwargs)\nself.factory = factory\nself.chapter_section = chapter_section\nself.content_translations = content_translations", "for language, content in self.content_translations.items():\n i = 0\n if content.heading_tree:\n for heading_node in content.heading_tree:\n self...
<|body_start_0|> super().__init__(**kwargs) self.factory = factory self.chapter_section = chapter_section self.content_translations = content_translations <|end_body_0|> <|body_start_1|> for language, content in self.content_translations.items(): i = 0 if...
Custom loader for loading headings for chapter sections.
ChapterSectionHeadingsLoader
[ "CC-BY-NC-SA-4.0", "BSD-3-Clause", "CC0-1.0", "ISC", "Unlicense", "LicenseRef-scancode-secret-labs-2011", "WTFPL", "Apache-2.0", "LGPL-3.0-only", "MIT", "CC-BY-SA-4.0", "LicenseRef-scancode-public-domain", "CC-BY-NC-2.5", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown...
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChapterSectionHeadingsLoader: """Custom loader for loading headings for chapter sections.""" def __init__(self, factory, chapter_section, content_translations, **kwargs): """Create the loader for loading chapter section headings. Args: factory (LoaderFactory): LoaderFactory object fo...
stack_v2_sparse_classes_75kplus_train_003727
2,238
permissive
[ { "docstring": "Create the loader for loading chapter section headings. Args: factory (LoaderFactory): LoaderFactory object for creating loaders. chapter_section (ChapterSection): Object of related chapter section model. content_translation (dict): Dictionary of content translations.", "name": "__init__", ...
2
null
Implement the Python class `ChapterSectionHeadingsLoader` described below. Class description: Custom loader for loading headings for chapter sections. Method signatures and docstrings: - def __init__(self, factory, chapter_section, content_translations, **kwargs): Create the loader for loading chapter section heading...
Implement the Python class `ChapterSectionHeadingsLoader` described below. Class description: Custom loader for loading headings for chapter sections. Method signatures and docstrings: - def __init__(self, factory, chapter_section, content_translations, **kwargs): Create the loader for loading chapter section heading...
ea3281ec6f4d17538f6d3cf6f88d74fa54581b34
<|skeleton|> class ChapterSectionHeadingsLoader: """Custom loader for loading headings for chapter sections.""" def __init__(self, factory, chapter_section, content_translations, **kwargs): """Create the loader for loading chapter section headings. Args: factory (LoaderFactory): LoaderFactory object fo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChapterSectionHeadingsLoader: """Custom loader for loading headings for chapter sections.""" def __init__(self, factory, chapter_section, content_translations, **kwargs): """Create the loader for loading chapter section headings. Args: factory (LoaderFactory): LoaderFactory object for creating lo...
the_stack_v2_python_sparse
csfieldguide/chapters/management/commands/_ChapterSectionHeadingsLoader.py
uccser/cs-field-guide
train
364
90e03ffb126dfed8c9ede8b699f7557e3da83338
[ "pygame.sprite.Sprite.__init__(self)\nif image:\n self.image = image\nelse:\n self.image = Puff.IMAGE.copy()\nself.rect = self.image.get_rect()\nif alpha:\n self.image.set_alpha(int(alpha))\nelse:\n self.image.set_alpha(255)\nself.rect.centerx = coord[0]\nself.rect.centery = coord[1]\nself.countdown = l...
<|body_start_0|> pygame.sprite.Sprite.__init__(self) if image: self.image = image else: self.image = Puff.IMAGE.copy() self.rect = self.image.get_rect() if alpha: self.image.set_alpha(int(alpha)) else: self.image.set_alpha(2...
A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out
Puff
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alph...
stack_v2_sparse_classes_75kplus_train_003728
2,118
permissive
[ { "docstring": "Creates a puff of smoke coord(list) --> (x,y) center point of the puff life(int) --> frames before dissapearing (PRESET: 60 frames)(-1 = infinite) alpha(int) --> Alpha value of the surface (PRESET: fully opaque) alpha_decrease --> Alpha decrease per frame (PRESET: No decrease) image(Surface) -->...
2
stack_v2_sparse_classes_30k_train_038850
Implement the Python class `Puff` described below. Class description: A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out Method ...
Implement the Python class `Puff` described below. Class description: A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out Method ...
35b7127f9af204798615d820ec664a00eb45e1d2
<|skeleton|> class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alph...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Puff: """A class which acts as temporary image, it has a life, and Surface as well as a location The class can be given an alpha value, which can be made to change at a specified rate The object will automatically kill itself after its life runs out""" def __init__(self, coord, life=60, alpha=None, alpha...
the_stack_v2_python_sparse
Puff.py
Saevon/Arkanoid
train
0
e5ebd27549b6c06a06ea864f3e9d02364f0a05b7
[ "if type(network_distribution) is not type(known_distribution):\n raise TypeError('Input distributions must be of same type')\nif isinstance(network_distribution, dict):\n if network_distribution.keys() != known_distribution.keys():\n for key in list(network_distribution.keys()):\n if key no...
<|body_start_0|> if type(network_distribution) is not type(known_distribution): raise TypeError('Input distributions must be of same type') if isinstance(network_distribution, dict): if network_distribution.keys() != known_distribution.keys(): for key in list(netw...
Class of metrics/distances (norms) between probability distributions
Metrics
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Metrics: """Class of metrics/distances (norms) between probability distributions""" def __init__(self, network_distribution, known_distribution): """Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray...
stack_v2_sparse_classes_75kplus_train_003729
11,971
permissive
[ { "docstring": "Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray Output probability distribution from network circuit. known_distribution : dict or np.ndarray Actual probability distribution from data.", "name": "__init__...
5
stack_v2_sparse_classes_30k_train_048225
Implement the Python class `Metrics` described below. Class description: Class of metrics/distances (norms) between probability distributions Method signatures and docstrings: - def __init__(self, network_distribution, known_distribution): Initializes a metric to compare distance between network and known (data) dist...
Implement the Python class `Metrics` described below. Class description: Class of metrics/distances (norms) between probability distributions Method signatures and docstrings: - def __init__(self, network_distribution, known_distribution): Initializes a metric to compare distance between network and known (data) dist...
5fe919f100f54310a9300b32a838f965f834bbdf
<|skeleton|> class Metrics: """Class of metrics/distances (norms) between probability distributions""" def __init__(self, network_distribution, known_distribution): """Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Metrics: """Class of metrics/distances (norms) between probability distributions""" def __init__(self, network_distribution, known_distribution): """Initializes a metric to compare distance between network and known (data) distribution. Args: network_distribution : dict or np.ndarray Output proba...
the_stack_v2_python_sparse
src/nisqai/cost/_classical_costs.py
rmlarose/nisqai-dev
train
15
b764c9e186da963d07af840d9743b87cc3fec3a4
[ "with self._preprocess_graph_lock:\n if self._preprocess_graph is None:\n self._preprocess_graph = PreprocessGraph()", "dataset, image_path, label = element\nimage_data = tf.io.gfile.GFile(image_path, 'rb').read()\nif self._preprocess_graph is None:\n raise RuntimeError('self._preprocess_graph not in...
<|body_start_0|> with self._preprocess_graph_lock: if self._preprocess_graph is None: self._preprocess_graph = PreprocessGraph() <|end_body_0|> <|body_start_1|> dataset, image_path, label = element image_data = tf.io.gfile.GFile(image_path, 'rb').read() if se...
Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord.
PreprocessImage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreprocessImage: """Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord.""" def start_bundle(self): ...
stack_v2_sparse_classes_75kplus_train_003730
12,153
permissive
[ { "docstring": "Starts an Apache Beam bundle. We cache the Tensorflow session per bundle to avoid cold starts for the processing of each element.", "name": "start_bundle", "signature": "def start_bundle(self)" }, { "docstring": "Calculates the bottleneck for an image. Args: element: A beam.PColl...
2
stack_v2_sparse_classes_30k_train_018459
Implement the Python class `PreprocessImage` described below. Class description: Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRe...
Implement the Python class `PreprocessImage` described below. Class description: Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRe...
cb8ad454b351b86c70a32b70a0ff57049ab1d9c6
<|skeleton|> class PreprocessImage: """Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord.""" def start_bundle(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreprocessImage: """Workflow step to preprocess input images. This workflow step does the following: 1) Reads input image from GCS 2) Resize and encodes the image as required by Inception V3 model. 3) Calculate Inception V3 bottleneck and stores it as a TFRecord.""" def start_bundle(self): """Sta...
the_stack_v2_python_sparse
imaging/ml/ml_codelab/scripts/preprocess/preprocess.py
GoogleCloudPlatform/healthcare
train
368
8fe4df5297b5c3d086d36d332683153b8137b822
[ "if default_values:\n self._config_values = default_values\nelse:\n self._config_values = {}\ntry:\n fp = open(config_file)\n for line in fp:\n line = line.strip()\n if line and line[0] != '#':\n key, value = line.split(' ')\n self._config_values[key] = value\n fp....
<|body_start_0|> if default_values: self._config_values = default_values else: self._config_values = {} try: fp = open(config_file) for line in fp: line = line.strip() if line and line[0] != '#': ...
Class for loading and provide configuration parameters.
Configs
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Configs: """Class for loading and provide configuration parameters.""" def __init__(self, config_file, default_values=None): """Load config key/value pairs from the config file.""" <|body_0|> def GetStr(self, key): """Returns the value for the given key from the ...
stack_v2_sparse_classes_75kplus_train_003731
1,901
permissive
[ { "docstring": "Load config key/value pairs from the config file.", "name": "__init__", "signature": "def __init__(self, config_file, default_values=None)" }, { "docstring": "Returns the value for the given key from the config file.", "name": "GetStr", "signature": "def GetStr(self, key)...
4
null
Implement the Python class `Configs` described below. Class description: Class for loading and provide configuration parameters. Method signatures and docstrings: - def __init__(self, config_file, default_values=None): Load config key/value pairs from the config file. - def GetStr(self, key): Returns the value for th...
Implement the Python class `Configs` described below. Class description: Class for loading and provide configuration parameters. Method signatures and docstrings: - def __init__(self, config_file, default_values=None): Load config key/value pairs from the config file. - def GetStr(self, key): Returns the value for th...
f7ea83f769485d9c28021b951fec8f15f641b16c
<|skeleton|> class Configs: """Class for loading and provide configuration parameters.""" def __init__(self, config_file, default_values=None): """Load config key/value pairs from the config file.""" <|body_0|> def GetStr(self, key): """Returns the value for the given key from the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Configs: """Class for loading and provide configuration parameters.""" def __init__(self, config_file, default_values=None): """Load config key/value pairs from the config file.""" if default_values: self._config_values = default_values else: self._config_v...
the_stack_v2_python_sparse
earth_enterprise/src/server/wsgi/wms/ogc/common/configs.py
tst-ccamp/earthenterprise
train
2
55e1abb258743c4cc50fdf4aa1c4549d94582153
[ "self.model = GMF(config['model'])\nself.loss = torch.nn.BCELoss()\nsuper(GMFEngine, self).__init__(config)", "assert hasattr(self, 'model'), 'Please specify the exact model !'\nusers, items, ratings = (users.to(self.device), items.to(self.device), ratings.to(self.device))\nself.optimizer.zero_grad()\nratings_pre...
<|body_start_0|> self.model = GMF(config['model']) self.loss = torch.nn.BCELoss() super(GMFEngine, self).__init__(config) <|end_body_0|> <|body_start_1|> assert hasattr(self, 'model'), 'Please specify the exact model !' users, items, ratings = (users.to(self.device), items.to(se...
Engine for training & evaluating GMF model.
GMFEngine
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GMFEngine: """Engine for training & evaluating GMF model.""" def __init__(self, config): """Initialize GMFEngine Class.""" <|body_0|> def train_single_batch(self, users, items, ratings): """Train the model in a single batch. Args: batch_data (list): batch users, ...
stack_v2_sparse_classes_75kplus_train_003732
3,601
permissive
[ { "docstring": "Initialize GMFEngine Class.", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Train the model in a single batch. Args: batch_data (list): batch users, positive items and negative items. Return: loss (float): batch loss.", "name": "train_single...
3
stack_v2_sparse_classes_30k_train_042922
Implement the Python class `GMFEngine` described below. Class description: Engine for training & evaluating GMF model. Method signatures and docstrings: - def __init__(self, config): Initialize GMFEngine Class. - def train_single_batch(self, users, items, ratings): Train the model in a single batch. Args: batch_data ...
Implement the Python class `GMFEngine` described below. Class description: Engine for training & evaluating GMF model. Method signatures and docstrings: - def __init__(self, config): Initialize GMFEngine Class. - def train_single_batch(self, users, items, ratings): Train the model in a single batch. Args: batch_data ...
625189d5e1002a3edc27c3e3ce075fddf7ae1c92
<|skeleton|> class GMFEngine: """Engine for training & evaluating GMF model.""" def __init__(self, config): """Initialize GMFEngine Class.""" <|body_0|> def train_single_batch(self, users, items, ratings): """Train the model in a single batch. Args: batch_data (list): batch users, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GMFEngine: """Engine for training & evaluating GMF model.""" def __init__(self, config): """Initialize GMFEngine Class.""" self.model = GMF(config['model']) self.loss = torch.nn.BCELoss() super(GMFEngine, self).__init__(config) def train_single_batch(self, users, item...
the_stack_v2_python_sparse
beta_rec/models/gmf.py
beta-team/beta-recsys
train
156
5c044354700c6fdd8a0353c0bcc55b2872fa286d
[ "Entry.objects.create(pub_date=self.now, is_active=False, headline='inactive', slug='a')\nEntry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b')\nself.assertQuerysetEqual(Entry.objects.published(), ['active'], transform=lambda entry: entry.headline)", "Entry.objects.create(pub_date=s...
<|body_start_0|> Entry.objects.create(pub_date=self.now, is_active=False, headline='inactive', slug='a') Entry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b') self.assertQuerysetEqual(Entry.objects.published(), ['active'], transform=lambda entry: entry.headline) <|...
EntryTestCase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EntryTestCase: def test_manager_active(self): """Make sure that the Entry manager's `active` method works""" <|body_0|> def test_manager_published(self): """Make sure that the Entry manager's `published` method works""" <|body_1|> def test_docutils_safe(...
stack_v2_sparse_classes_75kplus_train_003733
5,555
permissive
[ { "docstring": "Make sure that the Entry manager's `active` method works", "name": "test_manager_active", "signature": "def test_manager_active(self)" }, { "docstring": "Make sure that the Entry manager's `published` method works", "name": "test_manager_published", "signature": "def test...
3
null
Implement the Python class `EntryTestCase` described below. Class description: Implement the EntryTestCase class. Method signatures and docstrings: - def test_manager_active(self): Make sure that the Entry manager's `active` method works - def test_manager_published(self): Make sure that the Entry manager's `publishe...
Implement the Python class `EntryTestCase` described below. Class description: Implement the EntryTestCase class. Method signatures and docstrings: - def test_manager_active(self): Make sure that the Entry manager's `active` method works - def test_manager_published(self): Make sure that the Entry manager's `publishe...
66a6e87290ee43b4935bc178c737c565570fbc7f
<|skeleton|> class EntryTestCase: def test_manager_active(self): """Make sure that the Entry manager's `active` method works""" <|body_0|> def test_manager_published(self): """Make sure that the Entry manager's `published` method works""" <|body_1|> def test_docutils_safe(...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EntryTestCase: def test_manager_active(self): """Make sure that the Entry manager's `active` method works""" Entry.objects.create(pub_date=self.now, is_active=False, headline='inactive', slug='a') Entry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b') ...
the_stack_v2_python_sparse
blog/tests.py
django/djangoproject.com
train
1,807
36e48b0590000fa827a2e56b9dce38f137090867
[ "if N == 0:\n return []\nif N == 1:\n return [TreeNode(0)]\nif N % 2 == 0:\n return []\nleft_num = 1\nright_num = N - 2\nres = []\nwhile right_num > 0:\n lefts = self.allPossibleFBT(left_num)\n rights = self.allPossibleFBT(right_num)\n for i in range(len(lefts)):\n for j in range(len(rights...
<|body_start_0|> if N == 0: return [] if N == 1: return [TreeNode(0)] if N % 2 == 0: return [] left_num = 1 right_num = N - 2 res = [] while right_num > 0: lefts = self.allPossibleFBT(left_num) rights = s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def allPossibleFBT(self, N): """:type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。""" <|body_0|> def allPossibleFBT2(self, N): """:type N: int :rtype: List[TreeNode]""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus_train_003734
2,349
no_license
[ { "docstring": ":type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。", "name": "allPossibleFBT", "signature": "def allPossibleFBT(self, N)" }, { "docstring": ":type N: int :rtype: List[TreeNode]", "name": "allPossibleFBT2", "...
2
stack_v2_sparse_classes_30k_train_013337
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def allPossibleFBT(self, N): :type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。 - def allPossibleFBT2(self, N): :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def allPossibleFBT(self, N): :type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。 - def allPossibleFBT2(self, N): :...
4105e18050b15fc0409c75353ad31be17187dd34
<|skeleton|> class Solution: def allPossibleFBT(self, N): """:type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。""" <|body_0|> def allPossibleFBT2(self, N): """:type N: int :rtype: List[TreeNode]""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def allPossibleFBT(self, N): """:type N: int :rtype: List[TreeNode] 现在这个树一共是N个节点的话,根节点算一个,左子树一共i个,那右子树一共就N-1-i个。 然后迭代的时候每次左边+2个,右边-2个。把所有的结果加起来就好啦。""" if N == 0: return [] if N == 1: return [TreeNode(0)] if N % 2 == 0: return [] ...
the_stack_v2_python_sparse
allPossibleFBT.py
NeilWangziyu/Leetcode_py
train
2
f2020912a71289a8bd434ec54c6ec29d3f6b9747
[ "self.lockIO = Lock()\nself.bus = bus\nself.bus.register(self)\nself.data = [0] * (16131 + 1)\nreturn", "if self.bus.address < 16636 or self.bus.address > 32767:\n return\nif self.bus.mode == MODE.READ:\n self.lockIO.acquire()\n self.bus.data = self.data[self.bus.address - 16636]\n self.lockIO.release...
<|body_start_0|> self.lockIO = Lock() self.bus = bus self.bus.register(self) self.data = [0] * (16131 + 1) return <|end_body_0|> <|body_start_1|> if self.bus.address < 16636 or self.bus.address > 32767: return if self.bus.mode == MODE.READ: ...
class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())
IO
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IO: """class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())""" def __init__(self, bus): ...
stack_v2_sparse_classes_75kplus_train_003735
4,185
permissive
[ { "docstring": "Constructeur de la classe IO. Le constructeur s'occupe d'initialiser la mémoire IO et lie ce composant avec le bus. :example: >>> test = IO(modBus.Bus()) :param bus: Composant Bus du Micro-Ordinateur. :type bus: Bus", "name": "__init__", "signature": "def __init__(self, bus)" }, { ...
3
stack_v2_sparse_classes_30k_train_036415
Implement the Python class `IO` described below. Class description: class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus()...
Implement the Python class `IO` described below. Class description: class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus()...
0a3a9b0deffa16e8c851eb53e6aad1a8983936e6
<|skeleton|> class IO: """class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())""" def __init__(self, bus): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IO: """class IO ======================== Cette classe représente les entrées/sorties du micro-ordinateur. À chaque coup d'horloge (clock/event), la classe vérifie si elle doit effectuer une lecture ou écriture en mémoire. :example: >>> test = IO(modBus.Bus())""" def __init__(self, bus): """Constr...
the_stack_v2_python_sparse
Modules/04-05-IO.py
MarcAndreJean/PCONC
train
0
34a39be9d385b93e2a7616fc7a8d4e6f213d6890
[ "matches = []\nstring_params = cfn.get_sub_parameters(sub_string)\nif not string_params:\n message = \"Fn::Sub isn't needed because there are no variables at {0}\"\n matches.append(RuleMatch(tree, message.format('/'.join(map(str, tree)))))\nreturn matches", "matches = []\nsub_objs = cfn.transform_pre.get('F...
<|body_start_0|> matches = [] string_params = cfn.get_sub_parameters(sub_string) if not string_params: message = "Fn::Sub isn't needed because there are no variables at {0}" matches.append(RuleMatch(tree, message.format('/'.join(map(str, tree))))) return matches <...
Check if Sub is using a variable
SubUnneeded
[ "MIT-0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubUnneeded: """Check if Sub is using a variable""" def _test_string(self, cfn, sub_string, tree): """Test if a string has appropriate parameters""" <|body_0|> def match(self, cfn): """Check CloudFormation Join""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_75kplus_train_003736
2,531
permissive
[ { "docstring": "Test if a string has appropriate parameters", "name": "_test_string", "signature": "def _test_string(self, cfn, sub_string, tree)" }, { "docstring": "Check CloudFormation Join", "name": "match", "signature": "def match(self, cfn)" } ]
2
null
Implement the Python class `SubUnneeded` described below. Class description: Check if Sub is using a variable Method signatures and docstrings: - def _test_string(self, cfn, sub_string, tree): Test if a string has appropriate parameters - def match(self, cfn): Check CloudFormation Join
Implement the Python class `SubUnneeded` described below. Class description: Check if Sub is using a variable Method signatures and docstrings: - def _test_string(self, cfn, sub_string, tree): Test if a string has appropriate parameters - def match(self, cfn): Check CloudFormation Join <|skeleton|> class SubUnneeded...
3f5324cfd000e14d9324a242bb7fad528b22a7df
<|skeleton|> class SubUnneeded: """Check if Sub is using a variable""" def _test_string(self, cfn, sub_string, tree): """Test if a string has appropriate parameters""" <|body_0|> def match(self, cfn): """Check CloudFormation Join""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SubUnneeded: """Check if Sub is using a variable""" def _test_string(self, cfn, sub_string, tree): """Test if a string has appropriate parameters""" matches = [] string_params = cfn.get_sub_parameters(sub_string) if not string_params: message = "Fn::Sub isn't n...
the_stack_v2_python_sparse
src/cfnlint/rules/functions/SubUnneeded.py
jlongtine/cfn-python-lint
train
1
c8cd3b38b3574c70ca73f8ba67902a270b85999c
[ "jumps = 0\ni, n = (0, len(nums))\nif n <= 1:\n return jumps\nwhile i < n:\n j = i + nums[i]\n if j < n - 1:\n i = max(range(i + 1, j + 1), key=lambda ind: ind + nums[ind])\n jumps += 1\n else:\n jumps += 1\n return jumps", "jumps = 0\ncurEnd, curMax = (0, 0)\nfor i in rang...
<|body_start_0|> jumps = 0 i, n = (0, len(nums)) if n <= 1: return jumps while i < n: j = i + nums[i] if j < n - 1: i = max(range(i + 1, j + 1), key=lambda ind: ind + nums[ind]) jumps += 1 else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def jump(self, nums: List[int]) -> int: """1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点""" <|body_0|> def jump_1(self, nums: List[int]) -> int: """2. 重构代码 - curEnd 表示选择一个点后的可达边界,curMax 所有可达点中可以跳最远的那个点 - 初始时:位于 0 处,curEnd=0 - 在可达边界点内选择跳的最...
stack_v2_sparse_classes_75kplus_train_003737
2,327
no_license
[ { "docstring": "1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点", "name": "jump", "signature": "def jump(self, nums: List[int]) -> int" }, { "docstring": "2. 重构代码 - curEnd 表示选择一个点后的可达边界,curMax 所有可达点中可以跳最远的那个点 - 初始时:位于 0 处,curEnd=0 - 在可达边界点内选择跳的最远的那一个,即每次达到边界处时,一定已经进行了一次选择", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums: List[int]) -> int: 1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点 - def jump_1(self, nums: List[int]) -> int: 2. 重构代码 - curEnd 表示选择一个点后的可达边...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums: List[int]) -> int: 1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点 - def jump_1(self, nums: List[int]) -> int: 2. 重构代码 - curEnd 表示选择一个点后的可达边...
4732fb80710a08a715c3e7080c394f5298b8326d
<|skeleton|> class Solution: def jump(self, nums: List[int]) -> int: """1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点""" <|body_0|> def jump_1(self, nums: List[int]) -> int: """2. 重构代码 - curEnd 表示选择一个点后的可达边界,curMax 所有可达点中可以跳最远的那个点 - 初始时:位于 0 处,curEnd=0 - 在可达边界点内选择跳的最...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def jump(self, nums: List[int]) -> int: """1. 贪心算法:位置i可达的点 i+1~i+nums[i],从中选择可以跳最远的那个点为下一点 直观、且可直接记录下每次的跳跃点""" jumps = 0 i, n = (0, len(nums)) if n <= 1: return jumps while i < n: j = i + nums[i] if j < n - 1: ...
the_stack_v2_python_sparse
.leetcode/45.跳跃游戏-ii.py
xiaoruijiang/algorithm
train
0
eed7c5fb5ce9a5f6f17c55de3988356cead6fc17
[ "self.cloud_tier_download = cloud_tier_download\nself.cloud_tier_upload = cloud_tier_upload\nself.download = download\nself.upload = upload", "if dictionary is None:\n return None\ncloud_tier_download = cohesity_management_sdk.models.bandwidth_limit.BandwidthLimit.from_dictionary(dictionary.get('cloudTierDownl...
<|body_start_0|> self.cloud_tier_download = cloud_tier_download self.cloud_tier_upload = cloud_tier_upload self.download = download self.upload = upload <|end_body_0|> <|body_start_1|> if dictionary is None: return None cloud_tier_download = cohesity_manageme...
Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies the max rate limit at which we download the data to cloud tier vaults. cloud_tier_uplo...
VaultBandwidthLimits
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VaultBandwidthLimits: """Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies the max rate limit at which we downloa...
stack_v2_sparse_classes_75kplus_train_003738
3,010
permissive
[ { "docstring": "Constructor for the VaultBandwidthLimits class", "name": "__init__", "signature": "def __init__(self, cloud_tier_download=None, cloud_tier_upload=None, download=None, upload=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary...
2
stack_v2_sparse_classes_30k_train_035267
Implement the Python class `VaultBandwidthLimits` described below. Class description: Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies...
Implement the Python class `VaultBandwidthLimits` described below. Class description: Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class VaultBandwidthLimits: """Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies the max rate limit at which we downloa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VaultBandwidthLimits: """Implementation of the 'VaultBandwidthLimits' model. VaultBandwidthLimits represents the network bandwidth limits while uploading/downloading data to/from the external media. Attributes: cloud_tier_download (BandwidthLimit): Specifies the max rate limit at which we download the data to...
the_stack_v2_python_sparse
cohesity_management_sdk/models/vault_bandwidth_limits.py
cohesity/management-sdk-python
train
24
ec313e6d6a59df9f3b299beb2a087d79fc181060
[ "response = self.client.get('/accounts/register/')\nself.assertEqual(response.status_code, HTTPStatus.OK)\nself.assertContains(response, '<h2>Sign up</h2>', html=True)", "form = {'first_name': 'test', 'last_name': 'test', 'email': 'test@test.com', 'password1': '12345678!', 'password2': '12345678!', 'username': 't...
<|body_start_0|> response = self.client.get('/accounts/register/') self.assertEqual(response.status_code, HTTPStatus.OK) self.assertContains(response, '<h2>Sign up</h2>', html=True) <|end_body_0|> <|body_start_1|> form = {'first_name': 'test', 'last_name': 'test', 'email': 'test@test.co...
RegisterViewTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegisterViewTest: def test_register_view_load(self): """test if register view loads successfully""" <|body_0|> def test_register_success(self): """test if a valid registration redirects to the home page and creates a new user""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_003739
1,065
no_license
[ { "docstring": "test if register view loads successfully", "name": "test_register_view_load", "signature": "def test_register_view_load(self)" }, { "docstring": "test if a valid registration redirects to the home page and creates a new user", "name": "test_register_success", "signature":...
2
stack_v2_sparse_classes_30k_train_054199
Implement the Python class `RegisterViewTest` described below. Class description: Implement the RegisterViewTest class. Method signatures and docstrings: - def test_register_view_load(self): test if register view loads successfully - def test_register_success(self): test if a valid registration redirects to the home ...
Implement the Python class `RegisterViewTest` described below. Class description: Implement the RegisterViewTest class. Method signatures and docstrings: - def test_register_view_load(self): test if register view loads successfully - def test_register_success(self): test if a valid registration redirects to the home ...
be5b8d133a88340fe7347f1aaafb51660ad92f09
<|skeleton|> class RegisterViewTest: def test_register_view_load(self): """test if register view loads successfully""" <|body_0|> def test_register_success(self): """test if a valid registration redirects to the home page and creates a new user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegisterViewTest: def test_register_view_load(self): """test if register view loads successfully""" response = self.client.get('/accounts/register/') self.assertEqual(response.status_code, HTTPStatus.OK) self.assertContains(response, '<h2>Sign up</h2>', html=True) def test...
the_stack_v2_python_sparse
accounts/tests.py
harteros/MovieRama
train
0
61facdd6002d4a64240f621f884ef31cfb6d8596
[ "if s == '':\n return 1\nif s[0] == '0':\n return 0\nways = 0\nif int(s[0]) != 0:\n ways += self._numDecodings(s[1:])\nif len(s) >= 2 and 1 <= int(s[0:2]) <= 26:\n ways += self._numDecodings(s[2:])\nreturn ways", "if s == '':\n return 0\nreturn self._numDecodings(s)" ]
<|body_start_0|> if s == '': return 1 if s[0] == '0': return 0 ways = 0 if int(s[0]) != 0: ways += self._numDecodings(s[1:]) if len(s) >= 2 and 1 <= int(s[0:2]) <= 26: ways += self._numDecodings(s[2:]) return ways <|end_body...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _numDecodings(self, s): """:type s:str :rtype: int""" <|body_0|> def numDecodings(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if s == '': return 1 if s[0] == '0': ...
stack_v2_sparse_classes_75kplus_train_003740
875
no_license
[ { "docstring": ":type s:str :rtype: int", "name": "_numDecodings", "signature": "def _numDecodings(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "numDecodings", "signature": "def numDecodings(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_017777
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _numDecodings(self, s): :type s:str :rtype: int - def numDecodings(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 _numDecodings(self, s): :type s:str :rtype: int - def numDecodings(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def _numDecodings(self, s): "...
cd3900a7d91d1d94d308bc7a65533b8262781ee9
<|skeleton|> class Solution: def _numDecodings(self, s): """:type s:str :rtype: int""" <|body_0|> def numDecodings(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 _numDecodings(self, s): """:type s:str :rtype: int""" if s == '': return 1 if s[0] == '0': return 0 ways = 0 if int(s[0]) != 0: ways += self._numDecodings(s[1:]) if len(s) >= 2 and 1 <= int(s[0:2]) <= 26: ...
the_stack_v2_python_sparse
lc0091_DecodeWays/lc0091.py
cgi0911/LeetCodePractice
train
0
706b1292cd76563f798b9614c6f02bc933d9c7b1
[ "self.candidate_class = candidate_class\nself.candidate_spaces = cspaces if type(cspaces) in [list, tuple] else [cspaces]\nself.matchers = matchers if type(matchers) in [list, tuple] else [matchers]\nself.candidate_filter = candidate_filter\nself.nested_relations = nested_relations\nself.self_relations = self_relat...
<|body_start_0|> self.candidate_class = candidate_class self.candidate_spaces = cspaces if type(cspaces) in [list, tuple] else [cspaces] self.matchers = matchers if type(matchers) in [list, tuple] else [matchers] self.candidate_filter = candidate_filter self.nested_relations = ne...
UDF for performing candidate extraction.
CandidateExtractorUDF
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CandidateExtractorUDF: """UDF for performing candidate extraction.""" def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs): """Initialize the CandidateExtractorUDF.""" <|body_0|> def app...
stack_v2_sparse_classes_75kplus_train_003741
11,751
permissive
[ { "docstring": "Initialize the CandidateExtractorUDF.", "name": "__init__", "signature": "def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs)" }, { "docstring": "Extract candidates from the given Context. Here,...
2
stack_v2_sparse_classes_30k_train_012490
Implement the Python class `CandidateExtractorUDF` described below. Class description: UDF for performing candidate extraction. Method signatures and docstrings: - def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs): Initialize the ...
Implement the Python class `CandidateExtractorUDF` described below. Class description: UDF for performing candidate extraction. Method signatures and docstrings: - def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs): Initialize the ...
362aa56afe60194498c8e0a67b37053abebf04a2
<|skeleton|> class CandidateExtractorUDF: """UDF for performing candidate extraction.""" def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs): """Initialize the CandidateExtractorUDF.""" <|body_0|> def app...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CandidateExtractorUDF: """UDF for performing candidate extraction.""" def __init__(self, candidate_class, cspaces, matchers, candidate_filter, self_relations, nested_relations, symmetric_relations, **kwargs): """Initialize the CandidateExtractorUDF.""" self.candidate_class = candidate_cla...
the_stack_v2_python_sparse
fonduer/candidates/candidates.py
stevenMevans/fonduer
train
1
c5fb848c63bea4cfe0e1da7984780e4f83828bb8
[ "self.primary_language = primary_language\nself.secondary_language = secondary_language\nself.xml_signature = xml_signature\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nprimary_language = dictionary.get('PrimaryLanguage')\nsecondary_language = dictionary.get('Sec...
<|body_start_0|> self.primary_language = primary_language self.secondary_language = secondary_language self.xml_signature = xml_signature self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None pri...
Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_signature (string): Xml package signa...
TemplateWithIdPreview
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplateWithIdPreview: """Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op...
stack_v2_sparse_classes_75kplus_train_003742
2,616
permissive
[ { "docstring": "Constructor for the TemplateWithIdPreview class", "name": "__init__", "signature": "def __init__(self, primary_language=None, secondary_language=None, xml_signature=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dicti...
2
stack_v2_sparse_classes_30k_val_003019
Implement the Python class `TemplateWithIdPreview` described below. Class description: Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second...
Implement the Python class `TemplateWithIdPreview` described below. Class description: Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class TemplateWithIdPreview: """Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TemplateWithIdPreview: """Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_s...
the_stack_v2_python_sparse
idfy_rest_client/models/template_with_id_preview.py
dealflowteam/Idfy
train
0
5061e129e9736dc1118f104472f16efaea4ba612
[ "if self.model.metadata['file_in']:\n self.model._read_from_file(tag_scripts=['p1.individuals.tag = 0;', 'tags = rbinom(1, p0.individualCount, 0.5);', 'p0.individuals.tag = tags;'])\nelse:\n self.model.early(time=1, scripts=[\"sim.addSubpop('p1', SPO_POP_SIZE)\", \"sim.addSubpop('p0', 0)\", 'p1.individuals.ta...
<|body_start_0|> if self.model.metadata['file_in']: self.model._read_from_file(tag_scripts=['p1.individuals.tag = 0;', 'tags = rbinom(1, p0.individualCount, 0.5);', 'p0.individuals.tag = tags;']) else: self.model.early(time=1, scripts=["sim.addSubpop('p1', SPO_POP_SIZE)", "sim.ad...
Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alternative is to implement a WF model.
NonWrightFisher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NonWrightFisher: """Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alternative is to implement a WF model.""" ...
stack_v2_sparse_classes_75kplus_train_003743
11,092
no_license
[ { "docstring": "add haploid and diploid life stages as subpopulations.", "name": "_define_subpopulations", "signature": "def _define_subpopulations(self)" }, { "docstring": "Add defineConstant calls to init variables. When this is called by different superclasses that have different attributes u...
3
null
Implement the Python class `NonWrightFisher` described below. Class description: Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alterna...
Implement the Python class `NonWrightFisher` described below. Class description: Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alterna...
dfdd853ed4ff3fd8f8d3430a9c74ab8db5d3d096
<|skeleton|> class NonWrightFisher: """Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alternative is to implement a WF model.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NonWrightFisher: """Reproduction mode based on NON Wright-Fisher model. This is a subclass that is extended for organism specific reproduction models in shadie.reproduction. All NonWF models include alternation of generations (p0 and p1 subpops). The alternative is to implement a WF model.""" def _define...
the_stack_v2_python_sparse
shadie/reproduction/base.py
eaton-lab/shadie
train
0
158a984a3eb238590f8c559a4ddb68550061853e
[ "for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]:\n n = 64\n ident = jnp.eye(n)[:, :, None]\n sqrt_b_dense = sqrt_b.forward(ident)[Ellipsis, 0]\n _, slogdet = jnp.linalg.slogdet(sqrt_b_dense)\n logdet = slogdet * 2\n logdet2 = sqrt_b.logdet((ident + jnp.zeros(2)).shape)[0]\n ...
<|body_start_0|> for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]: n = 64 ident = jnp.eye(n)[:, :, None] sqrt_b_dense = sqrt_b.forward(ident)[Ellipsis, 0] _, slogdet = jnp.linalg.slogdet(sqrt_b_dense) logdet = slogdet * 2 ...
CovarianceTest
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CovarianceTest: def test_covariance_logdet(self): """Test whether logdet method matches numpy logdet with dense matrix.""" <|body_0|> def test_covariance_inverse(self): """Test covariance forward and inverse are in fact inverses of each other.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_003744
2,268
permissive
[ { "docstring": "Test whether logdet method matches numpy logdet with dense matrix.", "name": "test_covariance_logdet", "signature": "def test_covariance_logdet(self)" }, { "docstring": "Test covariance forward and inverse are in fact inverses of each other.", "name": "test_covariance_inverse...
2
stack_v2_sparse_classes_30k_train_036249
Implement the Python class `CovarianceTest` described below. Class description: Implement the CovarianceTest class. Method signatures and docstrings: - def test_covariance_logdet(self): Test whether logdet method matches numpy logdet with dense matrix. - def test_covariance_inverse(self): Test covariance forward and ...
Implement the Python class `CovarianceTest` described below. Class description: Implement the CovarianceTest class. Method signatures and docstrings: - def test_covariance_logdet(self): Test whether logdet method matches numpy logdet with dense matrix. - def test_covariance_inverse(self): Test covariance forward and ...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class CovarianceTest: def test_covariance_logdet(self): """Test whether logdet method matches numpy logdet with dense matrix.""" <|body_0|> def test_covariance_inverse(self): """Test covariance forward and inverse are in fact inverses of each other.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CovarianceTest: def test_covariance_logdet(self): """Test whether logdet method matches numpy logdet with dense matrix.""" for sqrt_b in [WhiteCovariance, BrownianCovariance, PinkCovariance]: n = 64 ident = jnp.eye(n)[:, :, None] sqrt_b_dense = sqrt_b.forwar...
the_stack_v2_python_sparse
simulation_research/diffusion/covariance_test.py
Jimmy-INL/google-research
train
1
0804b3860a9d58ea9e9fde52399b3a06dd72c61d
[ "if self.config_file is None:\n msg = ' %(cls)s 未定义配置文件路径,需定义config_file的值' % {'cls': self.__class__.__name__}\n error_logger.error(msg)\n raise ValueError(msg)\nreturn self.config_file", "_config = self.get_config_file()\nwith open(_config) as f:\n content = yaml.load(f)\nif key is not None:\n try...
<|body_start_0|> if self.config_file is None: msg = ' %(cls)s 未定义配置文件路径,需定义config_file的值' % {'cls': self.__class__.__name__} error_logger.error(msg) raise ValueError(msg) return self.config_file <|end_body_0|> <|body_start_1|> _config = self.get_config_file()...
ConfigFileMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigFileMixin: def get_config_file(self): """获取配置文件""" <|body_0|> def get_conf_content(self, *key): """获取配置文件对应的key""" <|body_1|> <|end_skeleton|> <|body_start_0|> if self.config_file is None: msg = ' %(cls)s 未定义配置文件路径,需定义config_file的值...
stack_v2_sparse_classes_75kplus_train_003745
3,226
no_license
[ { "docstring": "获取配置文件", "name": "get_config_file", "signature": "def get_config_file(self)" }, { "docstring": "获取配置文件对应的key", "name": "get_conf_content", "signature": "def get_conf_content(self, *key)" } ]
2
stack_v2_sparse_classes_30k_train_002626
Implement the Python class `ConfigFileMixin` described below. Class description: Implement the ConfigFileMixin class. Method signatures and docstrings: - def get_config_file(self): 获取配置文件 - def get_conf_content(self, *key): 获取配置文件对应的key
Implement the Python class `ConfigFileMixin` described below. Class description: Implement the ConfigFileMixin class. Method signatures and docstrings: - def get_config_file(self): 获取配置文件 - def get_conf_content(self, *key): 获取配置文件对应的key <|skeleton|> class ConfigFileMixin: def get_config_file(self): """获...
abf784479ed90b47b6a2611991baf202aea662d2
<|skeleton|> class ConfigFileMixin: def get_config_file(self): """获取配置文件""" <|body_0|> def get_conf_content(self, *key): """获取配置文件对应的key""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfigFileMixin: def get_config_file(self): """获取配置文件""" if self.config_file is None: msg = ' %(cls)s 未定义配置文件路径,需定义config_file的值' % {'cls': self.__class__.__name__} error_logger.error(msg) raise ValueError(msg) return self.config_file def get_co...
the_stack_v2_python_sparse
apps/utils/common.py
Sirius1942/rock2020
train
2
b9d714996f4458349c371fa7e16d4499fea2638b
[ "self.item_code = item_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price", "outputdict = {}\noutputdict['item_code'] = self.item_code\noutputdict['description'] = self.description\noutputdict['market_price'] = self.market_price\noutputdict['rental_price'] = s...
<|body_start_0|> self.item_code = item_code self.description = description self.market_price = market_price self.rental_price = rental_price <|end_body_0|> <|body_start_1|> outputdict = {} outputdict['item_code'] = self.item_code outputdict['description'] = self....
some stuff8
Inventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Inventory: """some stuff8""" def __init__(self, item_code, description, market_price, rental_price): """some stuff9""" <|body_0|> def return_as_dictionary(self): """some stuff10""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.item_code = it...
stack_v2_sparse_classes_75kplus_train_003746
684
no_license
[ { "docstring": "some stuff9", "name": "__init__", "signature": "def __init__(self, item_code, description, market_price, rental_price)" }, { "docstring": "some stuff10", "name": "return_as_dictionary", "signature": "def return_as_dictionary(self)" } ]
2
stack_v2_sparse_classes_30k_train_016037
Implement the Python class `Inventory` described below. Class description: some stuff8 Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price): some stuff9 - def return_as_dictionary(self): some stuff10
Implement the Python class `Inventory` described below. Class description: some stuff8 Method signatures and docstrings: - def __init__(self, item_code, description, market_price, rental_price): some stuff9 - def return_as_dictionary(self): some stuff10 <|skeleton|> class Inventory: """some stuff8""" def __...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class Inventory: """some stuff8""" def __init__(self, item_code, description, market_price, rental_price): """some stuff9""" <|body_0|> def return_as_dictionary(self): """some stuff10""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Inventory: """some stuff8""" def __init__(self, item_code, description, market_price, rental_price): """some stuff9""" self.item_code = item_code self.description = description self.market_price = market_price self.rental_price = rental_price def return_as_dic...
the_stack_v2_python_sparse
students/ScotchWSplenda/lesson01/assignment/inventory_management/inventory_class.py
JavaRod/SP_Python220B_2019
train
1
69197fe0f6c84c807e50d5836c7931d11955d9e0
[ "self.workflow = kwargs.pop('workflow')\nself.user = kwargs.pop('user')\nsuper().__init__(*args, **kwargs)", "if record.is_verified:\n return format_html('<a href=\"{0}\" ' + 'data-bs-toggle=\"tooltip\" title=\"{1}\">{2}', reverse('dataops:plugin_invoke', kwargs={'pk': record.id}), _('Execute the transformatio...
<|body_start_0|> self.workflow = kwargs.pop('workflow') self.user = kwargs.pop('user') super().__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> if record.is_verified: return format_html('<a href="{0}" ' + 'data-bs-toggle="tooltip" title="{1}">{2}', reverse('dataops:...
Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.
PluginAvailableTable
[ "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 PluginAvailableTable: """Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.""" def __init__(self, *args, **kwargs): """Set workflow and user from the given args.""" <|body_0|>...
stack_v2_sparse_classes_75kplus_train_003747
5,524
permissive
[ { "docstring": "Set workflow and user from the given args.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Render as a link or empty if it has not been verified.", "name": "render_name", "signature": "def render_name(record)" }, { "docs...
3
null
Implement the Python class `PluginAvailableTable` described below. Class description: Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Set wor...
Implement the Python class `PluginAvailableTable` described below. Class description: Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Set wor...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class PluginAvailableTable: """Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.""" def __init__(self, *args, **kwargs): """Set workflow and user from the given args.""" <|body_0|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PluginAvailableTable: """Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.""" def __init__(self, *args, **kwargs): """Set workflow and user from the given args.""" self.workflow = kwargs....
the_stack_v2_python_sparse
ontask/dataops/services/plugin_run.py
abelardopardo/ontask_b
train
43
fcb0bded96199e93c2eb5196f72d8da001de0924
[ "if not overwrite_destination and os.path.exists(installation_dir):\n raise ValueError(f'Plugin {repr(cls)} cannot be installed into existing path {installation_dir} because overwrite_destination={overwrite_destination}.')\nsuper().install(installation_dir=installation_dir, overwrite_destination=True)\nprint(f'P...
<|body_start_0|> if not overwrite_destination and os.path.exists(installation_dir): raise ValueError(f'Plugin {repr(cls)} cannot be installed into existing path {installation_dir} because overwrite_destination={overwrite_destination}.') super().install(installation_dir=installation_dir, over...
Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obtained using the enb CLI (e.g., with...
Plugin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Plugin: """Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obta...
stack_v2_sparse_classes_75kplus_train_003748
5,481
permissive
[ { "docstring": "Make a copy of this plugin into installation_dir, ready to be imported. By default, a verbatim copy of the source plugin's dir is made. Any previous contents in installation_dir are overwritten. Then any explicit requirements are met (external software may be downloaded and pip packages installe...
2
stack_v2_sparse_classes_30k_val_002338
Implement the Python class `Plugin` described below. Class description: Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of pl...
Implement the Python class `Plugin` described below. Class description: Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of pl...
35f9eecd93a3e8cc90631c3a819a36de1c40401f
<|skeleton|> class Plugin: """Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obta...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Plugin: """Plugins are self-contained, python modules that may assume enb is installed. - They can be installed into your projects via the enb CLI (e.g., with `enb plugin install <name> <clone_dir>`), and then imported like any other module. - The list of plugins available off-the-box can be obtained using th...
the_stack_v2_python_sparse
enb/plugins/plugin.py
esterjara/experiment-notebook
train
0
db13b1c29f3c8393d943bb6497f11772104e5255
[ "self.use_default = use_default\nself.included_cidr = included_cidr\nself.excluded_cidr = excluded_cidr", "if dictionary is None:\n return None\nuse_default = dictionary.get('useDefault')\nincluded_cidr = dictionary.get('includedCidr')\nexcluded_cidr = dictionary.get('excludedCidr')\nreturn cls(use_default, in...
<|body_start_0|> self.use_default = use_default self.included_cidr = included_cidr self.excluded_cidr = excluded_cidr <|end_body_0|> <|body_start_1|> if dictionary is None: return None use_default = dictionary.get('useDefault') included_cidr = dictionary.get(...
Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_default (bool): true/false whether to use special IPv4 addresses: https://tools.ietf.org/h...
ProtectedNetworksModel
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtectedNetworksModel: """Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_default (bool): true/false whether to us...
stack_v2_sparse_classes_75kplus_train_003749
2,461
permissive
[ { "docstring": "Constructor for the ProtectedNetworksModel class", "name": "__init__", "signature": "def __init__(self, use_default=None, included_cidr=None, excluded_cidr=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary re...
2
null
Implement the Python class `ProtectedNetworksModel` described below. Class description: Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_d...
Implement the Python class `ProtectedNetworksModel` described below. Class description: Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_d...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class ProtectedNetworksModel: """Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_default (bool): true/false whether to us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProtectedNetworksModel: """Implementation of the 'ProtectedNetworks' model. Set the included/excluded networks from the intrusion engine (optional - omitting will leave current config unchanged). This is available only in 'passthrough' mode Attributes: use_default (bool): true/false whether to use special IPv...
the_stack_v2_python_sparse
meraki_sdk/models/protected_networks_model.py
RaulCatalano/meraki-python-sdk
train
1
7855050aa19aabacc405f76bc8e7b56d9b1df5c4
[ "self.factory = RequestFactory()\nself.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password=\"Abdullah's passwd\")\nself.airline = Airline.objects.create(title='Summer Break', verified=True)\nself.airline_url = 'airlines:create_airline'\nself.review_url = 'airlines:create_review'", "sel...
<|body_start_0|> self.factory = RequestFactory() self.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password="Abdullah's passwd") self.airline = Airline.objects.create(title='Summer Break', verified=True) self.airline_url = 'airlines:create_airline' self....
Users add Airline and Review objects to the database.
AirlineAndReviewCreateTests
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AirlineAndReviewCreateTests: """Users add Airline and Review objects to the database.""" def setUp(self): """Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing.""" <|body_0|> def test_get_create_airline_form(self): """User req...
stack_v2_sparse_classes_75kplus_train_003750
8,369
permissive
[ { "docstring": "Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "User requests to see the form to add a new airline.", "name": "test_get_create_airline_form", "signature": "def te...
5
stack_v2_sparse_classes_30k_train_051573
Implement the Python class `AirlineAndReviewCreateTests` described below. Class description: Users add Airline and Review objects to the database. Method signatures and docstrings: - def setUp(self): Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing. - def test_get_create_airline...
Implement the Python class `AirlineAndReviewCreateTests` described below. Class description: Users add Airline and Review objects to the database. Method signatures and docstrings: - def setUp(self): Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing. - def test_get_create_airline...
65d933c64a3bf830f51ac237f5781ddfb69f342c
<|skeleton|> class AirlineAndReviewCreateTests: """Users add Airline and Review objects to the database.""" def setUp(self): """Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing.""" <|body_0|> def test_get_create_airline_form(self): """User req...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AirlineAndReviewCreateTests: """Users add Airline and Review objects to the database.""" def setUp(self): """Instantiate the Users, Airline, Review, and RequestFactory instances needed for testing.""" self.factory = RequestFactory() self.user = User.objects.create(username='Abdull...
the_stack_v2_python_sparse
travelly/airlines/tests.py
UPstartDeveloper/fiercely-souvenir
train
0
52b989eb48d45c51964beca7ce85a4cb7a654c78
[ "mtz_file = mtz.object()\nmtz_file.set_title(f'From {env.dispatcher_name}')\ndate_str = time.strftime('%Y-%m-%d at %H:%M:%S %Z')\nif time.strftime('%Z') != 'GMT':\n date_str += time.strftime(' (%Y-%m-%d at %H:%M:%S %Z)', time.gmtime())\nmtz_file.add_history(f'From {dials_version()}, run on {date_str}')\nmtz_fil...
<|body_start_0|> mtz_file = mtz.object() mtz_file.set_title(f'From {env.dispatcher_name}') date_str = time.strftime('%Y-%m-%d at %H:%M:%S %Z') if time.strftime('%Z') != 'GMT': date_str += time.strftime(' (%Y-%m-%d at %H:%M:%S %Z)', time.gmtime()) mtz_file.add_history...
Helper for adding metadata, crystals and datasets to an mtz file object.
MTZWriterBase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MTZWriterBase: """Helper for adding metadata, crystals and datasets to an mtz file object.""" def __init__(self, space_group, unit_cell=None): """If a unit cell is provided, will be used as default unless specified for each crystal.""" <|body_0|> def add_crystal(self, cr...
stack_v2_sparse_classes_75kplus_train_003751
23,243
permissive
[ { "docstring": "If a unit cell is provided, will be used as default unless specified for each crystal.", "name": "__init__", "signature": "def __init__(self, space_group, unit_cell=None)" }, { "docstring": "Add a crystal to the mtz file object.", "name": "add_crystal", "signature": "def ...
3
stack_v2_sparse_classes_30k_train_042385
Implement the Python class `MTZWriterBase` described below. Class description: Helper for adding metadata, crystals and datasets to an mtz file object. Method signatures and docstrings: - def __init__(self, space_group, unit_cell=None): If a unit cell is provided, will be used as default unless specified for each cry...
Implement the Python class `MTZWriterBase` described below. Class description: Helper for adding metadata, crystals and datasets to an mtz file object. Method signatures and docstrings: - def __init__(self, space_group, unit_cell=None): If a unit cell is provided, will be used as default unless specified for each cry...
e611c7680a02b5766a8f476557834daf6361d124
<|skeleton|> class MTZWriterBase: """Helper for adding metadata, crystals and datasets to an mtz file object.""" def __init__(self, space_group, unit_cell=None): """If a unit cell is provided, will be used as default unless specified for each crystal.""" <|body_0|> def add_crystal(self, cr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MTZWriterBase: """Helper for adding metadata, crystals and datasets to an mtz file object.""" def __init__(self, space_group, unit_cell=None): """If a unit cell is provided, will be used as default unless specified for each crystal.""" mtz_file = mtz.object() mtz_file.set_title(f'...
the_stack_v2_python_sparse
util/export_mtz.py
dagewa/dials
train
1
9c756a6141f5477340b66a77efaa26821bf7ef29
[ "work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)\nif not work_pool:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Work pool \"{work_pool_name}\" not found.')\nreturn work_pool.id", "work_pool = await models.workers.read_work_pool_b...
<|body_start_0|> work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name) if not work_pool: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Work pool "{work_pool_name}" not found.') return work_pool.id <|end_body_0|> ...
WorkerLookups
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkerLookups: async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: """Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).""" <|body_0|> async d...
stack_v2_sparse_classes_75kplus_train_003752
18,979
permissive
[ { "docstring": "Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).", "name": "_get_work_pool_id_from_name", "signature": "async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUI...
3
stack_v2_sparse_classes_30k_train_004553
Implement the Python class `WorkerLookups` described below. Class description: Implement the WorkerLookups class. Method signatures and docstrings: - async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing...
Implement the Python class `WorkerLookups` described below. Class description: Implement the WorkerLookups class. Method signatures and docstrings: - async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing...
2c50d2b64c811c364cbc5faa2b5c80a742572090
<|skeleton|> class WorkerLookups: async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: """Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).""" <|body_0|> async d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WorkerLookups: async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: """Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).""" work_pool = await models.workers.read...
the_stack_v2_python_sparse
src/prefect/server/api/workers.py
PrefectHQ/prefect
train
12,917
a3a7385e79a5496d92d8fa0b6500965a2dd01f3a
[ "super(My_attention, self).__init__()\nself.encoder_att = nn.Linear(encoder_dim, attention_dim)\nself.decoder_att = nn.Linear(decoder_dim, attention_dim)\nself.full_att = nn.Linear(attention_dim, 1)\nself.relu = nn.ReLU()\nself.softmax = nn.Softmax(dim=1)", "att1 = self.encoder_att(encoder_out)\natt2 = self.decod...
<|body_start_0|> super(My_attention, self).__init__() self.encoder_att = nn.Linear(encoder_dim, attention_dim) self.decoder_att = nn.Linear(decoder_dim, attention_dim) self.full_att = nn.Linear(attention_dim, 1) self.relu = nn.ReLU() self.softmax = nn.Softmax(dim=1) <|end...
Attention Network.
My_attention
[ "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class My_attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" <|body_0|> def forwa...
stack_v2_sparse_classes_75kplus_train_003753
30,636
permissive
[ { "docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network", "name": "__init__", "signature": "def __init__(self, encoder_dim, decoder_dim, attention_dim)" }, { "docstring": "Forward propagation...
2
stack_v2_sparse_classes_30k_train_048646
Implement the Python class `My_attention` described below. Class description: Attention Network. Method signatures and docstrings: - def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of t...
Implement the Python class `My_attention` described below. Class description: Attention Network. Method signatures and docstrings: - def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of t...
54e05d68c66c9cc5b9698e453981c0f1a6b216cf
<|skeleton|> class My_attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" <|body_0|> def forwa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class My_attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" super(My_attention, self).__init__() ...
the_stack_v2_python_sparse
src/model/decoder/decoder_vis_old.py
daniil-777/geneuclidean
train
0
ca33239d16e723674ac0b47248a63a19bb204b7c
[ "self.redshift = redshift\nself.light_profile_list = light_profile_list\nself.mass_profile_list = mass_profile_list", "if self.light_profile_list is not None:\n return sum(map(lambda p: p.image_from_grid(grid=grid), self.light_profile_list))\nreturn np.zeros((grid.shape[0],))", "if self.mass_profile_list is ...
<|body_start_0|> self.redshift = redshift self.light_profile_list = light_profile_list self.mass_profile_list = mass_profile_list <|end_body_0|> <|body_start_1|> if self.light_profile_list is not None: return sum(map(lambda p: p.image_from_grid(grid=grid), self.light_profile...
Galaxy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list ...
stack_v2_sparse_classes_75kplus_train_003754
2,345
no_license
[ { "docstring": "A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list of the galaxy's light profiles. mass_profile_list A list of the galaxy's mass profiles.", "name": "__init__", "signature": "def _...
3
stack_v2_sparse_classes_30k_train_000941
Implement the Python class `Galaxy` described below. Class description: Implement the Galaxy class. Method signatures and docstrings: - def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): A galaxy, which contains light and mass profiles at a specified ...
Implement the Python class `Galaxy` described below. Class description: Implement the Galaxy class. Method signatures and docstrings: - def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): A galaxy, which contains light and mass profiles at a specified ...
ac76dfef4643189a130ce18d23070bb81272a93c
<|skeleton|> class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list of the galaxy'...
the_stack_v2_python_sparse
projects/cosmology/src/galaxy.py
Jammy2211/autofit_workspace
train
6
e934afdf672100acc5c3383f840b000fcf000a7b
[ "n = len(nums)\nbuffer, res = ([0] * n, [0] * n)\nind = list(range(0, n))\n\ndef merge_sort(l, r):\n if l >= r:\n return\n m = l + (r - l >> 1)\n merge_sort(l, m)\n merge_sort(m + 1, r)\n i, j, k = (l, m + 1, 0)\n while i <= m:\n while j <= r and nums[ind[i]] > nums[ind[j]]:\n ...
<|body_start_0|> n = len(nums) buffer, res = ([0] * n, [0] * n) ind = list(range(0, n)) def merge_sort(l, r): if l >= r: return m = l + (r - l >> 1) merge_sort(l, m) merge_sort(m + 1, r) i, j, k = (l, m + 1, 0) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def countSmaller_with_binary_search(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums...
stack_v2_sparse_classes_75kplus_train_003755
2,379
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "countSmaller", "signature": "def countSmaller(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "countSmaller_with_binary_search", "signature": "def countSmaller_with_binary_search(self, nu...
2
stack_v2_sparse_classes_30k_train_029711
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSmaller(self, nums): :type nums: List[int] :rtype: List[int] - def countSmaller_with_binary_search(self, nums): :type nums: List[int] :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSmaller(self, nums): :type nums: List[int] :rtype: List[int] - def countSmaller_with_binary_search(self, nums): :type nums: List[int] :rtype: List[int] <|skeleton|> cla...
6c640581a642fc1a1c43e4b9f9f397b4d67bb67b
<|skeleton|> class Solution: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def countSmaller_with_binary_search(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int]""" n = len(nums) buffer, res = ([0] * n, [0] * n) ind = list(range(0, n)) def merge_sort(l, r): if l >= r: return m = l + (r - l >> 1) ...
the_stack_v2_python_sparse
python/315-counter-of-smaller-numbers-after-self.py
whiledoing/leetcode
train
0
3296013021e21a4b02247ad50aa6f1474999508f
[ "resource_args.AddConversionWorkspaceResourceArg(parser, 'to describe issues')\ncw_flags.AddCommitIdFlag(parser)\ncw_flags.AddUncomittedFlag(parser)\ncw_flags.AddFilterFlag(parser)\nparser.display_info.AddFormat('\\n table(\\n parentEntity:label=PARENT,\\n shortName:label=NAME,\\n ...
<|body_start_0|> resource_args.AddConversionWorkspaceResourceArg(parser, 'to describe issues') cw_flags.AddCommitIdFlag(parser) cw_flags.AddUncomittedFlag(parser) cw_flags.AddFilterFlag(parser) parser.display_info.AddFormat('\n table(\n parentEntity:label=PARE...
Describe issues in a Database Migration Service conversion workspace.
DescribeIssues
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DescribeIssues: """Describe issues in a Database Migration Service conversion workspace.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this ...
stack_v2_sparse_classes_75kplus_train_003756
3,120
permissive
[ { "docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.", "name": "Args", "signature": "def Args(parser)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_002824
Implement the Python class `DescribeIssues` described below. Class description: Describe issues in a Database Migration Service conversion workspace. Method signatures and docstrings: - def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use...
Implement the Python class `DescribeIssues` described below. Class description: Describe issues in a Database Migration Service conversion workspace. Method signatures and docstrings: - def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class DescribeIssues: """Describe issues in a Database Migration Service conversion workspace.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DescribeIssues: """Describe issues in a Database Migration Service conversion workspace.""" def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Posi...
the_stack_v2_python_sparse
lib/surface/database_migration/conversion_workspaces/describe_issues.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
d8984cecf28de1ce3a47112c5f4c4706c0c67f2b
[ "qs = super(NHDLakeManager, self).get_queryset().filter(ftype__in=[390, 436], parent=None, is_in_oregon=True)\nqs = qs.prefetch_related('county_set')\nqs = qs.extra(select={'is_important': 'has_mussels OR has_docs OR has_photos OR has_plants OR (aol_page IS NOT NULL)'}, order_by=['-is_important'])\nreturn qs", "q...
<|body_start_0|> qs = super(NHDLakeManager, self).get_queryset().filter(ftype__in=[390, 436], parent=None, is_in_oregon=True) qs = qs.prefetch_related('county_set') qs = qs.extra(select={'is_important': 'has_mussels OR has_docs OR has_photos OR has_plants OR (aol_page IS NOT NULL)'}, order_by=['...
NHDLakeManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NHDLakeManager: def get_queryset(self): """We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0_poster_6_2_2010.pdf We also only want to get lakes in oregon""" <|body_0|> def search(sel...
stack_v2_sparse_classes_75kplus_train_003757
19,344
no_license
[ { "docstring": "We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0_poster_6_2_2010.pdf We also only want to get lakes in oregon", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstr...
4
stack_v2_sparse_classes_30k_train_053783
Implement the Python class `NHDLakeManager` described below. Class description: Implement the NHDLakeManager class. Method signatures and docstrings: - def get_queryset(self): We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0...
Implement the Python class `NHDLakeManager` described below. Class description: Implement the NHDLakeManager class. Method signatures and docstrings: - def get_queryset(self): We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0...
d29538a502d028574e142baca508db5bfc4430ca
<|skeleton|> class NHDLakeManager: def get_queryset(self): """We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0_poster_6_2_2010.pdf We also only want to get lakes in oregon""" <|body_0|> def search(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NHDLakeManager: def get_queryset(self): """We only want to return lakes that are coded as LakePond or Reservoir which have the types 390, 436 in the NHD. See http://nhd.usgs.gov/NHDv2.0_poster_6_2_2010.pdf We also only want to get lakes in oregon""" qs = super(NHDLakeManager, self).get_queryse...
the_stack_v2_python_sparse
aol/lakes/models.py
conwayb/aol
train
0
40b63c91b082df3233ea7d3be1192db92e0e6fa1
[ "def _preorderTraversal(root, result):\n if not root:\n return result\n result.append(root.val)\n _preorderTraversal(root.left, result)\n _preorderTraversal(root.right, result)\n return result\nresult = []\nreturn _preorderTraversal(root, result)", "result, stack = ([], [root])\nwhile stack:...
<|body_start_0|> def _preorderTraversal(root, result): if not root: return result result.append(root.val) _preorderTraversal(root.left, result) _preorderTraversal(root.right, result) return result result = [] return _pre...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树;""" <|body_0|> def preorderTraversal2(self, root): """:type root: TreeNode :rtype List[int] (knowledge) 非递归解法 思路: 1. ...
stack_v2_sparse_classes_75kplus_train_003758
1,962
no_license
[ { "docstring": ":type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树;", "name": "preorderTraversal", "signature": "def preorderTraversal(self, root)" }, { "docstring": ":type root: TreeNode :rtype List[int] (knowledge) 非递归解法 思路: 1. 使用一个列表记录遍历过的值; ...
2
stack_v2_sparse_classes_30k_train_023395
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树; - def preorderTraversal2(self, root): :t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树; - def preorderTraversal2(self, root): :t...
19ea28c38762c65318275007932786e648a8b415
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树;""" <|body_0|> def preorderTraversal2(self, root): """:type root: TreeNode :rtype List[int] (knowledge) 非递归解法 思路: 1. ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype List[int] (knowledge) 思路: 1. 使用一个列表记录遍历过的值; 2. 每次先将当前节点的值加入结果集,然后递归遍历左右子树;""" def _preorderTraversal(root, result): if not root: return result result.append(root.val) ...
the_stack_v2_python_sparse
chapter9/7_binary-tree-preorder-traversal.py
SunnyQjm/algorithm-review
train
2
2b4892d09f731faadfd2f0200810abde0eaee104
[ "self.client = TcpClient(ip=ip, port=port, port_out=port_out, exceed_time=timeout)\nself.use_center = use_center\npass", "text, centers = parse_json(content)\nres = self.client.request([text])\nif self.use_center:\n res = center_json(res[0], centers)\nreturn res" ]
<|body_start_0|> self.client = TcpClient(ip=ip, port=port, port_out=port_out, exceed_time=timeout) self.use_center = use_center pass <|end_body_0|> <|body_start_1|> text, centers = parse_json(content) res = self.client.request([text]) if self.use_center: res ...
Predictor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Predictor: def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True): """初始化模型、配置""" <|body_0|> def predict(self, content: dict) -> dict: """输入标注格式,已转为dict 输出同标注格式,dict格式 :param content: :return str:""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_75kplus_train_003759
1,684
no_license
[ { "docstring": "初始化模型、配置", "name": "__init__", "signature": "def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True)" }, { "docstring": "输入标注格式,已转为dict 输出同标注格式,dict格式 :param content: :return str:", "name": "predict", "signature": "def predict(self, conte...
2
stack_v2_sparse_classes_30k_train_043395
Implement the Python class `Predictor` described below. Class description: Implement the Predictor class. Method signatures and docstrings: - def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True): 初始化模型、配置 - def predict(self, content: dict) -> dict: 输入标注格式,已转为dict 输出同标注格式,dict格式 :p...
Implement the Python class `Predictor` described below. Class description: Implement the Predictor class. Method signatures and docstrings: - def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True): 初始化模型、配置 - def predict(self, content: dict) -> dict: 输入标注格式,已转为dict 输出同标注格式,dict格式 :p...
5355abd4bc18f1294fe07f324c21ef88baa30f81
<|skeleton|> class Predictor: def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True): """初始化模型、配置""" <|body_0|> def predict(self, content: dict) -> dict: """输入标注格式,已转为dict 输出同标注格式,dict格式 :param content: :return str:""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Predictor: def __init__(self, ip='localhost', port=5555, port_out=5556, timeout=-1, use_center=True): """初始化模型、配置""" self.client = TcpClient(ip=ip, port=port, port_out=port_out, exceed_time=timeout) self.use_center = use_center pass def predict(self, content: dict) -> dict...
the_stack_v2_python_sparse
predictor.py
homzer/BERT-CRF
train
1
80d987c09743f66d7c7997655523d5e0aa163d1d
[ "result = 0\nfor i in xrange(0, len(nums)):\n for j in xrange(i + 1, len(nums)):\n result += self.findHammingDistance(nums[i] ^ nums[j])\nreturn result", "count = 0\nwhile num != 0:\n count += num & 1\n num >>= 1\nreturn count" ]
<|body_start_0|> result = 0 for i in xrange(0, len(nums)): for j in xrange(i + 1, len(nums)): result += self.findHammingDistance(nums[i] ^ nums[j]) return result <|end_body_0|> <|body_start_1|> count = 0 while num != 0: count += num & 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def totalHammingDistance(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findHammingDistance(self, num): """:param num: int :return: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> result = 0 for i in xrange...
stack_v2_sparse_classes_75kplus_train_003760
561
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "totalHammingDistance", "signature": "def totalHammingDistance(self, nums)" }, { "docstring": ":param num: int :return: int", "name": "findHammingDistance", "signature": "def findHammingDistance(self, num)" } ]
2
stack_v2_sparse_classes_30k_train_027495
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalHammingDistance(self, nums): :type nums: List[int] :rtype: int - def findHammingDistance(self, num): :param num: int :return: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalHammingDistance(self, nums): :type nums: List[int] :rtype: int - def findHammingDistance(self, num): :param num: int :return: int <|skeleton|> class Solution: def ...
0a833b8f666385500de5a55731b1a5590827b207
<|skeleton|> class Solution: def totalHammingDistance(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findHammingDistance(self, num): """:param num: int :return: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def totalHammingDistance(self, nums): """:type nums: List[int] :rtype: int""" result = 0 for i in xrange(0, len(nums)): for j in xrange(i + 1, len(nums)): result += self.findHammingDistance(nums[i] ^ nums[j]) return result def findHamm...
the_stack_v2_python_sparse
LeetCode-Python/477. Total Hamming Distance.py
KaranJaswani/Codes
train
0
8ec785a2db8cc441907ac8788750a33fe5528388
[ "try:\n import pypdf\nexcept ImportError:\n raise ValueError('pypdf package not found, please install it with `pip install pypdf`')\nself._file_path = file_path", "import pypdf\nwith open(self._file_path, 'rb') as pdf_file_obj:\n pdf_reader = pypdf.PdfReader(pdf_file_obj)\n return [Document(page_conte...
<|body_start_0|> try: import pypdf except ImportError: raise ValueError('pypdf package not found, please install it with `pip install pypdf`') self._file_path = file_path <|end_body_0|> <|body_start_1|> import pypdf with open(self._file_path, 'rb') as pdf...
Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas.
PagedPDFSplitter
[ "LicenseRef-scancode-generic-cla", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PagedPDFSplitter: """Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas.""" def __init__(self, file_path: str): """Initialize with file path.""" <|body_0|> def load(self) -> List[Document]: """Load given path as pag...
stack_v2_sparse_classes_75kplus_train_003761
1,152
permissive
[ { "docstring": "Initialize with file path.", "name": "__init__", "signature": "def __init__(self, file_path: str)" }, { "docstring": "Load given path as pages.", "name": "load", "signature": "def load(self) -> List[Document]" } ]
2
null
Implement the Python class `PagedPDFSplitter` described below. Class description: Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas. Method signatures and docstrings: - def __init__(self, file_path: str): Initialize with file path. - def load(self) -> List[Document]: L...
Implement the Python class `PagedPDFSplitter` described below. Class description: Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas. Method signatures and docstrings: - def __init__(self, file_path: str): Initialize with file path. - def load(self) -> List[Document]: L...
b8f29af7f3c24cf3a4554bebfa2053064467fbdb
<|skeleton|> class PagedPDFSplitter: """Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas.""" def __init__(self, file_path: str): """Initialize with file path.""" <|body_0|> def load(self) -> List[Document]: """Load given path as pag...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PagedPDFSplitter: """Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas.""" def __init__(self, file_path: str): """Initialize with file path.""" try: import pypdf except ImportError: raise ValueError('pypdf pa...
the_stack_v2_python_sparse
langchain/document_loaders/paged_pdf.py
microsoft/MM-REACT
train
705
53a18cd3e81f48926d87984ecbb2520100c8a375
[ "if new_level is not None:\n Msg.level = new_level\ntry:\n if Msg.nullfp is None:\n Msg.nullfp = open('/dev/null', 'w')\nexcept (IOError, OSError):\n Msg.chlderr = sys.stderr\n Msg.chldout = sys.stdout\n Msg.chldnul = sys.stderr\nelse:\n Msg.chlderr = Msg.nullfp\n Msg.chldout = Msg.nullf...
<|body_start_0|> if new_level is not None: Msg.level = new_level try: if Msg.nullfp is None: Msg.nullfp = open('/dev/null', 'w') except (IOError, OSError): Msg.chlderr = sys.stderr Msg.chldout = sys.stdout Msg.chldnul = ...
Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null
Msg
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Msg: """Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null""" def __init__(self, new_level=None): """Initia...
stack_v2_sparse_classes_75kplus_train_003762
2,136
permissive
[ { "docstring": "Initialize Msg level and /dev/null file pointers to be used in subprocess calls to obfuscate output and errors", "name": "__init__", "signature": "def __init__(self, new_level=None)" }, { "docstring": "Define debug level", "name": "setlevel", "signature": "def setlevel(se...
4
null
Implement the Python class `Msg` described below. Class description: Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null Method signatures and...
Implement the Python class `Msg` described below. Class description: Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null Method signatures and...
f50104a4ee9c83af207a2de1aef46e2f1ec67379
<|skeleton|> class Msg: """Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null""" def __init__(self, new_level=None): """Initia...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Msg: """Write messages to stdout and stderr. Allows to filter the messages to be displayed through a verbose level, also allows to control if child process that produce output through a file descriptor should be redirected to /dev/null""" def __init__(self, new_level=None): """Initialize Msg leve...
the_stack_v2_python_sparse
udocker/msg.py
indigo-dc/udocker
train
1,121
9195d92fbcaf14c4e970203f0d86e8062dc87da8
[ "super(CompoundForm, self).__init__(*args, **kwargs)\nself.compound = None\nself.chemSpider = ChemSpider(settings.CHEMSPIDER_TOKEN)\nself.fields['labGroup'].queryset = user.labgroup_set.all()\nif user.labgroup_set.all().exists():\n self.fields['labGroup'].empty_label = None", "searchResults = self.chemSpider.s...
<|body_start_0|> super(CompoundForm, self).__init__(*args, **kwargs) self.compound = None self.chemSpider = ChemSpider(settings.CHEMSPIDER_TOKEN) self.fields['labGroup'].queryset = user.labgroup_set.all() if user.labgroup_set.all().exists(): self.fields['labGroup'].em...
A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.
CompoundForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allo...
stack_v2_sparse_classes_75kplus_train_003763
9,303
no_license
[ { "docstring": "Overridden version of the init method allows us to place the user's lab groups as a restricted set.", "name": "__init__", "signature": "def __init__(self, user, *args, **kwargs)" }, { "docstring": "Check that the CSID is actually a valid id from chemspider.", "name": "clean_C...
4
stack_v2_sparse_classes_30k_train_030633
Implement the Python class `CompoundForm` described below. Class description: A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide. Method signatures and docstrings: - def __init__(self, user, *ar...
Implement the Python class `CompoundForm` described below. Class description: A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide. Method signatures and docstrings: - def __init__(self, user, *ar...
eae2009eadf87ffd2378233f3e153d385f4654d2
<|skeleton|> class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allows us to plac...
the_stack_v2_python_sparse
DRP/forms/compound/modelforms.py
zhaojhao/DRP
train
0
87d3fa012c78f75bc18022837963c26b26839da6
[ "threading.Thread.__init__(self, *args, **kw)\nself.queue = q\nself.workers = N\nself.sorting = sorting\nself.output = []", "while self.workers:\n p = self.queue.get()\n if p is None:\n self.workers -= 1\n else:\n self.output.append(p)\nprint('Length of Final String: {} chars'.format(len(se...
<|body_start_0|> threading.Thread.__init__(self, *args, **kw) self.queue = q self.workers = N self.sorting = sorting self.output = [] <|end_body_0|> <|body_start_1|> while self.workers: p = self.queue.get() if p is None: self.worke...
OutThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OutThread: def __init__(self, N, q, sorting=True, *args, **kw): """Initialize thread and save queue reference.""" <|body_0|> def run(self): """Extract items from the output queue and print until all done""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_003764
1,297
no_license
[ { "docstring": "Initialize thread and save queue reference.", "name": "__init__", "signature": "def __init__(self, N, q, sorting=True, *args, **kw)" }, { "docstring": "Extract items from the output queue and print until all done", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_020465
Implement the Python class `OutThread` described below. Class description: Implement the OutThread class. Method signatures and docstrings: - def __init__(self, N, q, sorting=True, *args, **kw): Initialize thread and save queue reference. - def run(self): Extract items from the output queue and print until all done
Implement the Python class `OutThread` described below. Class description: Implement the OutThread class. Method signatures and docstrings: - def __init__(self, N, q, sorting=True, *args, **kw): Initialize thread and save queue reference. - def run(self): Extract items from the output queue and print until all done ...
b32f83aa1b705a5ad384b73c618f04f7d2622753
<|skeleton|> class OutThread: def __init__(self, N, q, sorting=True, *args, **kw): """Initialize thread and save queue reference.""" <|body_0|> def run(self): """Extract items from the output queue and print until all done""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OutThread: def __init__(self, N, q, sorting=True, *args, **kw): """Initialize thread and save queue reference.""" threading.Thread.__init__(self, *args, **kw) self.queue = q self.workers = N self.sorting = sorting self.output = [] def run(self): """...
the_stack_v2_python_sparse
ostPython4/output.py
deepbsd/OST_Python
train
1
60a03e5b5fe81c9dc1e08ca8ed48f6f3e3442d15
[ "self.analyzer = analyzer\nself.running = True\nTealThread.__init__(self)\nreturn", "try:\n try:\n while self.running:\n func, item = self.analyzer.queue.get()\n try:\n func(item)\n except ThreadKilled:\n raise\n except:\n ...
<|body_start_0|> self.analyzer = analyzer self.running = True TealThread.__init__(self) return <|end_body_0|> <|body_start_1|> try: try: while self.running: func, item = self.analyzer.queue.get() try: ...
This class is used to spawn a separate thread to run the analyzer in
AnalyzerAsynch
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnalyzerAsynch: """This class is used to spawn a separate thread to run the analyzer in""" def __init__(self, analyzer): """Constructor""" <|body_0|> def run(self): """Wait on the input queue""" <|body_1|> <|end_skeleton|> <|body_start_0|> self....
stack_v2_sparse_classes_75kplus_train_003765
24,649
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, analyzer)" }, { "docstring": "Wait on the input queue", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_002144
Implement the Python class `AnalyzerAsynch` described below. Class description: This class is used to spawn a separate thread to run the analyzer in Method signatures and docstrings: - def __init__(self, analyzer): Constructor - def run(self): Wait on the input queue
Implement the Python class `AnalyzerAsynch` described below. Class description: This class is used to spawn a separate thread to run the analyzer in Method signatures and docstrings: - def __init__(self, analyzer): Constructor - def run(self): Wait on the input queue <|skeleton|> class AnalyzerAsynch: """This cl...
eba6c1489b503fdcf040a126942643b355867bcd
<|skeleton|> class AnalyzerAsynch: """This class is used to spawn a separate thread to run the analyzer in""" def __init__(self, analyzer): """Constructor""" <|body_0|> def run(self): """Wait on the input queue""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AnalyzerAsynch: """This class is used to spawn a separate thread to run the analyzer in""" def __init__(self, analyzer): """Constructor""" self.analyzer = analyzer self.running = True TealThread.__init__(self) return def run(self): """Wait on the input...
the_stack_v2_python_sparse
src/ibm/teal/analyzer/analyzer.py
ppjsand/pyteal
train
1
202f46bca7ca06dc9848361e4647c25c8c85317c
[ "expired, invalid, user = confirm_email_token_status(token)\nif not user or invalid:\n _abort(get_message('INVALID_CONFIRMATION_TOKEN'))\nalready_confirmed = user is not None and user.confirmed_at is not None\nif expired and (not already_confirmed):\n _abort(get_message('CONFIRMATION_EXPIRED', email=user.emai...
<|body_start_0|> expired, invalid, user = confirm_email_token_status(token) if not user or invalid: _abort(get_message('INVALID_CONFIRMATION_TOKEN')) already_confirmed = user is not None and user.confirmed_at is not None if expired and (not already_confirmed): _ab...
View that handles a email confirmation request.
ConfirmEmailView
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfirmEmailView: """View that handles a email confirmation request.""" def get_user(self, token=None, **kwargs): """Retrieve a user by the provided arguments.""" <|body_0|> def post(self, **kwargs): """Confirm user email.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_003766
19,229
permissive
[ { "docstring": "Retrieve a user by the provided arguments.", "name": "get_user", "signature": "def get_user(self, token=None, **kwargs)" }, { "docstring": "Confirm user email.", "name": "post", "signature": "def post(self, **kwargs)" } ]
2
null
Implement the Python class `ConfirmEmailView` described below. Class description: View that handles a email confirmation request. Method signatures and docstrings: - def get_user(self, token=None, **kwargs): Retrieve a user by the provided arguments. - def post(self, **kwargs): Confirm user email.
Implement the Python class `ConfirmEmailView` described below. Class description: View that handles a email confirmation request. Method signatures and docstrings: - def get_user(self, token=None, **kwargs): Retrieve a user by the provided arguments. - def post(self, **kwargs): Confirm user email. <|skeleton|> class...
3caced556fdc5fe5737416e8672fa8e4c03cdb7f
<|skeleton|> class ConfirmEmailView: """View that handles a email confirmation request.""" def get_user(self, token=None, **kwargs): """Retrieve a user by the provided arguments.""" <|body_0|> def post(self, **kwargs): """Confirm user email.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfirmEmailView: """View that handles a email confirmation request.""" def get_user(self, token=None, **kwargs): """Retrieve a user by the provided arguments.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: _abort(get_message('INV...
the_stack_v2_python_sparse
invenio_accounts/views/rest.py
inveniosoftware/invenio-accounts
train
5
0fac23f0c9200a8706078c2e92389f4385c455a8
[ "labextensions_path = labextensions_path or []\next_paths = []\nfor ext_dir in labextensions_path:\n theme_pattern = ext_dir + '/**/themes'\n ext_paths.extend([path for path in glob(theme_pattern, recursive=True)])\nif not isinstance(path, list):\n path = [path]\npath = ext_paths + path\nFileFindHandler.in...
<|body_start_0|> labextensions_path = labextensions_path or [] ext_paths = [] for ext_dir in labextensions_path: theme_pattern = ext_dir + '/**/themes' ext_paths.extend([path for path in glob(theme_pattern, recursive=True)]) if not isinstance(path, list): ...
A file handler that mangles local urls in CSS files.
ThemesHandler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThemesHandler: """A file handler that mangles local urls in CSS files.""" def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs): """Initialize the handler.""" <|body_0|> def get_content(self, abspath, s...
stack_v2_sparse_classes_75kplus_train_003767
3,206
permissive
[ { "docstring": "Initialize the handler.", "name": "initialize", "signature": "def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs)" }, { "docstring": "Retrieve the content of the requested resource which is located at the give...
4
stack_v2_sparse_classes_30k_train_042286
Implement the Python class `ThemesHandler` described below. Class description: A file handler that mangles local urls in CSS files. Method signatures and docstrings: - def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs): Initialize the handler. - ...
Implement the Python class `ThemesHandler` described below. Class description: A file handler that mangles local urls in CSS files. Method signatures and docstrings: - def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs): Initialize the handler. - ...
b3e9bc150e64c1c915ab600557ea267783939684
<|skeleton|> class ThemesHandler: """A file handler that mangles local urls in CSS files.""" def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs): """Initialize the handler.""" <|body_0|> def get_content(self, abspath, s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThemesHandler: """A file handler that mangles local urls in CSS files.""" def initialize(self, path, default_filename=None, no_cache_paths=None, themes_url=None, labextensions_path=None, **kwargs): """Initialize the handler.""" labextensions_path = labextensions_path or [] ext_pat...
the_stack_v2_python_sparse
jupyterlab_server/themes_handler.py
jupyterlab/jupyterlab_server
train
108
f2f2e397e5c3d816e0664f9b35e93a2710c3b6b4
[ "so_far = []\n\ndef dfs(node):\n if not node:\n so_far.append('None')\n return\n so_far.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ','.join(so_far)", "def create_tree(node_list):\n first_elem_val = node_list.pop(0)\n if first_elem_val == 'None':\n ...
<|body_start_0|> so_far = [] def dfs(node): if not node: so_far.append('None') return so_far.append(str(node.val)) dfs(node.left) dfs(node.right) dfs(root) return ','.join(so_far) <|end_body_0|> <|body_star...
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_003768
2,410
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_025323
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:...
a5635356953df472e71d49c8db3b493ac59b860f
<|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""" so_far = [] def dfs(node): if not node: so_far.append('None') return so_far.append(str(node.val)) dfs(node.le...
the_stack_v2_python_sparse
python/tree/q449_serialize_second.py
ksparkje/leetcode-practice
train
1
68024d45a6397e03ccc2bd7a7bfe9c0bd4ec51c5
[ "list_ = List.objects.create()\nfirst_item = Item.objects.create(text='Hai', list=list_)\nnew_item = {'item_text': 'new item!'}\nself.client.post(f'/lists/{list_.id}/add_item', data=new_item)\nresponse = self.client.get(f'/lists/{list_.id}/')\nself.assertEqual(response.status_code, 200)\nself.assertContains(respons...
<|body_start_0|> list_ = List.objects.create() first_item = Item.objects.create(text='Hai', list=list_) new_item = {'item_text': 'new item!'} self.client.post(f'/lists/{list_.id}/add_item', data=new_item) response = self.client.get(f'/lists/{list_.id}/') self.assertEqual(...
Tests the addition of new items to a current list
NewItemTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewItemTest: """Tests the addition of new items to a current list""" def test_can_save_a_post_request_to_an_existing_list(self): """as written by me!""" <|body_0|> def test_can_save_a_post_request_to_an_existing_list_book(self): """as appears on the book""" ...
stack_v2_sparse_classes_75kplus_train_003769
6,998
no_license
[ { "docstring": "as written by me!", "name": "test_can_save_a_post_request_to_an_existing_list", "signature": "def test_can_save_a_post_request_to_an_existing_list(self)" }, { "docstring": "as appears on the book", "name": "test_can_save_a_post_request_to_an_existing_list_book", "signatur...
3
null
Implement the Python class `NewItemTest` described below. Class description: Tests the addition of new items to a current list Method signatures and docstrings: - def test_can_save_a_post_request_to_an_existing_list(self): as written by me! - def test_can_save_a_post_request_to_an_existing_list_book(self): as appears...
Implement the Python class `NewItemTest` described below. Class description: Tests the addition of new items to a current list Method signatures and docstrings: - def test_can_save_a_post_request_to_an_existing_list(self): as written by me! - def test_can_save_a_post_request_to_an_existing_list_book(self): as appears...
41651b51cade98cd4fe22c248ac67ba90ce68f25
<|skeleton|> class NewItemTest: """Tests the addition of new items to a current list""" def test_can_save_a_post_request_to_an_existing_list(self): """as written by me!""" <|body_0|> def test_can_save_a_post_request_to_an_existing_list_book(self): """as appears on the book""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NewItemTest: """Tests the addition of new items to a current list""" def test_can_save_a_post_request_to_an_existing_list(self): """as written by me!""" list_ = List.objects.create() first_item = Item.objects.create(text='Hai', list=list_) new_item = {'item_text': 'new ite...
the_stack_v2_python_sparse
tdd-python/project01/superlists/lists/tests.py
fbidu/Etudes
train
2
e94d8964679264d6e5b9a26d94c73a57982fc7bc
[ "new_list = sorted(points, key=lambda point: (point[0], point[1]))\nprint(new_list)\nif len(new_list) <= 0:\n return 0\nend = new_list[0][1]\ncount = 1\nfor i in new_list[1:]:\n if i[0] <= end:\n end = min(end, i[1])\n continue\n else:\n count += 1\n end = i[1]\nreturn count", ...
<|body_start_0|> new_list = sorted(points, key=lambda point: (point[0], point[1])) print(new_list) if len(new_list) <= 0: return 0 end = new_list[0][1] count = 1 for i in new_list[1:]: if i[0] <= end: end = min(end, i[1]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findMinArrowShots(self, points): """:type points: List[List[int]] :rtype: int 209ms""" <|body_0|> def findMinArrowShots_1(self, points): """:type points: List[List[int]] :rtype: int 122ms""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_003770
2,261
no_license
[ { "docstring": ":type points: List[List[int]] :rtype: int 209ms", "name": "findMinArrowShots", "signature": "def findMinArrowShots(self, points)" }, { "docstring": ":type points: List[List[int]] :rtype: int 122ms", "name": "findMinArrowShots_1", "signature": "def findMinArrowShots_1(self...
2
stack_v2_sparse_classes_30k_train_015092
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 209ms - def findMinArrowShots_1(self, points): :type points: List[List[int]] :rtype: int 122ms
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int 209ms - def findMinArrowShots_1(self, points): :type points: List[List[int]] :rtype: int 122ms <|s...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def findMinArrowShots(self, points): """:type points: List[List[int]] :rtype: int 209ms""" <|body_0|> def findMinArrowShots_1(self, points): """:type points: List[List[int]] :rtype: int 122ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findMinArrowShots(self, points): """:type points: List[List[int]] :rtype: int 209ms""" new_list = sorted(points, key=lambda point: (point[0], point[1])) print(new_list) if len(new_list) <= 0: return 0 end = new_list[0][1] count = 1 ...
the_stack_v2_python_sparse
Minimum NumberOfArrowsToBurstBalloons_MID_452.py
953250587/leetcode-python
train
2
8eeb7cdcd401bb143d843667d6ab05850e646e07
[ "tkinter.ttk.Frame.__init__(self, parent)\nself.parent = parent\nself.var = var\nself.funcs = funcs\nself.kwargs = kwargs\nself.label = tkinter.ttk.Label(self, textvariable=self.var, **self.kwargs)\nself.entry = tkinter.ttk.Entry(self, textvariable=self.var, **self.kwargs)\nself.label.bind('<Double-Button-1>', self...
<|body_start_0|> tkinter.ttk.Frame.__init__(self, parent) self.parent = parent self.var = var self.funcs = funcs self.kwargs = kwargs self.label = tkinter.ttk.Label(self, textvariable=self.var, **self.kwargs) self.entry = tkinter.ttk.Entry(self, textvariable=self....
ModifiableLabel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModifiableLabel: def __init__(self, parent, var, funcs=(None, None), **kwargs): """:param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of two functions called :param kwargs: passed to entry and label widgets""" <|body_0|> def sh...
stack_v2_sparse_classes_75kplus_train_003771
36,391
permissive
[ { "docstring": ":param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of two functions called :param kwargs: passed to entry and label widgets", "name": "__init__", "signature": "def __init__(self, parent, var, funcs=(None, None), **kwargs)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_052408
Implement the Python class `ModifiableLabel` described below. Class description: Implement the ModifiableLabel class. Method signatures and docstrings: - def __init__(self, parent, var, funcs=(None, None), **kwargs): :param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of...
Implement the Python class `ModifiableLabel` described below. Class description: Implement the ModifiableLabel class. Method signatures and docstrings: - def __init__(self, parent, var, funcs=(None, None), **kwargs): :param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of...
c6d8091239712df209914fcf6490c0fdca92c741
<|skeleton|> class ModifiableLabel: def __init__(self, parent, var, funcs=(None, None), **kwargs): """:param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of two functions called :param kwargs: passed to entry and label widgets""" <|body_0|> def sh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ModifiableLabel: def __init__(self, parent, var, funcs=(None, None), **kwargs): """:param parent: parent frame or window :param var: variable stocking the string :param funcs: tuple of two functions called :param kwargs: passed to entry and label widgets""" tkinter.ttk.Frame.__init__(self, par...
the_stack_v2_python_sparse
tkinter_utilities.py
PyDEF/PyDEF-2.0
train
1
a8a148c64de5c00d6e3e3fb29f6fa235012c3aa1
[ "self.front = -1\nself.rare = -1\nself.max_size = 5\nself.queue = [0] * self.max_size", "if self.front == 0 and self.rare == self.max_size - 1 or self.front == self.rare + 1:\n print('Overflow')\nelse:\n if self.front == -1:\n self.front = 0\n self.rare = 0\n elif self.rare == self.max_size...
<|body_start_0|> self.front = -1 self.rare = -1 self.max_size = 5 self.queue = [0] * self.max_size <|end_body_0|> <|body_start_1|> if self.front == 0 and self.rare == self.max_size - 1 or self.front == self.rare + 1: print('Overflow') else: if sel...
This class contains functions for doubly ended queue.
deQueue
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def insert_rare(self, item): """This function inserts at the rare position. Argum...
stack_v2_sparse_classes_75kplus_train_003772
3,636
no_license
[ { "docstring": "Constructor function. Argument: self -- represents the object of the class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function inserts at the rare position. Arguments: self -- represents the object of the class. item -- integer value, the val...
6
stack_v2_sparse_classes_30k_train_018368
Implement the Python class `deQueue` described below. Class description: This class contains functions for doubly ended queue. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def insert_rare(self, item): This function inserts at the...
Implement the Python class `deQueue` described below. Class description: This class contains functions for doubly ended queue. Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def insert_rare(self, item): This function inserts at the...
6870426104aef417086788221dad29e887ddfe3f
<|skeleton|> class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def insert_rare(self, item): """This function inserts at the rare position. Argum...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class deQueue: """This class contains functions for doubly ended queue.""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" self.front = -1 self.rare = -1 self.max_size = 5 self.queue = [0] * self.max_size def ins...
the_stack_v2_python_sparse
Data Structure/03. Queue/03. Doubly Ended Queue/py_code.py
Slothfulwave612/Coding-Problems
train
5
b956596338ec082f9ab18daa3abece65b6978826
[ "employees = []\ntry:\n with transaction.atomic():\n for employee in data['employees']:\n user = self.find_or_create_user(employee['email'])\n token, _ = Token.objects.get_or_create(user=user)\n company = Company.objects.get(id=data['company_id'])\n self.__creat...
<|body_start_0|> employees = [] try: with transaction.atomic(): for employee in data['employees']: user = self.find_or_create_user(employee['email']) token, _ = Token.objects.get_or_create(user=user) company = Compan...
Employees serializer list.
EmployeesSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmployeesSerializer: """Employees serializer list.""" def create(self, data): """Create employees.""" <|body_0|> def to_representation(self, instance): """Represent serializer data.""" <|body_1|> def find_or_create_user(self, email): """Find ...
stack_v2_sparse_classes_75kplus_train_003773
3,659
no_license
[ { "docstring": "Create employees.", "name": "create", "signature": "def create(self, data)" }, { "docstring": "Represent serializer data.", "name": "to_representation", "signature": "def to_representation(self, instance)" }, { "docstring": "Find or create user by email.", "na...
5
stack_v2_sparse_classes_30k_train_040368
Implement the Python class `EmployeesSerializer` described below. Class description: Employees serializer list. Method signatures and docstrings: - def create(self, data): Create employees. - def to_representation(self, instance): Represent serializer data. - def find_or_create_user(self, email): Find or create user ...
Implement the Python class `EmployeesSerializer` described below. Class description: Employees serializer list. Method signatures and docstrings: - def create(self, data): Create employees. - def to_representation(self, instance): Represent serializer data. - def find_or_create_user(self, email): Find or create user ...
252b0ebd77eefbcc945a0efc3068cc3421f46d5f
<|skeleton|> class EmployeesSerializer: """Employees serializer list.""" def create(self, data): """Create employees.""" <|body_0|> def to_representation(self, instance): """Represent serializer data.""" <|body_1|> def find_or_create_user(self, email): """Find ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EmployeesSerializer: """Employees serializer list.""" def create(self, data): """Create employees.""" employees = [] try: with transaction.atomic(): for employee in data['employees']: user = self.find_or_create_user(employee['email']...
the_stack_v2_python_sparse
app/companies/serializers/employees_serializer.py
vsokoltsov/Interview360Server
train
2
34e0d578c4c401fbd18d61e0b2ed758f5523bb73
[ "instance = get_object_or_404(Mapping, pk=pk)\ndata = request.data\nif request.FILES or 'files' in data:\n return self.partial_update_with_files(request, instance)\nif 'xforms' not in data:\n return Response(data={'xforms': [_('This field is required')]}, status=status.HTTP_400_BAD_REQUEST)\nreturn self.parti...
<|body_start_0|> instance = get_object_or_404(Mapping, pk=pk) data = request.data if request.FILES or 'files' in data: return self.partial_update_with_files(request, instance) if 'xforms' not in data: return Response(data={'xforms': [_('This field is required')]},...
Create new Mapping entries.
MappingViewSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MappingViewSet: """Create new Mapping entries.""" def partial_update(self, request, pk, *args, **kwargs): """We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multipart format The first case will be straight forward, the s...
stack_v2_sparse_classes_75kplus_train_003774
15,950
permissive
[ { "docstring": "We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multipart format The first case will be straight forward, the second one will imply FILES. This means that only a list with the xform id and the file will be sent. The xforms will be c...
3
null
Implement the Python class `MappingViewSet` described below. Class description: Create new Mapping entries. Method signatures and docstrings: - def partial_update(self, request, pk, *args, **kwargs): We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multip...
Implement the Python class `MappingViewSet` described below. Class description: Create new Mapping entries. Method signatures and docstrings: - def partial_update(self, request, pk, *args, **kwargs): We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multip...
36cc8c2d7d9fb4f7bd9cf6019f8d726e18540dc9
<|skeleton|> class MappingViewSet: """Create new Mapping entries.""" def partial_update(self, request, pk, *args, **kwargs): """We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multipart format The first case will be straight forward, the s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MappingViewSet: """Create new Mapping entries.""" def partial_update(self, request, pk, *args, **kwargs): """We are posting the xForms in only one call, to update them all together. There are two options: - JSON format - Multipart format The first case will be straight forward, the second one wil...
the_stack_v2_python_sparse
aether-odk-module/aether/odk/api/views.py
zabi-kamran/aether
train
0
3bf4e22d92209198c370e2ad995abc2083cb1475
[ "if 'partial_game_from' in kwargs.keys():\n self.game = kwargs['partial_game_from']\n self.attacker_types = kwargs['attacker_types']\n self._create_partial_game()\nelif 'game' in kwargs.keys():\n self.game = kwargs['game']\n if self.game.type == 'compact':\n self._compact_to_normal()\n ...
<|body_start_0|> if 'partial_game_from' in kwargs.keys(): self.game = kwargs['partial_game_from'] self.attacker_types = kwargs['attacker_types'] self._create_partial_game() elif 'game' in kwargs.keys(): self.game = kwargs['game'] if self.game.t...
NormalFormGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NormalFormGame: def __init__(self, **kwargs): """Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in normalform. Otherwise, generate a random game given arguments.""" <|body_0|> def _generate_...
stack_v2_sparse_classes_75kplus_train_003775
16,375
no_license
[ { "docstring": "Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in normalform. Otherwise, generate a random game given arguments.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring"...
6
stack_v2_sparse_classes_30k_train_030294
Implement the Python class `NormalFormGame` described below. Class description: Implement the NormalFormGame class. Method signatures and docstrings: - def __init__(self, **kwargs): Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in n...
Implement the Python class `NormalFormGame` described below. Class description: Implement the NormalFormGame class. Method signatures and docstrings: - def __init__(self, **kwargs): Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in n...
44a0df025ca73065f291994df103dcb39da59b55
<|skeleton|> class NormalFormGame: def __init__(self, **kwargs): """Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in normalform. Otherwise, generate a random game given arguments.""" <|body_0|> def _generate_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NormalFormGame: def __init__(self, **kwargs): """Transform given game into normalform if it's compact form, Conduct harsanyi transformation if requested or if given game is already in normalform. Otherwise, generate a random game given arguments.""" if 'partial_game_from' in kwargs.keys(): ...
the_stack_v2_python_sparse
games.py
adriangonciarz/game_theory
train
0
1a98cc9ab99016897fb2d2a97ac2904ffffa5978
[ "filename = 'rented_items.csv'\nfile = open(filename, 'a')\nfile.close()\nwith open('test_items.csv', 'a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(['LR04', 'Leather Sofa', 25.0])\n writer.writerow(['KT78', 'Kitchen Tablee', 10.0])\n writer.writerow(['BR02', 'Queen Mattress', 1...
<|body_start_0|> filename = 'rented_items.csv' file = open(filename, 'a') file.close() with open('test_items.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow(['LR04', 'Leather Sofa', 25.0]) writer.writerow(['KT78', 'Kitchen Tab...
Tests the inventory functionalities
TestInventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInventory: """Tests the inventory functionalities""" def setUp(self): """Sets up the environment for testing""" <|body_0|> def tearDown(self): """Tears down all creations for testing""" <|body_1|> def test_add_furniture(self): """test to ...
stack_v2_sparse_classes_75kplus_train_003776
2,415
no_license
[ { "docstring": "Sets up the environment for testing", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Tears down all creations for testing", "name": "tearDown", "signature": "def tearDown(self)" }, { "docstring": "test to make sure an entry is added to the file...
4
stack_v2_sparse_classes_30k_train_043623
Implement the Python class `TestInventory` described below. Class description: Tests the inventory functionalities Method signatures and docstrings: - def setUp(self): Sets up the environment for testing - def tearDown(self): Tears down all creations for testing - def test_add_furniture(self): test to make sure an en...
Implement the Python class `TestInventory` described below. Class description: Tests the inventory functionalities Method signatures and docstrings: - def setUp(self): Sets up the environment for testing - def tearDown(self): Tears down all creations for testing - def test_add_furniture(self): test to make sure an en...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class TestInventory: """Tests the inventory functionalities""" def setUp(self): """Sets up the environment for testing""" <|body_0|> def tearDown(self): """Tears down all creations for testing""" <|body_1|> def test_add_furniture(self): """test to ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestInventory: """Tests the inventory functionalities""" def setUp(self): """Sets up the environment for testing""" filename = 'rented_items.csv' file = open(filename, 'a') file.close() with open('test_items.csv', 'a', newline='') as file: writer = csv....
the_stack_v2_python_sparse
students/humberto_gonzalez/lesson08/test_unit.py
JavaRod/SP_Python220B_2019
train
1
bac7b55908cf76bd816555628da09384d3d2d77d
[ "def path(x: int, y: int) -> int:\n if x == 0 or y == 0:\n return 1\n return path(x - 1, y) + path(x, y - 1)\nreturn path(m - 1, n - 1)", "if m == 0 or n == 0:\n return 0\ndp = [[0] * n for _ in range(m)]\nfor i in range(m):\n dp[i][0] = 1\nfor i in range(n):\n dp[0][i] = 1\nfor i in range(1...
<|body_start_0|> def path(x: int, y: int) -> int: if x == 0 or y == 0: return 1 return path(x - 1, y) + path(x, y - 1) return path(m - 1, n - 1) <|end_body_0|> <|body_start_1|> if m == 0 or n == 0: return 0 dp = [[0] * n for _ in range...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def uniquePaths(self, m: int, n: int) -> int: """递归""" <|body_0|> def uniquePaths_2(self, m: int, n: int) -> int: """动态规划, 时间复杂度O(m*n), 空间复杂度O(m*n)""" <|body_1|> def uniquePaths_3(self, m: int, n: int) -> int: """优化动态规划, 通过画表可以将空间复杂度优化为...
stack_v2_sparse_classes_75kplus_train_003777
2,196
no_license
[ { "docstring": "递归", "name": "uniquePaths", "signature": "def uniquePaths(self, m: int, n: int) -> int" }, { "docstring": "动态规划, 时间复杂度O(m*n), 空间复杂度O(m*n)", "name": "uniquePaths_2", "signature": "def uniquePaths_2(self, m: int, n: int) -> int" }, { "docstring": "优化动态规划, 通过画表可以将空间复...
3
stack_v2_sparse_classes_30k_train_000469
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m: int, n: int) -> int: 递归 - def uniquePaths_2(self, m: int, n: int) -> int: 动态规划, 时间复杂度O(m*n), 空间复杂度O(m*n) - def uniquePaths_3(self, m: int, n: int) -> int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m: int, n: int) -> int: 递归 - def uniquePaths_2(self, m: int, n: int) -> int: 动态规划, 时间复杂度O(m*n), 空间复杂度O(m*n) - def uniquePaths_3(self, m: int, n: int) -> int...
13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08
<|skeleton|> class Solution: def uniquePaths(self, m: int, n: int) -> int: """递归""" <|body_0|> def uniquePaths_2(self, m: int, n: int) -> int: """动态规划, 时间复杂度O(m*n), 空间复杂度O(m*n)""" <|body_1|> def uniquePaths_3(self, m: int, n: int) -> int: """优化动态规划, 通过画表可以将空间复杂度优化为...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def uniquePaths(self, m: int, n: int) -> int: """递归""" def path(x: int, y: int) -> int: if x == 0 or y == 0: return 1 return path(x - 1, y) + path(x, y - 1) return path(m - 1, n - 1) def uniquePaths_2(self, m: int, n: int) -> int: ...
the_stack_v2_python_sparse
Algorithms/62_Unique_Paths/Unique_Paths.py
lirui-ML/my_leetcode
train
1
12163a0ec70b6745928f98b90f40bab8f2833585
[ "super(SMPLFlow, self).__init__()\nself.cfg = cfg\nself.npose = 6 * (cfg.SMPL.NUM_BODY_JOINTS + 1)\nself.flow = ConditionalGlow(cfg.MODEL.FLOW.DIM, cfg.MODEL.FLOW.LAYER_HIDDEN_FEATURES, cfg.MODEL.FLOW.NUM_LAYERS, cfg.MODEL.FLOW.LAYER_DEPTH, context_features=cfg.MODEL.FLOW.CONTEXT_FEATURES)\nself.fc_head = FCHead(cf...
<|body_start_0|> super(SMPLFlow, self).__init__() self.cfg = cfg self.npose = 6 * (cfg.SMPL.NUM_BODY_JOINTS + 1) self.flow = ConditionalGlow(cfg.MODEL.FLOW.DIM, cfg.MODEL.FLOW.LAYER_HIDDEN_FEATURES, cfg.MODEL.FLOW.NUM_LAYERS, cfg.MODEL.FLOW.LAYER_DEPTH, context_features=cfg.MODEL.FLOW.CO...
SMPLFlow
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SMPLFlow: def __init__(self, cfg: CfgNode): """Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode.""" <|body_0|> def log_prob(self, smpl_params: Dict, feats: torch.Tensor) -> Tuple: """Compute the log-probability of a s...
stack_v2_sparse_classes_75kplus_train_003778
4,412
permissive
[ { "docstring": "Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode.", "name": "__init__", "signature": "def __init__(self, cfg: CfgNode)" }, { "docstring": "Compute the log-probability of a set of smpl_params given a batch of images. Args: smpl_par...
3
stack_v2_sparse_classes_30k_train_018213
Implement the Python class `SMPLFlow` described below. Class description: Implement the SMPLFlow class. Method signatures and docstrings: - def __init__(self, cfg: CfgNode): Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode. - def log_prob(self, smpl_params: Dict, feat...
Implement the Python class `SMPLFlow` described below. Class description: Implement the SMPLFlow class. Method signatures and docstrings: - def __init__(self, cfg: CfgNode): Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode. - def log_prob(self, smpl_params: Dict, feat...
dac2409c0b451b6dd5d91f03cbe7132aa495792f
<|skeleton|> class SMPLFlow: def __init__(self, cfg: CfgNode): """Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode.""" <|body_0|> def log_prob(self, smpl_params: Dict, feats: torch.Tensor) -> Tuple: """Compute the log-probability of a s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SMPLFlow: def __init__(self, cfg: CfgNode): """Probabilistic SMPL head using Normalizing Flows. Args: cfg (CfgNode): Model config as yacs CfgNode.""" super(SMPLFlow, self).__init__() self.cfg = cfg self.npose = 6 * (cfg.SMPL.NUM_BODY_JOINTS + 1) self.flow = ConditionalG...
the_stack_v2_python_sparse
prohmr/models/heads/smpl_flow.py
goyallon/ProHMR
train
0
9c2645d349bde35c198a6ddce725eb846ecb36f0
[ "self = object.__new__(cls)\nself.name = name\nself.value = value\nself.args = args\nreturn self", "repr_parts = [self.__class__.__name__, '(', repr(self.value), ', ', repr(self.name)]\nargs = self.args\nfor arg in args:\n repr_parts.append(', ')\n repr_parts.append(repr(arg))\nrepr_parts.append(')')\nretur...
<|body_start_0|> self = object.__new__(cls) self.name = name self.value = value self.args = args return self <|end_body_0|> <|body_start_1|> repr_parts = [self.__class__.__name__, '(', repr(self.value), ', ', repr(self.name)] args = self.args for arg in a...
name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with.
Preinstance
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Preinstance: """name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with.""" def __new__(cls, value, name, *args): """Creates a new ``Preinstance`` with the given parameters. Parameters ---------- v...
stack_v2_sparse_classes_75kplus_train_003779
8,693
permissive
[ { "docstring": "Creates a new ``Preinstance`` with the given parameters. Parameters ---------- value : `str`, `int` The instance's value. name : `str` The instance's name. *args : Parameters Additional parameters to preinstance with.", "name": "__new__", "signature": "def __new__(cls, value, name, *args...
2
stack_v2_sparse_classes_30k_train_043656
Implement the Python class `Preinstance` described below. Class description: name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with. Method signatures and docstrings: - def __new__(cls, value, name, *args): Creates a new ``Preinst...
Implement the Python class `Preinstance` described below. Class description: name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with. Method signatures and docstrings: - def __new__(cls, value, name, *args): Creates a new ``Preinst...
53f24fdb38459dc5a4fd04f11bdbfee8295b76a4
<|skeleton|> class Preinstance: """name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with.""" def __new__(cls, value, name, *args): """Creates a new ``Preinstance`` with the given parameters. Parameters ---------- v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Preinstance: """name : `str` The instance's name. value : `str`, `int` The instance's value. args : `tuple` of `Any` Additional parameters to preinstance with.""" def __new__(cls, value, name, *args): """Creates a new ``Preinstance`` with the given parameters. Parameters ---------- value : `str`,...
the_stack_v2_python_sparse
hata/discord/bases/preinstanced.py
HuyaneMatsu/hata
train
3
e77a820a86d3222217a9fbe36cc494e583f4c6c5
[ "try:\n date = ElectionDay.objects.get(date=self.kwargs['date'])\nexcept:\n raise APIException('No elections on {}.'.format(self.kwargs['date']))\nbody_ids = []\nfor election in date.elections.all():\n body = election.race.office.body\n if body:\n body_ids.append(body.uid)\nreturn Body.objects.fi...
<|body_start_0|> try: date = ElectionDay.objects.get(date=self.kwargs['date']) except: raise APIException('No elections on {}.'.format(self.kwargs['date'])) body_ids = [] for election in date.elections.all(): body = election.race.office.body ...
BodyMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BodyMixin: def get_queryset(self): """Returns a queryset of all bodies holding an election on a date.""" <|body_0|> def get_serializer_context(self): """Adds ``election_day`` to serializer context.""" <|body_1|> <|end_skeleton|> <|body_start_0|> try...
stack_v2_sparse_classes_75kplus_train_003780
5,447
no_license
[ { "docstring": "Returns a queryset of all bodies holding an election on a date.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Adds ``election_day`` to serializer context.", "name": "get_serializer_context", "signature": "def get_serializer_context(sel...
2
stack_v2_sparse_classes_30k_train_038749
Implement the Python class `BodyMixin` described below. Class description: Implement the BodyMixin class. Method signatures and docstrings: - def get_queryset(self): Returns a queryset of all bodies holding an election on a date. - def get_serializer_context(self): Adds ``election_day`` to serializer context.
Implement the Python class `BodyMixin` described below. Class description: Implement the BodyMixin class. Method signatures and docstrings: - def get_queryset(self): Returns a queryset of all bodies holding an election on a date. - def get_serializer_context(self): Adds ``election_day`` to serializer context. <|skel...
9137a0c59e044d081d6c34f0e9e97b789e69bdbf
<|skeleton|> class BodyMixin: def get_queryset(self): """Returns a queryset of all bodies holding an election on a date.""" <|body_0|> def get_serializer_context(self): """Adds ``election_day`` to serializer context.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BodyMixin: def get_queryset(self): """Returns a queryset of all bodies holding an election on a date.""" try: date = ElectionDay.objects.get(date=self.kwargs['date']) except: raise APIException('No elections on {}.'.format(self.kwargs['date'])) body_ids ...
the_stack_v2_python_sparse
theshow/viewsets.py
The-Politico/politico-elections
train
0
7f84373b522c4f315b7cafc9536a6a957bf152d2
[ "if data:\n useragent = data['useragent']\n print(useragent)\n if 'mobile' in useragent:\n return packinfo(infostatus=2, infomsg='此系统不支持移动端浏览器!请切换至计算机上使用。')\n elif 'firefox' in useragent:\n return packinfo(infostatus=1, infomsg='支持的浏览器')\n elif 'edge' in useragent:\n return packi...
<|body_start_0|> if data: useragent = data['useragent'] print(useragent) if 'mobile' in useragent: return packinfo(infostatus=2, infomsg='此系统不支持移动端浏览器!请切换至计算机上使用。') elif 'firefox' in useragent: return packinfo(infostatus=1, infomsg=...
LoginDAO
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoginDAO: def checkuseragent(data): """检测浏览器""" <|body_0|> def checktoken(username, token): """检测admin的token""" <|body_1|> def logout(token, username, req): """用户退出""" <|body_2|> def login(username, password, req): """用户登录"""...
stack_v2_sparse_classes_75kplus_train_003781
3,343
no_license
[ { "docstring": "检测浏览器", "name": "checkuseragent", "signature": "def checkuseragent(data)" }, { "docstring": "检测admin的token", "name": "checktoken", "signature": "def checktoken(username, token)" }, { "docstring": "用户退出", "name": "logout", "signature": "def logout(token, us...
4
stack_v2_sparse_classes_30k_train_007320
Implement the Python class `LoginDAO` described below. Class description: Implement the LoginDAO class. Method signatures and docstrings: - def checkuseragent(data): 检测浏览器 - def checktoken(username, token): 检测admin的token - def logout(token, username, req): 用户退出 - def login(username, password, req): 用户登录
Implement the Python class `LoginDAO` described below. Class description: Implement the LoginDAO class. Method signatures and docstrings: - def checkuseragent(data): 检测浏览器 - def checktoken(username, token): 检测admin的token - def logout(token, username, req): 用户退出 - def login(username, password, req): 用户登录 <|skeleton|>...
473d330fab9ee6b42af446d68b03668c286021d6
<|skeleton|> class LoginDAO: def checkuseragent(data): """检测浏览器""" <|body_0|> def checktoken(username, token): """检测admin的token""" <|body_1|> def logout(token, username, req): """用户退出""" <|body_2|> def login(username, password, req): """用户登录"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoginDAO: def checkuseragent(data): """检测浏览器""" if data: useragent = data['useragent'] print(useragent) if 'mobile' in useragent: return packinfo(infostatus=2, infomsg='此系统不支持移动端浏览器!请切换至计算机上使用。') elif 'firefox' in useragent: ...
the_stack_v2_python_sparse
services/daos/loginDAO.py
tanoshiisekai/examsystem
train
0
aee94e2b32578a600c058fd946f736913c19698a
[ "Process.__init__(self)\nself.v = v\nself.event = event", "self.event.wait()\nsumme = 0\nfor i in range(self.v.value + 1):\n summe += i\nself.v.value = summe" ]
<|body_start_0|> Process.__init__(self) self.v = v self.event = event <|end_body_0|> <|body_start_1|> self.event.wait() summe = 0 for i in range(self.v.value + 1): summe += i self.v.value = summe <|end_body_1|>
Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt.
CalculatorProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CalculatorProcess: """Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt.""" def __init__(self, v, event): """Initialisiert die Basisklasse Process :param v: ein geteilte...
stack_v2_sparse_classes_75kplus_train_003782
1,243
no_license
[ { "docstring": "Initialisiert die Basisklasse Process :param v: ein geteilter Wert :param event: das Event, auf welches gewartet wird", "name": "__init__", "signature": "def __init__(self, v, event)" }, { "docstring": "Wartet auf das Event und legt das Ergebnis in den geteilten Speicher :return:...
2
stack_v2_sparse_classes_30k_train_023608
Implement the Python class `CalculatorProcess` described below. Class description: Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt. Method signatures and docstrings: - def __init__(self, v, event): Ini...
Implement the Python class `CalculatorProcess` described below. Class description: Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt. Method signatures and docstrings: - def __init__(self, v, event): Ini...
262499bbbc5ed6a53280dc2d596592c48155dcd7
<|skeleton|> class CalculatorProcess: """Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt.""" def __init__(self, v, event): """Initialisiert die Basisklasse Process :param v: ein geteilte...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CalculatorProcess: """Stellt einen simplen Worker-Prozess dar, welcher auf ein Event wartet und dann die Summe von 1 bis n berechnet. Das Ergebnis wird in einen geteilten Speicher gelegt.""" def __init__(self, v, event): """Initialisiert die Basisklasse Process :param v: ein geteilter Wert :param...
the_stack_v2_python_sparse
Interprozesskommunikation/multiprocessing/multiprocess_event.py
mborko/sew4_foerderkurs
train
0
d37c5a53aa46a706f3d0e7d54fde0c7ed069cf97
[ "if root is None:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST(root.left, val)\nelse:\n return self.searchBST(root.right, val)", "if not root:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST2(root...
<|body_start_0|> if root is None: return None if root.val == val: return root elif val < root.val: return self.searchBST(root.left, val) else: return self.searchBST(root.right, val) <|end_body_0|> <|body_start_1|> if not root: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def searchBST(self, root, val): """:type root: TreeNode :type val: int :rtype: TreeNode""" <|body_0|> def searchBST2(self, root, val): """:param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_75kplus_train_003783
2,333
no_license
[ { "docstring": ":type root: TreeNode :type val: int :rtype: TreeNode", "name": "searchBST", "signature": "def searchBST(self, root, val)" }, { "docstring": ":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)", "name": "searchBST2", "signature": "def searchBST2(self,...
2
stack_v2_sparse_classes_30k_train_053440
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode - def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode - def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)...
a5b02044ef39154b6a8d32eb57682f447e1632ba
<|skeleton|> class Solution: def searchBST(self, root, val): """:type root: TreeNode :type val: int :rtype: TreeNode""" <|body_0|> def searchBST2(self, root, val): """:param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def searchBST(self, root, val): """:type root: TreeNode :type val: int :rtype: TreeNode""" if root is None: return None if root.val == val: return root elif val < root.val: return self.searchBST(root.left, val) else: ...
the_stack_v2_python_sparse
algo/tree/search_in_binary_search_tree.py
xys234/coding-problems
train
0
5ab1ef018811ab2e46fbd5412ac2ca820e9a5588
[ "try:\n setattr(type(self), '__optimize_not_implemented__', True)\n out = self.self_optimize_with_info(dataset, **kwargs)[0]\n delattr(type(self), '__optimize_not_implemented__')\nexcept NotImplementedError as e:\n raise NotImplementedError() from e\nreturn out", "try:\n if getattr(type(self), '__o...
<|body_start_0|> try: setattr(type(self), '__optimize_not_implemented__', True) out = self.self_optimize_with_info(dataset, **kwargs)[0] delattr(type(self), '__optimize_not_implemented__') except NotImplementedError as e: raise NotImplementedError() from e...
Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp.pipelines.GridSearch` should be used directly....
OptimizablePipeline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp...
stack_v2_sparse_classes_75kplus_train_003784
7,840
permissive
[ { "docstring": "Optimize the input parameters of the pipeline or algorithm using any logic. This method can be used to adapt the input parameters (values provided in the init) based on any data driven heuristic. .. note:: The optimizations must only modify the input parameters (aka `self.clone` should retain th...
2
stack_v2_sparse_classes_30k_train_009190
Implement the Python class `OptimizablePipeline` described below. Class description: Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or...
Implement the Python class `OptimizablePipeline` described below. Class description: Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or...
75b958ee691d6d5b0eee070c1eb20d1017ec619b
<|skeleton|> class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp.pipelines.Gr...
the_stack_v2_python_sparse
tpcp/_pipeline.py
mad-lab-fau/tpcp
train
11
2ec247a99e66f79f4dc75cc0817e473c113075c6
[ "form = super(AjaxCreateView, self).get_form()\nif form.initial.get('part', None):\n form.fields['part'].widget = HiddenInput()\nreturn form", "initials = super(SupplierPartCreate, self).get_initial().copy()\nmanufacturer_id = self.get_param('manufacturer')\nsupplier_id = self.get_param('supplier')\npart_id = ...
<|body_start_0|> form = super(AjaxCreateView, self).get_form() if form.initial.get('part', None): form.fields['part'].widget = HiddenInput() return form <|end_body_0|> <|body_start_1|> initials = super(SupplierPartCreate, self).get_initial().copy() manufacturer_id = ...
Create view for making new SupplierPart
SupplierPartCreate
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SupplierPartCreate: """Create view for making new SupplierPart""" def get_form(self): """Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context""" <|body_0|> def get_initial(self): """Provide initial data...
stack_v2_sparse_classes_75kplus_train_003785
12,536
permissive
[ { "docstring": "Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context", "name": "get_form", "signature": "def get_form(self)" }, { "docstring": "Provide initial data for new SupplierPart: - If 'supplier_id' provided, pre-fill supplier f...
2
stack_v2_sparse_classes_30k_train_010861
Implement the Python class `SupplierPartCreate` described below. Class description: Create view for making new SupplierPart Method signatures and docstrings: - def get_form(self): Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context - def get_initial(self):...
Implement the Python class `SupplierPartCreate` described below. Class description: Create view for making new SupplierPart Method signatures and docstrings: - def get_form(self): Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context - def get_initial(self):...
daab81fa2cf6f3ce1760e31d8cd94951c6dffdd2
<|skeleton|> class SupplierPartCreate: """Create view for making new SupplierPart""" def get_form(self): """Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context""" <|body_0|> def get_initial(self): """Provide initial data...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SupplierPartCreate: """Create view for making new SupplierPart""" def get_form(self): """Create Form instance to create a new SupplierPart object. Hide some fields if they are not appropriate in context""" form = super(AjaxCreateView, self).get_form() if form.initial.get('part', N...
the_stack_v2_python_sparse
InvenTree/company/views.py
fritzlim/InvenTree
train
1
97938a132a550eadcd181989f6c163445c517cbd
[ "super(_ExprInMatch, self).__init__(backend, key, operand, transform, args)\nself._prefix = prefix\nself._suffix = suffix", "def _InMatch(value):\n \"\"\"Applies case insensitive string prefix/suffix match to value.\"\"\"\n if value is None:\n return False\n v = str(value).lower()\n return (not...
<|body_start_0|> super(_ExprInMatch, self).__init__(backend, key, operand, transform, args) self._prefix = prefix self._suffix = suffix <|end_body_0|> <|body_start_1|> def _InMatch(value): """Applies case insensitive string prefix/suffix match to value.""" if val...
Membership and anchored prefix*suffix match node.
_ExprInMatch
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _ExprInMatch: """Membership and anchored prefix*suffix match node.""" def __init__(self, backend, key, operand, transform, args, prefix, suffix): """Initializes the anchored prefix and suffix patterns. Args: backend: The parser backend object. key: Resource object key (list of str, i...
stack_v2_sparse_classes_75kplus_train_003786
15,555
permissive
[ { "docstring": "Initializes the anchored prefix and suffix patterns. Args: backend: The parser backend object. key: Resource object key (list of str, int and/or None values). operand: The term ExprOperand operand. transform: Optional key value transform function. args: Optional key value transform function actu...
2
stack_v2_sparse_classes_30k_train_024090
Implement the Python class `_ExprInMatch` described below. Class description: Membership and anchored prefix*suffix match node. Method signatures and docstrings: - def __init__(self, backend, key, operand, transform, args, prefix, suffix): Initializes the anchored prefix and suffix patterns. Args: backend: The parser...
Implement the Python class `_ExprInMatch` described below. Class description: Membership and anchored prefix*suffix match node. Method signatures and docstrings: - def __init__(self, backend, key, operand, transform, args, prefix, suffix): Initializes the anchored prefix and suffix patterns. Args: backend: The parser...
dcf4886d4ec06b13282143ef795c5f0ff20ffee3
<|skeleton|> class _ExprInMatch: """Membership and anchored prefix*suffix match node.""" def __init__(self, backend, key, operand, transform, args, prefix, suffix): """Initializes the anchored prefix and suffix patterns. Args: backend: The parser backend object. key: Resource object key (list of str, i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _ExprInMatch: """Membership and anchored prefix*suffix match node.""" def __init__(self, backend, key, operand, transform, args, prefix, suffix): """Initializes the anchored prefix and suffix patterns. Args: backend: The parser backend object. key: Resource object key (list of str, int and/or Non...
the_stack_v2_python_sparse
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/core/resource/resource_expr.py
MD-Anderson-Bioinformatics/NG-CHM_Galaxy
train
0
de3197270ef377218c6fe275535386ba842e3898
[ "self.rgb = rgb\nself.lwir = lwir\nself.bsize = args.batch_size\nself.psize = args.patch_size\nself.hdisp = int(float(args.max_disparity) / 2.0)\nself.channels = 3\nself.ptr = 0\nself.disparity = io.read_disparity_gt(disparity)\nprint(f'total testing locations: {self.disparity.shape[0]}')\npatch_size = 2 * self.psi...
<|body_start_0|> self.rgb = rgb self.lwir = lwir self.bsize = args.batch_size self.psize = args.patch_size self.hdisp = int(float(args.max_disparity) / 2.0) self.channels = 3 self.ptr = 0 self.disparity = io.read_disparity_gt(disparity) print(f'tot...
TestLITIVDataset
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLITIVDataset: def __init__(self, rgb: List[str], lwir: List[str], disparity: str, args: Namespace): """represents the LITIV dataset used for testing. :param rgb: list of paths to rgb images. :param lwir: list of paths to lwir images. :param disparity: file contraining all data points...
stack_v2_sparse_classes_75kplus_train_003787
6,156
permissive
[ { "docstring": "represents the LITIV dataset used for testing. :param rgb: list of paths to rgb images. :param lwir: list of paths to lwir images. :param disparity: file contraining all data points. :param args: structure containing all user arguments.", "name": "__init__", "signature": "def __init__(se...
2
stack_v2_sparse_classes_30k_val_000685
Implement the Python class `TestLITIVDataset` described below. Class description: Implement the TestLITIVDataset class. Method signatures and docstrings: - def __init__(self, rgb: List[str], lwir: List[str], disparity: str, args: Namespace): represents the LITIV dataset used for testing. :param rgb: list of paths to ...
Implement the Python class `TestLITIVDataset` described below. Class description: Implement the TestLITIVDataset class. Method signatures and docstrings: - def __init__(self, rgb: List[str], lwir: List[str], disparity: str, args: Namespace): represents the LITIV dataset used for testing. :param rgb: list of paths to ...
583e6868864582f081f18689124e74e9ca169f28
<|skeleton|> class TestLITIVDataset: def __init__(self, rgb: List[str], lwir: List[str], disparity: str, args: Namespace): """represents the LITIV dataset used for testing. :param rgb: list of paths to rgb images. :param lwir: list of paths to lwir images. :param disparity: file contraining all data points...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestLITIVDataset: def __init__(self, rgb: List[str], lwir: List[str], disparity: str, args: Namespace): """represents the LITIV dataset used for testing. :param rgb: list of paths to rgb images. :param lwir: list of paths to lwir images. :param disparity: file contraining all data points. :param args:...
the_stack_v2_python_sparse
datahandler/LITIVDataset.py
beaupreda/domain-networks
train
1
60eecbc9886dc6e7e022d5c87830e49e1975c31f
[ "self.quark = quark\nself.nucleon = nucleon\nself.ip = input_dict", "self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2\nif self.nucleon == 'p':\n if self.quark == 'u':\n return self.mN ** 2 * 2 * self.ip['gA']\n if self.quark == 'd':\n return -self.mN ** 2 * 2 * self.ip['gA']\n if se...
<|body_start_0|> self.quark = quark self.nucleon = nucleon self.ip = input_dict <|end_body_0|> <|body_start_1|> self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2 if self.nucleon == 'p': if self.quark == 'u': return self.mN ** 2 * 2 * self.ip['g...
FPprimed
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FPprimed: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (option...
stack_v2_sparse_classes_75kplus_train_003788
18,337
permissive
[ { "docstring": "The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadronic input parameters (default is Num_inpu...
3
stack_v2_sparse_classes_30k_train_041057
Implement the Python class `FPprimed` described below. Class description: Implement the FPprimed class. Method signatures and docstrings: - def __init__(self, quark, nucleon, input_dict): The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark fl...
Implement the Python class `FPprimed` described below. Class description: Implement the FPprimed class. Method signatures and docstrings: - def __init__(self, quark, nucleon, input_dict): The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark fl...
4a714e4701f817fdc96e10e461eef7c4756ef71d
<|skeleton|> class FPprimed: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (option...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FPprimed: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FPprimed Return the nuclear form factor FPprimed Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dicti...
the_stack_v2_python_sparse
directdm/num/single_nucleon_form_factors.py
DirectDM/directdm-py
train
6
aad0bf99b79d76a1c8563c40a4dd035058c8ae4f
[ "add_failed = kwargs.get('add_failed', False)\nadd_succeeded = kwargs.get('add_succeeded', False)\nbook_list = get_object_or_404(models.List, id=list_id)\nbook_list.raise_visible_to_user(request.user)\nif is_api_request(request):\n return ActivitypubResponse(book_list.to_activity(**request.GET))\nif (redirect_op...
<|body_start_0|> add_failed = kwargs.get('add_failed', False) add_succeeded = kwargs.get('add_succeeded', False) book_list = get_object_or_404(models.List, id=list_id) book_list.raise_visible_to_user(request.user) if is_api_request(request): return ActivitypubResponse...
book list page
List
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class List: """book list page""" def get(self, request, list_id, **kwargs): """display a book list""" <|body_0|> def post(self, request, list_id): """edit a list""" <|body_1|> <|end_skeleton|> <|body_start_0|> add_failed = kwargs.get('add_failed', Fal...
stack_v2_sparse_classes_75kplus_train_003789
11,267
no_license
[ { "docstring": "display a book list", "name": "get", "signature": "def get(self, request, list_id, **kwargs)" }, { "docstring": "edit a list", "name": "post", "signature": "def post(self, request, list_id)" } ]
2
stack_v2_sparse_classes_30k_train_008900
Implement the Python class `List` described below. Class description: book list page Method signatures and docstrings: - def get(self, request, list_id, **kwargs): display a book list - def post(self, request, list_id): edit a list
Implement the Python class `List` described below. Class description: book list page Method signatures and docstrings: - def get(self, request, list_id, **kwargs): display a book list - def post(self, request, list_id): edit a list <|skeleton|> class List: """book list page""" def get(self, request, list_id...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class List: """book list page""" def get(self, request, list_id, **kwargs): """display a book list""" <|body_0|> def post(self, request, list_id): """edit a list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class List: """book list page""" def get(self, request, list_id, **kwargs): """display a book list""" add_failed = kwargs.get('add_failed', False) add_succeeded = kwargs.get('add_succeeded', False) book_list = get_object_or_404(models.List, id=list_id) book_list.raise_vi...
the_stack_v2_python_sparse
bookwyrm/views/list/list.py
bookwyrm-social/bookwyrm
train
1,398
136179789a29ac14403dc31ad56dfe9f1db9e318
[ "try:\n from avx_commons import get_db_credentials\n self.hostname = socket.gethostbyname(socket.gethostname())\n self.db_username, self.db_password, self.db_name = get_db_credentials()\n self.db_ip = db_ip\n self.db_port = db_port\n self.path = path\nexcept Exception as e:\n print(colored(e, '...
<|body_start_0|> try: from avx_commons import get_db_credentials self.hostname = socket.gethostbyname(socket.gethostname()) self.db_username, self.db_password, self.db_name = get_db_credentials() self.db_ip = db_ip self.db_port = db_port se...
.
PushLB
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PushLB: """.""" def __init__(self, path, db_ip, db_port): """.""" <|body_0|> def generate_load_balancer(): """.""" <|body_1|> def push_load_balancer(self): """.""" <|body_2|> def initialize(self): """.""" <|body_3...
stack_v2_sparse_classes_75kplus_train_003790
4,027
no_license
[ { "docstring": ".", "name": "__init__", "signature": "def __init__(self, path, db_ip, db_port)" }, { "docstring": ".", "name": "generate_load_balancer", "signature": "def generate_load_balancer()" }, { "docstring": ".", "name": "push_load_balancer", "signature": "def push...
4
stack_v2_sparse_classes_30k_train_001430
Implement the Python class `PushLB` described below. Class description: . Method signatures and docstrings: - def __init__(self, path, db_ip, db_port): . - def generate_load_balancer(): . - def push_load_balancer(self): . - def initialize(self): .
Implement the Python class `PushLB` described below. Class description: . Method signatures and docstrings: - def __init__(self, path, db_ip, db_port): . - def generate_load_balancer(): . - def push_load_balancer(self): . - def initialize(self): . <|skeleton|> class PushLB: """.""" def __init__(self, path, ...
e513224364dce05ea4d17ac25ecfa981238b1311
<|skeleton|> class PushLB: """.""" def __init__(self, path, db_ip, db_port): """.""" <|body_0|> def generate_load_balancer(): """.""" <|body_1|> def push_load_balancer(self): """.""" <|body_2|> def initialize(self): """.""" <|body_3...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PushLB: """.""" def __init__(self, path, db_ip, db_port): """.""" try: from avx_commons import get_db_credentials self.hostname = socket.gethostbyname(socket.gethostname()) self.db_username, self.db_password, self.db_name = get_db_credentials() ...
the_stack_v2_python_sparse
scripts_avx/scripts/scripts/Commons/push_lb.py
Poonammahunta/Integration
train
0
8ff9cd90e7067709f148f66e5048cd5825d7dd22
[ "if masksModel == 'deeplab_resnet':\n print('Creating Deeplabv3-Resnet model for masks and loading checkpoint')\n self.model = deeplab_masks.DeepLab(num_classes=2, backbone='resnet', sync_bn=True, freeze_bn=False)\nelif masksModel == 'deeplab_xception':\n self.model = deeplab_masks.DeepLab(num_classes=2, b...
<|body_start_0|> if masksModel == 'deeplab_resnet': print('Creating Deeplabv3-Resnet model for masks and loading checkpoint') self.model = deeplab_masks.DeepLab(num_classes=2, backbone='resnet', sync_bn=True, freeze_bn=False) elif masksModel == 'deeplab_xception': sel...
InferenceMasks
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InferenceMasks: def __init__(self, masksWeightsFile, masksModel='drn', imgHeight=288, imgWidth=512): """Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (str): Path to the weights file for the model masksModel (str): Which model to use. Can be one of ["deepl...
stack_v2_sparse_classes_75kplus_train_003791
17,088
permissive
[ { "docstring": "Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (str): Path to the weights file for the model masksModel (str): Which model to use. Can be one of [\"deeplab_xception\", \"deeplab_resnet\", \"drn\"] imgHeight (int): The height to which images should be resized to be...
2
null
Implement the Python class `InferenceMasks` described below. Class description: Implement the InferenceMasks class. Method signatures and docstrings: - def __init__(self, masksWeightsFile, masksModel='drn', imgHeight=288, imgWidth=512): Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (s...
Implement the Python class `InferenceMasks` described below. Class description: Implement the InferenceMasks class. Method signatures and docstrings: - def __init__(self, masksWeightsFile, masksModel='drn', imgHeight=288, imgWidth=512): Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (s...
0688647e49380139e440bacbe8562132bb2afbd7
<|skeleton|> class InferenceMasks: def __init__(self, masksWeightsFile, masksModel='drn', imgHeight=288, imgWidth=512): """Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (str): Path to the weights file for the model masksModel (str): Which model to use. Can be one of ["deepl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InferenceMasks: def __init__(self, masksWeightsFile, masksModel='drn', imgHeight=288, imgWidth=512): """Class to run Inference of the Outlines Prediction Model Args: masksWeightsFile (str): Path to the weights file for the model masksModel (str): Which model to use. Can be one of ["deeplab_xception", ...
the_stack_v2_python_sparse
api/inference_models.py
Shreeyak/cleargrasp
train
253
61fb61379af3f23f6e053eaf8d7c1e5904a72afa
[ "if qca_passwd is None:\n qca_passwd = os.environ.get('QCAUSR', None)\nself.qc_spec = qc_spec\nself.client = FractalClient(address, username='user', password=qca_passwd, verify=False)\ntry:\n self.coll = base_class.from_server(name=coll_name, client=self.client)\nexcept KeyError as ex:\n if create:\n ...
<|body_start_0|> if qca_passwd is None: qca_passwd = os.environ.get('QCAUSR', None) self.qc_spec = qc_spec self.client = FractalClient(address, username='user', password=qca_passwd, verify=False) try: self.coll = base_class.from_server(name=coll_name, client=self....
Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate XYZ coordinates to allow for a 'just add this SMILES'), using a consistent identifi...
QCFractalWrapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QCFractalWrapper: """Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate XYZ coordinates to allow for a 'just ad...
stack_v2_sparse_classes_75kplus_train_003792
29,582
no_license
[ { "docstring": "Open the geometry computation dataset Args: address: Address for the QCFractal server base_class: Type of the collection qc_spec: Name of the QC specification coll_name: Name of the collection holding the data qca_passwd: Password for the QCFractal server create: Whether creating a new collectio...
2
stack_v2_sparse_classes_30k_train_002360
Implement the Python class `QCFractalWrapper` described below. Class description: Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate ...
Implement the Python class `QCFractalWrapper` described below. Class description: Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate ...
ef9e586e89053d1f6bea541717db8be43dbce0a4
<|skeleton|> class QCFractalWrapper: """Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate XYZ coordinates to allow for a 'just ad...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QCFractalWrapper: """Wrapper over a QFractal Dataset class Handles creating and authenticating with the underlying class method. It is a base class for building superclasses that create utility operations for adding molecules to the database (e.g., generate XYZ coordinates to allow for a 'just add this SMILES...
the_stack_v2_python_sparse
moldesign/simulate/qcfractal.py
exalearn/electrolyte-design
train
4
9e66e39888d060d7556ebc9be2c468239e5e95c4
[ "try:\n return os.environ[key]\nexcept KeyError:\n return ''", "env = []\nfor ek in os.environ.keys():\n env.append((ek, os.environ[ek]))\nreturn env" ]
<|body_start_0|> try: return os.environ[key] except KeyError: return '' <|end_body_0|> <|body_start_1|> env = [] for ek in os.environ.keys(): env.append((ek, os.environ[ek])) return env <|end_body_1|>
basic miscellanous functions
Base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Base: """basic miscellanous functions""" def Env(self, key): """return operating system enviroment variables""" <|body_0|> def EnvAll(self): """return all environment variables as a list with containing tuples (key, value)""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_75kplus_train_003793
585
no_license
[ { "docstring": "return operating system enviroment variables", "name": "Env", "signature": "def Env(self, key)" }, { "docstring": "return all environment variables as a list with containing tuples (key, value)", "name": "EnvAll", "signature": "def EnvAll(self)" } ]
2
stack_v2_sparse_classes_30k_train_048105
Implement the Python class `Base` described below. Class description: basic miscellanous functions Method signatures and docstrings: - def Env(self, key): return operating system enviroment variables - def EnvAll(self): return all environment variables as a list with containing tuples (key, value)
Implement the Python class `Base` described below. Class description: basic miscellanous functions Method signatures and docstrings: - def Env(self, key): return operating system enviroment variables - def EnvAll(self): return all environment variables as a list with containing tuples (key, value) <|skeleton|> class...
3cfcae894c165189cc3ff61e27ca284f09e87871
<|skeleton|> class Base: """basic miscellanous functions""" def Env(self, key): """return operating system enviroment variables""" <|body_0|> def EnvAll(self): """return all environment variables as a list with containing tuples (key, value)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Base: """basic miscellanous functions""" def Env(self, key): """return operating system enviroment variables""" try: return os.environ[key] except KeyError: return '' def EnvAll(self): """return all environment variables as a list with containi...
the_stack_v2_python_sparse
dmerce2/Core/OS.py
rbe/dmerce
train
0
65e5d45f9cdc0835a3f8d7a3229b49b7d68a21a0
[ "self.K = K\nfile = open(file, 'r')\nself.file_data = file.readlines()\nfile.close()", "vertices_and_edges = self.file_data[0].replace('\\n', '').split(' ')\nself.number_of_vertices = int(vertices_and_edges[0])\nself.number_of_edges = int(vertices_and_edges[1])\nself.vertexes = list()\nself.edges = list()\nfile_i...
<|body_start_0|> self.K = K file = open(file, 'r') self.file_data = file.readlines() file.close() <|end_body_0|> <|body_start_1|> vertices_and_edges = self.file_data[0].replace('\n', '').split(' ') self.number_of_vertices = int(vertices_and_edges[0]) self.number_...
self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type float self. self.edges = 2-dimensional list. For each edge, [0] denotes t...
Board
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Board: """self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type float self. self.edges = 2-dimensional l...
stack_v2_sparse_classes_75kplus_train_003794
2,456
no_license
[ { "docstring": "Initializes by reading a file, and setting the K value.", "name": "__init__", "signature": "def __init__(self, file, K)" }, { "docstring": "Parses the text file, and placing values in data structures.", "name": "parse_text_file", "signature": "def parse_text_file(self)" ...
4
null
Implement the Python class `Board` described below. Class description: self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type f...
Implement the Python class `Board` described below. Class description: self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type f...
9f3d6d040406a183d25fca8801af48fcb8b6d875
<|skeleton|> class Board: """self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type float self. self.edges = 2-dimensional l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Board: """self.numberOfVertices = the number of vertices in the graph self.numberOfEdges = the number of edges in the graph self.vertexes = 2-dimensional list. For each vertex, [0] denotes the index, [1] the x coord and [2] the y coord. Values are all type float self. self.edges = 2-dimensional list. For each...
the_stack_v2_python_sparse
module2/board.py
talepre/AIProg
train
0
700fb28af3caa49e9b8acc28cc41c7452f945845
[ "ret = []\n\ndef preorder(root):\n if not root:\n return\n ret.append(root.val)\n preorder(root.left)\n preorder(root.right)\npreorder(root)\nreturn ret", "ret = []\ns = []\nif root:\n s.append(root)\nwhile s:\n node = s.pop()\n ret.append(node.val)\n if node.right:\n s.appen...
<|body_start_0|> ret = [] def preorder(root): if not root: return ret.append(root.val) preorder(root.left) preorder(root.right) preorder(root) return ret <|end_body_0|> <|body_start_1|> ret = [] s = [] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def preorderTraversal2(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ret = [] def ...
stack_v2_sparse_classes_75kplus_train_003795
1,093
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "preorderTraversal", "signature": "def preorderTraversal(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "preorderTraversal2", "signature": "def preorderTraversal2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_019056
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def preorderTraversal2(self, root): :type root: TreeNode :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def preorderTraversal2(self, root): :type root: TreeNode :rtype: List[int] <|skeleton|> class Solutio...
f55573181bf1ed29c998e0b9d22d307ee4d7b42e
<|skeleton|> class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def preorderTraversal2(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def preorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" ret = [] def preorder(root): if not root: return ret.append(root.val) preorder(root.left) preorder(root.right) preorder(roo...
the_stack_v2_python_sparse
stack/二叉树的前序遍历-144.py
chenchaojie/leetcode350
train
1
42ffa662c5f7dd12746030c45d9256227a477f9f
[ "average = 0.040577\nstd_dev = 0.014887\nbetter_sign = -1\nreturn (average, std_dev, better_sign)", "total = source_data.B25014_001E\nper_1_0 = source_data.B25014_004E + source_data.B25014_010E\nper_1_5 = source_data.B25014_005E + source_data.B25014_011E\nper_2_0 = source_data.B25014_006E + source_data.B25014_012...
<|body_start_0|> average = 0.040577 std_dev = 0.014887 better_sign = -1 return (average, std_dev, better_sign) <|end_body_0|> <|body_start_1|> total = source_data.B25014_001E per_1_0 = source_data.B25014_004E + source_data.B25014_010E per_1_5 = source_data.B25014...
Score based on weighted occupants per room
PercentOvercrowdingAlgorithm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PercentOvercrowdingAlgorithm: """Score based on weighted occupants per room""" def get_default_stats(self, source_data): """Stats for census tracts in Oklahoma""" <|body_0|> def local_percent(self, source_data): """Return a weighted percentage of over-occupied re...
stack_v2_sparse_classes_75kplus_train_003796
34,944
no_license
[ { "docstring": "Stats for census tracts in Oklahoma", "name": "get_default_stats", "signature": "def get_default_stats(self, source_data)" }, { "docstring": "Return a weighted percentage of over-occupied residences", "name": "local_percent", "signature": "def local_percent(self, source_d...
2
null
Implement the Python class `PercentOvercrowdingAlgorithm` described below. Class description: Score based on weighted occupants per room Method signatures and docstrings: - def get_default_stats(self, source_data): Stats for census tracts in Oklahoma - def local_percent(self, source_data): Return a weighted percentag...
Implement the Python class `PercentOvercrowdingAlgorithm` described below. Class description: Score based on weighted occupants per room Method signatures and docstrings: - def get_default_stats(self, source_data): Stats for census tracts in Oklahoma - def local_percent(self, source_data): Return a weighted percentag...
0d29c3e1599b187c17ea2a2c68f8a9b78f430442
<|skeleton|> class PercentOvercrowdingAlgorithm: """Score based on weighted occupants per room""" def get_default_stats(self, source_data): """Stats for census tracts in Oklahoma""" <|body_0|> def local_percent(self, source_data): """Return a weighted percentage of over-occupied re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PercentOvercrowdingAlgorithm: """Score based on weighted occupants per room""" def get_default_stats(self, source_data): """Stats for census tracts in Oklahoma""" average = 0.040577 std_dev = 0.014887 better_sign = -1 return (average, std_dev, better_sign) def...
the_stack_v2_python_sparse
healthdata/algorithms.py
CivicNinjas/HealthAround.me
train
1
218b1351e4058fee2cb91eff1bd0534136acc9a3
[ "n = len(nums)\nmax_window = []\nfor i in range(0, n - k + 1):\n curr_max = float('-inf')\n for j in range(i, i + k):\n curr_max = max(curr_max, nums[j])\n max_window.append(curr_max)\nreturn max_window", "if not nums:\n return []\nif k > len(nums):\n return [max(nums)]\nmax_window = []\ndeq...
<|body_start_0|> n = len(nums) max_window = [] for i in range(0, n - k + 1): curr_max = float('-inf') for j in range(i, i + k): curr_max = max(curr_max, nums[j]) max_window.append(curr_max) return max_window <|end_body_0|> <|body_start...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" <|body_0|> def max_window_deque(self, nums, k): """Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity...
stack_v2_sparse_classes_75kplus_train_003797
2,969
no_license
[ { "docstring": "Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).", "name": "max_window_brute", "signature": "def max_window_brute(self, nums, k)" }, { "docstring": "Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity: O(n). Space com...
2
stack_v2_sparse_classes_30k_train_020659
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_window_brute(self, nums, k): Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums). - def max_window_deque(self, nums, k): Algorithm ba...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_window_brute(self, nums, k): Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums). - def max_window_deque(self, nums, k): Algorithm ba...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" <|body_0|> def max_window_deque(self, nums, k): """Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" n = len(nums) max_window = [] for i in range(0, n - k + 1): curr_max = float('-inf') for j in range(i, i + k): ...
the_stack_v2_python_sparse
Stack/sliding_window_maximum.py
vladn90/Algorithms
train
0
227b67acc3af1459d1f52eb6dea52e39782e2e39
[ "if not root:\n return None\nif key > root.val:\n root.right = self.deleteNode(root.right, key)\nelif key < root.val:\n root.left = self.deleteNode(root.left, key)\nelif not root.left and (not root.right):\n root = None\nelif root.right:\n root.val = self.successor(root)\n root.right = self.delete...
<|body_start_0|> if not root: return None if key > root.val: root.right = self.deleteNode(root.right, key) elif key < root.val: root.left = self.deleteNode(root.left, key) elif not root.left and (not root.right): root = None elif ro...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def deleteNode(self, root, key): """:type root: TreeNode :type key: int :rtype: TreeNode""" <|body_0|> def successor(self, root): """One step right and then always left""" <|body_1|> def predecessor(self, root): """One step left and the...
stack_v2_sparse_classes_75kplus_train_003798
2,749
no_license
[ { "docstring": ":type root: TreeNode :type key: int :rtype: TreeNode", "name": "deleteNode", "signature": "def deleteNode(self, root, key)" }, { "docstring": "One step right and then always left", "name": "successor", "signature": "def successor(self, root)" }, { "docstring": "On...
3
stack_v2_sparse_classes_30k_train_040436
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode - def successor(self, root): One step right and then always left - def predecessor(self, roo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteNode(self, root, key): :type root: TreeNode :type key: int :rtype: TreeNode - def successor(self, root): One step right and then always left - def predecessor(self, roo...
90c000c3be70727cde4f7494fbbb1c425bfd3da4
<|skeleton|> class Solution: def deleteNode(self, root, key): """:type root: TreeNode :type key: int :rtype: TreeNode""" <|body_0|> def successor(self, root): """One step right and then always left""" <|body_1|> def predecessor(self, root): """One step left and the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def deleteNode(self, root, key): """:type root: TreeNode :type key: int :rtype: TreeNode""" if not root: return None if key > root.val: root.right = self.deleteNode(root.right, key) elif key < root.val: root.left = self.deleteNode(r...
the_stack_v2_python_sparse
450.delete-node-in-a-bst.py
chenjienan/python-leetcode
train
16
e28aa78fd6a3e653cd88e47e8dc2131e748e875f
[ "self.key = int(key, 16).to_bytes(16, byteorder='little')\nself.max = bound\nself.byte_length = len(self.key) + ((bound - 1).bit_length() + 7) // 8", "n_ = n if n else 1\nl = self.byte_length\ndk = hashlib.pbkdf2_hmac('sha1', self.key, s.encode(), 1, n_ * l)\nx = [int.from_bytes(dk[i * l:(i + 1) * l], byteorder='...
<|body_start_0|> self.key = int(key, 16).to_bytes(16, byteorder='little') self.max = bound self.byte_length = len(self.key) + ((bound - 1).bit_length() + 7) // 8 <|end_body_0|> <|body_start_1|> n_ = n if n else 1 l = self.byte_length dk = hashlib.pbkdf2_hmac('sha1', self...
A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.
PRF
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PRF: """A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.""" def __init__(self, key, bound): """Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will ...
stack_v2_sparse_classes_75kplus_train_003799
6,165
no_license
[ { "docstring": "Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will be in range(bound).", "name": "__init__", "signature": "def __init__(self, key, bound)" }, { "docstring": "Return a number or list of numbers in rang...
2
stack_v2_sparse_classes_30k_train_024836
Implement the Python class `PRF` described below. Class description: A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum. Method signatures and docstrings: - def __init__(self, key, bound): Create a PRF determined by the given key and (upper) bound. The key is a h...
Implement the Python class `PRF` described below. Class description: A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum. Method signatures and docstrings: - def __init__(self, key, bound): Create a PRF determined by the given key and (upper) bound. The key is a h...
ae8e421fb840937ccd7c8d5c35a011e5eb2c63df
<|skeleton|> class PRF: """A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.""" def __init__(self, key, bound): """Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PRF: """A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.""" def __init__(self, key, bound): """Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will be in range(b...
the_stack_v2_python_sparse
device/mpyc/mpyc/thresha.py
Fluxmux/securefacematching
train
4