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
b0143bb6d0bb82f09f48ba6f9ec3a1c38761bc7d
[ "if field_name == 'name':\n return 'name__iexact'\nreturn field_name", "sources = [serializer.fields[field_name].source for field_name in self.fields]\nif serializer.instance is not None:\n for source in sources:\n if source not in attrs:\n attrs[source] = getattr(serializer.instance, sour...
<|body_start_0|> if field_name == 'name': return 'name__iexact' return field_name <|end_body_0|> <|body_start_1|> sources = [serializer.fields[field_name].source for field_name in self.fields] if serializer.instance is not None: for source in sources: ...
CaseInsensitiveUniqueTogetherValidator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CaseInsensitiveUniqueTogetherValidator: def process_field_name(self, field_name): """Right now, we presume that certain names are string-y, and can be case-insensitive compared.""" <|body_0|> def filter_queryset(self, attrs, queryset, serializer): """Filter the query...
stack_v2_sparse_classes_75kplus_train_000400
1,977
permissive
[ { "docstring": "Right now, we presume that certain names are string-y, and can be case-insensitive compared.", "name": "process_field_name", "signature": "def process_field_name(self, field_name)" }, { "docstring": "Filter the queryset to all instances matching the given attributes.", "name"...
2
stack_v2_sparse_classes_30k_train_022667
Implement the Python class `CaseInsensitiveUniqueTogetherValidator` described below. Class description: Implement the CaseInsensitiveUniqueTogetherValidator class. Method signatures and docstrings: - def process_field_name(self, field_name): Right now, we presume that certain names are string-y, and can be case-insen...
Implement the Python class `CaseInsensitiveUniqueTogetherValidator` described below. Class description: Implement the CaseInsensitiveUniqueTogetherValidator class. Method signatures and docstrings: - def process_field_name(self, field_name): Right now, we presume that certain names are string-y, and can be case-insen...
5423ac74635fb313732b1f84e6238a8bd5c356b0
<|skeleton|> class CaseInsensitiveUniqueTogetherValidator: def process_field_name(self, field_name): """Right now, we presume that certain names are string-y, and can be case-insensitive compared.""" <|body_0|> def filter_queryset(self, attrs, queryset, serializer): """Filter the query...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CaseInsensitiveUniqueTogetherValidator: def process_field_name(self, field_name): """Right now, we presume that certain names are string-y, and can be case-insensitive compared.""" if field_name == 'name': return 'name__iexact' return field_name def filter_queryset(sel...
the_stack_v2_python_sparse
metecho/api/validators.py
anspaujd/Metecho
train
0
9566707095fed517fb2e60767227fc540e48e93d
[ "try:\n responseData = User.fetchAll()\n if len(responseData) > 0:\n response = jsonify(responseData)\n else:\n response = jsonify()\n return make_response(response, 200)\nexcept:\n handle400error(users_ns, 'Invalid username')\nreturn handle500error(users_ns)", "args = update_user_arg...
<|body_start_0|> try: responseData = User.fetchAll() if len(responseData) > 0: response = jsonify(responseData) else: response = jsonify() return make_response(response, 200) except: handle400error(users_ns, 'Inv...
UserCollection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCollection: def get(self, username): """Gets all users""" <|body_0|> def put(self, username): """Updates data and password of a user""" <|body_1|> def delete(self, username): """Deletes a user""" <|body_2|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_75kplus_train_000401
8,609
no_license
[ { "docstring": "Gets all users", "name": "get", "signature": "def get(self, username)" }, { "docstring": "Updates data and password of a user", "name": "put", "signature": "def put(self, username)" }, { "docstring": "Deletes a user", "name": "delete", "signature": "def de...
3
stack_v2_sparse_classes_30k_val_000050
Implement the Python class `UserCollection` described below. Class description: Implement the UserCollection class. Method signatures and docstrings: - def get(self, username): Gets all users - def put(self, username): Updates data and password of a user - def delete(self, username): Deletes a user
Implement the Python class `UserCollection` described below. Class description: Implement the UserCollection class. Method signatures and docstrings: - def get(self, username): Gets all users - def put(self, username): Updates data and password of a user - def delete(self, username): Deletes a user <|skeleton|> clas...
72ba34ce64482da23020d84a41819b889dad51f1
<|skeleton|> class UserCollection: def get(self, username): """Gets all users""" <|body_0|> def put(self, username): """Updates data and password of a user""" <|body_1|> def delete(self, username): """Deletes a user""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserCollection: def get(self, username): """Gets all users""" try: responseData = User.fetchAll() if len(responseData) > 0: response = jsonify(responseData) else: response = jsonify() return make_response(response,...
the_stack_v2_python_sparse
WakeOnLan-server/flask/api/namespaces/users_ns.py
DarioGar/WakeOnLan
train
0
eb82dc3a97647cf6c4ca89d86135ce11cc88a391
[ "slow = fast = head\nwhile fast and fast.next:\n slow, fast = (slow.next, fast.next.next)\npre, length = (None, 0)\nwhile slow:\n slow.next, pre, slow = (pre, slow, slow.next)\nwhile pre:\n if head.val != pre.val:\n return False\n head, pre = (head.next, pre.next)\nreturn True", "size, node = (...
<|body_start_0|> slow = fast = head while fast and fast.next: slow, fast = (slow.next, fast.next.next) pre, length = (None, 0) while slow: slow.next, pre, slow = (pre, slow, slow.next) while pre: if head.val != pre.val: return F...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, head: ListNode) -> bool: """先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可""" <|body_0|> def isPalindrome2(self, head: ListNode) -> bool: """计数法找中间的节点,效率不高""" <|body_1|> <|end_skeleton|> <|body_start_0|> slow = fas...
stack_v2_sparse_classes_75kplus_train_000402
1,565
permissive
[ { "docstring": "先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可", "name": "isPalindrome", "signature": "def isPalindrome(self, head: ListNode) -> bool" }, { "docstring": "计数法找中间的节点,效率不高", "name": "isPalindrome2", "signature": "def isPalindrome2(self, head: ListNode) -> bool" } ]
2
stack_v2_sparse_classes_30k_train_003241
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: ListNode) -> bool: 先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可 - def isPalindrome2(self, head: ListNode) -> bool: 计数法找中间的节点,效率不高
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: ListNode) -> bool: 先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可 - def isPalindrome2(self, head: ListNode) -> bool: 计数法找中间的节点,效率不高 <|skeleton|> c...
d203aecd1afe1af13a0384a9c657c8424aab322d
<|skeleton|> class Solution: def isPalindrome(self, head: ListNode) -> bool: """先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可""" <|body_0|> def isPalindrome2(self, head: ListNode) -> bool: """计数法找中间的节点,效率不高""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isPalindrome(self, head: ListNode) -> bool: """先快慢指针找出中间的(奇数)或中点的下一个(偶数),然后从它开始反序后面一半,最后比较两部分即可""" slow = fast = head while fast and fast.next: slow, fast = (slow.next, fast.next.next) pre, length = (None, 0) while slow: slow.next, ...
the_stack_v2_python_sparse
easy/Q234_PalindromeLinkedList.py
Kaciras/leetcode
train
0
efa536d5c0bc3f0090d18b020efc769c13da86fd
[ "from rbintegrations.extension import RBIntegrationsExtension\nextension = RBIntegrationsExtension.instance\nreturn {'1x': extension.get_static_url('images/circleci/icon.png'), '2x': extension.get_static_url('images/circleci/icon@2x.png')}", "repository = prep_data.repository\nif not repository or not repository....
<|body_start_0|> from rbintegrations.extension import RBIntegrationsExtension extension = RBIntegrationsExtension.instance return {'1x': extension.get_static_url('images/circleci/icon.png'), '2x': extension.get_static_url('images/circleci/icon@2x.png')} <|end_body_0|> <|body_start_1|> r...
Integrates Review Board with CircleCI.
CircleCIIntegration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CircleCIIntegration: """Integrates Review Board with CircleCI.""" def icon_static_urls(self): """Return the icons used for the integration. Returns: dict: The icons for CircleCI.""" <|body_0|> def prepare_builds(self, prep_data: BuildPrepData) -> bool: """Prepare...
stack_v2_sparse_classes_75kplus_train_000403
8,423
permissive
[ { "docstring": "Return the icons used for the integration. Returns: dict: The icons for CircleCI.", "name": "icon_static_urls", "signature": "def icon_static_urls(self)" }, { "docstring": "Prepare for builds. This will check if the change is on a supported hosting service (GitHub or Bitbucket), ...
4
null
Implement the Python class `CircleCIIntegration` described below. Class description: Integrates Review Board with CircleCI. Method signatures and docstrings: - def icon_static_urls(self): Return the icons used for the integration. Returns: dict: The icons for CircleCI. - def prepare_builds(self, prep_data: BuildPrepD...
Implement the Python class `CircleCIIntegration` described below. Class description: Integrates Review Board with CircleCI. Method signatures and docstrings: - def icon_static_urls(self): Return the icons used for the integration. Returns: dict: The icons for CircleCI. - def prepare_builds(self, prep_data: BuildPrepD...
52bbaecc1227764f3e9a66f03226e0013f2b0c48
<|skeleton|> class CircleCIIntegration: """Integrates Review Board with CircleCI.""" def icon_static_urls(self): """Return the icons used for the integration. Returns: dict: The icons for CircleCI.""" <|body_0|> def prepare_builds(self, prep_data: BuildPrepData) -> bool: """Prepare...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CircleCIIntegration: """Integrates Review Board with CircleCI.""" def icon_static_urls(self): """Return the icons used for the integration. Returns: dict: The icons for CircleCI.""" from rbintegrations.extension import RBIntegrationsExtension extension = RBIntegrationsExtension.in...
the_stack_v2_python_sparse
rbintegrations/circleci/integration.py
reviewboard/rbintegrations
train
0
f06dfdb48bc83bcbe21b5e16d356a23ddd61e328
[ "data = {'Queue': {'Current': 0, 'Max': 0}, 'Sessions': {'Current': 0, 'Max': 0, 'Total': 0}, 'Bytes': {'In': 0, 'Out': 0}, 'Denied': {'Request': 0, 'Response': 0}, 'Errors': {'Request': 0, 'Response': 0, 'Connections': 0}, 'Warnings': {'Retry': 0, 'Redispatch': 0}, 'Server': {'Downtime': 0}}\nfor row in stats:\n ...
<|body_start_0|> data = {'Queue': {'Current': 0, 'Max': 0}, 'Sessions': {'Current': 0, 'Max': 0, 'Total': 0}, 'Bytes': {'In': 0, 'Out': 0}, 'Denied': {'Request': 0, 'Response': 0}, 'Errors': {'Request': 0, 'Response': 0, 'Connections': 0}, 'Warnings': {'Retry': 0, 'Redispatch': 0}, 'Server': {'Downtime': 0}} ...
HAProxy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HAProxy: def sum_data(self, stats): """Return the summed data as a dict :rtype: dict""" <|body_0|> def add_datapoints(self, stats): """Add all of the data points for a node :param list stats: The parsed csv content""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_75kplus_train_000404
3,086
permissive
[ { "docstring": "Return the summed data as a dict :rtype: dict", "name": "sum_data", "signature": "def sum_data(self, stats)" }, { "docstring": "Add all of the data points for a node :param list stats: The parsed csv content", "name": "add_datapoints", "signature": "def add_datapoints(sel...
2
stack_v2_sparse_classes_30k_train_042790
Implement the Python class `HAProxy` described below. Class description: Implement the HAProxy class. Method signatures and docstrings: - def sum_data(self, stats): Return the summed data as a dict :rtype: dict - def add_datapoints(self, stats): Add all of the data points for a node :param list stats: The parsed csv ...
Implement the Python class `HAProxy` described below. Class description: Implement the HAProxy class. Method signatures and docstrings: - def sum_data(self, stats): Return the summed data as a dict :rtype: dict - def add_datapoints(self, stats): Add all of the data points for a node :param list stats: The parsed csv ...
e2671baf0f92e04de6dfc17a29325d6a43002185
<|skeleton|> class HAProxy: def sum_data(self, stats): """Return the summed data as a dict :rtype: dict""" <|body_0|> def add_datapoints(self, stats): """Add all of the data points for a node :param list stats: The parsed csv content""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HAProxy: def sum_data(self, stats): """Return the summed data as a dict :rtype: dict""" data = {'Queue': {'Current': 0, 'Max': 0}, 'Sessions': {'Current': 0, 'Max': 0, 'Total': 0}, 'Bytes': {'In': 0, 'Out': 0}, 'Denied': {'Request': 0, 'Response': 0}, 'Errors': {'Request': 0, 'Response': 0, 'C...
the_stack_v2_python_sparse
newrelic_python_agent/plugins/haproxy.py
NewRelic-Python-Plugins/newrelic-python-agent
train
7
0261107220b884863048d4bb18b15a618ff4ea17
[ "super().__init__(observation_spec, action_spec, reward_spec=reward_spec, env=env, config=config, debug_summaries=debug_summaries, name=name)\nself._distance_to_decelerate = distance_to_decelerate\nself._distance_to_stop = distance_to_stop", "waypoints = alf.nest.get_field(observation, 'observation.navigation')\n...
<|body_start_0|> super().__init__(observation_spec, action_spec, reward_spec=reward_spec, env=env, config=config, debug_summaries=debug_summaries, name=name) self._distance_to_decelerate = distance_to_decelerate self._distance_to_stop = distance_to_stop <|end_body_0|> <|body_start_1|> w...
A simple controller for Carla environment.
SimpleCarlaAlgorithm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleCarlaAlgorithm: """A simple controller for Carla environment.""" def __init__(self, observation_spec, action_spec: BoundedTensorSpec, reward_spec=TensorSpec(()), distance_to_decelerate=50.0, distance_to_stop=1.0, env=None, config: TrainerConfig=None, debug_summaries=False, name='Simple...
stack_v2_sparse_classes_75kplus_train_000405
8,254
permissive
[ { "docstring": "Args: observation_spec (nested TensorSpec): representing the observations. action_spec (nested BoundedTensorSpec): representing the actions. reward_spec (TensorSpec): a rank-1 or rank-0 tensor spec representing the reward(s). distance_to_decelerate (float|int): the distance in meter to goal from...
2
stack_v2_sparse_classes_30k_train_051408
Implement the Python class `SimpleCarlaAlgorithm` described below. Class description: A simple controller for Carla environment. Method signatures and docstrings: - def __init__(self, observation_spec, action_spec: BoundedTensorSpec, reward_spec=TensorSpec(()), distance_to_decelerate=50.0, distance_to_stop=1.0, env=N...
Implement the Python class `SimpleCarlaAlgorithm` described below. Class description: A simple controller for Carla environment. Method signatures and docstrings: - def __init__(self, observation_spec, action_spec: BoundedTensorSpec, reward_spec=TensorSpec(()), distance_to_decelerate=50.0, distance_to_stop=1.0, env=N...
b00ff2fa5e660de31020338ba340263183fbeaa4
<|skeleton|> class SimpleCarlaAlgorithm: """A simple controller for Carla environment.""" def __init__(self, observation_spec, action_spec: BoundedTensorSpec, reward_spec=TensorSpec(()), distance_to_decelerate=50.0, distance_to_stop=1.0, env=None, config: TrainerConfig=None, debug_summaries=False, name='Simple...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleCarlaAlgorithm: """A simple controller for Carla environment.""" def __init__(self, observation_spec, action_spec: BoundedTensorSpec, reward_spec=TensorSpec(()), distance_to_decelerate=50.0, distance_to_stop=1.0, env=None, config: TrainerConfig=None, debug_summaries=False, name='SimpleCarlaAlgorith...
the_stack_v2_python_sparse
alf/algorithms/handcrafted_algorithm.py
HorizonRobotics/alf
train
288
0dcf9aa6aea253d6604e92f92d305b06e94df33f
[ "neighbourhood_method = 'nonsense'\nradii = 10000\nmsg = 'nonsense is not a valid neighbourhood_method'\nwith self.assertRaisesRegex(ValueError, msg):\n NeighbourhoodProcessing(neighbourhood_method, radii)", "radii = 10000\nmsg = 'weighted_mode can only be used if neighbourhood_method is circular'\nwith self.a...
<|body_start_0|> neighbourhood_method = 'nonsense' radii = 10000 msg = 'nonsense is not a valid neighbourhood_method' with self.assertRaisesRegex(ValueError, msg): NeighbourhoodProcessing(neighbourhood_method, radii) <|end_body_0|> <|body_start_1|> radii = 10000 ...
Test the __init__ method of NeighbourhoodProcessing.
Test__init__
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test__init__: """Test the __init__ method of NeighbourhoodProcessing.""" def test_neighbourhood_method_does_not_exist(self): """Test that desired error message is raised, if the neighbourhood method does not exist.""" <|body_0|> def test_square_nbhood_with_weighted_mode(...
stack_v2_sparse_classes_75kplus_train_000406
15,840
permissive
[ { "docstring": "Test that desired error message is raised, if the neighbourhood method does not exist.", "name": "test_neighbourhood_method_does_not_exist", "signature": "def test_neighbourhood_method_does_not_exist(self)" }, { "docstring": "Test that desired error message is raised, if the neig...
2
null
Implement the Python class `Test__init__` described below. Class description: Test the __init__ method of NeighbourhoodProcessing. Method signatures and docstrings: - def test_neighbourhood_method_does_not_exist(self): Test that desired error message is raised, if the neighbourhood method does not exist. - def test_s...
Implement the Python class `Test__init__` described below. Class description: Test the __init__ method of NeighbourhoodProcessing. Method signatures and docstrings: - def test_neighbourhood_method_does_not_exist(self): Test that desired error message is raised, if the neighbourhood method does not exist. - def test_s...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test__init__: """Test the __init__ method of NeighbourhoodProcessing.""" def test_neighbourhood_method_does_not_exist(self): """Test that desired error message is raised, if the neighbourhood method does not exist.""" <|body_0|> def test_square_nbhood_with_weighted_mode(...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test__init__: """Test the __init__ method of NeighbourhoodProcessing.""" def test_neighbourhood_method_does_not_exist(self): """Test that desired error message is raised, if the neighbourhood method does not exist.""" neighbourhood_method = 'nonsense' radii = 10000 msg = '...
the_stack_v2_python_sparse
improver_tests/nbhood/nbhood/test_NeighbourhoodProcessing.py
metoppv/improver
train
101
15798e43839f90647b603e93dde540c9b0a761b8
[ "self.sid = sid\nself.uid = uid.encode()\nself.ch_type = channel_type\nself.cb_obj = callback_obj\nself.ip = ip\nself.port = int(port)\nself.udp_timeout = timeout\nself.tcp_timeout = timeout * 5\nself.tx = init_tx\nself.chunks_size = chunks_size\nself.cap = 2 ** 31\nself.loop = asyncio.get_event_loop()\nself.udp = ...
<|body_start_0|> self.sid = sid self.uid = uid.encode() self.ch_type = channel_type self.cb_obj = callback_obj self.ip = ip self.port = int(port) self.udp_timeout = timeout self.tcp_timeout = timeout * 5 self.tx = init_tx self.chunks_size =...
Creates an instance of a sender channel
SenderChannel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SenderChannel: """Creates an instance of a sender channel""" def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024): """Define all parameters that is specific to this channel""" <|body_0|> async def receive(self, tok...
stack_v2_sparse_classes_75kplus_train_000407
6,029
permissive
[ { "docstring": "Define all parameters that is specific to this channel", "name": "__init__", "signature": "def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024)" }, { "docstring": "Waits for data on either tcp or udp port to be received and...
6
stack_v2_sparse_classes_30k_train_013234
Implement the Python class `SenderChannel` described below. Class description: Creates an instance of a sender channel Method signatures and docstrings: - def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024): Define all parameters that is specific to this chann...
Implement the Python class `SenderChannel` described below. Class description: Creates an instance of a sender channel Method signatures and docstrings: - def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024): Define all parameters that is specific to this chann...
c44b71b782afcae360fb3ed90b1d43da78eae338
<|skeleton|> class SenderChannel: """Creates an instance of a sender channel""" def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024): """Define all parameters that is specific to this channel""" <|body_0|> async def receive(self, tok...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SenderChannel: """Creates an instance of a sender channel""" def __init__(self, sid, uid, channel_type, callback_obj, ip, port, timeout=2, init_tx=None, chunks_size=1024): """Define all parameters that is specific to this channel""" self.sid = sid self.uid = uid.encode() s...
the_stack_v2_python_sparse
self-stabilizing-coded-atomic-storage/code/channel/SenderChannel.py
eladschiller/self-stabilizing-cloud
train
0
25113283467f6f7f1fd0579d4d8c4175fbf64033
[ "super(GumbelSoftmaxWrapper, self).__init__()\nself.agent = agent\nself.straight_through = straight_through\nif not trainable_temperature:\n self.temperature = temperature\nelse:\n self.temperature = torch.nn.Parameter(torch.tensor([temperature]), requires_grad=True)\nself.distr_type = Categorical", "scores...
<|body_start_0|> super(GumbelSoftmaxWrapper, self).__init__() self.agent = agent self.straight_through = straight_through if not trainable_temperature: self.temperature = temperature else: self.temperature = torch.nn.Parameter(torch.tensor([temperature]), ...
Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from the Gumbel-Softmax (GS) distribution.
GumbelSoftmaxWrapper
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GumbelSoftmaxWrapper: """Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from the Gumbel-Softmax (GS) distribution."...
stack_v2_sparse_classes_75kplus_train_000408
11,543
permissive
[ { "docstring": "Arguments: agent -- The agent to be wrapped. agent.forward() has to output scores over the categories Keyword Arguments: temperature {float} -- The temperature of the Gumbel-Softmax distribution (default: {1.0}) trainable_temperature {bool} -- If set to True, the temperature becomes a trainable ...
3
null
Implement the Python class `GumbelSoftmaxWrapper` described below. Class description: Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from...
Implement the Python class `GumbelSoftmaxWrapper` described below. Class description: Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from...
e161e55432f5e30fedf7eae8ae11189c01bcd54a
<|skeleton|> class GumbelSoftmaxWrapper: """Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from the Gumbel-Softmax (GS) distribution."...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GumbelSoftmaxWrapper: """Gumbel-Softmax Wrapper for a network that parameterizes a Categorical distribution. Assumes that during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a sample from the Gumbel-Softmax (GS) distribution.""" def _...
the_stack_v2_python_sparse
mnist_ssvae/lvmhelpers/gumbel.py
Zirui0623/EvSoftmax
train
0
0cc433f93e459e7b55e0de954860add3ffc98d21
[ "nameExtension = os.path.splitext(video_file.name)[1]\nfrom utils.utils import create_md5\nhash = create_md5()\nif nameExtension.startswith(('.',)):\n file_name = hash + nameExtension\nelse:\n file_name = hash + '.' + nameExtension\nvideo_file.name = file_name", "self.fix_video_file_name(validated_data['vid...
<|body_start_0|> nameExtension = os.path.splitext(video_file.name)[1] from utils.utils import create_md5 hash = create_md5() if nameExtension.startswith(('.',)): file_name = hash + nameExtension else: file_name = hash + '.' + nameExtension video_fi...
创建视频序列化 并对这些字段的验证
VideoCreateSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VideoCreateSerializer: """创建视频序列化 并对这些字段的验证""" def fix_video_file_name(self, video_file): """解决上传的文件名太长问题 :param video_file: :return:""" <|body_0|> def create(self, validated_data): """重载父类方法,为了将处理视频及其封面并保存到本地 :param validated_data: :return:""" <|body_1|>...
stack_v2_sparse_classes_75kplus_train_000409
6,031
permissive
[ { "docstring": "解决上传的文件名太长问题 :param video_file: :return:", "name": "fix_video_file_name", "signature": "def fix_video_file_name(self, video_file)" }, { "docstring": "重载父类方法,为了将处理视频及其封面并保存到本地 :param validated_data: :return:", "name": "create", "signature": "def create(self, validated_data...
2
stack_v2_sparse_classes_30k_train_044237
Implement the Python class `VideoCreateSerializer` described below. Class description: 创建视频序列化 并对这些字段的验证 Method signatures and docstrings: - def fix_video_file_name(self, video_file): 解决上传的文件名太长问题 :param video_file: :return: - def create(self, validated_data): 重载父类方法,为了将处理视频及其封面并保存到本地 :param validated_data: :return:
Implement the Python class `VideoCreateSerializer` described below. Class description: 创建视频序列化 并对这些字段的验证 Method signatures and docstrings: - def fix_video_file_name(self, video_file): 解决上传的文件名太长问题 :param video_file: :return: - def create(self, validated_data): 重载父类方法,为了将处理视频及其封面并保存到本地 :param validated_data: :return: ...
fb64440ec7f84f08cf9cd706bec374fa357d7936
<|skeleton|> class VideoCreateSerializer: """创建视频序列化 并对这些字段的验证""" def fix_video_file_name(self, video_file): """解决上传的文件名太长问题 :param video_file: :return:""" <|body_0|> def create(self, validated_data): """重载父类方法,为了将处理视频及其封面并保存到本地 :param validated_data: :return:""" <|body_1|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VideoCreateSerializer: """创建视频序列化 并对这些字段的验证""" def fix_video_file_name(self, video_file): """解决上传的文件名太长问题 :param video_file: :return:""" nameExtension = os.path.splitext(video_file.name)[1] from utils.utils import create_md5 hash = create_md5() if nameExtension.sta...
the_stack_v2_python_sparse
apps/video/serializers.py
tuxi/video-hub
train
18
e0f513381a213bfe98e3a6923f107f772ad27497
[ "self.object_detector = object_detector\nself.feature_transformer = feature_transformer\nself.object_ranker = object_ranker\nself.use_masks = use_masks\nself.box_expansion_factor = box_expansion_factor\nself.logger = logging.getLogger(ImageObjectRankerComponent.__name__)", "self.logger.debug('Starting object dete...
<|body_start_0|> self.object_detector = object_detector self.feature_transformer = feature_transformer self.object_ranker = object_ranker self.use_masks = use_masks self.box_expansion_factor = box_expansion_factor self.logger = logging.getLogger(ImageObjectRankerComponent...
ImageObjectRankerComponent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageObjectRankerComponent: def __init__(self, object_detector, feature_transformer, object_ranker, use_masks=False, box_expansion_factor=0, **kwargs): """Creates an image object ranker (component architecture) that uses the delivered components. :param object_detector: Object detector c...
stack_v2_sparse_classes_75kplus_train_000410
4,324
no_license
[ { "docstring": "Creates an image object ranker (component architecture) that uses the delivered components. :param object_detector: Object detector component :param feature_transformer: Feature transformer component :param object_ranker: Object ranker component :param use_masks: If True, object masks are used f...
3
stack_v2_sparse_classes_30k_train_049010
Implement the Python class `ImageObjectRankerComponent` described below. Class description: Implement the ImageObjectRankerComponent class. Method signatures and docstrings: - def __init__(self, object_detector, feature_transformer, object_ranker, use_masks=False, box_expansion_factor=0, **kwargs): Creates an image o...
Implement the Python class `ImageObjectRankerComponent` described below. Class description: Implement the ImageObjectRankerComponent class. Method signatures and docstrings: - def __init__(self, object_detector, feature_transformer, object_ranker, use_masks=False, box_expansion_factor=0, **kwargs): Creates an image o...
259fff9b7576055ba1534375de859f8708f79337
<|skeleton|> class ImageObjectRankerComponent: def __init__(self, object_detector, feature_transformer, object_ranker, use_masks=False, box_expansion_factor=0, **kwargs): """Creates an image object ranker (component architecture) that uses the delivered components. :param object_detector: Object detector c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImageObjectRankerComponent: def __init__(self, object_detector, feature_transformer, object_ranker, use_masks=False, box_expansion_factor=0, **kwargs): """Creates an image object ranker (component architecture) that uses the delivered components. :param object_detector: Object detector component :para...
the_stack_v2_python_sparse
iorank/image_object_ranker_component.py
fweiland8/iorank
train
3
1b1410532e60719cdc65b0b7b86070f289323594
[ "self.min_cutoff = min_cutoff\nself.beta = beta\nself.d_cutoff = d_cutoff", "t_e = 1\na_d = smoothing_factor(t_e, self.d_cutoff)\ndx = np.sqrt(np.sum((x - x_prev) ** 2, axis=1))\ndx_prev = np.sqrt(np.sum(dx_prev ** 2, axis=1))\ndx_hat = exponential_smoothing(a_d, dx, dx_prev)\ncutoff = self.min_cutoff + self.beta...
<|body_start_0|> self.min_cutoff = min_cutoff self.beta = beta self.d_cutoff = d_cutoff <|end_body_0|> <|body_start_1|> t_e = 1 a_d = smoothing_factor(t_e, self.d_cutoff) dx = np.sqrt(np.sum((x - x_prev) ** 2, axis=1)) dx_prev = np.sqrt(np.sum(dx_prev ** 2, axis=...
OneEuroFilter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OneEuroFilter: def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1): """Initialize the one euro filter.""" <|body_0|> def __call__(self, x, x_prev, dx_prev): """Compute the filtered signal.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_000411
4,561
permissive
[ { "docstring": "Initialize the one euro filter.", "name": "__init__", "signature": "def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1)" }, { "docstring": "Compute the filtered signal.", "name": "__call__", "signature": "def __call__(self, x, x_prev, dx_prev)" } ]
2
stack_v2_sparse_classes_30k_train_044554
Implement the Python class `OneEuroFilter` described below. Class description: Implement the OneEuroFilter class. Method signatures and docstrings: - def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1): Initialize the one euro filter. - def __call__(self, x, x_prev, dx_prev): Compute the filtered signa...
Implement the Python class `OneEuroFilter` described below. Class description: Implement the OneEuroFilter class. Method signatures and docstrings: - def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1): Initialize the one euro filter. - def __call__(self, x, x_prev, dx_prev): Compute the filtered signa...
3f1aaa3a8724078b080d64cf5d18dcdfae41bafe
<|skeleton|> class OneEuroFilter: def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1): """Initialize the one euro filter.""" <|body_0|> def __call__(self, x, x_prev, dx_prev): """Compute the filtered signal.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OneEuroFilter: def __init__(self, dx0=0.0, min_cutoff=0.15, beta=0.8, d_cutoff=1): """Initialize the one euro filter.""" self.min_cutoff = min_cutoff self.beta = beta self.d_cutoff = d_cutoff def __call__(self, x, x_prev, dx_prev): """Compute the filtered signal.""...
the_stack_v2_python_sparse
Skps/core/smoother/lk.py
1996scarlet/Peppa_Pig_Face_Engine
train
1
a1d5e7eaf1af13478f592cc8054788993b873189
[ "super(CopyTask, self).__init__(*args, **kwargs)\nself.setMetadata('dispatch.split', True)\nself.setMetadata('dispatch.splitSize', 20)", "for crawler in self.crawlers():\n filePath = self.target(crawler)\n try:\n os.makedirs(os.path.dirname(filePath))\n except OSError:\n pass\n sourceFil...
<|body_start_0|> super(CopyTask, self).__init__(*args, **kwargs) self.setMetadata('dispatch.split', True) self.setMetadata('dispatch.splitSize', 20) <|end_body_0|> <|body_start_1|> for crawler in self.crawlers(): filePath = self.target(crawler) try: ...
Copies a file to the filePath.
CopyTask
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CopyTask: """Copies a file to the filePath.""" def __init__(self, *args, **kwargs): """Create a CopyTask task.""" <|body_0|> def _perform(self): """Perform the task.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(CopyTask, self).__init__(...
stack_v2_sparse_classes_75kplus_train_000412
1,671
permissive
[ { "docstring": "Create a CopyTask task.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Perform the task.", "name": "_perform", "signature": "def _perform(self)" } ]
2
stack_v2_sparse_classes_30k_train_006922
Implement the Python class `CopyTask` described below. Class description: Copies a file to the filePath. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Create a CopyTask task. - def _perform(self): Perform the task.
Implement the Python class `CopyTask` described below. Class description: Copies a file to the filePath. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Create a CopyTask task. - def _perform(self): Perform the task. <|skeleton|> class CopyTask: """Copies a file to the filePath.""" ...
046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4
<|skeleton|> class CopyTask: """Copies a file to the filePath.""" def __init__(self, *args, **kwargs): """Create a CopyTask task.""" <|body_0|> def _perform(self): """Perform the task.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CopyTask: """Copies a file to the filePath.""" def __init__(self, *args, **kwargs): """Create a CopyTask task.""" super(CopyTask, self).__init__(*args, **kwargs) self.setMetadata('dispatch.split', True) self.setMetadata('dispatch.splitSize', 20) def _perform(self): ...
the_stack_v2_python_sparse
src/lib/kombi/Task/Fs/CopyTask.py
kombiHQ/kombi
train
2
903b141831749b713db7a5a24373536baa40d7df
[ "true = []\npreds = []\nfor modeling_instance in dataset.instances:\n true.append(modeling_instance.label.causal)\n preds.append(modeling_instance.pred.causal)\nreturn Metrics.task1(true, preds)", "true = []\npreds = []\nfor modeling_instance in dataset.instances:\n true.append(modeling_instance.label.ca...
<|body_start_0|> true = [] preds = [] for modeling_instance in dataset.instances: true.append(modeling_instance.label.causal) preds.append(modeling_instance.pred.causal) return Metrics.task1(true, preds) <|end_body_0|> <|body_start_1|> true = [] p...
MetricsWrapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricsWrapper: def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]: """calculates the metrics for FinCausal Taks 1""" <|body_0|> def calculate_confusionmatrix_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, int]: """cal...
stack_v2_sparse_classes_75kplus_train_000413
2,714
no_license
[ { "docstring": "calculates the metrics for FinCausal Taks 1", "name": "calculate_metrics_task1", "signature": "def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]" }, { "docstring": "calculates TP, FP, FN and TN for FinCausal Task 1", "name": "calculate_co...
2
stack_v2_sparse_classes_30k_train_030459
Implement the Python class `MetricsWrapper` described below. Class description: Implement the MetricsWrapper class. Method signatures and docstrings: - def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]: calculates the metrics for FinCausal Taks 1 - def calculate_confusionmatrix_t...
Implement the Python class `MetricsWrapper` described below. Class description: Implement the MetricsWrapper class. Method signatures and docstrings: - def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]: calculates the metrics for FinCausal Taks 1 - def calculate_confusionmatrix_t...
fe7d0e14c4c96741cc424a42712d2611e06cdc03
<|skeleton|> class MetricsWrapper: def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]: """calculates the metrics for FinCausal Taks 1""" <|body_0|> def calculate_confusionmatrix_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, int]: """cal...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetricsWrapper: def calculate_metrics_task1(dataset: FinCausalTask1ModelingDataset) -> Dict[str, float]: """calculates the metrics for FinCausal Taks 1""" true = [] preds = [] for modeling_instance in dataset.instances: true.append(modeling_instance.label.causal) ...
the_stack_v2_python_sparse
fnp/fincausal/evaluation/metrics.py
sarthakTUM/fincausal
train
1
76f9b2dabf8e91810c16c02f10edc48858557929
[ "input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape\nrand_min, rand_max = rand_range\nself.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes])\nself.num_trials = num_trials\nself.num_input_per_trial = nu...
<|body_start_0|> input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape rand_min, rand_max = rand_range self.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes]) self.num_trials = ...
AvgOnnxLatency
[ "MIT", "LicenseRef-scancode-free-unknown", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AvgOnnxLatency: def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None): """Measure the...
stack_v2_sparse_classes_75kplus_train_000414
4,455
permissive
[ { "docstring": "Measure the average ONNX Latency (in millseconds) of a model Args: input_shape (Union[Tuple, List[Tuple]]): Model Input shape or list of model input shapes. num_trials (int, optional): Number of trials. Defaults to 15. num_input (int, optional): Number of input per trial. Defaults to 15. input_d...
3
stack_v2_sparse_classes_30k_test_000684
Implement the Python class `AvgOnnxLatency` described below. Class description: Implement the AvgOnnxLatency class. Method signatures and docstrings: - def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float...
Implement the Python class `AvgOnnxLatency` described below. Class description: Implement the AvgOnnxLatency class. Method signatures and docstrings: - def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float...
95d6e19a1523a701b3fbc249dd1a7d1e7ba44aee
<|skeleton|> class AvgOnnxLatency: def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None): """Measure the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AvgOnnxLatency: def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None): """Measure the average ONNX ...
the_stack_v2_python_sparse
tasks/facial_landmark_detection/latency.py
microsoft/archai
train
439
f3f5c3430f5c84f13b6654527d1004225d139f50
[ "self.Wz = np.random.normal(size=(h + i, h))\nself.Wr = np.random.normal(size=(h + i, h))\nself.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))", "x_max = np.max(x, axis=...
<|body_start_0|> self.Wz = np.random.normal(size=(h + i, h)) self.Wr = np.random.normal(size=(h + i, h)) self.Wh = np.random.normal(size=(h + i, h)) self.Wy = np.random.normal(size=(h, o)) self.bz = np.zeros((1, h)) self.br = np.zeros((1, h)) self.bh = np.zeros((1...
Class GRUCell that represents a gated recurrent unit
GRUCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GRUCell: """Class GRUCell that represents a gated recurrent unit""" def __init__(self, i, h, o): """class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz,...
stack_v2_sparse_classes_75kplus_train_000415
2,573
no_license
[ { "docstring": "class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz, Wr, Wh, Wy, bz, br, bh, by that represent the weights and biases of the cell - Wzand bz are for the update gate...
3
stack_v2_sparse_classes_30k_train_036031
Implement the Python class `GRUCell` described below. Class description: Class GRUCell that represents a gated recurrent unit Method signatures and docstrings: - def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dim...
Implement the Python class `GRUCell` described below. Class description: Class GRUCell that represents a gated recurrent unit Method signatures and docstrings: - def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dim...
fc2cec306961f7ca2448965ddd3a2f656bbe10c7
<|skeleton|> class GRUCell: """Class GRUCell that represents a gated recurrent unit""" def __init__(self, i, h, o): """class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GRUCell: """Class GRUCell that represents a gated recurrent unit""" def __init__(self, i, h, o): """class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wz, Wr, Wh, Wy, ...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/2-gru_cell.py
dalexach/holbertonschool-machine_learning
train
2
81c3f329d93adc3b57df685c68b719f9a16e112d
[ "zk_client = KazooClient(hosts=','.join(zk_locations), connection_retry=ZK_PERSISTENT_RECONNECTS)\nzk_client.start()\nself.ioloop = io_loop\nself.target = target\nself.start_time = None\nself.status = 'Not started'\nself.finish_time = None\nself.solr_adapter = solr_adapter.SolrAdapter(zk_client)\nself.scheduled_ind...
<|body_start_0|> zk_client = KazooClient(hosts=','.join(zk_locations), connection_retry=ZK_PERSISTENT_RECONNECTS) zk_client.start() self.ioloop = io_loop self.target = target self.start_time = None self.status = 'Not started' self.finish_time = None self.s...
Exports data from Search Service 2 to target storage.
Exporter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exporter: """Exports data from Search Service 2 to target storage.""" def __init__(self, io_loop, zk_locations, target, max_concurrency): """Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target)...
stack_v2_sparse_classes_75kplus_train_000416
10,087
permissive
[ { "docstring": "Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target). max_concurrency: an int - maximum number of concurrent jobs.", "name": "__init__", "signature": "def __init__(self, io_loop, zk_locations, targ...
4
stack_v2_sparse_classes_30k_train_046817
Implement the Python class `Exporter` described below. Class description: Exports data from Search Service 2 to target storage. Method signatures and docstrings: - def __init__(self, io_loop, zk_locations, target, max_concurrency): Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locatio...
Implement the Python class `Exporter` described below. Class description: Exports data from Search Service 2 to target storage. Method signatures and docstrings: - def __init__(self, io_loop, zk_locations, target, max_concurrency): Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locatio...
be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f
<|skeleton|> class Exporter: """Exports data from Search Service 2 to target storage.""" def __init__(self, io_loop, zk_locations, target, max_concurrency): """Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Exporter: """Exports data from Search Service 2 to target storage.""" def __init__(self, io_loop, zk_locations, target, max_concurrency): """Args: io_loop: an instance of tornado IOLoop. zk_locations: a list - Zookeeper locations. target: an instance of export Target (e.g.: S3Target). max_concurr...
the_stack_v2_python_sparse
SearchService2/appscale/search/backup_restore/backup_from_v2.py
obino/appscale
train
1
d2b1908815875ef9a26bcb5af85bcf7ade7de7e8
[ "next_nodes = [[] for _ in range(numCourses)]\nin_degree = [0] * numCourses\nfree_courses = []\nfor edge in prerequisites:\n next_nodes[edge[1]].append(edge[0])\n in_degree[edge[0]] += 1\nfor i in range(len(in_degree)):\n if in_degree[i] == 0:\n free_courses.append(i)\nfor i in free_courses:\n fo...
<|body_start_0|> next_nodes = [[] for _ in range(numCourses)] in_degree = [0] * numCourses free_courses = [] for edge in prerequisites: next_nodes[edge[1]].append(edge[0]) in_degree[edge[0]] += 1 for i in range(len(in_degree)): if in_degree[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canFinish(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: bool""" <|body_0|> def canFinish1(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: b...
stack_v2_sparse_classes_75kplus_train_000417
2,912
no_license
[ { "docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool", "name": "canFinish", "signature": "def canFinish(self, numCourses, prerequisites)" }, { "docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool", "name": "canFinish1", ...
2
stack_v2_sparse_classes_30k_train_043906
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool - def canFinish1(self, numCourses, prerequisites): :type n...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool - def canFinish1(self, numCourses, prerequisites): :type n...
ff9118b8a0ce9a3db89c2bf6f2f79def7ae4f17f
<|skeleton|> class Solution: def canFinish(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: bool""" <|body_0|> def canFinish1(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def canFinish(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: bool""" next_nodes = [[] for _ in range(numCourses)] in_degree = [0] * numCourses free_courses = [] for edge in prerequisites: nex...
the_stack_v2_python_sparse
201-300/207.py
JianghaoPi/LeetCode
train
0
25c0e14b661f5db7373d9a3e39854461a80d5ef0
[ "with patch('builtins.open', mock_open()) as open_mock:\n with patch('os.path.exists'):\n with patch('os.path.getsize') as get_size:\n get_size.return_value = 0\n add_furnature('x.csv', 'Cresenta Starchelle', 'xy_z', 'stuff', 8231.3164879)\n expected = 'Cresenta Starchelle...
<|body_start_0|> with patch('builtins.open', mock_open()) as open_mock: with patch('os.path.exists'): with patch('os.path.getsize') as get_size: get_size.return_value = 0 add_furnature('x.csv', 'Cresenta Starchelle', 'xy_z', 'stuff', 8231.31648...
A suite of test cases for inventory.py
TestInventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInventory: """A suite of test cases for inventory.py""" def test_add_furnature_empty_file(self): """Validates add furnature with an empty file""" <|body_0|> def test_add_furnature_existing_file(self): """Validates add furnature with an existing file""" ...
stack_v2_sparse_classes_75kplus_train_000418
4,317
no_license
[ { "docstring": "Validates add furnature with an empty file", "name": "test_add_furnature_empty_file", "signature": "def test_add_furnature_empty_file(self)" }, { "docstring": "Validates add furnature with an existing file", "name": "test_add_furnature_existing_file", "signature": "def te...
4
null
Implement the Python class `TestInventory` described below. Class description: A suite of test cases for inventory.py Method signatures and docstrings: - def test_add_furnature_empty_file(self): Validates add furnature with an empty file - def test_add_furnature_existing_file(self): Validates add furnature with an ex...
Implement the Python class `TestInventory` described below. Class description: A suite of test cases for inventory.py Method signatures and docstrings: - def test_add_furnature_empty_file(self): Validates add furnature with an empty file - def test_add_furnature_existing_file(self): Validates add furnature with an ex...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class TestInventory: """A suite of test cases for inventory.py""" def test_add_furnature_empty_file(self): """Validates add furnature with an empty file""" <|body_0|> def test_add_furnature_existing_file(self): """Validates add furnature with an existing file""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestInventory: """A suite of test cases for inventory.py""" def test_add_furnature_empty_file(self): """Validates add furnature with an empty file""" with patch('builtins.open', mock_open()) as open_mock: with patch('os.path.exists'): with patch('os.path.getsiz...
the_stack_v2_python_sparse
students/anthony_mckeever/lesson_8/assignment_1/test_unit.py
JavaRod/SP_Python220B_2019
train
1
dd0748fddbaba406b8d42ca4620c5a9618b5d2a5
[ "response = self.client.get('/profiles/')\nself.assertEqual(response.status_code, 302)\nuser = User.objects.create(username='testuser')\nuser.set_password('12345')\nuser.save()\nlogged_in = self.client.login(username='testuser', password='12345')\nresponse = self.client.get('/profiles/')\nself.assertEqual(response....
<|body_start_0|> response = self.client.get('/profiles/') self.assertEqual(response.status_code, 302) user = User.objects.create(username='testuser') user.set_password('12345') user.save() logged_in = self.client.login(username='testuser', password='12345') respon...
TestView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestView: def test_profiles(self): """testing if the profile page works and template used""" <|body_0|> def test_show_correct_orders(self): """testing if orders shown are correctly associated to profile""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_000419
2,441
no_license
[ { "docstring": "testing if the profile page works and template used", "name": "test_profiles", "signature": "def test_profiles(self)" }, { "docstring": "testing if orders shown are correctly associated to profile", "name": "test_show_correct_orders", "signature": "def test_show_correct_o...
2
stack_v2_sparse_classes_30k_train_042131
Implement the Python class `TestView` described below. Class description: Implement the TestView class. Method signatures and docstrings: - def test_profiles(self): testing if the profile page works and template used - def test_show_correct_orders(self): testing if orders shown are correctly associated to profile
Implement the Python class `TestView` described below. Class description: Implement the TestView class. Method signatures and docstrings: - def test_profiles(self): testing if the profile page works and template used - def test_show_correct_orders(self): testing if orders shown are correctly associated to profile <|...
e61dde21f68e84c312016fd2672c138b60b76344
<|skeleton|> class TestView: def test_profiles(self): """testing if the profile page works and template used""" <|body_0|> def test_show_correct_orders(self): """testing if orders shown are correctly associated to profile""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestView: def test_profiles(self): """testing if the profile page works and template used""" response = self.client.get('/profiles/') self.assertEqual(response.status_code, 302) user = User.objects.create(username='testuser') user.set_password('12345') user.save...
the_stack_v2_python_sparse
profiles/test_views.py
Code-Institute-Submissions/furnitart
train
0
6dc481e5f463f2677c05316be025fe7e4c5214b2
[ "self.udp_target = udp_target\nself.udp_port = udp_port\nself.verbosity = verbosity\nself.peer = '{}:{}'.format(self.udp_target, self.udp_port)\nif is_ipv4(self.udp_target):\n self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nelif is_ipv6(self.udp_target):\n self.udp_client = socket.socket(s...
<|body_start_0|> self.udp_target = udp_target self.udp_port = udp_port self.verbosity = verbosity self.peer = '{}:{}'.format(self.udp_target, self.udp_port) if is_ipv4(self.udp_target): self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) elif is...
UDP Client provides methods to handle communication with UDP server
UDPCli
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UDPCli: """UDP Client provides methods to handle communication with UDP server""" def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False) -> None: """UDP client constructor :param str udp_target: target UDP server ip address :param int udp_port: target UDP server po...
stack_v2_sparse_classes_75kplus_train_000420
3,289
permissive
[ { "docstring": "UDP client constructor :param str udp_target: target UDP server ip address :param int udp_port: target UDP server port :param bool verbosity: display verbose output :return None:", "name": "__init__", "signature": "def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False)...
4
stack_v2_sparse_classes_30k_train_035465
Implement the Python class `UDPCli` described below. Class description: UDP Client provides methods to handle communication with UDP server Method signatures and docstrings: - def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False) -> None: UDP client constructor :param str udp_target: target UDP se...
Implement the Python class `UDPCli` described below. Class description: UDP Client provides methods to handle communication with UDP server Method signatures and docstrings: - def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False) -> None: UDP client constructor :param str udp_target: target UDP se...
56ae6325c08bcedd22c57b9fe11b58f1b38314ca
<|skeleton|> class UDPCli: """UDP Client provides methods to handle communication with UDP server""" def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False) -> None: """UDP client constructor :param str udp_target: target UDP server ip address :param int udp_port: target UDP server po...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UDPCli: """UDP Client provides methods to handle communication with UDP server""" def __init__(self, udp_target: str, udp_port: int, verbosity: bool=False) -> None: """UDP client constructor :param str udp_target: target UDP server ip address :param int udp_port: target UDP server port :param boo...
the_stack_v2_python_sparse
maza/core/udp/udp_client.py
ArturSpirin/maza
train
2
1256d96f7e526597a2fa769a7cc25f395cc16cb0
[ "file, offset = data.split('@')\nraw = open(file, 'r').read()\nptr = int(offset, 16)\nnum = ord(raw[ptr])\nptr = ptr + 4\nlst = []\nfor i in range(num):\n length = ord(raw[ptr])\n lst.append(raw[ptr + 2:ptr + 2 + length])\n ptr += 2 + length\nreturn lst", "d = {'size': (cls.Width / twips_per_pixel, cls.H...
<|body_start_0|> file, offset = data.split('@') raw = open(file, 'r').read() ptr = int(offset, 16) num = ord(raw[ptr]) ptr = ptr + 4 lst = [] for i in range(num): length = ord(raw[ptr]) lst.append(raw[ptr + 2:ptr + 2 + length]) ...
ComboBox
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ComboBox: def _getEntriesFromFRX(cls, data): """Get list entries from FRX file""" <|body_0|> def _getClassSpecificControlEntries(cls): """Return additional items for this entry""" <|body_1|> <|end_skeleton|> <|body_start_0|> file, offset = data.spli...
stack_v2_sparse_classes_75kplus_train_000421
21,850
permissive
[ { "docstring": "Get list entries from FRX file", "name": "_getEntriesFromFRX", "signature": "def _getEntriesFromFRX(cls, data)" }, { "docstring": "Return additional items for this entry", "name": "_getClassSpecificControlEntries", "signature": "def _getClassSpecificControlEntries(cls)" ...
2
stack_v2_sparse_classes_30k_train_021391
Implement the Python class `ComboBox` described below. Class description: Implement the ComboBox class. Method signatures and docstrings: - def _getEntriesFromFRX(cls, data): Get list entries from FRX file - def _getClassSpecificControlEntries(cls): Return additional items for this entry
Implement the Python class `ComboBox` described below. Class description: Implement the ComboBox class. Method signatures and docstrings: - def _getEntriesFromFRX(cls, data): Get list entries from FRX file - def _getClassSpecificControlEntries(cls): Return additional items for this entry <|skeleton|> class ComboBox:...
847ce71e85093ea5ee668ec61dbfba760ffa6bbd
<|skeleton|> class ComboBox: def _getEntriesFromFRX(cls, data): """Get list entries from FRX file""" <|body_0|> def _getClassSpecificControlEntries(cls): """Return additional items for this entry""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ComboBox: def _getEntriesFromFRX(cls, data): """Get list entries from FRX file""" file, offset = data.split('@') raw = open(file, 'r').read() ptr = int(offset, 16) num = ord(raw[ptr]) ptr = ptr + 4 lst = [] for i in range(num): length...
the_stack_v2_python_sparse
vb2py/targets/pythoncard/controls.py
rayzamgh/sumurProjection
train
1
56bebe72b0a3496f4fc6c07d090d7df22c8fcb3b
[ "self._fake_lock = fake_lock\nself._lock = Lock()\nself._status = Status()\nself._name = []\nself._mode = []\nself._nest = 0\nself._auto_from_script = False\nif self._fake_lock:\n self.log = open('lock.log', 'w')", "if self._status.debug:\n sys.stdout.write(\"debug> Execution lock: Acquisition by '%s' ('%s...
<|body_start_0|> self._fake_lock = fake_lock self._lock = Lock() self._status = Status() self._name = [] self._mode = [] self._nest = 0 self._auto_from_script = False if self._fake_lock: self.log = open('lock.log', 'w') <|end_body_0|> <|body_s...
A type of locking object for locking execution of relax.
Exec_lock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exec_lock: """A type of locking object for locking execution of relax.""" def __init__(self, fake_lock=False): """Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as the locking mechanism is turned off. @type fake_lock: bool"...
stack_v2_sparse_classes_75kplus_train_000422
18,991
no_license
[ { "docstring": "Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as the locking mechanism is turned off. @type fake_lock: bool", "name": "__init__", "signature": "def __init__(self, fake_lock=False)" }, { "docstring": "Simulate the Lock....
4
null
Implement the Python class `Exec_lock` described below. Class description: A type of locking object for locking execution of relax. Method signatures and docstrings: - def __init__(self, fake_lock=False): Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as th...
Implement the Python class `Exec_lock` described below. Class description: A type of locking object for locking execution of relax. Method signatures and docstrings: - def __init__(self, fake_lock=False): Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as th...
c317326ddeacd1a1c608128769676899daeae531
<|skeleton|> class Exec_lock: """A type of locking object for locking execution of relax.""" def __init__(self, fake_lock=False): """Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as the locking mechanism is turned off. @type fake_lock: bool"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Exec_lock: """A type of locking object for locking execution of relax.""" def __init__(self, fake_lock=False): """Set up the lock-like object. @keyword fake_lock: A flag which is True will allow this object to be debugged as the locking mechanism is turned off. @type fake_lock: bool""" se...
the_stack_v2_python_sparse
status.py
jlec/relax
train
4
c218f1e0526ac89f6daec4f458cc5c311c8fb4fb
[ "self.event_str = event_str\nself.date = convert_str_to_date(date_str)\nself.start_time_str = start_time_str\nself.end_time_str = end_time_str", "date_str = datetime.datetime.strftime(self.date, DATE_STR_FMT)\nret = ' '.join([self.event_str, 'on', date_str])\nif self.start_time_str:\n if self.end_time_str:\n ...
<|body_start_0|> self.event_str = event_str self.date = convert_str_to_date(date_str) self.start_time_str = start_time_str self.end_time_str = end_time_str <|end_body_0|> <|body_start_1|> date_str = datetime.datetime.strftime(self.date, DATE_STR_FMT) ret = ' '.join([self...
Class for storing calendar event information.
CalendarEvent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CalendarEvent: """Class for storing calendar event information.""" def __init__(self, event_str='', date_str='', start_time_str='', end_time_str=''): """Initialize this CalendarEvent instance.""" <|body_0|> def __str__(self): """Returns the string representation ...
stack_v2_sparse_classes_75kplus_train_000423
4,660
permissive
[ { "docstring": "Initialize this CalendarEvent instance.", "name": "__init__", "signature": "def __init__(self, event_str='', date_str='', start_time_str='', end_time_str='')" }, { "docstring": "Returns the string representation of this CalendarEvent.", "name": "__str__", "signature": "de...
2
stack_v2_sparse_classes_30k_train_036474
Implement the Python class `CalendarEvent` described below. Class description: Class for storing calendar event information. Method signatures and docstrings: - def __init__(self, event_str='', date_str='', start_time_str='', end_time_str=''): Initialize this CalendarEvent instance. - def __str__(self): Returns the s...
Implement the Python class `CalendarEvent` described below. Class description: Class for storing calendar event information. Method signatures and docstrings: - def __init__(self, event_str='', date_str='', start_time_str='', end_time_str=''): Initialize this CalendarEvent instance. - def __str__(self): Returns the s...
bf04c4fdb53de4e3c9fbc0959464f106e41b52bf
<|skeleton|> class CalendarEvent: """Class for storing calendar event information.""" def __init__(self, event_str='', date_str='', start_time_str='', end_time_str=''): """Initialize this CalendarEvent instance.""" <|body_0|> def __str__(self): """Returns the string representation ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CalendarEvent: """Class for storing calendar event information.""" def __init__(self, event_str='', date_str='', start_time_str='', end_time_str=''): """Initialize this CalendarEvent instance.""" self.event_str = event_str self.date = convert_str_to_date(date_str) self.sta...
the_stack_v2_python_sparse
LTUAssistantPlus/calendardb.py
saswat01/LTUAssistantPlus
train
0
4fb10ceba0490c5bee46dca5188cd638c6f6a316
[ "self.capacity = capacity\nself.dict = collections.defaultdict(int)\nself.q = collections.deque()", "if key in self.dict:\n self.q.remove(key)\n self.q.append(key)\n return self.dict[key]\nreturn -1", "if key in self.dict:\n self.q.remove(key)\nelif len(self.dict) >= self.capacity:\n del self.dic...
<|body_start_0|> self.capacity = capacity self.dict = collections.defaultdict(int) self.q = collections.deque() <|end_body_0|> <|body_start_1|> if key in self.dict: self.q.remove(key) self.q.append(key) return self.dict[key] return -1 <|end_bo...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_000424
824
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
474886c5c43a6192db2708e664663542c2e39548
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.dict = collections.defaultdict(int) self.q = collections.deque() def get(self, key): """:type key: int :rtype: int""" if key in self.dict: self.q.rem...
the_stack_v2_python_sparse
question_leetcode/146_1.py
paul0920/leetcode
train
1
5d36b7a52eded29bd53e248c315d4d27729bb223
[ "super().__init__(grid_proportion)\nself.level = level\nself.text = text\nself.id = 'heading_' + str(uuid.uuid4())", "env = templates.environment\ntemplate = env.get_template('heading.html')\nreturn template.render(level=self.level, text=self.text, id=self.id)" ]
<|body_start_0|> super().__init__(grid_proportion) self.level = level self.text = text self.id = 'heading_' + str(uuid.uuid4()) <|end_body_0|> <|body_start_1|> env = templates.environment template = env.get_template('heading.html') return template.render(level=se...
HeadingElement
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeadingElement: def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): """Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The te...
stack_v2_sparse_classes_75kplus_train_000425
1,875
permissive
[ { "docstring": "Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The text to display in the heading.", "name": "__init__", "signature": "def __init__(self, level: int, text: str, grid_pro...
2
stack_v2_sparse_classes_30k_train_016125
Implement the Python class `HeadingElement` described below. Class description: Implement the HeadingElement class. Method signatures and docstrings: - def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): Represents an ordinary heading, usually used to start a new section i...
Implement the Python class `HeadingElement` described below. Class description: Implement the HeadingElement class. Method signatures and docstrings: - def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): Represents an ordinary heading, usually used to start a new section i...
f707e51bc2ff45f6e46dcdd24d59d83ce7dc4f94
<|skeleton|> class HeadingElement: def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): """Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HeadingElement: def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): """Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The text to display ...
the_stack_v2_python_sparse
qf_lib/documents_utils/document_exporting/element/heading.py
quarkfin/qf-lib
train
379
49f2feb3fda61cb48cf79da4067115caec467000
[ "user = User.objects.create_user(username='username', email='myemail@test.com', password='password', is_staff=True)\nself.client.login(username='username', password='password')\npost = Post(title='Title', content='content', category='test category', tag='test tag', view_on_front_page='True')\npost.save()\npage = se...
<|body_start_0|> user = User.objects.create_user(username='username', email='myemail@test.com', password='password', is_staff=True) self.client.login(username='username', password='password') post = Post(title='Title', content='content', category='test category', tag='test tag', view_on_front_pa...
test delete posts
TestDeletPostView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDeletPostView: """test delete posts""" def test_to_delete_a_post(self): """test deleting a post""" <|body_0|> def test_to_delete_a_post_with_no_one_logged_in(self): """test to delete post when no-one is logged in""" <|body_1|> def test_to_delete_...
stack_v2_sparse_classes_75kplus_train_000426
11,691
no_license
[ { "docstring": "test deleting a post", "name": "test_to_delete_a_post", "signature": "def test_to_delete_a_post(self)" }, { "docstring": "test to delete post when no-one is logged in", "name": "test_to_delete_a_post_with_no_one_logged_in", "signature": "def test_to_delete_a_post_with_no_...
3
null
Implement the Python class `TestDeletPostView` described below. Class description: test delete posts Method signatures and docstrings: - def test_to_delete_a_post(self): test deleting a post - def test_to_delete_a_post_with_no_one_logged_in(self): test to delete post when no-one is logged in - def test_to_delete_a_po...
Implement the Python class `TestDeletPostView` described below. Class description: test delete posts Method signatures and docstrings: - def test_to_delete_a_post(self): test deleting a post - def test_to_delete_a_post_with_no_one_logged_in(self): test to delete post when no-one is logged in - def test_to_delete_a_po...
a80148cb642cb09dac57cff18483be14fed67dfd
<|skeleton|> class TestDeletPostView: """test delete posts""" def test_to_delete_a_post(self): """test deleting a post""" <|body_0|> def test_to_delete_a_post_with_no_one_logged_in(self): """test to delete post when no-one is logged in""" <|body_1|> def test_to_delete_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestDeletPostView: """test delete posts""" def test_to_delete_a_post(self): """test deleting a post""" user = User.objects.create_user(username='username', email='myemail@test.com', password='password', is_staff=True) self.client.login(username='username', password='password') ...
the_stack_v2_python_sparse
posts/tests_views.py
sarahbarron/Stream-3-Project
train
1
a42eea4c6e2dfe6aaab11263c36996bca663d9f1
[ "states = states[1:]\ndiscounted_rewards = self.discount_reward(rewards)\nfor state, reward in zip(states, discounted_rewards):\n self.state_values[self.convert_to_immutable(state)] = self.state_values[self.convert_to_immutable(state)] + self.alpha * (reward - self.get_value(state))", "discounted_rewards = []\...
<|body_start_0|> states = states[1:] discounted_rewards = self.discount_reward(rewards) for state, reward in zip(states, discounted_rewards): self.state_values[self.convert_to_immutable(state)] = self.state_values[self.convert_to_immutable(state)] + self.alpha * (reward - self.get_va...
Learns optimum behavior using the iterative tabular MC method.
MonteCarloTabular
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MonteCarloTabular: """Learns optimum behavior using the iterative tabular MC method.""" def batch_update(self, states, rewards, actions): """Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s_t) + alpha(G_t - V(s_t))""" <|body_0|> def ...
stack_v2_sparse_classes_75kplus_train_000427
1,207
no_license
[ { "docstring": "Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s_t) + alpha(G_t - V(s_t))", "name": "batch_update", "signature": "def batch_update(self, states, rewards, actions)" }, { "docstring": "Calculate the future discounted reward.", "name": "disc...
2
null
Implement the Python class `MonteCarloTabular` described below. Class description: Learns optimum behavior using the iterative tabular MC method. Method signatures and docstrings: - def batch_update(self, states, rewards, actions): Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s...
Implement the Python class `MonteCarloTabular` described below. Class description: Learns optimum behavior using the iterative tabular MC method. Method signatures and docstrings: - def batch_update(self, states, rewards, actions): Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s...
00b6f97c98e0bf6da2c0732911e165418b54291e
<|skeleton|> class MonteCarloTabular: """Learns optimum behavior using the iterative tabular MC method.""" def batch_update(self, states, rewards, actions): """Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s_t) + alpha(G_t - V(s_t))""" <|body_0|> def ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MonteCarloTabular: """Learns optimum behavior using the iterative tabular MC method.""" def batch_update(self, states, rewards, actions): """Update the model using the states, rewards using the iterative MC update. V(s_t) = V(s_t) + alpha(G_t - V(s_t))""" states = states[1:] disco...
the_stack_v2_python_sparse
RL_for_gridworld/Tabular_methods/State_Value/MonteCarloTabular.py
sachag678/Reinforcement_learning
train
8
81c6259ccf50aec3166e6e8165e01bae53c11a05
[ "super().__init__(**kwargs)\nif num_spatial_dims <= 0:\n raise ValueError(f'We only support convolution operations for `num_spatial_dims` greater than 0, received num_spatial_dims={num_spatial_dims}.')\nself.num_spatial_dims = num_spatial_dims\nself.output_channels = output_channels\nself.kernel_shape = hk_utils...
<|body_start_0|> super().__init__(**kwargs) if num_spatial_dims <= 0: raise ValueError(f'We only support convolution operations for `num_spatial_dims` greater than 0, received num_spatial_dims={num_spatial_dims}.') self.num_spatial_dims = num_spatial_dims self.output_channels...
General N-dimensional convolutional.
ConvND
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvND: """General N-dimensional convolutional.""" def __init__(self, num_spatial_dims: int, output_channels: int, kernel_shape: tp.Union[int, tp.Sequence[int]], stride: tp.Union[int, tp.Sequence[int]]=1, rate: tp.Union[int, tp.Sequence[int]]=1, padding: tp.Union[str, tp.Sequence[tp.Tuple[in...
stack_v2_sparse_classes_75kplus_train_000428
28,799
permissive
[ { "docstring": "Initializes the module. Args: num_spatial_dims: The number of spatial dimensions of the input. output_channels: Number of output channels. kernel_shape: The shape of the kernel. Either an integer or a sequence of length ``num_spatial_dims``. stride: tp.Optional stride for the kernel. Either an i...
2
stack_v2_sparse_classes_30k_train_006192
Implement the Python class `ConvND` described below. Class description: General N-dimensional convolutional. Method signatures and docstrings: - def __init__(self, num_spatial_dims: int, output_channels: int, kernel_shape: tp.Union[int, tp.Sequence[int]], stride: tp.Union[int, tp.Sequence[int]]=1, rate: tp.Union[int,...
Implement the Python class `ConvND` described below. Class description: General N-dimensional convolutional. Method signatures and docstrings: - def __init__(self, num_spatial_dims: int, output_channels: int, kernel_shape: tp.Union[int, tp.Sequence[int]], stride: tp.Union[int, tp.Sequence[int]]=1, rate: tp.Union[int,...
3494cc7d495198f4c383d3560ea05df65bb669ff
<|skeleton|> class ConvND: """General N-dimensional convolutional.""" def __init__(self, num_spatial_dims: int, output_channels: int, kernel_shape: tp.Union[int, tp.Sequence[int]], stride: tp.Union[int, tp.Sequence[int]]=1, rate: tp.Union[int, tp.Sequence[int]]=1, padding: tp.Union[str, tp.Sequence[tp.Tuple[in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConvND: """General N-dimensional convolutional.""" def __init__(self, num_spatial_dims: int, output_channels: int, kernel_shape: tp.Union[int, tp.Sequence[int]], stride: tp.Union[int, tp.Sequence[int]]=1, rate: tp.Union[int, tp.Sequence[int]]=1, padding: tp.Union[str, tp.Sequence[tp.Tuple[int, int]], typ...
the_stack_v2_python_sparse
elegy/nn/conv.py
cgarciae/elegy
train
1
234bd46347bcdd506f8727f60f60632d55540982
[ "super(JointRelativeGlobalDecoder, self).__init__()\nself.feature_embed_dim = feature_embed_dim\nself.join_type = join_type\nif self.join_type == 'cat':\n self.post_linear = nn.Linear(self.feature_embed_dim * 2, self.feature_embed_dim)\nelse:\n self.post_linear = nn.Linear(self.feature_embed_dim, self.feature...
<|body_start_0|> super(JointRelativeGlobalDecoder, self).__init__() self.feature_embed_dim = feature_embed_dim self.join_type = join_type if self.join_type == 'cat': self.post_linear = nn.Linear(self.feature_embed_dim * 2, self.feature_embed_dim) else: sel...
JointRelativeGlobalDecoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JointRelativeGlobalDecoder: def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat'): """Args: feature_embed_dim: the feature embedding dimention f_act: the final activation function applied to get the final result""" <|body_0|> def forward(self, ...
stack_v2_sparse_classes_75kplus_train_000429
22,520
permissive
[ { "docstring": "Args: feature_embed_dim: the feature embedding dimention f_act: the final activation function applied to get the final result", "name": "__init__", "signature": "def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat')" }, { "docstring": "Args: context...
2
stack_v2_sparse_classes_30k_train_052703
Implement the Python class `JointRelativeGlobalDecoder` described below. Class description: Implement the JointRelativeGlobalDecoder class. Method signatures and docstrings: - def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat'): Args: feature_embed_dim: the feature embedding dimention...
Implement the Python class `JointRelativeGlobalDecoder` described below. Class description: Implement the JointRelativeGlobalDecoder class. Method signatures and docstrings: - def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat'): Args: feature_embed_dim: the feature embedding dimention...
a29793336e6a1ebdb497289c286a0b4d5a83079f
<|skeleton|> class JointRelativeGlobalDecoder: def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat'): """Args: feature_embed_dim: the feature embedding dimention f_act: the final activation function applied to get the final result""" <|body_0|> def forward(self, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JointRelativeGlobalDecoder: def __init__(self, feature_embed_dim, f_act='sigmoid', dropout=0.5, join_type='cat'): """Args: feature_embed_dim: the feature embedding dimention f_act: the final activation function applied to get the final result""" super(JointRelativeGlobalDecoder, self).__init__...
the_stack_v2_python_sparse
spacegraph/spacegraph_codebase/decoder.py
daima2017/space2vec
train
0
dec845ae990881e0c002deabd6f8dfc850dc4aac
[ "import array\nfrom vistrails.tests.utils import execute, intercept_result\nfrom ..identifiers import identifier\nwith intercept_result(WriteNumPy, 'file') as results:\n self.assertFalse(execute([('write|WriteNumPy', identifier, [('array', [('List', '[0, 1, 258, 6758]')]), ('datatype', [('String', 'uint32')])])]...
<|body_start_0|> import array from vistrails.tests.utils import execute, intercept_result from ..identifiers import identifier with intercept_result(WriteNumPy, 'file') as results: self.assertFalse(execute([('write|WriteNumPy', identifier, [('array', [('List', '[0, 1, 258, 67...
WriteNumpyTestCase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WriteNumpyTestCase: def test_raw_numpy(self): """Uses WriteNumPy to write an array in raw format.""" <|body_0|> def test_npy_numpy(self): """Uses WriteNumPy to write an array in .NPY format.""" <|body_1|> def test_write_read(self): """Uses WriteN...
stack_v2_sparse_classes_75kplus_train_000430
4,235
permissive
[ { "docstring": "Uses WriteNumPy to write an array in raw format.", "name": "test_raw_numpy", "signature": "def test_raw_numpy(self)" }, { "docstring": "Uses WriteNumPy to write an array in .NPY format.", "name": "test_npy_numpy", "signature": "def test_npy_numpy(self)" }, { "docs...
3
stack_v2_sparse_classes_30k_train_005280
Implement the Python class `WriteNumpyTestCase` described below. Class description: Implement the WriteNumpyTestCase class. Method signatures and docstrings: - def test_raw_numpy(self): Uses WriteNumPy to write an array in raw format. - def test_npy_numpy(self): Uses WriteNumPy to write an array in .NPY format. - def...
Implement the Python class `WriteNumpyTestCase` described below. Class description: Implement the WriteNumpyTestCase class. Method signatures and docstrings: - def test_raw_numpy(self): Uses WriteNumPy to write an array in raw format. - def test_npy_numpy(self): Uses WriteNumPy to write an array in .NPY format. - def...
93f1e5d375ee1e870f9bad699a22c9aafb954090
<|skeleton|> class WriteNumpyTestCase: def test_raw_numpy(self): """Uses WriteNumPy to write an array in raw format.""" <|body_0|> def test_npy_numpy(self): """Uses WriteNumPy to write an array in .NPY format.""" <|body_1|> def test_write_read(self): """Uses WriteN...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WriteNumpyTestCase: def test_raw_numpy(self): """Uses WriteNumPy to write an array in raw format.""" import array from vistrails.tests.utils import execute, intercept_result from ..identifiers import identifier with intercept_result(WriteNumPy, 'file') as results: ...
the_stack_v2_python_sparse
vistrails/packages/tabledata/write/write_numpy.py
alexmavr/VisTrails
train
1
b4b0bb45cb9dd83973be2dc4ac1f50f87524f7ad
[ "sale_order_obj = self.pool.get('sale.order')\nsale_order_brws = sale_order_obj.browse(cr, uid, values['order_id'], context)\nproduct_brws = self.pool.get('product.product').browse(cr, uid, values['product_id'], context)\nfields_to_default = ['product_uom', 'discount', 'product_uom_qty', 'product_uos_qty', 'state']...
<|body_start_0|> sale_order_obj = self.pool.get('sale.order') sale_order_brws = sale_order_obj.browse(cr, uid, values['order_id'], context) product_brws = self.pool.get('product.product').browse(cr, uid, values['product_id'], context) fields_to_default = ['product_uom', 'discount', 'prod...
sale_order_line
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sale_order_line: def create_and_update_prices(self, cr, uid, values, context={}): """Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, name, product_uom_qty :param context: :return:""" <|body_0|> def write_and_update_prices(sel...
stack_v2_sparse_classes_75kplus_train_000431
11,160
no_license
[ { "docstring": "Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, name, product_uom_qty :param context: :return:", "name": "create_and_update_prices", "signature": "def create_and_update_prices(self, cr, uid, values, context={})" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_030805
Implement the Python class `sale_order_line` described below. Class description: Implement the sale_order_line class. Method signatures and docstrings: - def create_and_update_prices(self, cr, uid, values, context={}): Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, n...
Implement the Python class `sale_order_line` described below. Class description: Implement the sale_order_line class. Method signatures and docstrings: - def create_and_update_prices(self, cr, uid, values, context={}): Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, n...
bb925edf7eaee44a96da12cbb86263ece0ae052c
<|skeleton|> class sale_order_line: def create_and_update_prices(self, cr, uid, values, context={}): """Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, name, product_uom_qty :param context: :return:""" <|body_0|> def write_and_update_prices(sel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class sale_order_line: def create_and_update_prices(self, cr, uid, values, context={}): """Create and update prices :param cr: :param uid: :param values: Must contain order_id, product_id, name, product_uom_qty :param context: :return:""" sale_order_obj = self.pool.get('sale.order') sale_ord...
the_stack_v2_python_sparse
ax_ws_sale_order/models/sale_order_line.py
davidts-leathergoods/odoo7
train
0
2d06ce1adacc8916efcb3081f462477a628f4e06
[ "super().__init__(api=api, url=url, request_data=request_data, errors_mapping=errors_mapping, required_sid=required_sid, return_constructor=return_constructor)\nself._paginated_field = paginated_field\nself._rows_in_page = DEFAULT_ROWS_IN_PAGINATION_PAGE", "rows_in_page = int(rows_in_page)\nif rows_in_page > 5000...
<|body_start_0|> super().__init__(api=api, url=url, request_data=request_data, errors_mapping=errors_mapping, required_sid=required_sid, return_constructor=return_constructor) self._paginated_field = paginated_field self._rows_in_page = DEFAULT_ROWS_IN_PAGINATION_PAGE <|end_body_0|> <|body_star...
Base query with pagination.
BaseQueryP
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseQueryP: """Base query with pagination.""" def __init__(self, api, url: str, request_data: Dict[str, Any], errors_mapping: ERROR_MAPPING, paginated_field: str, required_sid: bool=False, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box): """Query initialization. :param api: ...
stack_v2_sparse_classes_75kplus_train_000432
3,627
permissive
[ { "docstring": "Query initialization. :param api: Api instance :param url: query url :param request_data: data for request :param errors_mapping: map of error name and exception :param required_sid: is sid requred for this query :param paginated_field: field for pagination :param return_constructor: constructor...
2
stack_v2_sparse_classes_30k_train_021775
Implement the Python class `BaseQueryP` described below. Class description: Base query with pagination. Method signatures and docstrings: - def __init__(self, api, url: str, request_data: Dict[str, Any], errors_mapping: ERROR_MAPPING, paginated_field: str, required_sid: bool=False, return_constructor: Callable[..., J...
Implement the Python class `BaseQueryP` described below. Class description: Base query with pagination. Method signatures and docstrings: - def __init__(self, api, url: str, request_data: Dict[str, Any], errors_mapping: ERROR_MAPPING, paginated_field: str, required_sid: bool=False, return_constructor: Callable[..., J...
2618e682d38339439340d86080e8bc6ee6cf21b5
<|skeleton|> class BaseQueryP: """Base query with pagination.""" def __init__(self, api, url: str, request_data: Dict[str, Any], errors_mapping: ERROR_MAPPING, paginated_field: str, required_sid: bool=False, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box): """Query initialization. :param api: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseQueryP: """Base query with pagination.""" def __init__(self, api, url: str, request_data: Dict[str, Any], errors_mapping: ERROR_MAPPING, paginated_field: str, required_sid: bool=False, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box): """Query initialization. :param api: Api instance ...
the_stack_v2_python_sparse
ambra_sdk/service/query/base_query.py
dicomgrid/sdk-python
train
11
7ae19a18b4c5fb7d095a1bca020a7ca7d3230f86
[ "with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device:\n CrOS_AU = auto_updater.ChromiumOSUpdater(device, 'fake/image', self.payload_dir)\n auto_updater.DELAY_SEC_FOR_RETRY = 10\n auto_updater.MAX_RETRY = 1\n transfer_devserver = self.PatchObject(auto_updater.ChromiumOSFlashUpdater, 'Transfer...
<|body_start_0|> with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device: CrOS_AU = auto_updater.ChromiumOSUpdater(device, 'fake/image', self.payload_dir) auto_updater.DELAY_SEC_FOR_RETRY = 10 auto_updater.MAX_RETRY = 1 transfer_devserver = self.PatchObjec...
Test whether ChromiumOSUpdater's transfer functions are retried.
ChromiumOSUpdaterRetryTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" <|body_0|> def testErrorTriggerRetryTransferStateful(self): """Te...
stack_v2_sparse_classes_75kplus_train_000433
20,190
permissive
[ { "docstring": "Test ChromiumOSUpdate is retried properly.", "name": "testErrorTriggerRetryTransferDevServer", "signature": "def testErrorTriggerRetryTransferDevServer(self)" }, { "docstring": "Test ChromiumOSUpdate is retried properly.", "name": "testErrorTriggerRetryTransferStateful", ...
3
stack_v2_sparse_classes_30k_train_034222
Implement the Python class `ChromiumOSUpdaterRetryTest` described below. Class description: Test whether ChromiumOSUpdater's transfer functions are retried. Method signatures and docstrings: - def testErrorTriggerRetryTransferDevServer(self): Test ChromiumOSUpdate is retried properly. - def testErrorTriggerRetryTrans...
Implement the Python class `ChromiumOSUpdaterRetryTest` described below. Class description: Test whether ChromiumOSUpdater's transfer functions are retried. Method signatures and docstrings: - def testErrorTriggerRetryTransferDevServer(self): Test ChromiumOSUpdate is retried properly. - def testErrorTriggerRetryTrans...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" <|body_0|> def testErrorTriggerRetryTransferStateful(self): """Te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device: CrOS_AU = auto...
the_stack_v2_python_sparse
third_party/chromite/lib/auto_updater_unittest.py
metux/chromium-suckless
train
5
64779b64ce63e400a1b2ba2fe2b72227fac7ac8c
[ "length = len(A)\nif length <= 2:\n return length\nclosed_ptr = 0\nduplicate_count = 0\nopen_ptr = closed_ptr + 1\nwhile open_ptr < length:\n if A[closed_ptr] == A[open_ptr]:\n if duplicate_count >= 1:\n try:\n while A[closed_ptr] == A[open_ptr]:\n open_ptr ...
<|body_start_0|> length = len(A) if length <= 2: return length closed_ptr = 0 duplicate_count = 0 open_ptr = closed_ptr + 1 while open_ptr < length: if A[closed_ptr] == A[open_ptr]: if duplicate_count >= 1: try: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeDuplicates_complicated(self, A): """Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer""" <|body_0|> def removeDuplicates(self, A): """Two pointers algorithm, open_ptr & closed_ptr :param A: a list of in...
stack_v2_sparse_classes_75kplus_train_000434
2,324
permissive
[ { "docstring": "Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer", "name": "removeDuplicates_complicated", "signature": "def removeDuplicates_complicated(self, A)" }, { "docstring": "Two pointers algorithm, open_ptr & closed_ptr :param A: a list of i...
2
stack_v2_sparse_classes_30k_train_031777
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicates_complicated(self, A): Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer - def removeDuplicates(self, A): Two poi...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicates_complicated(self, A): Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer - def removeDuplicates(self, A): Two poi...
cbbd4a67ab342ada2421e13f82d660b1d47d4d20
<|skeleton|> class Solution: def removeDuplicates_complicated(self, A): """Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer""" <|body_0|> def removeDuplicates(self, A): """Two pointers algorithm, open_ptr & closed_ptr :param A: a list of in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def removeDuplicates_complicated(self, A): """Two pointers algorithm, open_ptr & closed_ptr :param A: a list of integers :return: an integer""" length = len(A) if length <= 2: return length closed_ptr = 0 duplicate_count = 0 open_ptr = clos...
the_stack_v2_python_sparse
081 Remove Duplicates from Sorted Array II.py
Aminaba123/LeetCode
train
1
6e6d6ade4ff5207f3f27e89817678565d30012dd
[ "index_i = 0\nindex_j = 0\nloop_i = 0\nwhile loop_i < m and index_j < n:\n if nums1[index_i] <= nums2[index_j]:\n index_i += 1\n else:\n nums1.insert(index_i, nums2[index_j])\n nums1.pop()\n index_i += 1\n index_j += 1\n loop_i -= 1\n loop_i += 1\nwhile index_j < n...
<|body_start_0|> index_i = 0 index_j = 0 loop_i = 0 while loop_i < m and index_j < n: if nums1[index_i] <= nums2[index_j]: index_i += 1 else: nums1.insert(index_i, nums2[index_j]) nums1.pop() index_i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_0|> def merge_2(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_1|> def merge_LC(self, nums1...
stack_v2_sparse_classes_75kplus_train_000435
3,309
no_license
[ { "docstring": "Do not return anything, modify nums1 in-place instead.", "name": "merge", "signature": "def merge(self, nums1, m, nums2, n)" }, { "docstring": "Do not return anything, modify nums1 in-place instead.", "name": "merge_2", "signature": "def merge_2(self, nums1, m, nums2, n)"...
3
stack_v2_sparse_classes_30k_train_005040
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead. - def merge_2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def merge(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead. - def merge_2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place...
ec48cbde4356208afac226d41752daffe674be2c
<|skeleton|> class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_0|> def merge_2(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" <|body_1|> def merge_LC(self, nums1...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def merge(self, nums1, m, nums2, n): """Do not return anything, modify nums1 in-place instead.""" index_i = 0 index_j = 0 loop_i = 0 while loop_i < m and index_j < n: if nums1[index_i] <= nums2[index_j]: index_i += 1 els...
the_stack_v2_python_sparse
Leetcode/Python/Easy/Sorting/merge_sorted_array.py
librar127/PythonDS
train
0
3f60918da0a8a5c5a2bc156aef2277b8fc282960
[ "db = self.db_obj.create(db_name)\ntry:\n self.db_obj.createCollection(db, collection, scope)\n created_Collection = self.db_obj.collectionObject(db, collection, scope)\n created_CollectionName = self.collection_obj.collectionName(created_Collection)\n assert created_CollectionName == collection, 'Scope...
<|body_start_0|> db = self.db_obj.create(db_name) try: self.db_obj.createCollection(db, collection, scope) created_Collection = self.db_obj.collectionObject(db, collection, scope) created_CollectionName = self.collection_obj.collectionName(created_Collection) ...
TestScopeCollection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestScopeCollection: def test_scope_collection_name_with_space(self, db_name, scope, collection): """@summary: Creating scope and collections with space in names""" <|body_0|> def test_same_collection_in_different_scope(self, db_name, no_of_scope, collection): """@su...
stack_v2_sparse_classes_75kplus_train_000436
4,538
no_license
[ { "docstring": "@summary: Creating scope and collections with space in names", "name": "test_scope_collection_name_with_space", "signature": "def test_scope_collection_name_with_space(self, db_name, scope, collection)" }, { "docstring": "@summary: Creating collection with same name in different ...
4
stack_v2_sparse_classes_30k_train_045322
Implement the Python class `TestScopeCollection` described below. Class description: Implement the TestScopeCollection class. Method signatures and docstrings: - def test_scope_collection_name_with_space(self, db_name, scope, collection): @summary: Creating scope and collections with space in names - def test_same_co...
Implement the Python class `TestScopeCollection` described below. Class description: Implement the TestScopeCollection class. Method signatures and docstrings: - def test_scope_collection_name_with_space(self, db_name, scope, collection): @summary: Creating scope and collections with space in names - def test_same_co...
9d78bd43665de2a0099d3e2ecf94495f3379f8fa
<|skeleton|> class TestScopeCollection: def test_scope_collection_name_with_space(self, db_name, scope, collection): """@summary: Creating scope and collections with space in names""" <|body_0|> def test_same_collection_in_different_scope(self, db_name, no_of_scope, collection): """@su...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestScopeCollection: def test_scope_collection_name_with_space(self, db_name, scope, collection): """@summary: Creating scope and collections with space in names""" db = self.db_obj.create(db_name) try: self.db_obj.createCollection(db, collection, scope) created...
the_stack_v2_python_sparse
testsuites/CBLTester/CBL_Functional_tests/APITests/test_scopesCollections.py
couchbaselabs/mobile-testkit
train
15
0b6838b5cca1b08a0174c806f58db117ec9a68fb
[ "N = N\nomega1 = omega\nc = np.zeros((L, N))\nb = np.zeros((L,))\nreturn (N, omega1, c, b)", "for i in range(L):\n for j in range(N):\n c[i, j] = np.sqrt(2.0 / (L + 1)) * np.sin((j + 1) * np.pi * (i + 1) / (L + 1))\n b[i] = np.sqrt(1.0 / (2.0 * omega1)) * (np.sqrt(omega1) * i + 1j)\nK = np.zeros((N *...
<|body_start_0|> N = N omega1 = omega c = np.zeros((L, N)) b = np.zeros((L,)) return (N, omega1, c, b) <|end_body_0|> <|body_start_1|> for i in range(L): for j in range(N): c[i, j] = np.sqrt(2.0 / (L + 1)) * np.sin((j + 1) * np.pi * (i + 1) / ...
This class solves the hamiltonian.
problemsolving
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class problemsolving: """This class solves the hamiltonian.""" def matrixmaking(N, omega): """This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b...
stack_v2_sparse_classes_75kplus_train_000437
3,762
no_license
[ { "docstring": "This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency", "name": "...
4
stack_v2_sparse_classes_30k_train_016818
Implement the Python class `problemsolving` described below. Class description: This class solves the hamiltonian. Method signatures and docstrings: - def matrixmaking(N, omega): This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (f...
Implement the Python class `problemsolving` described below. Class description: This class solves the hamiltonian. Method signatures and docstrings: - def matrixmaking(N, omega): This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (f...
0228f225873fb79bcc91bc3c7f4437a480e1004d
<|skeleton|> class problemsolving: """This class solves the hamiltonian.""" def matrixmaking(N, omega): """This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class problemsolving: """This class solves the hamiltonian.""" def matrixmaking(N, omega): """This function makes the matrixes. Args: c (matrix): Fermion opperator b (matrix): Phonon opperator N (float): number of electrons omega1 (float): Frequency Returns: c (matrix): Fermion opperator b (matrix): Ph...
the_stack_v2_python_sparse
MitchellStry/Homework/Homework8/homework8.py
AkimovLab/CHE512-Spring2023
train
0
07a7dfa1b9dba44da7ffcd1940a23358bdb020f3
[ "self.status = 'blocked'\nself.save(update_fields=['status'])\nself.user_set.filter(is_active=True).update(is_active=False, deactivation_reason='domain_block')\nif self.application_type == 'bookwyrm':\n connector_model = apps.get_model('bookwyrm.Connector', require_ready=True)\n connector_model.objects.filter...
<|body_start_0|> self.status = 'blocked' self.save(update_fields=['status']) self.user_set.filter(is_active=True).update(is_active=False, deactivation_reason='domain_block') if self.application_type == 'bookwyrm': connector_model = apps.get_model('bookwyrm.Connector', require...
store which servers we federate with
FederatedServer
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FederatedServer: """store which servers we federate with""" def block(self): """block a server""" <|body_0|> def unblock(self): """unblock a server""" <|body_1|> def is_blocked(cls, url: str) -> bool: """look up if a domain is blocked""" ...
stack_v2_sparse_classes_75kplus_train_000438
2,400
no_license
[ { "docstring": "block a server", "name": "block", "signature": "def block(self)" }, { "docstring": "unblock a server", "name": "unblock", "signature": "def unblock(self)" }, { "docstring": "look up if a domain is blocked", "name": "is_blocked", "signature": "def is_blocke...
3
null
Implement the Python class `FederatedServer` described below. Class description: store which servers we federate with Method signatures and docstrings: - def block(self): block a server - def unblock(self): unblock a server - def is_blocked(cls, url: str) -> bool: look up if a domain is blocked
Implement the Python class `FederatedServer` described below. Class description: store which servers we federate with Method signatures and docstrings: - def block(self): block a server - def unblock(self): unblock a server - def is_blocked(cls, url: str) -> bool: look up if a domain is blocked <|skeleton|> class Fe...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class FederatedServer: """store which servers we federate with""" def block(self): """block a server""" <|body_0|> def unblock(self): """unblock a server""" <|body_1|> def is_blocked(cls, url: str) -> bool: """look up if a domain is blocked""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FederatedServer: """store which servers we federate with""" def block(self): """block a server""" self.status = 'blocked' self.save(update_fields=['status']) self.user_set.filter(is_active=True).update(is_active=False, deactivation_reason='domain_block') if self.ap...
the_stack_v2_python_sparse
bookwyrm/models/federated_server.py
bookwyrm-social/bookwyrm
train
1,398
ee225ac9bf012a3d7824915fa9e698ad0e1aca64
[ "assert isinstance(gf, callflow.GraphFrame)\nassert 'component_path' in gf.df.columns\npaths = self.callsite_paths(callsites)\nmodule_name_group_df = gf.df.groupby(['module', 'name'])\nfor path in paths:\n component_edges = self.create_source_targets(path['component_path'])\n for idx, edge in enumerate(compon...
<|body_start_0|> assert isinstance(gf, callflow.GraphFrame) assert 'component_path' in gf.df.columns paths = self.callsite_paths(callsites) module_name_group_df = gf.df.groupby(['module', 'name']) for path in paths: component_edges = self.create_source_targets(path['c...
Split a callee if it is a module.
SplitCallee
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplitCallee: """Split a callee if it is a module.""" def __init__(self, gf, callsites): """:param gf: :param callsites:""" <|body_0|> def create_source_targets(self, component_path): """:param component_path: :return:""" <|body_1|> def callsite_paths...
stack_v2_sparse_classes_75kplus_train_000439
4,324
permissive
[ { "docstring": ":param gf: :param callsites:", "name": "__init__", "signature": "def __init__(self, gf, callsites)" }, { "docstring": ":param component_path: :return:", "name": "create_source_targets", "signature": "def create_source_targets(self, component_path)" }, { "docstring...
3
stack_v2_sparse_classes_30k_train_048399
Implement the Python class `SplitCallee` described below. Class description: Split a callee if it is a module. Method signatures and docstrings: - def __init__(self, gf, callsites): :param gf: :param callsites: - def create_source_targets(self, component_path): :param component_path: :return: - def callsite_paths(sel...
Implement the Python class `SplitCallee` described below. Class description: Split a callee if it is a module. Method signatures and docstrings: - def __init__(self, gf, callsites): :param gf: :param callsites: - def create_source_targets(self, component_path): :param component_path: :return: - def callsite_paths(sel...
6bbdabe4b71be369e616e3136d7f0120531c9fc8
<|skeleton|> class SplitCallee: """Split a callee if it is a module.""" def __init__(self, gf, callsites): """:param gf: :param callsites:""" <|body_0|> def create_source_targets(self, component_path): """:param component_path: :return:""" <|body_1|> def callsite_paths...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SplitCallee: """Split a callee if it is a module.""" def __init__(self, gf, callsites): """:param gf: :param callsites:""" assert isinstance(gf, callflow.GraphFrame) assert 'component_path' in gf.df.columns paths = self.callsite_paths(callsites) module_name_group_d...
the_stack_v2_python_sparse
callflow/operations/split_callee.py
LLNL/CallFlow
train
32
77087863d400a61d9612254c684f12adf8e617f8
[ "super(LSTMModel, self).__init__()\nself.device: torch.device = torch.device('cuda:0')\nself.embeds: nn.Sequential = nn.Sequential(nn.Embedding(config['vocab_size'], config['embedding_size']), nn.Dropout(config['dropout']))\nself.num_layers: int = config['num_lstm_layers']\nself.hidden_size: int = config['hidden_si...
<|body_start_0|> super(LSTMModel, self).__init__() self.device: torch.device = torch.device('cuda:0') self.embeds: nn.Sequential = nn.Sequential(nn.Embedding(config['vocab_size'], config['embedding_size']), nn.Dropout(config['dropout'])) self.num_layers: int = config['num_lstm_layers'] ...
LSTMModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTMModel: def __init__(self, config): """Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters.""" <|body_0|> def forward(self, x: torch.tensor): """Args: x (torch.tensor): Shape[batch_size, input_size] Returns: _type_:...
stack_v2_sparse_classes_75kplus_train_000440
2,786
no_license
[ { "docstring": "Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters.", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Args: x (torch.tensor): Shape[batch_size, input_size] Returns: _type_: _description_", "nam...
2
null
Implement the Python class `LSTMModel` described below. Class description: Implement the LSTMModel class. Method signatures and docstrings: - def __init__(self, config): Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters. - def forward(self, x: torch.tensor): Args: x ...
Implement the Python class `LSTMModel` described below. Class description: Implement the LSTMModel class. Method signatures and docstrings: - def __init__(self, config): Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters. - def forward(self, x: torch.tensor): Args: x ...
55d42d9caa7928e30e62231d1e3574716b8ed555
<|skeleton|> class LSTMModel: def __init__(self, config): """Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters.""" <|body_0|> def forward(self, x: torch.tensor): """Args: x (torch.tensor): Shape[batch_size, input_size] Returns: _type_:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LSTMModel: def __init__(self, config): """Instantiates NN linear model with arguments from Args: config (args): Model Configuration parameters.""" super(LSTMModel, self).__init__() self.device: torch.device = torch.device('cuda:0') self.embeds: nn.Sequential = nn.Sequential(nn....
the_stack_v2_python_sparse
da_for_polymers/ML_models/pytorch/LSTM/lstm_regression.py
aspuru-guzik-group/da_for_polymers
train
6
7d699325ade4a2586207ee9b172537847435d24f
[ "self.enable_capture = enable_capture\nself.sampling_percentage = sampling_percentage\nself.destination_s3_uri = destination_s3_uri\nsagemaker_session = sagemaker_session or Session()\nif self.destination_s3_uri is None:\n self.destination_s3_uri = s3.s3_path_join('s3://', sagemaker_session.default_bucket(), sag...
<|body_start_0|> self.enable_capture = enable_capture self.sampling_percentage = sampling_percentage self.destination_s3_uri = destination_s3_uri sagemaker_session = sagemaker_session or Session() if self.destination_s3_uri is None: self.destination_s3_uri = s3.s3_pat...
Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.
DataCaptureConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataCaptureConfig: """Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.""" def __init__(self, enable_capture, sampling_percentage=20, destina...
stack_v2_sparse_classes_75kplus_train_000441
5,109
permissive
[ { "docstring": "Initialize a DataCaptureConfig object for capturing data from Amazon SageMaker Endpoints. Args: enable_capture (bool): Required. Whether data capture should be enabled or not. sampling_percentage (int): Optional. Default=20. The percentage of data to sample. Must be between 0 and 100. destinatio...
2
stack_v2_sparse_classes_30k_train_025650
Implement the Python class `DataCaptureConfig` described below. Class description: Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring. Method signatures and docstrings: ...
Implement the Python class `DataCaptureConfig` described below. Class description: Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring. Method signatures and docstrings: ...
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class DataCaptureConfig: """Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.""" def __init__(self, enable_capture, sampling_percentage=20, destina...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataCaptureConfig: """Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.""" def __init__(self, enable_capture, sampling_percentage=20, destination_s3_uri=N...
the_stack_v2_python_sparse
src/sagemaker/model_monitor/data_capture_config.py
aws/sagemaker-python-sdk
train
2,050
cbcec3d5f688c71b4b4f36da33c75ad16147582f
[ "self.resolution = resolution\nif X_lower.shape[0] > 1:\n raise RuntimeError('Grid search works just for one dimensional functions')\nsuper(GridSearch, self).__init__(objective_function, X_lower, X_upper)", "x = np.linspace(self.X_lower[0], self.X_upper[0], self.resolution).reshape((self.resolu...
<|body_start_0|> self.resolution = resolution if X_lower.shape[0] > 1: raise RuntimeError('Grid search works just for one dimensional functions') super(GridSearch, self).__init__(objective_function, X_lower, X_upper) <|end_body_0|> <|body_start_1|> x = np.lin...
GridSearch
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GridSearch: def __init__(self, objective_function, X_lower, X_upper, resolution=1000): """Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input space. Parameters ---------- objective_function: acquisition function The acquisition function which w...
stack_v2_sparse_classes_75kplus_train_000442
1,615
permissive
[ { "docstring": "Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input space. Parameters ---------- objective_function: acquisition function The acquisition function which will be maximized X_lower: np.ndarray (D) Lower bounds of the input space X_upper: np.ndarray (D) U...
2
null
Implement the Python class `GridSearch` described below. Class description: Implement the GridSearch class. Method signatures and docstrings: - def __init__(self, objective_function, X_lower, X_upper, resolution=1000): Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input spa...
Implement the Python class `GridSearch` described below. Class description: Implement the GridSearch class. Method signatures and docstrings: - def __init__(self, objective_function, X_lower, X_upper, resolution=1000): Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input spa...
c2ce2e78bd98236618c99fe3453fc24389d48ead
<|skeleton|> class GridSearch: def __init__(self, objective_function, X_lower, X_upper, resolution=1000): """Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input space. Parameters ---------- objective_function: acquisition function The acquisition function which w...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GridSearch: def __init__(self, objective_function, X_lower, X_upper, resolution=1000): """Evaluates a equally spaced grid to maximize the acquisition function in a one dimensional input space. Parameters ---------- objective_function: acquisition function The acquisition function which will be maximiz...
the_stack_v2_python_sparse
RoBO/build/lib.linux-x86_64-2.7/robo/maximizers/grid_search.py
mrenoon/datafreezethaw
train
5
b56a033581dd529f285a21ea85b11b295499f7c2
[ "args = {}\nargs.update(csrf(request))\nreturn render(request, 'authentication/register.html', args)", "usersignupform = UserSignupForm(request.POST)\nemail = request.POST.get('email')\nsignup_new_user = User.objects.filter(email__exact=email)\nif signup_new_user:\n args = {}\n args.update(csrf(request))\n ...
<|body_start_0|> args = {} args.update(csrf(request)) return render(request, 'authentication/register.html', args) <|end_body_0|> <|body_start_1|> usersignupform = UserSignupForm(request.POST) email = request.POST.get('email') signup_new_user = User.objects.filter(email_...
This class handles user signup. Attributes: template_name
UserRegistrationView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRegistrationView: """This class handles user signup. Attributes: template_name""" def get(self, request, *args, **kwargs): """Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template.""" <|body_0|> def post(self, request):...
stack_v2_sparse_classes_75kplus_train_000443
17,941
permissive
[ { "docstring": "Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Handles POST requests to 'register' named route. Raw data posted from form is received...
2
stack_v2_sparse_classes_30k_train_048478
Implement the Python class `UserRegistrationView` described below. Class description: This class handles user signup. Attributes: template_name Method signatures and docstrings: - def get(self, request, *args, **kwargs): Handles the GET request to the 'register' named route. Returns: A HttpResponse with register temp...
Implement the Python class `UserRegistrationView` described below. Class description: This class handles user signup. Attributes: template_name Method signatures and docstrings: - def get(self, request, *args, **kwargs): Handles the GET request to the 'register' named route. Returns: A HttpResponse with register temp...
3704cbe6e69ba3e4c53401d3bbc339208e9ebccd
<|skeleton|> class UserRegistrationView: """This class handles user signup. Attributes: template_name""" def get(self, request, *args, **kwargs): """Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template.""" <|body_0|> def post(self, request):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserRegistrationView: """This class handles user signup. Attributes: template_name""" def get(self, request, *args, **kwargs): """Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template.""" args = {} args.update(csrf(request)) ...
the_stack_v2_python_sparse
troupon/authentication/views.py
morristech/troupon
train
0
037f2800301e94b00eb1355d29657143f28c38db
[ "u = self.request.cookies.get('name')\nself.username = check_secure_val(u)\nself.render('editcomment.html', comment=c, username=self.username)", "username = self.request.cookies.get('name')\ncomment = self.request.get('comment')\nif comment != '':\n c.comment = comment\n c.put()\n self.redirect('/')\nels...
<|body_start_0|> u = self.request.cookies.get('name') self.username = check_secure_val(u) self.render('editcomment.html', comment=c, username=self.username) <|end_body_0|> <|body_start_1|> username = self.request.cookies.get('name') comment = self.request.get('comment') ...
Allows a commentator to edit their comment
EditComment
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditComment: """Allows a commentator to edit their comment""" def get(self, comments_id, c): """Renders form to edit a comment.""" <|body_0|> def post(self, comments_id, c): """Allows author to edit a comment and post to ndb""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_000444
1,415
permissive
[ { "docstring": "Renders form to edit a comment.", "name": "get", "signature": "def get(self, comments_id, c)" }, { "docstring": "Allows author to edit a comment and post to ndb", "name": "post", "signature": "def post(self, comments_id, c)" } ]
2
stack_v2_sparse_classes_30k_train_017735
Implement the Python class `EditComment` described below. Class description: Allows a commentator to edit their comment Method signatures and docstrings: - def get(self, comments_id, c): Renders form to edit a comment. - def post(self, comments_id, c): Allows author to edit a comment and post to ndb
Implement the Python class `EditComment` described below. Class description: Allows a commentator to edit their comment Method signatures and docstrings: - def get(self, comments_id, c): Renders form to edit a comment. - def post(self, comments_id, c): Allows author to edit a comment and post to ndb <|skeleton|> cla...
61fc3a176153094be4ac0dba9e80c5da1d27c45c
<|skeleton|> class EditComment: """Allows a commentator to edit their comment""" def get(self, comments_id, c): """Renders form to edit a comment.""" <|body_0|> def post(self, comments_id, c): """Allows author to edit a comment and post to ndb""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EditComment: """Allows a commentator to edit their comment""" def get(self, comments_id, c): """Renders form to edit a comment.""" u = self.request.cookies.get('name') self.username = check_secure_val(u) self.render('editcomment.html', comment=c, username=self.username) ...
the_stack_v2_python_sparse
myapp/handlers/editcomment.py
sam-atkins/fsnd-blog
train
1
c92ed240399fb29c7229166432c0bbfd8ab4fa91
[ "self.alphabet.cls_idx = self.alphabet.get_idx('<cath>')\nbatch = []\nfor coords, confidence, seq in raw_batch:\n if confidence is None:\n confidence = 1.0\n if isinstance(confidence, float) or isinstance(confidence, int):\n confidence = [float(confidence)] * len(coords)\n if seq is None:\n ...
<|body_start_0|> self.alphabet.cls_idx = self.alphabet.get_idx('<cath>') batch = [] for coords, confidence, seq in raw_batch: if confidence is None: confidence = 1.0 if isinstance(confidence, float) or isinstance(confidence, int): confidenc...
CoordBatchConverter
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-proprietary-license", "CC-BY-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoordBatchConverter: def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): """Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords: list of floats, shape L x 3 x 3 confidence: list of floats, shape L; or scalar float; or None seq: string o...
stack_v2_sparse_classes_75kplus_train_000445
11,754
permissive
[ { "docstring": "Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords: list of floats, shape L x 3 x 3 confidence: list of floats, shape L; or scalar float; or None seq: string of length L Returns: coords: Tensor of shape batch_size x L x 3 x 3 confidence: Tensor of shape batch_size x ...
3
null
Implement the Python class `CoordBatchConverter` described below. Class description: Implement the CoordBatchConverter class. Method signatures and docstrings: - def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords:...
Implement the Python class `CoordBatchConverter` described below. Class description: Implement the CoordBatchConverter class. Method signatures and docstrings: - def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords:...
2b369911bb5b4b0dda914521b9475cad1656b2ac
<|skeleton|> class CoordBatchConverter: def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): """Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords: list of floats, shape L x 3 x 3 confidence: list of floats, shape L; or scalar float; or None seq: string o...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CoordBatchConverter: def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): """Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords: list of floats, shape L x 3 x 3 confidence: list of floats, shape L; or scalar float; or None seq: string of length L Ret...
the_stack_v2_python_sparse
esm/inverse_folding/util.py
facebookresearch/esm
train
2,293
2d439b36959eeb716a142a7d81fd13d69b63253d
[ "super(MayaData, self).__init__()\nself.dataType = 'MayaData'\nself.fileFilter = 'All Files (*.*)'", "filePath = mc.fileDialog2(fileFilter=self.fileFilter, dialogStyle=2, caption='Save As')\nif not filePath:\n return\nfilePath = filePath[0]\nself.save(filePath, force=True)\nreturn filePath", "if not filePath...
<|body_start_0|> super(MayaData, self).__init__() self.dataType = 'MayaData' self.fileFilter = 'All Files (*.*)' <|end_body_0|> <|body_start_1|> filePath = mc.fileDialog2(fileFilter=self.fileFilter, dialogStyle=2, caption='Save As') if not filePath: return fi...
Maya Data Object Class Contains functions to save and load standard maya data.
MayaData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MayaData: """Maya Data Object Class Contains functions to save and load standard maya data.""" def __init__(self): """Data Object Class Initializer""" <|body_0|> def saveAs(self): """Save data object to file. Opens a file dialog, to allow the user to specify a fi...
stack_v2_sparse_classes_75kplus_train_000446
1,379
permissive
[ { "docstring": "Data Object Class Initializer", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Save data object to file. Opens a file dialog, to allow the user to specify a file path.", "name": "saveAs", "signature": "def saveAs(self)" }, { "docstring": ...
3
null
Implement the Python class `MayaData` described below. Class description: Maya Data Object Class Contains functions to save and load standard maya data. Method signatures and docstrings: - def __init__(self): Data Object Class Initializer - def saveAs(self): Save data object to file. Opens a file dialog, to allow the...
Implement the Python class `MayaData` described below. Class description: Maya Data Object Class Contains functions to save and load standard maya data. Method signatures and docstrings: - def __init__(self): Data Object Class Initializer - def saveAs(self): Save data object to file. Opens a file dialog, to allow the...
c512a96c20ba7a4ee93a123690b626bb408a8fcd
<|skeleton|> class MayaData: """Maya Data Object Class Contains functions to save and load standard maya data.""" def __init__(self): """Data Object Class Initializer""" <|body_0|> def saveAs(self): """Save data object to file. Opens a file dialog, to allow the user to specify a fi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MayaData: """Maya Data Object Class Contains functions to save and load standard maya data.""" def __init__(self): """Data Object Class Initializer""" super(MayaData, self).__init__() self.dataType = 'MayaData' self.fileFilter = 'All Files (*.*)' def saveAs(self): ...
the_stack_v2_python_sparse
data/mayaData.py
rituparna/glTools
train
0
98140917a74b692d3f3d75c92dcf992fcff49e5d
[ "self.sentence = sentence\nself.event_domain = event_domain\nself.event_type = event_type\nself._allocate_arrays(params.get_int('max_sent_length'), params.get_int('embedding.none_token_index'), params.get_string('cnn.int_type'))", "num_labels = len(self.event_domain.event_types)\nself.label = np.zeros(num_labels,...
<|body_start_0|> self.sentence = sentence self.event_domain = event_domain self.event_type = event_type self._allocate_arrays(params.get_int('max_sent_length'), params.get_int('embedding.none_token_index'), params.get_string('cnn.int_type')) <|end_body_0|> <|body_start_1|> num_l...
EventSentenceExample
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventSentenceExample: def __init__(self, sentence, event_domain, params, event_type=None): """We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :...
stack_v2_sparse_classes_75kplus_train_000447
6,318
permissive
[ { "docstring": "We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type params: nlplingo.common.parameters.Parameters :type event_type: str", "name": "__init__", ...
2
stack_v2_sparse_classes_30k_train_043718
Implement the Python class `EventSentenceExample` described below. Class description: Implement the EventSentenceExample class. Method signatures and docstrings: - def __init__(self, sentence, event_domain, params, event_type=None): We are given a sentence as the tasks span, and event_type (present during training) :...
Implement the Python class `EventSentenceExample` described below. Class description: Implement the EventSentenceExample class. Method signatures and docstrings: - def __init__(self, sentence, event_domain, params, event_type=None): We are given a sentence as the tasks span, and event_type (present during training) :...
32ff17b1320937faa3d3ebe727032f4b3e7a353d
<|skeleton|> class EventSentenceExample: def __init__(self, sentence, event_domain, params, event_type=None): """We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventSentenceExample: def __init__(self, sentence, event_domain, params, event_type=None): """We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type params: n...
the_stack_v2_python_sparse
nlplingo/sandbox/misc/event_sentence.py
BBN-E/nlplingo
train
3
eb4ed989f04dcdce30a03f0b2cce08868ac1a1de
[ "super(Inception3c, self).__init__()\nself.branch1 = paddle.nn.Sequential(ConvBNLayer(num_channels=num_channels, num_filters=ch3x3reduced, filter_size=1, stride=1, padding=0), ConvBNLayer(num_channels=ch3x3reduced, num_filters=ch3x3, filter_size=3, stride=2, padding=1))\nself.branch2 = paddle.nn.Sequential(ConvBNLa...
<|body_start_0|> super(Inception3c, self).__init__() self.branch1 = paddle.nn.Sequential(ConvBNLayer(num_channels=num_channels, num_filters=ch3x3reduced, filter_size=1, stride=1, padding=0), ConvBNLayer(num_channels=ch3x3reduced, num_filters=ch3x3, filter_size=3, stride=2, padding=1)) self.branc...
Inception3c
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Inception3c: def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2): """@Brief `Inception3c` @Parameters num_channels : channel numbers of input tensor ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbe...
stack_v2_sparse_classes_75kplus_train_000448
23,805
permissive
[ { "docstring": "@Brief `Inception3c` @Parameters num_channels : channel numbers of input tensor ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbers of 3x3 conv doublech3x3reduced : channel numbers of 1x1 conv before the double 3x3 convs doublech3x3_1 : output channel number...
2
stack_v2_sparse_classes_30k_train_026225
Implement the Python class `Inception3c` described below. Class description: Implement the Inception3c class. Method signatures and docstrings: - def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2): @Brief `Inception3c` @Parameters num_channels : channel numbers of ...
Implement the Python class `Inception3c` described below. Class description: Implement the Inception3c class. Method signatures and docstrings: - def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2): @Brief `Inception3c` @Parameters num_channels : channel numbers of ...
78ff3c3ab3906012a0f4a612251347632aa493a7
<|skeleton|> class Inception3c: def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2): """@Brief `Inception3c` @Parameters num_channels : channel numbers of input tensor ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Inception3c: def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2): """@Brief `Inception3c` @Parameters num_channels : channel numbers of input tensor ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbers of 3x3 conv...
the_stack_v2_python_sparse
ECO/paddle2.0/model/ECO.py
thinkall/Contrib
train
1
40c43f6be967b886524b0e1ab9bf2ec0911202e7
[ "n = len(s)\nans = ''\nmap1 = [0] * 256\nfor c in s:\n map1[ord(c)] += 1\nmap2 = {}\nfor k, v in enumerate(map1):\n map2.setdefault(v, []).append(k)\nfor i in range(n, 0, -1):\n if i in map2:\n for c in map2[i]:\n ans += chr(c) * i\nreturn ans", "from collections import Counter\ncounter...
<|body_start_0|> n = len(s) ans = '' map1 = [0] * 256 for c in s: map1[ord(c)] += 1 map2 = {} for k, v in enumerate(map1): map2.setdefault(v, []).append(k) for i in range(n, 0, -1): if i in map2: for c in map2[i]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def frequencySort(self, s): """:type s: str :rtype: str""" <|body_0|> def frequencySort2(self, s): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(s) ans = '' map1 = [0] * 256 for...
stack_v2_sparse_classes_75kplus_train_000449
898
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "frequencySort", "signature": "def frequencySort(self, s)" }, { "docstring": ":type s: str :rtype: str", "name": "frequencySort2", "signature": "def frequencySort2(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def frequencySort(self, s): :type s: str :rtype: str - def frequencySort2(self, s): :type s: str :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def frequencySort(self, s): :type s: str :rtype: str - def frequencySort2(self, s): :type s: str :rtype: str <|skeleton|> class Solution: def frequencySort(self, s): ...
143aa25f92f3827aa379f29c67a9b7ec3757fef9
<|skeleton|> class Solution: def frequencySort(self, s): """:type s: str :rtype: str""" <|body_0|> def frequencySort2(self, s): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def frequencySort(self, s): """:type s: str :rtype: str""" n = len(s) ans = '' map1 = [0] * 256 for c in s: map1[ord(c)] += 1 map2 = {} for k, v in enumerate(map1): map2.setdefault(v, []).append(k) for i in range...
the_stack_v2_python_sparse
py/leetcode_py/451.py
imsure/tech-interview-prep
train
0
879632dab31a02b73b45bdf9cbedc164388ea1a1
[ "email = self.cleaned_data.get('email')\nif not email:\n raise forms.ValidationError(u'Email address must be included.')\nusername = self.cleaned_data.get('username')\nif User.objects.filter(email=email).exclude(username=username):\n raise forms.ValidationError(u'Email addresses must be unique.')\nreturn emai...
<|body_start_0|> email = self.cleaned_data.get('email') if not email: raise forms.ValidationError(u'Email address must be included.') username = self.cleaned_data.get('username') if User.objects.filter(email=email).exclude(username=username): raise forms.Validatio...
reisters user and is used to create new profile
UserRegistrationForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRegistrationForm: """reisters user and is used to create new profile""" def clean_email(self): """checks for user of same address and raises error. Also ensure the fields have content in them.""" <|body_0|> def clean_password2(self): """Compares passwords and...
stack_v2_sparse_classes_75kplus_train_000450
2,625
no_license
[ { "docstring": "checks for user of same address and raises error. Also ensure the fields have content in them.", "name": "clean_email", "signature": "def clean_email(self)" }, { "docstring": "Compares passwords and raises error if they are not matching", "name": "clean_password2", "signa...
2
stack_v2_sparse_classes_30k_train_052477
Implement the Python class `UserRegistrationForm` described below. Class description: reisters user and is used to create new profile Method signatures and docstrings: - def clean_email(self): checks for user of same address and raises error. Also ensure the fields have content in them. - def clean_password2(self): C...
Implement the Python class `UserRegistrationForm` described below. Class description: reisters user and is used to create new profile Method signatures and docstrings: - def clean_email(self): checks for user of same address and raises error. Also ensure the fields have content in them. - def clean_password2(self): C...
07445ddd12738a7e0bbc293619f92610d2df0c5e
<|skeleton|> class UserRegistrationForm: """reisters user and is used to create new profile""" def clean_email(self): """checks for user of same address and raises error. Also ensure the fields have content in them.""" <|body_0|> def clean_password2(self): """Compares passwords and...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserRegistrationForm: """reisters user and is used to create new profile""" def clean_email(self): """checks for user of same address and raises error. Also ensure the fields have content in them.""" email = self.cleaned_data.get('email') if not email: raise forms.Vali...
the_stack_v2_python_sparse
accounts/forms.py
brianscan14/XYfitness
train
1
7c38b8a071d09314ccc063999da239fc84e737f2
[ "self.session: object = session\nself.tcex: object = tcex\nself.args: Namespace = tcex.args\nself.allow_redirects: bool = True\nself.data: Optional[Union[dict, str]] = None\nself.headers: dict = {}\nself.max_mb: int = 500\nself.mt: callable = MimeTypes()\nself.output_prefix: str = self.tcex.ij.output_prefix\nself.p...
<|body_start_0|> self.session: object = session self.tcex: object = tcex self.args: Namespace = tcex.args self.allow_redirects: bool = True self.data: Optional[Union[dict, str]] = None self.headers: dict = {} self.max_mb: int = 500 self.mt: callable = Mime...
App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request.
AdvancedRequest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdvancedRequest: """App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request.""" def __init__(self, session: object, tcex: object, timeout: O...
stack_v2_sparse_classes_75kplus_train_000451
6,443
permissive
[ { "docstring": "Initialize class properties.", "name": "__init__", "signature": "def __init__(self, session: object, tcex: object, timeout: Optional[int]=600)" }, { "docstring": "Configure Body Args: tc_adv_req_body (Union[bytes, str]): The request body.", "name": "configure_body", "sign...
5
stack_v2_sparse_classes_30k_train_014793
Implement the Python class `AdvancedRequest` described below. Class description: App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request. Method signatures and docstr...
Implement the Python class `AdvancedRequest` described below. Class description: App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request. Method signatures and docstr...
7cf04fec048fadc71ff851970045b8a587269ccf
<|skeleton|> class AdvancedRequest: """App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request.""" def __init__(self, session: object, tcex: object, timeout: O...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdvancedRequest: """App Feature Advanced Request Module Args: session (object): An instance of Requests Session object. tcex (object): An instance of Tcex object. timeout (Optional[int] = 600): The timeout value for the request.""" def __init__(self, session: object, tcex: object, timeout: Optional[int]=...
the_stack_v2_python_sparse
tcex/app_feature/advanced_request.py
TpyoKnig/tcex
train
0
bcd9673f18a4b3f6d64d22d2e79f671b76e661de
[ "super().__init__(coordinator)\nself.entity_description = sensor_description\ndevice_name = data.name.title()\nself._attr_name = f'{device_name} {sensor_description.name}'\nself._attr_unique_id = f'{unique_id}_{sensor_description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, unique_id)}, name=dev...
<|body_start_0|> super().__init__(coordinator) self.entity_description = sensor_description device_name = data.name.title() self._attr_name = f'{device_name} {sensor_description.name}' self._attr_unique_id = f'{unique_id}_{sensor_description.key}' self._attr_device_info =...
Representation of a sensor entity for NUT status values.
NUTSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NUTSensor: """Representation of a sensor entity for NUT status values.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None: """Initialize the sensor.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_000452
28,254
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None" }, { "docstring": "Return entity state from ups.", "name": ...
2
stack_v2_sparse_classes_30k_train_049549
Implement the Python class `NUTSensor` described below. Class description: Representation of a sensor entity for NUT status values. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -...
Implement the Python class `NUTSensor` described below. Class description: Representation of a sensor entity for NUT status values. Method signatures and docstrings: - def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -...
bfa315be51371a1b63e04342a0b275a57ae148bd
<|skeleton|> class NUTSensor: """Representation of a sensor entity for NUT status values.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None: """Initialize the sensor.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NUTSensor: """Representation of a sensor entity for NUT status values.""" def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None: """Initialize the sensor.""" super().__init__(coordinator...
the_stack_v2_python_sparse
homeassistant/components/nut/sensor.py
bdraco/home-assistant
train
13
36fdcc5cd16aedc4ba3f9aefe11afcc6532b4dd0
[ "if os.path.exists(os.path.join(self.detectorModel, self.detectorModel + '.xml')):\n LOG.notice('Found detector model: %s' % os.path.join(self.detectorModel, self.detectorModel + '.xml'))\n return S_OK(os.path.join(self.detectorModel, self.detectorModel + '.xml'))\nelif os.path.exists(self.detectorModel + '.z...
<|body_start_0|> if os.path.exists(os.path.join(self.detectorModel, self.detectorModel + '.xml')): LOG.notice('Found detector model: %s' % os.path.join(self.detectorModel, self.detectorModel + '.xml')) return S_OK(os.path.join(self.detectorModel, self.detectorModel + '.xml')) eli...
mixin class for DD4hep functionality
DD4hepMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DD4hepMixin: """mixin class for DD4hep functionality""" def _getDetectorXML(self): """returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detector xml files :returns: S_OK(PathToXMLFile), S_ERROR""" ...
stack_v2_sparse_classes_75kplus_train_000453
3,493
no_license
[ { "docstring": "returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detector xml files :returns: S_OK(PathToXMLFile), S_ERROR", "name": "_getDetectorXML", "signature": "def _getDetectorXML(self)" }, { "docstring":...
3
stack_v2_sparse_classes_30k_train_053505
Implement the Python class `DD4hepMixin` described below. Class description: mixin class for DD4hep functionality Method signatures and docstrings: - def _getDetectorXML(self): returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detect...
Implement the Python class `DD4hepMixin` described below. Class description: mixin class for DD4hep functionality Method signatures and docstrings: - def _getDetectorXML(self): returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detect...
9c366957fdd680a284df675c318989cb88e5959c
<|skeleton|> class DD4hepMixin: """mixin class for DD4hep functionality""" def _getDetectorXML(self): """returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detector xml files :returns: S_OK(PathToXMLFile), S_ERROR""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DD4hepMixin: """mixin class for DD4hep functionality""" def _getDetectorXML(self): """returns the path to the detector XML file Checks the Configuration System for the Path to DetectorModels or extracts the input sandbox detector xml files :returns: S_OK(PathToXMLFile), S_ERROR""" if os.p...
the_stack_v2_python_sparse
Workflow/Utilities/DD4hepMixin.py
LCDsoft/ILCDIRAC
train
1
a064bb2cb484622400bb2deb41d55d9bcf44fc45
[ "pool = self.pool\nroom_id = context.get('room_id')\nroom = pool.get('ktv.room').browse(cr, uid, room_id)\nr_op = room.current_room_operate_id\nsum_refund_info = self.get_default_checkout_dict(cr, uid)\nrefund_minutes = ktv_helper.str_timedelta_minutes(ktv_helper.utc_now_str(), r_op.close_time) - r_op.present_minut...
<|body_start_0|> pool = self.pool room_id = context.get('room_id') room = pool.get('ktv.room').browse(cr, uid, room_id) r_op = room.current_room_operate_id sum_refund_info = self.get_default_checkout_dict(cr, uid) refund_minutes = ktv_helper.str_timedelta_minutes(ktv_help...
退钟操作,与买钟操作一致
room_checkout_buytime_refund
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class room_checkout_buytime_refund: """退钟操作,与买钟操作一致""" def re_calculate_fee(self, cr, uid, context): """重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required""" <|body_0|> def process_operate(self, cr, uid, refund_vals): """处理退钟结账事件...
stack_v2_sparse_classes_75kplus_train_000454
3,241
no_license
[ { "docstring": "重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required", "name": "re_calculate_fee", "signature": "def re_calculate_fee(self, cr, uid, context)" }, { "docstring": "处理退钟结账事件 :params dict refund_vals 退钟信息相关字段 :param refund_vals['room_id'] 要退钟的包厢i...
2
null
Implement the Python class `room_checkout_buytime_refund` described below. Class description: 退钟操作,与买钟操作一致 Method signatures and docstrings: - def re_calculate_fee(self, cr, uid, context): 重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required - def process_operate(self, cr, uid, r...
Implement the Python class `room_checkout_buytime_refund` described below. Class description: 退钟操作,与买钟操作一致 Method signatures and docstrings: - def re_calculate_fee(self, cr, uid, context): 重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required - def process_operate(self, cr, uid, r...
a07a26c04d71da7422e8953f04f2f51a3de871b1
<|skeleton|> class room_checkout_buytime_refund: """退钟操作,与买钟操作一致""" def re_calculate_fee(self, cr, uid, context): """重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required""" <|body_0|> def process_operate(self, cr, uid, refund_vals): """处理退钟结账事件...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class room_checkout_buytime_refund: """退钟操作,与买钟操作一致""" def re_calculate_fee(self, cr, uid, context): """重新计算应退费用 :params context 包含计算上下问信息,required :params context[room_id] integer 包厢id,required""" pool = self.pool room_id = context.get('room_id') room = pool.get('ktv.room').bro...
the_stack_v2_python_sparse
addons/ktv_sale/room_checkout_buytime_refund.py
firehot/ktv_sale
train
1
b631f846f7255382a311625a0b4adac02a75396d
[ "sID = super().create_session(user_id)\nif not sID:\n return None\ndt = {'user_id': user_id, 'session_id': sID}\nuSes = UserSession(**dt)\nuSes.save()\nUserSession.save_to_file()\nreturn sID", "if not session_id:\n return None\nUserSession.load_from_file()\nuSes = UserSession.search({'session_id': session_i...
<|body_start_0|> sID = super().create_session(user_id) if not sID: return None dt = {'user_id': user_id, 'session_id': sID} uSes = UserSession(**dt) uSes.save() UserSession.save_to_file() return sID <|end_body_0|> <|body_start_1|> if not sessi...
SessionDBAuth class
SessionDBAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """Creates a Session ID for a user""" <|body_0|> def user_id_for_session_id(self, session_id=None): """Returns a User ID based on a Session ID""" <|body_1|> def destroy_...
stack_v2_sparse_classes_75kplus_train_000455
1,718
no_license
[ { "docstring": "Creates a Session ID for a user", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "Returns a User ID based on a Session ID", "name": "user_id_for_session_id", "signature": "def user_id_for_session_id(self, session_id=None)...
3
stack_v2_sparse_classes_30k_train_051589
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth class Method signatures and docstrings: - def create_session(self, user_id=None): Creates a Session ID for a user - def user_id_for_session_id(self, session_id=None): Returns a User ID based on a Session ID - def destroy_sess...
Implement the Python class `SessionDBAuth` described below. Class description: SessionDBAuth class Method signatures and docstrings: - def create_session(self, user_id=None): Creates a Session ID for a user - def user_id_for_session_id(self, session_id=None): Returns a User ID based on a Session ID - def destroy_sess...
dfb69fff81fca7bccfc2cb9e3bbbdb222d318f92
<|skeleton|> class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """Creates a Session ID for a user""" <|body_0|> def user_id_for_session_id(self, session_id=None): """Returns a User ID based on a Session ID""" <|body_1|> def destroy_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionDBAuth: """SessionDBAuth class""" def create_session(self, user_id=None): """Creates a Session ID for a user""" sID = super().create_session(user_id) if not sID: return None dt = {'user_id': user_id, 'session_id': sID} uSes = UserSession(**dt) ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_db_auth.py
hunterxx0/holbertonschool-web_back_end
train
0
086586af4eeddcd12e45060a364c56d7d67f96f3
[ "try:\n return json.dumps(dict(json_data=dict_data))\nexcept:\n return {}", "try:\n d = json.loads(json_data)\n return d.get('json_data')\nexcept:\n pass" ]
<|body_start_0|> try: return json.dumps(dict(json_data=dict_data)) except: return {} <|end_body_0|> <|body_start_1|> try: d = json.loads(json_data) return d.get('json_data') except: pass <|end_body_1|>
JSON序列化对象
JsonSerializionPacker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonSerializionPacker: """JSON序列化对象""" def pack(dict_data): """导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据""" <|body_0|> def unpack(json_data): """导入序列化数据 Args: json_data: 输入对象 Returns: str: 序列化对象""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_000456
1,761
no_license
[ { "docstring": "导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据", "name": "pack", "signature": "def pack(dict_data)" }, { "docstring": "导入序列化数据 Args: json_data: 输入对象 Returns: str: 序列化对象", "name": "unpack", "signature": "def unpack(json_data)" } ]
2
stack_v2_sparse_classes_30k_test_000677
Implement the Python class `JsonSerializionPacker` described below. Class description: JSON序列化对象 Method signatures and docstrings: - def pack(dict_data): 导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据 - def unpack(json_data): 导入序列化数据 Args: json_data: 输入对象 Returns: str: 序列化对象
Implement the Python class `JsonSerializionPacker` described below. Class description: JSON序列化对象 Method signatures and docstrings: - def pack(dict_data): 导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据 - def unpack(json_data): 导入序列化数据 Args: json_data: 输入对象 Returns: str: 序列化对象 <|skeleton|> class JsonSerializionPack...
7349aac34eab1b66f8d7fc383f6c63bf7a5d2bc1
<|skeleton|> class JsonSerializionPacker: """JSON序列化对象""" def pack(dict_data): """导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据""" <|body_0|> def unpack(json_data): """导入序列化数据 Args: json_data: 输入对象 Returns: str: 序列化对象""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JsonSerializionPacker: """JSON序列化对象""" def pack(dict_data): """导出序列化数据 Args: dict_data: 输入对象 Returns: str: 序列化数据""" try: return json.dumps(dict(json_data=dict_data)) except: return {} def unpack(json_data): """导入序列化数据 Args: json_data: 输入对象 Retu...
the_stack_v2_python_sparse
transconf/packer.py
TerryIron/transconf
train
0
a12e6e37e68aadf36aaddf3a362ba5ab527d2522
[ "self.kmers = seq\nself.adj = {}\nself.inDegree = {}", "for kmer in self.kmers:\n prefix = kmer[:-1]\n suffix = kmer[1:]\n self.adj[prefix] = suffix\n self.inDegree[prefix] = 0\n self.inDegree[suffix] = 0\nfor key in self.adj:\n self.inDegree[self.adj.get(key)] += 1", "for key in self.adj:\n ...
<|body_start_0|> self.kmers = seq self.adj = {} self.inDegree = {} <|end_body_0|> <|body_start_1|> for kmer in self.kmers: prefix = kmer[:-1] suffix = kmer[1:] self.adj[prefix] = suffix self.inDegree[prefix] = 0 self.inDegree[s...
StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string
StringReconstruction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StringReconstruction: """StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string""" def __init__(self, seq): """initialzies the adjacency list and indegrees dict""" <|body_0|> def deBrujin(self): """constructs the...
stack_v2_sparse_classes_75kplus_train_000457
2,365
no_license
[ { "docstring": "initialzies the adjacency list and indegrees dict", "name": "__init__", "signature": "def __init__(self, seq)" }, { "docstring": "constructs the adjacency list of a deBrujin graph also calculates the indegrees of all nodes", "name": "deBrujin", "signature": "def deBrujin(...
4
null
Implement the Python class `StringReconstruction` described below. Class description: StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string Method signatures and docstrings: - def __init__(self, seq): initialzies the adjacency list and indegrees dict - def deBrujin(...
Implement the Python class `StringReconstruction` described below. Class description: StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string Method signatures and docstrings: - def __init__(self, seq): initialzies the adjacency list and indegrees dict - def deBrujin(...
b1fa51d603976dc8ed15f1f016e2879db6630f8c
<|skeleton|> class StringReconstruction: """StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string""" def __init__(self, seq): """initialzies the adjacency list and indegrees dict""" <|body_0|> def deBrujin(self): """constructs the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StringReconstruction: """StringReconstruction class creates a graph of kmers allows traversal in linear time to reconstruct string""" def __init__(self, seq): """initialzies the adjacency list and indegrees dict""" self.kmers = seq self.adj = {} self.inDegree = {} def...
the_stack_v2_python_sparse
problem14.py
cnk113/assignments
train
0
b171775bba32da2851be974ae361f32e34b0c955
[ "super(TapNetClassifier, self).__init__(model_save_directory=model_save_directory, model_name=model_name)\nself.batch_size = batch_size\nself.random_state = random_state\nself.kernel_size = kernel_sizes\nself.layers = layers\nself.rp_params = rp_params\nself.filter_sizes = filter_sizes\nself.use_att = use_att\nself...
<|body_start_0|> super(TapNetClassifier, self).__init__(model_save_directory=model_save_directory, model_name=model_name) self.batch_size = batch_size self.random_state = random_state self.kernel_size = kernel_sizes self.layers = layers self.rp_params = rp_params ...
Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: list or array of ints, default=[256, 256, 128] sets the kernel size argument for each ...
TapNetClassifier
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TapNetClassifier: """Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: list or array of ints, default=[256, 256, ...
stack_v2_sparse_classes_75kplus_train_000458
8,079
permissive
[ { "docstring": ":param kernel_size: int, specifying the length of the 1D convolution window :param avg_pool_size: int, size of the average pooling windows :param layers: int, size of dense layers :param filter_sizes: int, array of shape = (nb_conv_layers) :param random_state: int, seed to any needed random acti...
3
null
Implement the Python class `TapNetClassifier` described below. Class description: Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: lis...
Implement the Python class `TapNetClassifier` described below. Class description: Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: lis...
b565b7499f58f43da7314f1bf26eccce94e88134
<|skeleton|> class TapNetClassifier: """Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: list or array of ints, default=[256, 256, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TapNetClassifier: """Implementation of TapNetClassifier Zhang (2020). [1]_ Overview: Uses optionally an LSTM, CNN and self attention mechanism. Original implementation used pytorch so some features have not been added. Parameters ---------- filter_sizes: list or array of ints, default=[256, 256, 128] sets the...
the_stack_v2_python_sparse
sktime_dl/classification/_tapnet.py
sktime/sktime-dl
train
586
b80e52d2f5ae92891d6486075e20d9a98e04a0e0
[ "x, y, z = self.coords\nif self.orientation == '+x':\n yield (x - 1, y, z)\nelif self.orientation == '-x':\n yield (x + 1, y, z)\nelif self.orientation == '+z':\n yield (x, y, z - 1)\nelif self.orientation == '-z':\n yield (x, y, z + 1)\nelif self.orientation == '+y':\n yield (x, y - 1, z)", "x, y,...
<|body_start_0|> x, y, z = self.coords if self.orientation == '+x': yield (x - 1, y, z) elif self.orientation == '-x': yield (x + 1, y, z) elif self.orientation == '+z': yield (x, y, z - 1) elif self.orientation == '-z': yield (x, y...
A redstone torch. Torches do a NOT operation from their input.
Torch
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" <|body_0|> def iter_outputs(self): """Provide the outputs corresponding to the ...
stack_v2_sparse_classes_75kplus_train_000459
13,022
permissive
[ { "docstring": "Provide the input corresponding to the block upon which this torch is mounted.", "name": "iter_inputs", "signature": "def iter_inputs(self)" }, { "docstring": "Provide the outputs corresponding to the block upon which this torch is mounted.", "name": "iter_outputs", "sign...
2
stack_v2_sparse_classes_30k_train_010876
Implement the Python class `Torch` described below. Class description: A redstone torch. Torches do a NOT operation from their input. Method signatures and docstrings: - def iter_inputs(self): Provide the input corresponding to the block upon which this torch is mounted. - def iter_outputs(self): Provide the outputs ...
Implement the Python class `Torch` described below. Class description: A redstone torch. Torches do a NOT operation from their input. Method signatures and docstrings: - def iter_inputs(self): Provide the input corresponding to the block upon which this torch is mounted. - def iter_outputs(self): Provide the outputs ...
7be5d792871a8447499911fa1502c6a7c1437dc3
<|skeleton|> class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" <|body_0|> def iter_outputs(self): """Provide the outputs corresponding to the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" x, y, z = self.coords if self.orientation == '+x': yield (x - 1, y, z) elif s...
the_stack_v2_python_sparse
bravo/utilities/redstone.py
CyberFlameGO/bravo
train
0
d0e720246d040ced0da514017004dac13330ac59
[ "self.log = log\nself.boto3_factory = boto3_factory\nself.batch_client = boto3_factory.get_client('batch')", "jobs = self.batch_client.describe_jobs(jobs=job_ids)['jobs']\nself.log.debug(jobs)\nif len(jobs) != len(job_ids):\n available_job_ids = []\n for job in jobs:\n available_job_ids.append(job['j...
<|body_start_0|> self.log = log self.boto3_factory = boto3_factory self.batch_client = boto3_factory.get_client('batch') <|end_body_0|> <|body_start_1|> jobs = self.batch_client.describe_jobs(jobs=job_ids)['jobs'] self.log.debug(jobs) if len(jobs) != len(job_ids): ...
awsbkill command.
AWSBkillCommand
[ "Python-2.0", "GPL-1.0-or-later", "MPL-2.0", "MIT", "LicenseRef-scancode-python-cwi", "BSD-3-Clause", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-free-unknown", "Apache-2.0", "MIT-0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AWSBkillCommand: """awsbkill command.""" def __init__(self, log, boto3_factory): """Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object""" <|body_0|> def run(self, job_ids, reason): """Kill/cancel the jobs. :param...
stack_v2_sparse_classes_75kplus_train_000460
4,777
permissive
[ { "docstring": "Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object", "name": "__init__", "signature": "def __init__(self, log, boto3_factory)" }, { "docstring": "Kill/cancel the jobs. :param job_ids: list of job ids :param reason: optional reaso...
3
stack_v2_sparse_classes_30k_train_000109
Implement the Python class `AWSBkillCommand` described below. Class description: awsbkill command. Method signatures and docstrings: - def __init__(self, log, boto3_factory): Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object - def run(self, job_ids, reason): Kill/ca...
Implement the Python class `AWSBkillCommand` described below. Class description: awsbkill command. Method signatures and docstrings: - def __init__(self, log, boto3_factory): Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object - def run(self, job_ids, reason): Kill/ca...
a213978a09ea7fc80855bf55c539861ea95259f9
<|skeleton|> class AWSBkillCommand: """awsbkill command.""" def __init__(self, log, boto3_factory): """Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object""" <|body_0|> def run(self, job_ids, reason): """Kill/cancel the jobs. :param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AWSBkillCommand: """awsbkill command.""" def __init__(self, log, boto3_factory): """Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object""" self.log = log self.boto3_factory = boto3_factory self.batch_client = boto3_factory....
the_stack_v2_python_sparse
awsbatch-cli/src/awsbatch/awsbkill.py
aws/aws-parallelcluster
train
520
59b31be914a2537691382f86b0e408af190c0fa4
[ "if not nums:\n return 0\ndp = []\nfor i in range(len(nums)):\n dp.append(1)\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)", "dp = {1: 1, 2: 2}\nfor i in range(3, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[n]", "dp = [[0, 0]] *...
<|body_start_0|> if not nums: return 0 dp = [] for i in range(len(nums)): dp.append(1) for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp) <|end_body_0|> <|body_start_1|> dp...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums: List[int]) -> int: """300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。""" <|body_0|> def climb(self, n: int) -> int: """70. 爬楼梯问题 一次只能爬一步或者两步,一共n阶台阶 转移...
stack_v2_sparse_classes_75kplus_train_000461
3,592
no_license
[ { "docstring": "300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums: List[int]) -> int" }, { "docstring": "70. 爬楼梯问题 一次只能爬一步或者两步,一共n阶台阶 转移方程 f(i) = f(i - 1...
4
stack_v2_sparse_classes_30k_test_000378
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums: List[int]) -> int: 300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。 - de...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums: List[int]) -> int: 300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。 - de...
330330ef6bc42eeb17f4dea53c30d230506b4e8f
<|skeleton|> class Solution: def lengthOfLIS(self, nums: List[int]) -> int: """300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。""" <|body_0|> def climb(self, n: int) -> int: """70. 爬楼梯问题 一次只能爬一步或者两步,一共n阶台阶 转移...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: """300. 最长递增子序列 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。""" if not nums: return 0 dp = [] for i in range(len(nums)): dp.appe...
the_stack_v2_python_sparse
Code/leetcode_everyday/0310.py
NiceToMeeetU/ToGetReady
train
0
b7968d334791692082fdd99c2624240106846c7e
[ "sums = [0]\nfor x in nums:\n sums.append(sums[-1] + x)\ncount = 0\nfor j in range(len(sums)):\n for i in range(j):\n if sums[j] - sums[i] == k:\n count += 1\nreturn count", "count, sums = (0, 0)\ndic = {0: 1}\nfor x in nums:\n sums += x\n count += dic.get(sums - k, 0)\n dic[sums]...
<|body_start_0|> sums = [0] for x in nums: sums.append(sums[-1] + x) count = 0 for j in range(len(sums)): for i in range(j): if sums[j] - sums[i] == k: count += 1 return count <|end_body_0|> <|body_start_1|> cou...
求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" ...
stack_v2_sparse_classes_75kplus_train_000462
1,897
no_license
[ { "docstring": "前缀和:会超时,仅提供思路", "name": "subarraySum1", "signature": "def subarraySum1(self, nums: List[int], k: int) -> int" }, { "docstring": "前缀和+hash表优化: 问题转化为: 求i<j,满足sum(i) = sum(j) - k 对于每个j,记录之前所有的presum,然后查找有多少个presum==sum(j)-k", "name": "subarraySum2", "signature": "def subarra...
2
stack_v2_sparse_classes_30k_train_022250
Implement the Python class `Solution` described below. Class description: 求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景 Method signatures and docstrings: - def subarraySum1(self, ...
Implement the Python class `Solution` described below. Class description: 求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景 Method signatures and docstrings: - def subarraySum1(self, ...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: """求连续子数组的和,直接用暴力破解,穷举出所有子数组,算出和等于k即可。 如何求子数组的和sum(i,j)? 暴力法需要重复多次计算,而使用前缀和记录则是O(1) 即:sum(i,j) = sum(0,j) - sum(0,i-1) index: 0 1 2 4 nums: [ 1, 2, 1, 3 ] sum: 0, 1, 3, 4, 7 补位0,num==k的场景""" def subarraySum1(self, nums: List[int], k: int) -> int: """前缀和:会超时,仅提供思路""" sums = [0] ...
the_stack_v2_python_sparse
560_subarray-sum-equals-k.py
helloocc/algorithm
train
1
b49a49705750546cdf89e7854a2c5cedaf7d8096
[ "super(SEBlock, self).__init__()\nself.reduce = nn.Conv2d(in_channels=in_channels, out_channels=int(in_channels * rd_ratio), kernel_size=1, stride=1, bias=True)\nself.expand = nn.Conv2d(in_channels=int(in_channels * rd_ratio), out_channels=in_channels, kernel_size=1, stride=1, bias=True)", "b, c, h, w = inputs.si...
<|body_start_0|> super(SEBlock, self).__init__() self.reduce = nn.Conv2d(in_channels=in_channels, out_channels=int(in_channels * rd_ratio), kernel_size=1, stride=1, bias=True) self.expand = nn.Conv2d(in_channels=int(in_channels * rd_ratio), out_channels=in_channels, kernel_size=1, stride=1, bias...
Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf
SEBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SEBlock: """Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf""" def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None: """Construct a Squeeze and Excite Module. :param in_channels: Number of i...
stack_v2_sparse_classes_75kplus_train_000463
19,106
permissive
[ { "docstring": "Construct a Squeeze and Excite Module. :param in_channels: Number of input channels. :param rd_ratio: Input channel reduction ratio.", "name": "__init__", "signature": "def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None" }, { "docstring": "Apply forward pass.", ...
2
stack_v2_sparse_classes_30k_val_001234
Implement the Python class `SEBlock` described below. Class description: Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf Method signatures and docstrings: - def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None: Construct a S...
Implement the Python class `SEBlock` described below. Class description: Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf Method signatures and docstrings: - def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None: Construct a S...
6db76a1106426ac5b55f39fba68168f3bccae7f8
<|skeleton|> class SEBlock: """Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf""" def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None: """Construct a Squeeze and Excite Module. :param in_channels: Number of i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SEBlock: """Squeeze and Excite module. Pytorch implementation of `Squeeze-and-Excitation Networks` - https://arxiv.org/pdf/1709.01507.pdf""" def __init__(self, in_channels: int, rd_ratio: float=0.0625) -> None: """Construct a Squeeze and Excite Module. :param in_channels: Number of input channels...
the_stack_v2_python_sparse
segmentation_models_pytorch/encoders/mobileone.py
qubvel/segmentation_models.pytorch
train
8,150
1c6315bf1ee497701ab03a0319aa9cf1024b13f0
[ "url = '/success/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)", "url = '/success/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)", ...
<|body_start_0|> url = '/success/' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302) <|end_body_0|> <|body_start_1|> url = '/success/' self.client.login(username=self.adminUN, password='pass') response = self.client.g...
SuccessTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuccessTestCase: def test_not_logged_in(self): """Test that the success view will redirect whilst not logged in and no booking made.""" <|body_0|> def test_logged_in_admin(self): """Test that the success view will redirect whilst logged in as admin and no booking mad...
stack_v2_sparse_classes_75kplus_train_000464
26,818
permissive
[ { "docstring": "Test that the success view will redirect whilst not logged in and no booking made.", "name": "test_not_logged_in", "signature": "def test_not_logged_in(self)" }, { "docstring": "Test that the success view will redirect whilst logged in as admin and no booking made.", "name": ...
3
stack_v2_sparse_classes_30k_train_025675
Implement the Python class `SuccessTestCase` described below. Class description: Implement the SuccessTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the success view will redirect whilst not logged in and no booking made. - def test_logged_in_admin(self): Test that the suc...
Implement the Python class `SuccessTestCase` described below. Class description: Implement the SuccessTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the success view will redirect whilst not logged in and no booking made. - def test_logged_in_admin(self): Test that the suc...
37d2942efcbdaad072f7a06ac876a40e0f69f702
<|skeleton|> class SuccessTestCase: def test_not_logged_in(self): """Test that the success view will redirect whilst not logged in and no booking made.""" <|body_0|> def test_logged_in_admin(self): """Test that the success view will redirect whilst logged in as admin and no booking mad...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SuccessTestCase: def test_not_logged_in(self): """Test that the success view will redirect whilst not logged in and no booking made.""" url = '/success/' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302) def test_logged...
the_stack_v2_python_sparse
mooring/test_views.py
dbca-wa/moorings
train
0
cbf895cb04df73da9b773e63a4a66b9060b14e46
[ "if not isinstance(pos, (coords.Galactocentric,)):\n raise TypeError('currently only support Galactocentric')\nelse:\n self.pos = pos\nif vel is not None:\n raise TypeError('currently only support `pos`')\nif frame is not None:\n raise TypeError('currently only support `pos`')", "if galactocentric_fra...
<|body_start_0|> if not isinstance(pos, (coords.Galactocentric,)): raise TypeError('currently only support Galactocentric') else: self.pos = pos if vel is not None: raise TypeError('currently only support `pos`') if frame is not None: raise...
Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy.coordinates.SkyCoord`. Conversely, the :mod:`~gala` package implements a single class fo...
PhaseSpacePositionBase
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhaseSpacePositionBase: """Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy.coordinates.SkyCoord`. Conversely, the...
stack_v2_sparse_classes_75kplus_train_000465
12,794
permissive
[ { "docstring": "Phase Space Position Proxy. Parameters ---------- pos : SkyCoord or BaseCoordinateFrame", "name": "__init__", "signature": "def __init__(self, pos, vel=None, frame=None)" }, { "docstring": "To coordinate frame. Parameters ---------- frame : :class:`~astropy.coordinates.BaseCoordi...
2
null
Implement the Python class `PhaseSpacePositionBase` described below. Class description: Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy...
Implement the Python class `PhaseSpacePositionBase` described below. Class description: Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy...
9e1f41c6de1ca6adbd2bf99414a4c9b61838abf6
<|skeleton|> class PhaseSpacePositionBase: """Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy.coordinates.SkyCoord`. Conversely, the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PhaseSpacePositionBase: """Gala-style Initial Conditions Class. The initial condition (IC) construction process in :mod:`~galpy` is very flexible: the Orbits class accepts anything from a list of floats to `~astropy.units.Quantity` arrays to a full `~astropy.coordinates.SkyCoord`. Conversely, the :mod:`~gala`...
the_stack_v2_python_sparse
astronat/dynamics/coordinates/ic.py
nstarman/astronat
train
1
23f6d393e0cae3bd82b6274a4a3fde5988f5b513
[ "self._key_to_value: Dict[Hashable, object] = {}\nself._key_to_value_get = self._key_to_value.get\nself._key_to_value_set = self._key_to_value.__setitem__\nself._lock = Lock()", "assert isinstance(key, Hashable), f'{repr(key)} unhashable.'\nwith self._lock:\n value_old = self._key_to_value_get(key, _SENTINEL)\...
<|body_start_0|> self._key_to_value: Dict[Hashable, object] = {} self._key_to_value_get = self._key_to_value.get self._key_to_value_set = self._key_to_value.__setitem__ self._lock = Lock() <|end_body_0|> <|body_start_1|> assert isinstance(key, Hashable), f'{repr(key)} unhashable...
**Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak references for safety. Employing strong references...
CacheUnboundedStrong
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CacheUnboundedStrong: """**Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak re...
stack_v2_sparse_classes_75kplus_train_000466
8,884
permissive
[ { "docstring": "Initialize this cache to an empty cache.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Statically associate the passed key with the passed value if this cache has yet to cache this key (i.e., if this method has yet to be passed this key) and, ...
3
stack_v2_sparse_classes_30k_test_001771
Implement the Python class `CacheUnboundedStrong` described below. Class description: **Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache i...
Implement the Python class `CacheUnboundedStrong` described below. Class description: **Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache i...
3df840dfd11f09dc9b6f04cb6d29703909e2cb0a
<|skeleton|> class CacheUnboundedStrong: """**Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CacheUnboundedStrong: """**Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size from strongly referenced arbitrary keys onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak references for ...
the_stack_v2_python_sparse
beartype/_util/cache/map/utilmapbig.py
MTouny/beartype
train
0
1220756726be2b6218c7a9a85d718bb66c050fbd
[ "if user_id is None:\n return None\nif not isinstance(user_id, str):\n return None\nnew_session_id = str(uuid4())\nself.user_id_by_session_id[new_session_id] = user_id\nreturn new_session_id", "if session_id is None:\n return None\nif not isinstance(session_id, str):\n return None\nnew_user_id = self....
<|body_start_0|> if user_id is None: return None if not isinstance(user_id, str): return None new_session_id = str(uuid4()) self.user_id_by_session_id[new_session_id] = user_id return new_session_id <|end_body_0|> <|body_start_1|> if session_id is...
Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class]
SessionAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionAuth: """Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class]""" def create_session(self, user_id: str=None) -> str: """Method that creates a Session ID for a user_id""" <|body_0|> def user_id_for_session_id(self, session_id: str=None) ->...
stack_v2_sparse_classes_75kplus_train_000467
1,888
no_license
[ { "docstring": "Method that creates a Session ID for a user_id", "name": "create_session", "signature": "def create_session(self, user_id: str=None) -> str" }, { "docstring": "Method User ID for Session ID, Returns a User ID based on a Session ID", "name": "user_id_for_session_id", "sign...
4
stack_v2_sparse_classes_30k_train_029795
Implement the Python class `SessionAuth` described below. Class description: Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class] Method signatures and docstrings: - def create_session(self, user_id: str=None) -> str: Method that creates a Session ID for a user_id - def user_id_for_session_i...
Implement the Python class `SessionAuth` described below. Class description: Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class] Method signatures and docstrings: - def create_session(self, user_id: str=None) -> str: Method that creates a Session ID for a user_id - def user_id_for_session_i...
ddd3e32957f95e727a736be5658ef54a98f4cfb4
<|skeleton|> class SessionAuth: """Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class]""" def create_session(self, user_id: str=None) -> str: """Method that creates a Session ID for a user_id""" <|body_0|> def user_id_for_session_id(self, session_id: str=None) ->...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionAuth: """Class SessionAuth that inherits from Auth Args: Auth ([Class]): [Parent class]""" def create_session(self, user_id: str=None) -> str: """Method that creates a Session ID for a user_id""" if user_id is None: return None if not isinstance(user_id, str): ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_auth.py
monicajoa/holbertonschool-web_back_end
train
0
842f2814adda8bffb404500a3bc7343013df1d47
[ "if isinstance(obj, Singing):\n return SingingSerializer(obj, context=self.context).to_representation(obj)\nelif isinstance(obj, Dancing):\n return DancingSerializer(obj, context=self.context).to_representation(obj)\nelif isinstance(obj, Acting):\n return ActingSerializer(obj, context=self.context).to_repr...
<|body_start_0|> if isinstance(obj, Singing): return SingingSerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, Dancing): return DancingSerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, Acting): ret...
TalentSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TalentSerializer: def to_representation(self, obj): """Because Talent is Polymorphic""" <|body_0|> def to_internal_value(self, data): """Because Talent is Polymorphic""" <|body_1|> <|end_skeleton|> <|body_start_0|> if isinstance(obj, Singing): ...
stack_v2_sparse_classes_75kplus_train_000468
2,912
no_license
[ { "docstring": "Because Talent is Polymorphic", "name": "to_representation", "signature": "def to_representation(self, obj)" }, { "docstring": "Because Talent is Polymorphic", "name": "to_internal_value", "signature": "def to_internal_value(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_020305
Implement the Python class `TalentSerializer` described below. Class description: Implement the TalentSerializer class. Method signatures and docstrings: - def to_representation(self, obj): Because Talent is Polymorphic - def to_internal_value(self, data): Because Talent is Polymorphic
Implement the Python class `TalentSerializer` described below. Class description: Implement the TalentSerializer class. Method signatures and docstrings: - def to_representation(self, obj): Because Talent is Polymorphic - def to_internal_value(self, data): Because Talent is Polymorphic <|skeleton|> class TalentSeria...
88a8278db78a33b8b5777afdb87bd935930bd9ae
<|skeleton|> class TalentSerializer: def to_representation(self, obj): """Because Talent is Polymorphic""" <|body_0|> def to_internal_value(self, data): """Because Talent is Polymorphic""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TalentSerializer: def to_representation(self, obj): """Because Talent is Polymorphic""" if isinstance(obj, Singing): return SingingSerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, Dancing): return DancingSerializer(obj, context=s...
the_stack_v2_python_sparse
talent/serializers.py
n6151h/amato
train
0
03236625ed7677af3aba2cfb1d60e5fb5b202e3c
[ "if lang in self.EUROPEAN_TYPED_LANGUAGES:\n super(sppasNumEuropeanType, self).__init__(lang, dictionary)\nelse:\n raise sppasValueError(lang, str(sppasNumEuropeanType.EUROPEAN_TYPED_LANGUAGES))\nfor i in sppasNumEuropeanType.NUMBER_LIST:\n if self._lang_dict.is_unk(str(i)) is True:\n raise sppasVal...
<|body_start_0|> if lang in self.EUROPEAN_TYPED_LANGUAGES: super(sppasNumEuropeanType, self).__init__(lang, dictionary) else: raise sppasValueError(lang, str(sppasNumEuropeanType.EUROPEAN_TYPED_LANGUAGES)) for i in sppasNumEuropeanType.NUMBER_LIST: if self._la...
:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi
sppasNumEuropeanType
[ "GFDL-1.1-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class sppasNumEuropeanType: """:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi""" def __init__(self, lang=None, dictionary=None): """Return an ...
stack_v2_sparse_classes_75kplus_train_000469
5,535
permissive
[ { "docstring": "Return an instance of sppasNumEuropeanType. :param lang: (str) name of the language", "name": "__init__", "signature": "def __init__(self, lang=None, dictionary=None)" }, { "docstring": "Return the \"wordified\" version of a million number. Returns the word corresponding to the g...
3
stack_v2_sparse_classes_30k_train_004658
Implement the Python class `sppasNumEuropeanType` described below. Class description: :author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi Method signatures and docstrings: - d...
Implement the Python class `sppasNumEuropeanType` described below. Class description: :author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi Method signatures and docstrings: - d...
3167b65f576abcc27a8767d24c274a04712bd948
<|skeleton|> class sppasNumEuropeanType: """:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi""" def __init__(self, lang=None, dictionary=None): """Return an ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class sppasNumEuropeanType: """:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi""" def __init__(self, lang=None, dictionary=None): """Return an instance of s...
the_stack_v2_python_sparse
sppas/sppas/src/annotations/TextNorm/num2text/num_europ_lang.py
mirfan899/MTTS
train
0
cbfd5490a7f2791077198dc9af1bcca78dc1112c
[ "extresource = ExternalResource.get(pk=external_id)\nserializer = serialize(serializers.ExtResource, extresource)\nreturn QuaApiResponse(serializer.data)", "try:\n extresource = ExternalResource.get(pk=external_id)\n extresource.delete()\nexcept Exception as exc:\n log.exception(exc)\nreturn QuaApiRespon...
<|body_start_0|> extresource = ExternalResource.get(pk=external_id) serializer = serialize(serializers.ExtResource, extresource) return QuaApiResponse(serializer.data) <|end_body_0|> <|body_start_1|> try: extresource = ExternalResource.get(pk=external_id) extreso...
ExtResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtResource: def get(self, request, external_id): """Get extresource by extresource_id""" <|body_0|> def delete(self, request, external_id): """Delete specific external resource""" <|body_1|> <|end_skeleton|> <|body_start_0|> extresource = ExternalR...
stack_v2_sparse_classes_75kplus_train_000470
2,424
no_license
[ { "docstring": "Get extresource by extresource_id", "name": "get", "signature": "def get(self, request, external_id)" }, { "docstring": "Delete specific external resource", "name": "delete", "signature": "def delete(self, request, external_id)" } ]
2
stack_v2_sparse_classes_30k_train_006123
Implement the Python class `ExtResource` described below. Class description: Implement the ExtResource class. Method signatures and docstrings: - def get(self, request, external_id): Get extresource by extresource_id - def delete(self, request, external_id): Delete specific external resource
Implement the Python class `ExtResource` described below. Class description: Implement the ExtResource class. Method signatures and docstrings: - def get(self, request, external_id): Get extresource by extresource_id - def delete(self, request, external_id): Delete specific external resource <|skeleton|> class ExtRe...
670752a3b48619eeba2fa9f2cf133e6050737a73
<|skeleton|> class ExtResource: def get(self, request, external_id): """Get extresource by extresource_id""" <|body_0|> def delete(self, request, external_id): """Delete specific external resource""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExtResource: def get(self, request, external_id): """Get extresource by extresource_id""" extresource = ExternalResource.get(pk=external_id) serializer = serialize(serializers.ExtResource, extresource) return QuaApiResponse(serializer.data) def delete(self, request, extern...
the_stack_v2_python_sparse
controller/src/api/views/external.py
Sapunov/qua
train
1
88138f308b9e78ab57b98ee8225064261e5b15d1
[ "self.region_name = region_name\nself.rs_enduses_fuel = data['rs_fueldata_disagg'][region_name]\nself.ss_enduses_sectors_fuels = data['ss_fueldata_disagg'][region_name]\nself.is_enduses_sectors_fuels = data['is_fueldata_disagg'][region_name]\nself.ts_fuels = data['ts_fueldata_disagg'][region_name]\nclosest_station_...
<|body_start_0|> self.region_name = region_name self.rs_enduses_fuel = data['rs_fueldata_disagg'][region_name] self.ss_enduses_sectors_fuels = data['ss_fueldata_disagg'][region_name] self.is_enduses_sectors_fuels = data['is_fueldata_disagg'][region_name] self.ts_fuels = data['ts_...
Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technology stock is defined with help of regional temperature data technology spe...
Region
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Region: """Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technology stock is defined with help of region...
stack_v2_sparse_classes_75kplus_train_000471
2,927
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, region_name, data, submodel_type, weather_regions)" }, { "docstring": "Iterate list with weather regions and get weather region object", "name": "get_correct_weather_point", "signature": "def get_correct_w...
2
null
Implement the Python class `Region` described below. Class description: Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technolo...
Implement the Python class `Region` described below. Class description: Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technolo...
59a2712f353f47e3dc237479cc6cc46666b7d0f1
<|skeleton|> class Region: """Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technology stock is defined with help of region...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Region: """Region class For every Region, a Region object needs to be generated. Parameters ---------- region_name : str Unique identifyer of region_name data : dict Dictionary containing data Note ------------------------- - For each region_name, a technology stock is defined with help of regional temperatur...
the_stack_v2_python_sparse
energy_demand/geography/region.py
willu47/energy_demand
train
0
6b5a715832ae65b524ac08fb04e52e62d9ab9e24
[ "super().__init__()\nself.position_encoding = PositionalEncoding(e_dim)\nself.decoder_layers = nn.ModuleList([DecoderLayer(e_dim, h_dim, n_heads, drop_rate) for _ in range(n_layers)])", "seq_inputs = self.position_encoding(seq_inputs)\nmask = subsequent_mask(seq_inputs.shape[1])\nfor layer in self.decoder_layers:...
<|body_start_0|> super().__init__() self.position_encoding = PositionalEncoding(e_dim) self.decoder_layers = nn.ModuleList([DecoderLayer(e_dim, h_dim, n_heads, drop_rate) for _ in range(n_layers)]) <|end_body_0|> <|body_start_1|> seq_inputs = self.position_encoding(seq_inputs) m...
TransformerDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransformerDecoder: def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): """:param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例""" <|body_0|> def forward(self, seq_inputs, querys): ...
stack_v2_sparse_classes_75kplus_train_000472
10,000
no_license
[ { "docstring": ":param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例", "name": "__init__", "signature": "def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1)" }, { "docstring": ":param seq_inputs: 已经经过Embe...
2
stack_v2_sparse_classes_30k_train_043567
Implement the Python class `TransformerDecoder` described below. Class description: Implement the TransformerDecoder class. Method signatures and docstrings: - def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): :param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layer...
Implement the Python class `TransformerDecoder` described below. Class description: Implement the TransformerDecoder class. Method signatures and docstrings: - def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): :param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layer...
c7bef7c5ca6e755d0714a688e0c36f35146c8a10
<|skeleton|> class TransformerDecoder: def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): """:param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例""" <|body_0|> def forward(self, seq_inputs, querys): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TransformerDecoder: def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): """:param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例""" super().__init__() self.position_encoding = PositionalEncoding...
the_stack_v2_python_sparse
chapter3/s49_transformer.py
chenrj23/recbyhand
train
0
f910d200d81f62964c2efe9cfe31ad270396a356
[ "stk = []\nfor n in nums[::-1]:\n while stk and stk[-1] <= n:\n stk.pop()\n stk.append(n)\nret = []\nfor n in nums[::-1]:\n while stk and stk[-1] <= n:\n stk.pop()\n ret.append(stk[-1] if stk else -1)\n stk.append(n)\nreturn ret[::-1]", "A = nums + nums\nprint(A)\nret = []\nfor e in n...
<|body_start_0|> stk = [] for n in nums[::-1]: while stk and stk[-1] <= n: stk.pop() stk.append(n) ret = [] for n in nums[::-1]: while stk and stk[-1] <= n: stk.pop() ret.append(stk[-1] if stk else -1) ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nextGreaterElements(self, nums): """scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing numbers. if A[i] > any A[i+1: j] but A[i] < A[j], we can safely drop the numbers A[i+1:j] since ...
stack_v2_sparse_classes_75kplus_train_000473
2,077
permissive
[ { "docstring": "scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing numbers. if A[i] > any A[i+1: j] but A[i] < A[j], we can safely drop the numbers A[i+1:j] since they won't be useful. :type nums: List[int] :rtype: List[i...
2
stack_v2_sparse_classes_30k_train_028409
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextGreaterElements(self, nums): scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextGreaterElements(self, nums): scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing...
cbbd4a67ab342ada2421e13f82d660b1d47d4d20
<|skeleton|> class Solution: def nextGreaterElements(self, nums): """scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing numbers. if A[i] > any A[i+1: j] but A[i] < A[j], we can safely drop the numbers A[i+1:j] since ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def nextGreaterElements(self, nums): """scan the nums from right to left, since next largest number, you can drop certain information about the A[i:]. Use stack to keep a increasing numbers. if A[i] > any A[i+1: j] but A[i] < A[j], we can safely drop the numbers A[i+1:j] since they won't be ...
the_stack_v2_python_sparse
503 Next Greater Element II.py
Aminaba123/LeetCode
train
1
2ccc503f8a9efd4aa08f95ef77e3b4988adb1420
[ "comments = CommentsShows.query.order_by(asc(CommentsShows.ShowID), asc(CommentsShows.Created)).all()\ncontents = jsonify({'comments': [{'commentID': comment.CommentID, 'showID': comment.ShowID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'createdAt': get_iso_format(c...
<|body_start_0|> comments = CommentsShows.query.order_by(asc(CommentsShows.ShowID), asc(CommentsShows.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'showID': comment.ShowID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'c...
ShowCommentsView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShowCommentsView: def index(self): """Return all comments for all shows.""" <|body_0|> def get(self, show_id): """Return the comments for a specific show.""" <|body_1|> def post(self): """Add a comment to a show specified in the payload.""" ...
stack_v2_sparse_classes_75kplus_train_000474
26,847
permissive
[ { "docstring": "Return all comments for all shows.", "name": "index", "signature": "def index(self)" }, { "docstring": "Return the comments for a specific show.", "name": "get", "signature": "def get(self, show_id)" }, { "docstring": "Add a comment to a show specified in the payl...
5
stack_v2_sparse_classes_30k_train_053572
Implement the Python class `ShowCommentsView` described below. Class description: Implement the ShowCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all shows. - def get(self, show_id): Return the comments for a specific show. - def post(self): Add a comment to a show s...
Implement the Python class `ShowCommentsView` described below. Class description: Implement the ShowCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all shows. - def get(self, show_id): Return the comments for a specific show. - def post(self): Add a comment to a show s...
62f8e8e904e379541193f0cbb91a8434b47f538f
<|skeleton|> class ShowCommentsView: def index(self): """Return all comments for all shows.""" <|body_0|> def get(self, show_id): """Return the comments for a specific show.""" <|body_1|> def post(self): """Add a comment to a show specified in the payload.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ShowCommentsView: def index(self): """Return all comments for all shows.""" comments = CommentsShows.query.order_by(asc(CommentsShows.ShowID), asc(CommentsShows.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'showID': comment.ShowID, 'userID': comment...
the_stack_v2_python_sparse
apps/comments/views.py
Torniojaws/vortech-backend
train
0
27fd62b1419ea6cbed06f69608b3a50473f808aa
[ "for func in reversed(self.mime_func):\n codename = func(mime)\n if codename is not None:\n return codename", "assert mime is not None or cls is not None\nif mime is not None:\n cls = self.factories[self.get_type(mime)]\nreturn super(MIMETemplateLoader, self).load(path, cls=cls, relative_to=relati...
<|body_start_0|> for func in reversed(self.mime_func): codename = func(mime) if codename is not None: return codename <|end_body_0|> <|body_start_1|> assert mime is not None or cls is not None if mime is not None: cls = self.factories[self.get...
This subclass of TemplateLoader use mimetypes to search and find templates to load.
MIMETemplateLoader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MIMETemplateLoader: """This subclass of TemplateLoader use mimetypes to search and find templates to load.""" def get_type(self, mime): """finds the codename used by relatorio to work on a mimetype""" <|body_0|> def load(self, path, mime=None, relative_to=None, cls=None)...
stack_v2_sparse_classes_75kplus_train_000475
5,592
no_license
[ { "docstring": "finds the codename used by relatorio to work on a mimetype", "name": "get_type", "signature": "def get_type(self, mime)" }, { "docstring": "returns a template object based on path", "name": "load", "signature": "def load(self, path, mime=None, relative_to=None, cls=None)"...
3
stack_v2_sparse_classes_30k_train_022870
Implement the Python class `MIMETemplateLoader` described below. Class description: This subclass of TemplateLoader use mimetypes to search and find templates to load. Method signatures and docstrings: - def get_type(self, mime): finds the codename used by relatorio to work on a mimetype - def load(self, path, mime=N...
Implement the Python class `MIMETemplateLoader` described below. Class description: This subclass of TemplateLoader use mimetypes to search and find templates to load. Method signatures and docstrings: - def get_type(self, mime): finds the codename used by relatorio to work on a mimetype - def load(self, path, mime=N...
8d1ec4f2b623f7ca48f38bfda2ac15c01ded35a7
<|skeleton|> class MIMETemplateLoader: """This subclass of TemplateLoader use mimetypes to search and find templates to load.""" def get_type(self, mime): """finds the codename used by relatorio to work on a mimetype""" <|body_0|> def load(self, path, mime=None, relative_to=None, cls=None)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MIMETemplateLoader: """This subclass of TemplateLoader use mimetypes to search and find templates to load.""" def get_type(self, mime): """finds the codename used by relatorio to work on a mimetype""" for func in reversed(self.mime_func): codename = func(mime) if c...
the_stack_v2_python_sparse
lib/python3.8/site-packages/relatorio/reporting.py
Davidoff2103/tryton-training
train
0
2aba6c47bbc6679577596c1fabe9d49eea469484
[ "json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json...
<|body_start_0|> json_dict = json.loads(request.body.decode()) receiver = json_dict.get('receiver') province_id = json_dict.get('province_id') city_id = json_dict.get('city_id') district_id = json_dict.get('district_id') place = json_dict.get('place') mobile = jso...
修改和删除地址
UpdateDestroyAddressView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateDestroyAddressView: """修改和删除地址""" def put(self, request, address_id): """修改地址""" <|body_0|> def delete(self, request, address_id): """删除地址""" <|body_1|> <|end_skeleton|> <|body_start_0|> json_dict = json.loads(request.body.decode()) ...
stack_v2_sparse_classes_75kplus_train_000476
25,046
permissive
[ { "docstring": "修改地址", "name": "put", "signature": "def put(self, request, address_id)" }, { "docstring": "删除地址", "name": "delete", "signature": "def delete(self, request, address_id)" } ]
2
stack_v2_sparse_classes_30k_train_048229
Implement the Python class `UpdateDestroyAddressView` described below. Class description: 修改和删除地址 Method signatures and docstrings: - def put(self, request, address_id): 修改地址 - def delete(self, request, address_id): 删除地址
Implement the Python class `UpdateDestroyAddressView` described below. Class description: 修改和删除地址 Method signatures and docstrings: - def put(self, request, address_id): 修改地址 - def delete(self, request, address_id): 删除地址 <|skeleton|> class UpdateDestroyAddressView: """修改和删除地址""" def put(self, request, addre...
c3e5852016b8fe4bb63dedc5a9e4e5f158d46d20
<|skeleton|> class UpdateDestroyAddressView: """修改和删除地址""" def put(self, request, address_id): """修改地址""" <|body_0|> def delete(self, request, address_id): """删除地址""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UpdateDestroyAddressView: """修改和删除地址""" def put(self, request, address_id): """修改地址""" json_dict = json.loads(request.body.decode()) receiver = json_dict.get('receiver') province_id = json_dict.get('province_id') city_id = json_dict.get('city_id') district_...
the_stack_v2_python_sparse
meiduo_mall/apps/users/views.py
wuhaogithub/wuhao_project_2019_10
train
0
a2367671900f7143df73031b193cf75f010b3ade
[ "try:\n user_details = User.objects.get(username=username)\n user_following_data = get_user_following_data(user_details)\n return Response({'message': get_followers_found_message(username), 'following': user_following_data['following'], 'followers': user_following_data['followers'], 'followingCount': user_...
<|body_start_0|> try: user_details = User.objects.get(username=username) user_following_data = get_user_following_data(user_details) return Response({'message': get_followers_found_message(username), 'following': user_following_data['following'], 'followers': user_following_d...
A view that allows users to follow each other if the user is authenticated and verified.
ProfileFollowUserAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileFollowUserAPIView: """A view that allows users to follow each other if the user is authenticated and verified.""" def get(self, request, username): """View to return a users following i.e followers and those they are following. Params ------- request: Object with request data ...
stack_v2_sparse_classes_75kplus_train_000477
11,549
permissive
[ { "docstring": "View to return a users following i.e followers and those they are following. Params ------- request: Object with request data and functions. username: String providing the user to follow. Returns -------- Response object: { \"message\": \"message body\", \"following\": List, \"followers\": List,...
3
stack_v2_sparse_classes_30k_train_031998
Implement the Python class `ProfileFollowUserAPIView` described below. Class description: A view that allows users to follow each other if the user is authenticated and verified. Method signatures and docstrings: - def get(self, request, username): View to return a users following i.e followers and those they are fol...
Implement the Python class `ProfileFollowUserAPIView` described below. Class description: A view that allows users to follow each other if the user is authenticated and verified. Method signatures and docstrings: - def get(self, request, username): View to return a users following i.e followers and those they are fol...
5a31840856de4b361fe2594dfa7a33d7774d3fe2
<|skeleton|> class ProfileFollowUserAPIView: """A view that allows users to follow each other if the user is authenticated and verified.""" def get(self, request, username): """View to return a users following i.e followers and those they are following. Params ------- request: Object with request data ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileFollowUserAPIView: """A view that allows users to follow each other if the user is authenticated and verified.""" def get(self, request, username): """View to return a users following i.e followers and those they are following. Params ------- request: Object with request data and functions...
the_stack_v2_python_sparse
authors/apps/profiles/views.py
bl4ck4ndbr0wn/ah-centauri-backend
train
0
4224c8405a9967bed6d36b1ffd83b909f7cb0f8f
[ "modules = script.split('.')\nself.scriptname = modules[0]\nself.script = import_module('scripts.' + self.scriptname)\nfor m in modules:\n self.script = getattr(self.script, m)\nself.messages = {}\nfor msg in args:\n if hasattr(self.script, msg):\n self.messages[msg] = msg\n else:\n print(f'm...
<|body_start_0|> modules = script.split('.') self.scriptname = modules[0] self.script = import_module('scripts.' + self.scriptname) for m in modules: self.script = getattr(self.script, m) self.messages = {} for msg in args: if hasattr(self.script, ...
I18n bot.
i18nBot
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" <|body_0|> def print_all(self): """Pretty print the dict as a file content to screen.""" <|body_1|> def read(self, oldmsg, newmsg=None): """Read a single...
stack_v2_sparse_classes_75kplus_train_000478
5,029
permissive
[ { "docstring": "Initializer.", "name": "__init__", "signature": "def __init__(self, script, *args, **kwargs)" }, { "docstring": "Pretty print the dict as a file content to screen.", "name": "print_all", "signature": "def print_all(self)" }, { "docstring": "Read a single message f...
5
stack_v2_sparse_classes_30k_train_040610
Implement the Python class `i18nBot` described below. Class description: I18n bot. Method signatures and docstrings: - def __init__(self, script, *args, **kwargs): Initializer. - def print_all(self): Pretty print the dict as a file content to screen. - def read(self, oldmsg, newmsg=None): Read a single message from s...
Implement the Python class `i18nBot` described below. Class description: I18n bot. Method signatures and docstrings: - def __init__(self, script, *args, **kwargs): Initializer. - def print_all(self): Pretty print the dict as a file content to screen. - def read(self, oldmsg, newmsg=None): Read a single message from s...
5c01e6bfcd328bc6eae643e661f1a0ae57612808
<|skeleton|> class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" <|body_0|> def print_all(self): """Pretty print the dict as a file content to screen.""" <|body_1|> def read(self, oldmsg, newmsg=None): """Read a single...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class i18nBot: """I18n bot.""" def __init__(self, script, *args, **kwargs): """Initializer.""" modules = script.split('.') self.scriptname = modules[0] self.script = import_module('scripts.' + self.scriptname) for m in modules: self.script = getattr(self.scri...
the_stack_v2_python_sparse
scripts/maintenance/make_i18n_dict.py
wikimedia/pywikibot
train
432
6df66ae40131c1cedd570c1a85e6a6e44b6e5d1f
[ "result = []\nfor index in range(0, len(T)):\n location = 0\n for compare_index in range(index + 1, len(T)):\n if T[compare_index] > T[index]:\n location = compare_index - index\n break\n result.append(location)\nreturn result", "T = T[::-1]\nmax_num = T[0]\nresult = [0]\nfor...
<|body_start_0|> result = [] for index in range(0, len(T)): location = 0 for compare_index in range(index + 1, len(T)): if T[compare_index] > T[index]: location = compare_index - index break result.append(locatio...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_3(self, T): """策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:""" <|body_1|> def...
stack_v2_sparse_classes_75kplus_train_000479
2,119
no_license
[ { "docstring": "这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]", "name": "dailyTemperatures_1", "signature": "def dailyTemperatures_1(self, T)" }, { "docstring": "策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:", "name": "dailyTemperatures_3", ...
3
stack_v2_sparse_classes_30k_train_031178
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): 这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int] - def dailyTemperatures_3(self, T): 策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def dailyTemperatures_1(self, T): 这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int] - def dailyTemperatures_3(self, T): 策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向...
163b376acab84e28c74cb784d10fe39f11510921
<|skeleton|> class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" <|body_0|> def dailyTemperatures_3(self, T): """策略2: 还是超时的 从后往前,同时记录最大的元素 如果后面存在比当前大的,则向后找,如果没有就置为0 :param T: :return:""" <|body_1|> def...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def dailyTemperatures_1(self, T): """这种最简单的策略 肯定是会超时的..人家可是个medium题 :type T: List[int] :rtype: List[int]""" result = [] for index in range(0, len(T)): location = 0 for compare_index in range(index + 1, len(T)): if T[compare_index] > T[i...
the_stack_v2_python_sparse
code/739. Daily Temperatures.py
cathyxingchang/leetcode
train
2
28e6b261f0ae51c500fa66d953f5b28d2690ae22
[ "if not event.hasTrace(self.traceid):\n return\nisHandled = False\nfor ev in self.events['success']:\n if isEventMatching(event, ev):\n isHandled = True\n break\nfor ev in self.events['failure']:\n if isEventMatching(event, ev):\n self.runSuccessful = False\n self.logger.warn('A...
<|body_start_0|> if not event.hasTrace(self.traceid): return isHandled = False for ev in self.events['success']: if isEventMatching(event, ev): isHandled = True break for ev in self.events['failure']: if isEventMatching(...
Waiting for the test to complete
Waiting
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Waiting: """Waiting for the test to complete""" def onEvent(self, event): """Process all relevant events""" <|body_0|> def onStalledEvent(self, event): """If the FSM doesn't change state within a given thresshold, it's considered stale and it should be reaped cle...
stack_v2_sparse_classes_75kplus_train_000480
5,530
permissive
[ { "docstring": "Process all relevant events", "name": "onEvent", "signature": "def onEvent(self, event)" }, { "docstring": "If the FSM doesn't change state within a given thresshold, it's considered stale and it should be reaped cleanly. This handler will mark the status as \"Stalled\" and go to...
3
stack_v2_sparse_classes_30k_train_022444
Implement the Python class `Waiting` described below. Class description: Waiting for the test to complete Method signatures and docstrings: - def onEvent(self, event): Process all relevant events - def onStalledEvent(self, event): If the FSM doesn't change state within a given thresshold, it's considered stale and it...
Implement the Python class `Waiting` described below. Class description: Waiting for the test to complete Method signatures and docstrings: - def onEvent(self, event): Process all relevant events - def onStalledEvent(self, event): If the FSM doesn't change state within a given thresshold, it's considered stale and it...
8fba87cb6c6f64690c0b5bef5c7d9f2aa0fba06b
<|skeleton|> class Waiting: """Waiting for the test to complete""" def onEvent(self, event): """Process all relevant events""" <|body_0|> def onStalledEvent(self, event): """If the FSM doesn't change state within a given thresshold, it's considered stale and it should be reaped cle...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Waiting: """Waiting for the test to complete""" def onEvent(self, event): """Process all relevant events""" if not event.hasTrace(self.traceid): return isHandled = False for ev in self.events['success']: if isEventMatching(event, ev): ...
the_stack_v2_python_sparse
performance/driver/classes/policy/chaineddeployment.py
mesosphere/dcos-perf-test-driver
train
2
8e1ede0bd787fc5cb67c6d6a87dfae2633475e69
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('esaracin', 'esaracin')\nurl = 'https://data.cityofboston.gov/api/views/w4k7-yvrq/rows.csv?accessType=DOWNLOAD'\ndataset = pd.read_csv(url)\njson_set = dataset.to_json(orient='records')\nr = json.loads(js...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('esaracin', 'esaracin') url = 'https://data.cityofboston.gov/api/views/w4k7-yvrq/rows.csv?accessType=DOWNLOAD' dataset = pd.read_csv(url) j...
city_of_boston_extraction
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class city_of_boston_extraction: def execute(trial=False): """Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database.""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=...
stack_v2_sparse_classes_75kplus_train_000481
3,389
no_license
[ { "docstring": "Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database.", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Creates the provenance document describing the collection of data...
2
stack_v2_sparse_classes_30k_train_022244
Implement the Python class `city_of_boston_extraction` described below. Class description: Implement the city_of_boston_extraction class. Method signatures and docstrings: - def execute(trial=False): Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within ou...
Implement the Python class `city_of_boston_extraction` described below. Class description: Implement the city_of_boston_extraction class. Method signatures and docstrings: - def execute(trial=False): Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within ou...
97e72731ffadbeae57d7a332decd58706e7c08de
<|skeleton|> class city_of_boston_extraction: def execute(trial=False): """Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database.""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class city_of_boston_extraction: def execute(trial=False): """Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database.""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client...
the_stack_v2_python_sparse
esaracin/city_of_boston_extraction.py
ROODAY/course-2017-fal-proj
train
3
e1ded838c1b823a7788d34aa3523496747e06c4a
[ "super().__init__(**kwargs)\nself._bottom_radius: float = bottom_radius\nself._top_radius: float = top_radius\nself._meridians: int = meridians\nself._height: float = height\nself.build_cylinder()", "step_angle = math.radians(360 / self._meridians)\nu_step = 1.0 / self._meridians\nr_bot = self._bottom_radius\nr_t...
<|body_start_0|> super().__init__(**kwargs) self._bottom_radius: float = bottom_radius self._top_radius: float = top_radius self._meridians: int = meridians self._height: float = height self.build_cylinder() <|end_body_0|> <|body_start_1|> step_angle = math.radia...
Cylinder base class.
Cylinder
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cylinder: """Cylinder base class.""" def __init__(self, bottom_radius: float=0.5, top_radius: float=0.5, meridians: int=12, height: float=1.0, **kwargs: Any) -> None: """Define a Cylinder with given parameters. Keyword arguments: bottom_radius -- Bottom radius top_radius -- Top radiu...
stack_v2_sparse_classes_75kplus_train_000482
2,529
permissive
[ { "docstring": "Define a Cylinder with given parameters. Keyword arguments: bottom_radius -- Bottom radius top_radius -- Top radius meridians -- Vertical steps to draw the cylinder height -- Height of the cylinder", "name": "__init__", "signature": "def __init__(self, bottom_radius: float=0.5, top_radiu...
2
null
Implement the Python class `Cylinder` described below. Class description: Cylinder base class. Method signatures and docstrings: - def __init__(self, bottom_radius: float=0.5, top_radius: float=0.5, meridians: int=12, height: float=1.0, **kwargs: Any) -> None: Define a Cylinder with given parameters. Keyword argument...
Implement the Python class `Cylinder` described below. Class description: Cylinder base class. Method signatures and docstrings: - def __init__(self, bottom_radius: float=0.5, top_radius: float=0.5, meridians: int=12, height: float=1.0, **kwargs: Any) -> None: Define a Cylinder with given parameters. Keyword argument...
906f107050915800209fb884c626a8dff1b06291
<|skeleton|> class Cylinder: """Cylinder base class.""" def __init__(self, bottom_radius: float=0.5, top_radius: float=0.5, meridians: int=12, height: float=1.0, **kwargs: Any) -> None: """Define a Cylinder with given parameters. Keyword arguments: bottom_radius -- Bottom radius top_radius -- Top radiu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Cylinder: """Cylinder base class.""" def __init__(self, bottom_radius: float=0.5, top_radius: float=0.5, meridians: int=12, height: float=1.0, **kwargs: Any) -> None: """Define a Cylinder with given parameters. Keyword arguments: bottom_radius -- Bottom radius top_radius -- Top radius meridians -...
the_stack_v2_python_sparse
payton/scene/geometry/cylinder.py
sinanislekdemir/payton
train
59
ef681149ee9a244e88db1049cc9045ee31b21e66
[ "if not nums:\n return 0\nresult = nums[0]\nfor i in range(len(nums)):\n tmp = 1\n for j in range(i, len(nums)):\n tmp *= nums[j]\n if tmp > result:\n result = tmp\nreturn result", "if not nums:\n return 0\nn = len(nums)\ndpmax, dpmin, res = ([0 for _ in range(n)], [0 for _ in...
<|body_start_0|> if not nums: return 0 result = nums[0] for i in range(len(nums)): tmp = 1 for j in range(i, len(nums)): tmp *= nums[j] if tmp > result: result = tmp return result <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct(self, nums) -> int: """暴力法,时间复杂度为O(N*2),空间复杂度为O(1)""" <|body_0|> def maxProduct_2(self, nums) -> int: """动态规划,时间复杂度为 O(N),空间复杂度为 O(N)""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return 0 ...
stack_v2_sparse_classes_75kplus_train_000483
1,847
no_license
[ { "docstring": "暴力法,时间复杂度为O(N*2),空间复杂度为O(1)", "name": "maxProduct", "signature": "def maxProduct(self, nums) -> int" }, { "docstring": "动态规划,时间复杂度为 O(N),空间复杂度为 O(N)", "name": "maxProduct_2", "signature": "def maxProduct_2(self, nums) -> int" } ]
2
stack_v2_sparse_classes_30k_train_051912
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums) -> int: 暴力法,时间复杂度为O(N*2),空间复杂度为O(1) - def maxProduct_2(self, nums) -> int: 动态规划,时间复杂度为 O(N),空间复杂度为 O(N)
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums) -> int: 暴力法,时间复杂度为O(N*2),空间复杂度为O(1) - def maxProduct_2(self, nums) -> int: 动态规划,时间复杂度为 O(N),空间复杂度为 O(N) <|skeleton|> class Solution: def maxProdu...
13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08
<|skeleton|> class Solution: def maxProduct(self, nums) -> int: """暴力法,时间复杂度为O(N*2),空间复杂度为O(1)""" <|body_0|> def maxProduct_2(self, nums) -> int: """动态规划,时间复杂度为 O(N),空间复杂度为 O(N)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProduct(self, nums) -> int: """暴力法,时间复杂度为O(N*2),空间复杂度为O(1)""" if not nums: return 0 result = nums[0] for i in range(len(nums)): tmp = 1 for j in range(i, len(nums)): tmp *= nums[j] if tmp > res...
the_stack_v2_python_sparse
Algorithms/152_Maximum_Product_Subarray/Maximum_Product_Subarray.py
lirui-ML/my_leetcode
train
1
257624efba8fa3b5931dd0195ad37a78b24757a8
[ "with self.conn:\n with self.conn.cursor() as curs:\n pextra.execute_values(curs, 'INSERT INTO KibotDailyData (trade_symbol_id, date, open, high, low, close, volume) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, %(date)s, %(open)s, %(high)s, %(low)s, %(close)s, ...
<|body_start_0|> with self.conn: with self.conn.cursor() as curs: pextra.execute_values(curs, 'INSERT INTO KibotDailyData (trade_symbol_id, date, open, high, low, close, volume) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, %(date)s, %(open...
Manager of CRUD operations on a database defined in `im/db`.
KibotSqlWriterBackend
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KibotSqlWriterBackend: """Manager of CRUD operations on a database defined in `im/db`.""" def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: """Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3""" <|body_0|> def insert_...
stack_v2_sparse_classes_75kplus_train_000484
5,041
permissive
[ { "docstring": "Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3", "name": "insert_bulk_daily_data", "signature": "def insert_bulk_daily_data(self, df: pd.DataFrame) -> None" }, { "docstring": "Insert daily data for a particular TradeSymbol entry.", ...
5
stack_v2_sparse_classes_30k_train_050253
Implement the Python class `KibotSqlWriterBackend` described below. Class description: Manager of CRUD operations on a database defined in `im/db`. Method signatures and docstrings: - def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a...
Implement the Python class `KibotSqlWriterBackend` described below. Class description: Manager of CRUD operations on a database defined in `im/db`. Method signatures and docstrings: - def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a...
363c59fa29df2ba2719cbad2f8a19ae12cc54a92
<|skeleton|> class KibotSqlWriterBackend: """Manager of CRUD operations on a database defined in `im/db`.""" def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: """Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3""" <|body_0|> def insert_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KibotSqlWriterBackend: """Manager of CRUD operations on a database defined in `im/db`.""" def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: """Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3""" with self.conn: with self.co...
the_stack_v2_python_sparse
im/kibot/kibot_sql_writer_backend.py
srlindemann/amp
train
0
c1ddc9ffccf77597edde76ea1e557e38f2ae1d4b
[ "self.validate_parameters(network_id=network_id)\n_url_path = '/networks/{networkId}/cellularGateway/settings/subnetPool'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'networkId': network_id})\n_query_builder = Configuration.base_uri\n_query_builder += _url_path\n_query_url = APIHelper.cle...
<|body_start_0|> self.validate_parameters(network_id=network_id) _url_path = '/networks/{networkId}/cellularGateway/settings/subnetPool' _url_path = APIHelper.append_url_with_template_parameters(_url_path, {'networkId': network_id}) _query_builder = Configuration.base_uri _query_...
A Controller to access Endpoints in the meraki_sdk API.
MGSubnetPoolSettingsController
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MGSubnetPoolSettingsController: """A Controller to access Endpoints in the meraki_sdk API.""" def get_network_cellular_gateway_settings_subnet_pool(self, network_id): """Does a GET request to /networks/{networkId}/cellularGateway/settings/subnetPool. Return the subnet pool and mask c...
stack_v2_sparse_classes_75kplus_train_000485
4,796
permissive
[ { "docstring": "Does a GET request to /networks/{networkId}/cellularGateway/settings/subnetPool. Return the subnet pool and mask configured for MGs in the network. Args: network_id (string): TODO: type description here. Example: Returns: mixed: Response from the API. Successful operation Raises: APIException: W...
2
stack_v2_sparse_classes_30k_train_019201
Implement the Python class `MGSubnetPoolSettingsController` described below. Class description: A Controller to access Endpoints in the meraki_sdk API. Method signatures and docstrings: - def get_network_cellular_gateway_settings_subnet_pool(self, network_id): Does a GET request to /networks/{networkId}/cellularGatew...
Implement the Python class `MGSubnetPoolSettingsController` described below. Class description: A Controller to access Endpoints in the meraki_sdk API. Method signatures and docstrings: - def get_network_cellular_gateway_settings_subnet_pool(self, network_id): Does a GET request to /networks/{networkId}/cellularGatew...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class MGSubnetPoolSettingsController: """A Controller to access Endpoints in the meraki_sdk API.""" def get_network_cellular_gateway_settings_subnet_pool(self, network_id): """Does a GET request to /networks/{networkId}/cellularGateway/settings/subnetPool. Return the subnet pool and mask c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MGSubnetPoolSettingsController: """A Controller to access Endpoints in the meraki_sdk API.""" def get_network_cellular_gateway_settings_subnet_pool(self, network_id): """Does a GET request to /networks/{networkId}/cellularGateway/settings/subnetPool. Return the subnet pool and mask configured for...
the_stack_v2_python_sparse
meraki_sdk/controllers/mg_subnet_pool_settings_controller.py
RaulCatalano/meraki-python-sdk
train
1
876d1d26635d85f2f94a706ea78757ce80e3824d
[ "if 'even' == 'odd':\n arrayextension = 5\nelse:\n arrayextension = 0\narraylength = 96 + arrayextension\nMaxVal = 255\nMinVal = 0\nself.gentest = bytearray([MaxVal // 2] * arraylength)", "with self.assertRaises(TypeError):\n result = bytesfunc.bmin(1, nosimd=True)\nwith self.assertRaises(TypeError):\n ...
<|body_start_0|> if 'even' == 'odd': arrayextension = 5 else: arrayextension = 0 arraylength = 96 + arrayextension MaxVal = 255 MinVal = 0 self.gentest = bytearray([MaxVal // 2] * arraylength) <|end_body_0|> <|body_start_1|> with self.asse...
Test bmin for basic parameter tests. op_template_params
bmin_parameter_even_arraysize_without_simd_bytearray
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class bmin_parameter_even_arraysize_without_simd_bytearray: """Test bmin for basic parameter tests. op_template_params""" def setUp(self): """Initialise.""" <|body_0|> def test_bmin_param_function_01(self): """Test bmin - Sequence type bytearray. Test invalid parameter...
stack_v2_sparse_classes_75kplus_train_000486
49,998
permissive
[ { "docstring": "Initialise.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test bmin - Sequence type bytearray. Test invalid parameter type even length array without SIMD.", "name": "test_bmin_param_function_01", "signature": "def test_bmin_param_function_01(self)" ...
5
stack_v2_sparse_classes_30k_train_019580
Implement the Python class `bmin_parameter_even_arraysize_without_simd_bytearray` described below. Class description: Test bmin for basic parameter tests. op_template_params Method signatures and docstrings: - def setUp(self): Initialise. - def test_bmin_param_function_01(self): Test bmin - Sequence type bytearray. T...
Implement the Python class `bmin_parameter_even_arraysize_without_simd_bytearray` described below. Class description: Test bmin for basic parameter tests. op_template_params Method signatures and docstrings: - def setUp(self): Initialise. - def test_bmin_param_function_01(self): Test bmin - Sequence type bytearray. T...
28fe0705fc59b0646a4d44e539c919173e8e8b99
<|skeleton|> class bmin_parameter_even_arraysize_without_simd_bytearray: """Test bmin for basic parameter tests. op_template_params""" def setUp(self): """Initialise.""" <|body_0|> def test_bmin_param_function_01(self): """Test bmin - Sequence type bytearray. Test invalid parameter...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class bmin_parameter_even_arraysize_without_simd_bytearray: """Test bmin for basic parameter tests. op_template_params""" def setUp(self): """Initialise.""" if 'even' == 'odd': arrayextension = 5 else: arrayextension = 0 arraylength = 96 + arrayextension ...
the_stack_v2_python_sparse
unittest/test_bmin.py
m1griffin/bytesfunc
train
2
4b5138967c1399153a6017b312fffa391e733bdc
[ "cycletime = '20171122T0000Z'\ndt = 419808.0\nresult = cycletime_to_number(cycletime)\nself.assertIsInstance(result, float)\nself.assertAlmostEqual(result, dt)", "cycletime = '201711220000'\ndt = 419808.0\nresult = cycletime_to_number(cycletime, cycletime_format='%Y%m%d%H%M')\nself.assertAlmostEqual(result, dt)",...
<|body_start_0|> cycletime = '20171122T0000Z' dt = 419808.0 result = cycletime_to_number(cycletime) self.assertIsInstance(result, float) self.assertAlmostEqual(result, dt) <|end_body_0|> <|body_start_1|> cycletime = '201711220000' dt = 419808.0 result = c...
Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value.
Test_cycletime_to_number
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_cycletime_to_number: """Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value.""" def test_basic(self): """Test that a number is returned of the expected value.""" <|body_0|> def test_cycletime_format_defined(self): ...
stack_v2_sparse_classes_75kplus_train_000487
19,622
permissive
[ { "docstring": "Test that a number is returned of the expected value.", "name": "test_basic", "signature": "def test_basic(self)" }, { "docstring": "Test when a cycletime is defined.", "name": "test_cycletime_format_defined", "signature": "def test_cycletime_format_defined(self)" }, ...
4
stack_v2_sparse_classes_30k_train_000623
Implement the Python class `Test_cycletime_to_number` described below. Class description: Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value. Method signatures and docstrings: - def test_basic(self): Test that a number is returned of the expected value. - def test_cycletim...
Implement the Python class `Test_cycletime_to_number` described below. Class description: Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value. Method signatures and docstrings: - def test_basic(self): Test that a number is returned of the expected value. - def test_cycletim...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_cycletime_to_number: """Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value.""" def test_basic(self): """Test that a number is returned of the expected value.""" <|body_0|> def test_cycletime_format_defined(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test_cycletime_to_number: """Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value.""" def test_basic(self): """Test that a number is returned of the expected value.""" cycletime = '20171122T0000Z' dt = 419808.0 result = cycletime_...
the_stack_v2_python_sparse
improver_tests/utilities/temporal/test_temporal.py
metoppv/improver
train
101
a4d8ebce16b692324de7677a8d0d7343a64d5885
[ "self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml'))\ncode, payload = self.open_jrpc('Application.SetVolume', {'volume': 66})\nself.assertEqual(code, 200)\nself.assertPayloadEqual(payload, 75)\nself.assertEqual(self.receiver_moc...
<|body_start_0|> self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml')) code, payload = self.open_jrpc('Application.SetVolume', {'volume': 66}) self.assertEqual(code, 200) self.assertPayloadEqual(payload...
VolumeCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VolumeCase: def test_set_volume(self): """Setting the volume targets the receiver""" <|body_0|> def test_incr_volume(self): """Incrementing the volume targets the receiver""" <|body_1|> def test_get_properties_volume(self): """Getting the volume ...
stack_v2_sparse_classes_75kplus_train_000488
3,037
no_license
[ { "docstring": "Setting the volume targets the receiver", "name": "test_set_volume", "signature": "def test_set_volume(self)" }, { "docstring": "Incrementing the volume targets the receiver", "name": "test_incr_volume", "signature": "def test_incr_volume(self)" }, { "docstring": ...
4
stack_v2_sparse_classes_30k_train_018162
Implement the Python class `VolumeCase` described below. Class description: Implement the VolumeCase class. Method signatures and docstrings: - def test_set_volume(self): Setting the volume targets the receiver - def test_incr_volume(self): Incrementing the volume targets the receiver - def test_get_properties_volume...
Implement the Python class `VolumeCase` described below. Class description: Implement the VolumeCase class. Method signatures and docstrings: - def test_set_volume(self): Setting the volume targets the receiver - def test_incr_volume(self): Incrementing the volume targets the receiver - def test_get_properties_volume...
987a13298f289997d89a8ba25a05691f2e947efb
<|skeleton|> class VolumeCase: def test_set_volume(self): """Setting the volume targets the receiver""" <|body_0|> def test_incr_volume(self): """Incrementing the volume targets the receiver""" <|body_1|> def test_get_properties_volume(self): """Getting the volume ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VolumeCase: def test_set_volume(self): """Setting the volume targets the receiver""" self.receiver_mock.add_mock('volumeset', MockResponse(responses=[(200, VolumeCase.VOLUME_STATUS)], path='/goform/formiPhoneAppVolume.xml')) code, payload = self.open_jrpc('Application.SetVolume', {'vol...
the_stack_v2_python_sparse
kp/regression/volume_cases.py
Schwartzmorn/kodiproxy
train
0
c0efc8cedf5b9fcb7b80c80d531714cc44fb6991
[ "def rserialize(root, string):\n \"\"\" a recursive helper function for the serialize() function.\"\"\"\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return s...
<|body_start_0|> def rserialize(root, string): """ a recursive helper function for the serialize() function.""" if root is None: string += 'None,' else: string += str(root.val) + ',' string = rserialize(root.left, string) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> def rserialize...
stack_v2_sparse_classes_75kplus_train_000489
2,432
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
stack_v2_sparse_classes_30k_train_047709
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
6f8cf45c785b7b3bfe0f379375da26d5324aad25
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" def rserialize(root, string): """ a recursive helper function for the serialize() function.""" if root is None: string += 'None,' else: ...
the_stack_v2_python_sparse
Grokking/SystemDesign/449. Serialize and Deserialize BST.py
yash-bhat/Leetcode
train
3
cefbd0464db5762ad670394baf0502c961302603
[ "self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.gram = Unit.objects.create(name='gram', caffe=self.caffe)\nU...
<|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100') self.gram = Unit.objects.create...
Unit tests.
UnitModelTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnitModelTest: """Unit tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_unit(self): """Check creating units.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', stre...
stack_v2_sparse_classes_75kplus_train_000490
14,711
permissive
[ { "docstring": "Test data setup.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Check creating units.", "name": "test_unit", "signature": "def test_unit(self)" } ]
2
stack_v2_sparse_classes_30k_train_020931
Implement the Python class `UnitModelTest` described below. Class description: Unit tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_unit(self): Check creating units.
Implement the Python class `UnitModelTest` described below. Class description: Unit tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_unit(self): Check creating units. <|skeleton|> class UnitModelTest: """Unit tests.""" def setUp(self): """Test data setup.""" ...
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class UnitModelTest: """Unit tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_unit(self): """Check creating units.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UnitModelTest: """Unit tests.""" def setUp(self): """Test data setup.""" self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', h...
the_stack_v2_python_sparse
caffe/reports/test_models.py
VirrageS/io-kawiarnie
train
3
9028c3217ed381dda9cc56cc3c77dd2a85c8b02c
[ "self.ip_register = Registry.test_register(ip_register)\nServer.__init__(self, service, auto_register=True, protocol_config=PROTOCOL_CONFIG, registrar=UDPRegistryClient(ip=self.ip_register, port=REGISTRY_PORT))\nself.workers = 0\nself.max_threads = max_threads\nself.lock = threading.Lock()", "t = threading.Thread...
<|body_start_0|> self.ip_register = Registry.test_register(ip_register) Server.__init__(self, service, auto_register=True, protocol_config=PROTOCOL_CONFIG, registrar=UDPRegistryClient(ip=self.ip_register, port=REGISTRY_PORT)) self.workers = 0 self.max_threads = max_threads self.l...
ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation
ServiceServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceServer: """ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation""" def __init__(self, service, max_threads, ip_register): """Class initialization :param service: Service to serv...
stack_v2_sparse_classes_75kplus_train_000491
3,859
no_license
[ { "docstring": "Class initialization :param service: Service to serve on client connection :param max_threads: Integer for the maximum number of thread that the server can run in parallel", "name": "__init__", "signature": "def __init__(self, service, max_threads, ip_register)" }, { "docstring":...
5
stack_v2_sparse_classes_30k_train_029493
Implement the Python class `ServiceServer` described below. Class description: ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation Method signatures and docstrings: - def __init__(self, service, max_threads, ip_regist...
Implement the Python class `ServiceServer` described below. Class description: ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation Method signatures and docstrings: - def __init__(self, service, max_threads, ip_regist...
f4f212a7533a63d1148068bacf1cc13d3f64db49
<|skeleton|> class ServiceServer: """ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation""" def __init__(self, service, max_threads, ip_register): """Class initialization :param service: Service to serv...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServiceServer: """ServiceServer class is a rpyc server implementation to control the number of threads the server will run in parallel and to get errors during simulation""" def __init__(self, service, max_threads, ip_register): """Class initialization :param service: Service to serve on client c...
the_stack_v2_python_sparse
src/simulations/servers/serviceServer.py
mahedjaved/mouse_locomotion
train
0
801fce734921d722886c3a3cf8d4b83d96a29aa1
[ "self.input_models = []\nself.output_name = None\nwith datamodels.open(input) as input_models:\n if isinstance(input_models, datamodels.IFUImageModel):\n filename = input_models.meta.filename\n self.input_models.append(input_models)\n self.output_name = self.build_product_name(filename)\n ...
<|body_start_0|> self.input_models = [] self.output_name = None with datamodels.open(input) as input_models: if isinstance(input_models, datamodels.IFUImageModel): filename = input_models.meta.filename self.input_models.append(input_models) ...
Class to handle reading input data to cube_build.
DataTypes
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataTypes: """Class to handle reading input data to cube_build.""" def __init__(self, input, single, output_file, output_dir): """Read in input data and determine what type of input data. Open the input data using datamodels and determine if data is a single input model, an associati...
stack_v2_sparse_classes_75kplus_train_000492
4,838
permissive
[ { "docstring": "Read in input data and determine what type of input data. Open the input data using datamodels and determine if data is a single input model, an association, or a set of input models contained in a ModelContainer. Parameters ---------- input : datamodel or ModelContainer Input data to cube_build...
2
stack_v2_sparse_classes_30k_train_014653
Implement the Python class `DataTypes` described below. Class description: Class to handle reading input data to cube_build. Method signatures and docstrings: - def __init__(self, input, single, output_file, output_dir): Read in input data and determine what type of input data. Open the input data using datamodels an...
Implement the Python class `DataTypes` described below. Class description: Class to handle reading input data to cube_build. Method signatures and docstrings: - def __init__(self, input, single, output_file, output_dir): Read in input data and determine what type of input data. Open the input data using datamodels an...
a4a0e8ad2b88249f01445ee1dcf175229c51033f
<|skeleton|> class DataTypes: """Class to handle reading input data to cube_build.""" def __init__(self, input, single, output_file, output_dir): """Read in input data and determine what type of input data. Open the input data using datamodels and determine if data is a single input model, an associati...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DataTypes: """Class to handle reading input data to cube_build.""" def __init__(self, input, single, output_file, output_dir): """Read in input data and determine what type of input data. Open the input data using datamodels and determine if data is a single input model, an association, or a set ...
the_stack_v2_python_sparse
jwst/cube_build/data_types.py
spacetelescope/jwst
train
449
df94bd2dae0d74c9245f3edd8ee9e9820dc07ef6
[ "self.user = user\nself.first_name = first_name\nself.last_name = last_name\nself.facebook = facebook\nself.google = google\nself.github = github\nCreator.__init__(self)", "names = str(full_name).split(' ')\nself.last_name = ''\nself.first_name = names.pop(0)\nif len(names) > 0:\n self.last_name = ' '.join(nam...
<|body_start_0|> self.user = user self.first_name = first_name self.last_name = last_name self.facebook = facebook self.google = google self.github = github Creator.__init__(self) <|end_body_0|> <|body_start_1|> names = str(full_name).split(' ') s...
UserProfileCreator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserProfileCreator: def __init__(self, user, first_name='', last_name='', facebook='', google='', github=''): """The User Object must be passed into UserProfileCreator on init, the rest of the arguments are optional and could also be set after __init__ if needed. All the additional param...
stack_v2_sparse_classes_75kplus_train_000493
12,165
no_license
[ { "docstring": "The User Object must be passed into UserProfileCreator on init, the rest of the arguments are optional and could also be set after __init__ if needed. All the additional params are scalar column values belonging on the UserProfile table. :param user: :param first_name: :param last_name: :param f...
3
stack_v2_sparse_classes_30k_val_000655
Implement the Python class `UserProfileCreator` described below. Class description: Implement the UserProfileCreator class. Method signatures and docstrings: - def __init__(self, user, first_name='', last_name='', facebook='', google='', github=''): The User Object must be passed into UserProfileCreator on init, the ...
Implement the Python class `UserProfileCreator` described below. Class description: Implement the UserProfileCreator class. Method signatures and docstrings: - def __init__(self, user, first_name='', last_name='', facebook='', google='', github=''): The User Object must be passed into UserProfileCreator on init, the ...
e5401680f13299ece8d78f51e45c90773015cde4
<|skeleton|> class UserProfileCreator: def __init__(self, user, first_name='', last_name='', facebook='', google='', github=''): """The User Object must be passed into UserProfileCreator on init, the rest of the arguments are optional and could also be set after __init__ if needed. All the additional param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserProfileCreator: def __init__(self, user, first_name='', last_name='', facebook='', google='', github=''): """The User Object must be passed into UserProfileCreator on init, the rest of the arguments are optional and could also be set after __init__ if needed. All the additional params are scalar c...
the_stack_v2_python_sparse
doc_docs/public/creator/creator.py
mrosata/doc-docs
train
0
8ce6b80ced815d3432502abb90702bd4969f0454
[ "super(CtrTrainerCallback, self).__init__()\nself.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])\nself.selected_pairs = list()\nlogging.info('init autogate s2 trainer callback')", "super().before_train(logs)\n'Be called before the training process.'\nhpo_result = FileOps.load_pickle(FileO...
<|body_start_0|> super(CtrTrainerCallback, self).__init__() self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score']) self.selected_pairs = list() logging.info('init autogate s2 trainer callback') <|end_body_0|> <|body_start_1|> super().before_train(logs) ...
AutoGateGrdaS2TrainerCallback module.
AutoGateGrdaS2TrainerCallback
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AutoGateGrdaS2TrainerCallback: """AutoGateGrdaS2TrainerCallback module.""" def __init__(self): """Construct AutoGateGrdaS2TrainerCallback class.""" <|body_0|> def before_train(self, logs=None): """Call before_train of the managed callbacks.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus_train_000494
2,468
permissive
[ { "docstring": "Construct AutoGateGrdaS2TrainerCallback class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Call before_train of the managed callbacks.", "name": "before_train", "signature": "def before_train(self, logs=None)" }, { "docstring": "Call...
3
stack_v2_sparse_classes_30k_train_007039
Implement the Python class `AutoGateGrdaS2TrainerCallback` described below. Class description: AutoGateGrdaS2TrainerCallback module. Method signatures and docstrings: - def __init__(self): Construct AutoGateGrdaS2TrainerCallback class. - def before_train(self, logs=None): Call before_train of the managed callbacks. -...
Implement the Python class `AutoGateGrdaS2TrainerCallback` described below. Class description: AutoGateGrdaS2TrainerCallback module. Method signatures and docstrings: - def __init__(self): Construct AutoGateGrdaS2TrainerCallback class. - def before_train(self, logs=None): Call before_train of the managed callbacks. -...
df51ed9c1d6dbde1deef63f2a037a369f8554406
<|skeleton|> class AutoGateGrdaS2TrainerCallback: """AutoGateGrdaS2TrainerCallback module.""" def __init__(self): """Construct AutoGateGrdaS2TrainerCallback class.""" <|body_0|> def before_train(self, logs=None): """Call before_train of the managed callbacks.""" <|body_1|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AutoGateGrdaS2TrainerCallback: """AutoGateGrdaS2TrainerCallback module.""" def __init__(self): """Construct AutoGateGrdaS2TrainerCallback class.""" super(CtrTrainerCallback, self).__init__() self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score']) self....
the_stack_v2_python_sparse
built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/algorithms/nas/fis/autogate_grda_s2_trainer_callback.py
Huawei-Ascend/modelzoo
train
1
f0e875b78e55094c4570eb8996c784fc7a431c24
[ "if not isinstance(key, str):\n raise ValueError('Expected str type for key, but got: %s' % type(key))\nif len(key) not in AesCbc.VALID_AES_KEY_LENGTHS:\n raise ValueError('Incorrect sized AES key: %d' % len(key))\nself.__key = key", "if not isinstance(plaintext, str):\n raise ValueError('Expected str ty...
<|body_start_0|> if not isinstance(key, str): raise ValueError('Expected str type for key, but got: %s' % type(key)) if len(key) not in AesCbc.VALID_AES_KEY_LENGTHS: raise ValueError('Incorrect sized AES key: %d' % len(key)) self.__key = key <|end_body_0|> <|body_start_1...
Class for AES encryption using CBC/PKCS5Padding.
AesCbc
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AesCbc: """Class for AES encryption using CBC/PKCS5Padding.""" def __init__(self, key): """AesCbc is initialized with key of valid length.""" <|body_0|> def Encrypt(self, plaintext, iv=None): """Encrypts with AES/CBC/PKCS5PADDING mode. Aes encrypts plaintext usin...
stack_v2_sparse_classes_75kplus_train_000495
8,635
permissive
[ { "docstring": "AesCbc is initialized with key of valid length.", "name": "__init__", "signature": "def __init__(self, key)" }, { "docstring": "Encrypts with AES/CBC/PKCS5PADDING mode. Aes encrypts plaintext using cbc mode with pkcs5 padding. If no iv is provided then uses a random iv. Args: pla...
3
null
Implement the Python class `AesCbc` described below. Class description: Class for AES encryption using CBC/PKCS5Padding. Method signatures and docstrings: - def __init__(self, key): AesCbc is initialized with key of valid length. - def Encrypt(self, plaintext, iv=None): Encrypts with AES/CBC/PKCS5PADDING mode. Aes en...
Implement the Python class `AesCbc` described below. Class description: Class for AES encryption using CBC/PKCS5Padding. Method signatures and docstrings: - def __init__(self, key): AesCbc is initialized with key of valid length. - def Encrypt(self, plaintext, iv=None): Encrypts with AES/CBC/PKCS5PADDING mode. Aes en...
ff5ec7cd27d4c305cd039639d058a3be47c12604
<|skeleton|> class AesCbc: """Class for AES encryption using CBC/PKCS5Padding.""" def __init__(self, key): """AesCbc is initialized with key of valid length.""" <|body_0|> def Encrypt(self, plaintext, iv=None): """Encrypts with AES/CBC/PKCS5PADDING mode. Aes encrypts plaintext usin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AesCbc: """Class for AES encryption using CBC/PKCS5Padding.""" def __init__(self, key): """AesCbc is initialized with key of valid length.""" if not isinstance(key, str): raise ValueError('Expected str type for key, but got: %s' % type(key)) if len(key) not in AesCbc.V...
the_stack_v2_python_sparse
src/common_crypto.py
DanielBecker-IE/encrypted-bigquery-client
train
0
65e8fdfcd30fd0455abf6591d17eca87d99d8aa9
[ "y = column_or_1d(y, warn=True)\nself.classes_ = _encode(y)\nreturn self", "y = column_or_1d(y, warn=True)\nself.classes_, y = _encode(y, encode=True)\nreturn y.reshape(-1, 1)", "check_is_fitted(self, 'classes_')\ny = column_or_1d(y, warn=True)\nif _num_samples(y) == 0:\n return np.array([])\nself.classes_ =...
<|body_start_0|> y = column_or_1d(y, warn=True) self.classes_ = _encode(y) return self <|end_body_0|> <|body_start_1|> y = column_or_1d(y, warn=True) self.classes_, y = _encode(y, encode=True) return y.reshape(-1, 1) <|end_body_1|> <|body_start_2|> check_is_fitt...
multilabe encoder based on the labelEncoder
MutiLabelEncoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MutiLabelEncoder: """multilabe encoder based on the labelEncoder""" def fit(self, y, *args, **kwargs): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.""" <|body_0|> def fit...
stack_v2_sparse_classes_75kplus_train_000496
14,588
no_license
[ { "docstring": "Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.", "name": "fit", "signature": "def fit(self, y, *args, **kwargs)" }, { "docstring": "Fit label encoder and return encoded labels Paramet...
4
stack_v2_sparse_classes_30k_train_016214
Implement the Python class `MutiLabelEncoder` described below. Class description: multilabe encoder based on the labelEncoder Method signatures and docstrings: - def fit(self, y, *args, **kwargs): Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : return...
Implement the Python class `MutiLabelEncoder` described below. Class description: multilabe encoder based on the labelEncoder Method signatures and docstrings: - def fit(self, y, *args, **kwargs): Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : return...
351a63e8b81fc0378806587847bea24f7b5b8d2e
<|skeleton|> class MutiLabelEncoder: """multilabe encoder based on the labelEncoder""" def fit(self, y, *args, **kwargs): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.""" <|body_0|> def fit...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MutiLabelEncoder: """multilabe encoder based on the labelEncoder""" def fit(self, y, *args, **kwargs): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self.""" y = column_or_1d(y, warn=True) ...
the_stack_v2_python_sparse
Tools.py
jalynnliu/ExperiencedOptimizationExperiments
train
0
ce6b961d6c42626d94b5cd3565c8952d03d7d0b8
[ "self.input = input\nself.job = job\nself.qml = qml", "if self.job.status() == JobStatus.DONE:\n log.info('Circuits Executed!')\n return self.qml._read_result(len(self.input), self.job.result())\nelse:\n log.error('Circuits not executed!')\n log.error(self.job.status)\n return None" ]
<|body_start_0|> self.input = input self.job = job self.qml = qml <|end_body_0|> <|body_start_1|> if self.job.status() == JobStatus.DONE: log.info('Circuits Executed!') return self.qml._read_result(len(self.input), self.job.result()) else: log...
Wrapper for a qiskit BaseJob and classification experiments
AsyncPredictJob
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsyncPredictJob: """Wrapper for a qiskit BaseJob and classification experiments""" def __init__(self, input, job, qml): """Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob running the experiment :param qml: the classifier""" ...
stack_v2_sparse_classes_75kplus_train_000497
16,367
permissive
[ { "docstring": "Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob running the experiment :param qml: the classifier", "name": "__init__", "signature": "def __init__(self, input, job, qml)" }, { "docstring": "Returns the prediction result if it ...
2
stack_v2_sparse_classes_30k_train_012507
Implement the Python class `AsyncPredictJob` described below. Class description: Wrapper for a qiskit BaseJob and classification experiments Method signatures and docstrings: - def __init__(self, input, job, qml): Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob ru...
Implement the Python class `AsyncPredictJob` described below. Class description: Wrapper for a qiskit BaseJob and classification experiments Method signatures and docstrings: - def __init__(self, input, job, qml): Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob ru...
ffc7bc7bcdadb9beef3271f1620f963b4e8fe1bf
<|skeleton|> class AsyncPredictJob: """Wrapper for a qiskit BaseJob and classification experiments""" def __init__(self, input, job, qml): """Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob running the experiment :param qml: the classifier""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AsyncPredictJob: """Wrapper for a qiskit BaseJob and classification experiments""" def __init__(self, input, job, qml): """Constructs a new Wrapper :param input: the unclassified input data set :param job: the qiskit BaseJob running the experiment :param qml: the classifier""" self.input ...
the_stack_v2_python_sparse
dc_qiskit_qml/distance_based/hadamard/_QmlHadamardNeighborClassifier.py
adjs/dc-qiskit-qml
train
0
ba29354f901649b302fb0598e8691e815e691120
[ "if self.tool in RelengTool.detected:\n return RelengTool.detected[self.tool]\nfound = True\ntool = self.tool\nif execute([tool] + self.exists_args, quiet=True, critical=False):\n found = True\nelif sys.platform == 'win32' and os.path.basename(tool) == tool:\n debug('{} tool not available in path; attempti...
<|body_start_0|> if self.tool in RelengTool.detected: return RelengTool.detected[self.tool] found = True tool = self.tool if execute([tool] + self.exists_args, quiet=True, critical=False): found = True elif sys.platform == 'win32' and os.path.basename(tool...
python host tool Provides addition helper methods for Python-based tool interaction.
PythonTool
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PythonTool: """python host tool Provides addition helper methods for Python-based tool interaction.""" def exists(self): """return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` ot...
stack_v2_sparse_classes_75kplus_train_000498
3,764
permissive
[ { "docstring": "return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` otherwise", "name": "exists", "signature": "def exists(self)" }, { "docstring": "return a python path value for the python...
2
stack_v2_sparse_classes_30k_train_011052
Implement the Python class `PythonTool` described below. Class description: python host tool Provides addition helper methods for Python-based tool interaction. Method signatures and docstrings: - def exists(self): return whether or not the host tool exists Returns whether or not the tool is available on the host for...
Implement the Python class `PythonTool` described below. Class description: python host tool Provides addition helper methods for Python-based tool interaction. Method signatures and docstrings: - def exists(self): return whether or not the host tool exists Returns whether or not the tool is available on the host for...
d05eb2153c72e9bd82c5fdddd5eb41d5316592d6
<|skeleton|> class PythonTool: """python host tool Provides addition helper methods for Python-based tool interaction.""" def exists(self): """return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` ot...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PythonTool: """python host tool Provides addition helper methods for Python-based tool interaction.""" def exists(self): """return whether or not the host tool exists Returns whether or not the tool is available on the host for use. Returns: ``True``, if the tool exists; ``False`` otherwise""" ...
the_stack_v2_python_sparse
releng_tool/tool/python.py
releng-tool/releng-tool
train
12
0b38fc823705b556a046415e0fb6f39acbb7c77a
[ "abort_ride_not_found(rideID)\nabort_not_ride_owner(rideID, current_user.id)\nreqs = get_ride_requests(rideID)\nreturn (reqs, HTTPStatus.OK)", "abort_ride_not_found(rideID)\nabort_ride_owner(rideID, current_user.id)\nabort_already_made_request(rideID, current_user.id)\nreqs_args = r_request_parser.parse_args()\ns...
<|body_start_0|> abort_ride_not_found(rideID) abort_not_ride_owner(rideID, current_user.id) reqs = get_ride_requests(rideID) return (reqs, HTTPStatus.OK) <|end_body_0|> <|body_start_1|> abort_ride_not_found(rideID) abort_ride_owner(rideID, current_user.id) abort_...
Handle making and fetching requests
AllRequestsResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllRequestsResource: """Handle making and fetching requests""" def get(self, rideID): """Fetch all request on a ride""" <|body_0|> def post(self, rideID): """Make a request to join a ride""" <|body_1|> <|end_skeleton|> <|body_start_0|> abort_rid...
stack_v2_sparse_classes_75kplus_train_000499
5,861
permissive
[ { "docstring": "Fetch all request on a ride", "name": "get", "signature": "def get(self, rideID)" }, { "docstring": "Make a request to join a ride", "name": "post", "signature": "def post(self, rideID)" } ]
2
null
Implement the Python class `AllRequestsResource` described below. Class description: Handle making and fetching requests Method signatures and docstrings: - def get(self, rideID): Fetch all request on a ride - def post(self, rideID): Make a request to join a ride
Implement the Python class `AllRequestsResource` described below. Class description: Handle making and fetching requests Method signatures and docstrings: - def get(self, rideID): Fetch all request on a ride - def post(self, rideID): Make a request to join a ride <|skeleton|> class AllRequestsResource: """Handle...
4831094d973fc1abcd3d83e697a84fe5336e8827
<|skeleton|> class AllRequestsResource: """Handle making and fetching requests""" def get(self, rideID): """Fetch all request on a ride""" <|body_0|> def post(self, rideID): """Make a request to join a ride""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AllRequestsResource: """Handle making and fetching requests""" def get(self, rideID): """Fetch all request on a ride""" abort_ride_not_found(rideID) abort_not_ride_owner(rideID, current_user.id) reqs = get_ride_requests(rideID) return (reqs, HTTPStatus.OK) def...
the_stack_v2_python_sparse
app/api_BP/ns_requests.py
Xerrex/rmw-API
train
0