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
971732a3eb9197bc8edc5506f5308d2615bd7cea
[ "max_count = 0\ninvalid_index = -1\nstack = []\nfor i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n elif stack:\n stack.pop()\n start_index = stack[-1] if stack else invalid_index\n max_count = max(max_count, i - start_index)\n else:\n invalid_index = i\nreturn ...
<|body_start_0|> max_count = 0 invalid_index = -1 stack = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif stack: stack.pop() start_index = stack[-1] if stack else invalid_index max_cou...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParentheses_failed(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> max_count = 0 invalid_index = ...
stack_v2_sparse_classes_75kplus_train_065000
2,271
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "longestValidParentheses", "signature": "def longestValidParentheses(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "longestValidParentheses_failed", "signature": "def longestValidParentheses_failed(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_009584
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): :type s: str :rtype: int - def longestValidParentheses_failed(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): :type s: str :rtype: int - def longestValidParentheses_failed(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def long...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParentheses_failed(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" max_count = 0 invalid_index = -1 stack = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif stack: stack.pop() ...
the_stack_v2_python_sparse
src/lt_32.py
oxhead/CodingYourWay
train
0
849ee7756b4a2a7a10b4f607728664cad457cc32
[ "try:\n return get_app_name(i)\nexcept CatalogError as e:\n raise EntityNameError('Unable to find name for app id: {}'.format(i))", "try:\n return get_app_names(ids)\nexcept CatalogError as e:\n raise EntityNameError('Unable to find app names: {}'.format(str(e)))", "try:\n return get_app_name(i) ...
<|body_start_0|> try: return get_app_name(i) except CatalogError as e: raise EntityNameError('Unable to find name for app id: {}'.format(i)) <|end_body_0|> <|body_start_1|> try: return get_app_names(ids) except CatalogError as e: raise Ent...
AppType
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppType: def get_name_from_id(i: str, token: str) -> str: """Should return the name as a str. If a fail happens, raise an EntityNameError""" <|body_0|> def get_names_from_ids(ids: List[str], token: str) -> Dict[str, str]: """Should return a dict with keys -> values =...
stack_v2_sparse_classes_75kplus_train_065001
1,266
permissive
[ { "docstring": "Should return the name as a str. If a fail happens, raise an EntityNameError", "name": "get_name_from_id", "signature": "def get_name_from_id(i: str, token: str) -> str" }, { "docstring": "Should return a dict with keys -> values = ids -> names. If any of them fail, set id -> Non...
3
stack_v2_sparse_classes_30k_train_028334
Implement the Python class `AppType` described below. Class description: Implement the AppType class. Method signatures and docstrings: - def get_name_from_id(i: str, token: str) -> str: Should return the name as a str. If a fail happens, raise an EntityNameError - def get_names_from_ids(ids: List[str], token: str) -...
Implement the Python class `AppType` described below. Class description: Implement the AppType class. Method signatures and docstrings: - def get_name_from_id(i: str, token: str) -> str: Should return the name as a str. If a fail happens, raise an EntityNameError - def get_names_from_ids(ids: List[str], token: str) -...
a2ed4cb88120aeb10a295919cb0fba85e13d462d
<|skeleton|> class AppType: def get_name_from_id(i: str, token: str) -> str: """Should return the name as a str. If a fail happens, raise an EntityNameError""" <|body_0|> def get_names_from_ids(ids: List[str], token: str) -> Dict[str, str]: """Should return a dict with keys -> values =...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AppType: def get_name_from_id(i: str, token: str) -> str: """Should return the name as a str. If a fail happens, raise an EntityNameError""" try: return get_app_name(i) except CatalogError as e: raise EntityNameError('Unable to find name for app id: {}'.format(i...
the_stack_v2_python_sparse
feeds/entity/types/app.py
kbase/feeds
train
0
ebd1beec3027159b644104cbb2efc334f13b0c69
[ "self.person = person\nperson.manager = self\nself.career = ManagerCareer(manager=self)\nself.team = team\nself.strategy = Strategy(owner=self)", "positions = ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF')\npositions_already_covered = {p.position for p in self.team.players}\ntry:\n return next((p for p i...
<|body_start_0|> self.person = person person.manager = self self.career = ManagerCareer(manager=self) self.team = team self.strategy = Strategy(owner=self) <|end_body_0|> <|body_start_1|> positions = ('P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF') positions_...
The baseball-manager layer of a person's being.
Manager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Manager: """The baseball-manager layer of a person's being.""" def __init__(self, person, team): """Initialize a Manager object.""" <|body_0|> def decide_position_of_greatest_need(self): """Return the team's position of greatest need in the opinion of this manage...
stack_v2_sparse_classes_75kplus_train_065002
1,124
no_license
[ { "docstring": "Initialize a Manager object.", "name": "__init__", "signature": "def __init__(self, person, team)" }, { "docstring": "Return the team's position of greatest need in the opinion of this manager, given their strategy and other concerns.", "name": "decide_position_of_greatest_ne...
2
stack_v2_sparse_classes_30k_train_008073
Implement the Python class `Manager` described below. Class description: The baseball-manager layer of a person's being. Method signatures and docstrings: - def __init__(self, person, team): Initialize a Manager object. - def decide_position_of_greatest_need(self): Return the team's position of greatest need in the o...
Implement the Python class `Manager` described below. Class description: The baseball-manager layer of a person's being. Method signatures and docstrings: - def __init__(self, person, team): Initialize a Manager object. - def decide_position_of_greatest_need(self): Return the team's position of greatest need in the o...
78a9df3ff66d4956f817397c82be0b4e4176e73d
<|skeleton|> class Manager: """The baseball-manager layer of a person's being.""" def __init__(self, person, team): """Initialize a Manager object.""" <|body_0|> def decide_position_of_greatest_need(self): """Return the team's position of greatest need in the opinion of this manage...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Manager: """The baseball-manager layer of a person's being.""" def __init__(self, person, team): """Initialize a Manager object.""" self.person = person person.manager = self self.career = ManagerCareer(manager=self) self.team = team self.strategy = Strateg...
the_stack_v2_python_sparse
baseball/manager.py
hanok2/national_pastime
train
1
a79b236c599dd279e73918862a4bc6bd08b56819
[ "super().__init__(arg)\nself.headers = headers\nself.path = path\nself.path_params = path_params\nself.query_params = query_params\nself.accepted: bool = False\n'Whether the message was ever accepted by the server'\nself.close: Optional[Tuple[Sender, int]] = None\n'The sender who closed the connection, along with t...
<|body_start_0|> super().__init__(arg) self.headers = headers self.path = path self.path_params = path_params self.query_params = query_params self.accepted: bool = False 'Whether the message was ever accepted by the server' self.close: Optional[Tuple[Send...
A transcript of a single websocket connection
RecordedWSTranscript
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecordedWSTranscript: """A transcript of a single websocket connection""" def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]): """Args: arg: forwarded to super (List) heade...
stack_v2_sparse_classes_75kplus_train_065003
20,254
permissive
[ { "docstring": "Args: arg: forwarded to super (List) headers: the headers of the connection path: the path of the connection request path_params: the path params of the connection request, as specified by the route's starlette rule string query_params: the query params of the connection request", "name": "_...
2
stack_v2_sparse_classes_30k_train_040446
Implement the Python class `RecordedWSTranscript` described below. Class description: A transcript of a single websocket connection Method signatures and docstrings: - def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str...
Implement the Python class `RecordedWSTranscript` described below. Class description: A transcript of a single websocket connection Method signatures and docstrings: - def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str...
1914e42f33f8758d25cc985d672aaa3855ee9261
<|skeleton|> class RecordedWSTranscript: """A transcript of a single websocket connection""" def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]): """Args: arg: forwarded to super (List) heade...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RecordedWSTranscript: """A transcript of a single websocket connection""" def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]): """Args: arg: forwarded to super (List) headers: the heade...
the_stack_v2_python_sparse
yellowbox/extras/webserver/ws_request_capture.py
nx6110a5100/yellowbox
train
0
3dc151b6b2f3e52e809cc8fbecb3d9c507e61fd5
[ "assert trainable in ('lpips', 'net', 'both', False)\nif trainable and back_prop != True:\n raise Exception('Enable back_prop for training.')\nconfig.validate()\nself.config = config\nif config.metric in ('vgg', 'squeeze', 'vgg_ensemble', 'squeeze_ensemble_maxpool'):\n self.network = pnetlin.PNetLin(pnet_type...
<|body_start_0|> assert trainable in ('lpips', 'net', 'both', False) if trainable and back_prop != True: raise Exception('Enable back_prop for training.') config.validate() self.config = config if config.metric in ('vgg', 'squeeze', 'vgg_ensemble', 'squeeze_ensemble_m...
Metric
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Metric: def __init__(self, config, back_prop=True, trainable=False, use_lpips_dropout=False, custom_lpips_weights=None, custom_net_weights=None, custom_sample_ensemble=None): """Perceptual image distance metric. PARAMS: config: Metric configuration. One of: elpips.elpips_vgg(), elpips.el...
stack_v2_sparse_classes_75kplus_train_065004
11,615
permissive
[ { "docstring": "Perceptual image distance metric. PARAMS: config: Metric configuration. One of: elpips.elpips_vgg(), elpips.elpips_squeeze_maxpool(), elpips.lpips_vgg(), elpips.lpips_squeeze(). back_prop: Whether to store data for back_prop. trainable: Whether to make weights trainable. Options: 'lpips', 'net',...
2
stack_v2_sparse_classes_30k_train_043133
Implement the Python class `Metric` described below. Class description: Implement the Metric class. Method signatures and docstrings: - def __init__(self, config, back_prop=True, trainable=False, use_lpips_dropout=False, custom_lpips_weights=None, custom_net_weights=None, custom_sample_ensemble=None): Perceptual imag...
Implement the Python class `Metric` described below. Class description: Implement the Metric class. Method signatures and docstrings: - def __init__(self, config, back_prop=True, trainable=False, use_lpips_dropout=False, custom_lpips_weights=None, custom_net_weights=None, custom_sample_ensemble=None): Perceptual imag...
5f14208f00fdd69e99e8b055ffe5fd3c11a6e2b6
<|skeleton|> class Metric: def __init__(self, config, back_prop=True, trainable=False, use_lpips_dropout=False, custom_lpips_weights=None, custom_net_weights=None, custom_sample_ensemble=None): """Perceptual image distance metric. PARAMS: config: Metric configuration. One of: elpips.elpips_vgg(), elpips.el...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Metric: def __init__(self, config, back_prop=True, trainable=False, use_lpips_dropout=False, custom_lpips_weights=None, custom_net_weights=None, custom_sample_ensemble=None): """Perceptual image distance metric. PARAMS: config: Metric configuration. One of: elpips.elpips_vgg(), elpips.elpips_squeeze_m...
the_stack_v2_python_sparse
SeaAsiaDX11/SeaAisa/SeaAisa/ngpt/reconstruct/elpips/elpips.py
ChengGongXTU/SeaAsia
train
8
f8e5679c49ff1f700cc97bc9e6ca4d2d23d27725
[ "n, m = (len(matrix), len(matrix[0]))\nfor i in range(n):\n for j in range(m):\n if i == j or i > j:\n continue\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nfor i in range(n):\n for j in range(m // 2):\n matrix[i][j], matrix[i][m - j - 1] = (matrix[i][m - j - 1]...
<|body_start_0|> n, m = (len(matrix), len(matrix[0])) for i in range(n): for j in range(m): if i == j or i > j: continue matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j]) for i in range(n): for j in range(m // 2)...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate_intuition(self, matrix: List[List[int]]) -> None: """Do not return anything, modify matrix in-place instead....
stack_v2_sparse_classes_75kplus_train_065005
1,068
no_license
[ { "docstring": "Do not return anything, modify matrix in-place instead.", "name": "rotate_traverse_flip", "signature": "def rotate_traverse_flip(self, matrix: List[List[int]]) -> None" }, { "docstring": "Do not return anything, modify matrix in-place instead.", "name": "rotate_intuition", ...
2
stack_v2_sparse_classes_30k_val_001551
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. - def rotate_intuition(self, matrix: List[List[int]]) -> ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. - def rotate_intuition(self, matrix: List[List[int]]) -> ...
5ed070f22f4bc29777ee5cbb01bb9583726d8799
<|skeleton|> class Solution: def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate_intuition(self, matrix: List[List[int]]) -> None: """Do not return anything, modify matrix in-place instead....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: """Do not return anything, modify matrix in-place instead.""" n, m = (len(matrix), len(matrix[0])) for i in range(n): for j in range(m): if i == j or i > j: contin...
the_stack_v2_python_sparse
48_rotate_image.py
zdadadaz/coding_practice
train
0
59fc9fc694531d6db268d0c6ab66198e306b1a0e
[ "game = small.BiasedGame(seed)\nrandom = np.random.RandomState(seed)\nsuccesses = []\nfor _ in range(trials):\n dirichlet_alpha = np.ones(game.num_strategies()[0])\n dist = random.dirichlet(dirichlet_alpha)\n sample_best_responses = np.argmax(game.payoff_tensor()[0], axis=0)\n estimated_best_response = ...
<|body_start_0|> game = small.BiasedGame(seed) random = np.random.RandomState(seed) successes = [] for _ in range(trials): dirichlet_alpha = np.ones(game.num_strategies()[0]) dist = random.dirichlet(dirichlet_alpha) sample_best_responses = np.argmax(ga...
SmallTest
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" <|body_0|> def simp_to_euc(a, b, center): """Transforms a point [a, b] on the simplex to Euclidean space....
stack_v2_sparse_classes_75kplus_train_065006
3,917
permissive
[ { "docstring": "Test best responses to sampled opp. actions in BiasedGame are biased.", "name": "test_biased_game", "signature": "def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234)" }, { "docstring": "Transforms a point [a, b] on the simplex to Euclidean space. /\\\\ ^ b /...
3
stack_v2_sparse_classes_30k_train_028778
Implement the Python class `SmallTest` described below. Class description: Implement the SmallTest class. Method signatures and docstrings: - def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): Test best responses to sampled opp. actions in BiasedGame are biased. - def simp_to_euc(a, b, center)...
Implement the Python class `SmallTest` described below. Class description: Implement the SmallTest class. Method signatures and docstrings: - def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): Test best responses to sampled opp. actions in BiasedGame are biased. - def simp_to_euc(a, b, center)...
ee149736f7d85e16c119a463eee338c6d4c2ceb0
<|skeleton|> class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" <|body_0|> def simp_to_euc(a, b, center): """Transforms a point [a, b] on the simplex to Euclidean space....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SmallTest: def test_biased_game(self, trials=100, atol=1e-05, rtol=1e-05, seed=1234): """Test best responses to sampled opp. actions in BiasedGame are biased.""" game = small.BiasedGame(seed) random = np.random.RandomState(seed) successes = [] for _ in range(trials): ...
the_stack_v2_python_sparse
open_spiel/python/algorithms/adidas_utils/games/small_test.py
lanctot/open_spiel
train
1
e7921796297175c154cdabe5b5b2595aed7fc8ca
[ "if sample_kwargs is None:\n sample_kwargs = {}\nsuper().__init__(sample_ext=sample_ext, sample_fn=sample_fn, dtype=dtype, normalize=normalize, norm_fn=norm_fn, **sample_kwargs)\nself._label_ext = label_ext\nself._label_fn = label_fn\nself._label_kwargs = kwargs", "sample_dict = super().__call__(path)\nlabel_d...
<|body_start_0|> if sample_kwargs is None: sample_kwargs = {} super().__init__(sample_ext=sample_ext, sample_fn=sample_fn, dtype=dtype, normalize=normalize, norm_fn=norm_fn, **sample_kwargs) self._label_ext = label_ext self._label_fn = label_fn self._label_kwargs = kw...
LoadSampleLabel
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadSampleLabel: def __init__(self, sample_ext: dict, sample_fn: collections.abc.Callable, label_ext: str, label_fn: collections.abc.Callable, dtype: dict=None, normalize: tuple=(), norm_fn=norm_range('-1,1'), sample_kwargs=None, **kwargs): """Load sample and label from folder Parameters...
stack_v2_sparse_classes_75kplus_train_065007
9,192
permissive
[ { "docstring": "Load sample and label from folder Parameters ---------- sample_ext : dict of list Defines the data _sample_ext. The dict key defines the position of the sample inside the returned data dict, while the list defines the the files which should be loaded inside the data dict. Passed to LoadSample. s...
2
stack_v2_sparse_classes_30k_train_044651
Implement the Python class `LoadSampleLabel` described below. Class description: Implement the LoadSampleLabel class. Method signatures and docstrings: - def __init__(self, sample_ext: dict, sample_fn: collections.abc.Callable, label_ext: str, label_fn: collections.abc.Callable, dtype: dict=None, normalize: tuple=(),...
Implement the Python class `LoadSampleLabel` described below. Class description: Implement the LoadSampleLabel class. Method signatures and docstrings: - def __init__(self, sample_ext: dict, sample_fn: collections.abc.Callable, label_ext: str, label_fn: collections.abc.Callable, dtype: dict=None, normalize: tuple=(),...
024a4028856661ac8328443ef3cf3d456a30991c
<|skeleton|> class LoadSampleLabel: def __init__(self, sample_ext: dict, sample_fn: collections.abc.Callable, label_ext: str, label_fn: collections.abc.Callable, dtype: dict=None, normalize: tuple=(), norm_fn=norm_range('-1,1'), sample_kwargs=None, **kwargs): """Load sample and label from folder Parameters...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoadSampleLabel: def __init__(self, sample_ext: dict, sample_fn: collections.abc.Callable, label_ext: str, label_fn: collections.abc.Callable, dtype: dict=None, normalize: tuple=(), norm_fn=norm_range('-1,1'), sample_kwargs=None, **kwargs): """Load sample and label from folder Parameters ---------- sa...
the_stack_v2_python_sparse
delira/data_loading/load_utils.py
LTHODAVDOPL/delira
train
1
9575c09184ee2f111d688de7e502e9cbcff30a87
[ "try:\n authenticator = TokenAuthenticator(token=config['secret_key'])\n stream = Customers(authenticator=authenticator, start_date=config['start_date'])\n records = stream.read_records(sync_mode=SyncMode.full_refresh)\n next(records)\n return (True, None)\nexcept StopIteration:\n return (True, No...
<|body_start_0|> try: authenticator = TokenAuthenticator(token=config['secret_key']) stream = Customers(authenticator=authenticator, start_date=config['start_date']) records = stream.read_records(sync_mode=SyncMode.full_refresh) next(records) return (T...
SourcePaystack
[ "Apache-2.0", "BSD-3-Clause", "MIT", "Elastic-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourcePaystack: def check_connection(self, logger, config) -> Tuple[bool, any]: """Check connection by fetching customers :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input c...
stack_v2_sparse_classes_75kplus_train_065008
2,274
permissive
[ { "docstring": "Check connection by fetching customers :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be used to connect to the API successfully, (False, error) otherwise.", "name...
2
stack_v2_sparse_classes_30k_train_040157
Implement the Python class `SourcePaystack` described below. Class description: Implement the SourcePaystack class. Method signatures and docstrings: - def check_connection(self, logger, config) -> Tuple[bool, any]: Check connection by fetching customers :param config: the user-input config object conforming to the c...
Implement the Python class `SourcePaystack` described below. Class description: Implement the SourcePaystack class. Method signatures and docstrings: - def check_connection(self, logger, config) -> Tuple[bool, any]: Check connection by fetching customers :param config: the user-input config object conforming to the c...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class SourcePaystack: def check_connection(self, logger, config) -> Tuple[bool, any]: """Check connection by fetching customers :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SourcePaystack: def check_connection(self, logger, config) -> Tuple[bool, any]: """Check connection by fetching customers :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be u...
the_stack_v2_python_sparse
dts/airbyte/airbyte-integrations/connectors/source-paystack/source_paystack/source.py
alldatacenter/alldata
train
774
3b48ea9592b0dbbec16092364032cfa22d4503c3
[ "try:\n if type(file_name) == str and type(data) == list:\n with open(file_name, 'wb') as f:\n pickle.dump(data, f)\n print(f'The TRAIN_DATA has been pickled as file: {file_name}')\n else:\n raise ValueError('Please ensure that two arguments are string and list')\nexcept ValueE...
<|body_start_0|> try: if type(file_name) == str and type(data) == list: with open(file_name, 'wb') as f: pickle.dump(data, f) print(f'The TRAIN_DATA has been pickled as file: {file_name}') else: raise ValueError('Please ...
NerStats
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NerStats: def save_labelled_data(file_name: str, data: list): """Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return:""" <|body_0|> def load_labelled_data(file_name: str) -> list: """load labelled ...
stack_v2_sparse_classes_75kplus_train_065009
2,647
permissive
[ { "docstring": "Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return:", "name": "save_labelled_data", "signature": "def save_labelled_data(file_name: str, data: list)" }, { "docstring": "load labelled data for use Parameters: -...
4
stack_v2_sparse_classes_30k_train_053850
Implement the Python class `NerStats` described below. Class description: Implement the NerStats class. Method signatures and docstrings: - def save_labelled_data(file_name: str, data: list): Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return: - d...
Implement the Python class `NerStats` described below. Class description: Implement the NerStats class. Method signatures and docstrings: - def save_labelled_data(file_name: str, data: list): Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return: - d...
e2c8fe5f68e92d70249d37cd6eb13a3ab046a891
<|skeleton|> class NerStats: def save_labelled_data(file_name: str, data: list): """Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return:""" <|body_0|> def load_labelled_data(file_name: str) -> list: """load labelled ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NerStats: def save_labelled_data(file_name: str, data: list): """Pickle or save labelled dataset ------- print the name of the file to the console. :param file_name: :param data: :return:""" try: if type(file_name) == str and type(data) == list: with open(file_name,...
the_stack_v2_python_sparse
src/textlabelling/nerstats.py
aakinlalu/textlabelling
train
2
8fac3d402238a500e69c94077201ea26c70e40cc
[ "for i in range(len(nums) - 1, -1, -1):\n if nums[i] == 0:\n j = i\n while j + 1 <= len(nums) - 1 and nums[j + 1] != 0:\n nums[j], nums[j + 1] = (nums[j + 1], nums[j])\n j += 1", "idx = 0\nfor n in nums:\n if n != 0:\n nums[idx] = n\n idx += 1\nwhile idx < l...
<|body_start_0|> for i in range(len(nums) - 1, -1, -1): if nums[i] == 0: j = i while j + 1 <= len(nums) - 1 and nums[j + 1] != 0: nums[j], nums[j + 1] = (nums[j + 1], nums[j]) j += 1 <|end_body_0|> <|body_start_1|> idx ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def moveZeroes2(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_75kplus_train_065010
760
no_license
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "moveZeroes2", "signature": "def moveZeroes2(self, nums: List[int]) -> None" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "moveZeroes", "signature": "def moveZeroes(self,...
2
stack_v2_sparse_classes_30k_train_017057
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def moveZeroes(self, nums: List[int]) -> None: Do not return anything, mod...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def moveZeroes(self, nums: List[int]) -> None: Do not return anything, mod...
fe30d8ca54309caff975684648495ea953022048
<|skeleton|> class Solution: def moveZeroes2(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def moveZeroes2(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" for i in range(len(nums) - 1, -1, -1): if nums[i] == 0: j = i while j + 1 <= len(nums) - 1 and nums[j + 1] != 0: ...
the_stack_v2_python_sparse
algorithm/leetCode/0283_move_zeroes.py
dictator-x/practise_as
train
0
b1e1e32bee6df4aeb9ea0c5766d136e28ef5cbee
[ "self.game_referee = game_referee\nself.game_board = game_board\nself.players = players", "current_player = self.players[0]\nother_player = self.players[1]\nwinner = None\nwhile winner is None:\n winner, proposed_move = self.game_referee.ask_for_move(self.game_board, current_player, other_player)\n current_...
<|body_start_0|> self.game_referee = game_referee self.game_board = game_board self.players = players <|end_body_0|> <|body_start_1|> current_player = self.players[0] other_player = self.players[1] winner = None while winner is None: winner, proposed_...
Game
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Game: def __init__(self, game_referee=referee.Referee(), game_board=board.Board(), players=[player.Player(), player.Player()]): """The game constructor declares a new board, referee, and two players. First player should be listed first. Args: referee : the current game referee board : th...
stack_v2_sparse_classes_75kplus_train_065011
1,481
no_license
[ { "docstring": "The game constructor declares a new board, referee, and two players. First player should be listed first. Args: referee : the current game referee board : the game board players : the list of players", "name": "__init__", "signature": "def __init__(self, game_referee=referee.Referee(), g...
2
stack_v2_sparse_classes_30k_train_035829
Implement the Python class `Game` described below. Class description: Implement the Game class. Method signatures and docstrings: - def __init__(self, game_referee=referee.Referee(), game_board=board.Board(), players=[player.Player(), player.Player()]): The game constructor declares a new board, referee, and two play...
Implement the Python class `Game` described below. Class description: Implement the Game class. Method signatures and docstrings: - def __init__(self, game_referee=referee.Referee(), game_board=board.Board(), players=[player.Player(), player.Player()]): The game constructor declares a new board, referee, and two play...
4ec458d10bc6a377df212ebffe60562ee281c678
<|skeleton|> class Game: def __init__(self, game_referee=referee.Referee(), game_board=board.Board(), players=[player.Player(), player.Player()]): """The game constructor declares a new board, referee, and two players. First player should be listed first. Args: referee : the current game referee board : th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Game: def __init__(self, game_referee=referee.Referee(), game_board=board.Board(), players=[player.Player(), player.Player()]): """The game constructor declares a new board, referee, and two players. First player should be listed first. Args: referee : the current game referee board : the game board p...
the_stack_v2_python_sparse
simple_games/generic_classes/game.py
andrewpenland/TwoPlayerGames
train
0
a90c7bc9ef903d79cd82af5d14a69dcb9263b38f
[ "self.rate = rate\nself.random_seed = random_seed\nself.scope = scope\nself.device_spec = get_device_spec(default_gpu_id, num_gpus)", "with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):\n if self.rate > 0.0:\n output_dropout = tf.layers.dropout(input_data, self.rate, s...
<|body_start_0|> self.rate = rate self.random_seed = random_seed self.scope = scope self.device_spec = get_device_spec(default_gpu_id, num_gpus) <|end_body_0|> <|body_start_1|> with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec): if s...
dropout layer
Dropout
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dropout: """dropout layer""" def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout'): """initialize dropout layer""" <|body_0|> def __call__(self, input_data, input_mask): """call dropout layer""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_065012
2,850
permissive
[ { "docstring": "initialize dropout layer", "name": "__init__", "signature": "def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout')" }, { "docstring": "call dropout layer", "name": "__call__", "signature": "def __call__(self, input_data, input_mask)" } ]
2
stack_v2_sparse_classes_30k_val_000792
Implement the Python class `Dropout` described below. Class description: dropout layer Method signatures and docstrings: - def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout'): initialize dropout layer - def __call__(self, input_data, input_mask): call dropout layer
Implement the Python class `Dropout` described below. Class description: dropout layer Method signatures and docstrings: - def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout'): initialize dropout layer - def __call__(self, input_data, input_mask): call dropout layer <|skeleton|> cla...
05fcbec15e359e3db86af6c3798c13be8a6c58ee
<|skeleton|> class Dropout: """dropout layer""" def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout'): """initialize dropout layer""" <|body_0|> def __call__(self, input_data, input_mask): """call dropout layer""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dropout: """dropout layer""" def __init__(self, rate, num_gpus=1, default_gpu_id=0, random_seed=0, scope='dropout'): """initialize dropout layer""" self.rate = rate self.random_seed = random_seed self.scope = scope self.device_spec = get_device_spec(default_gpu_id,...
the_stack_v2_python_sparse
sequence_labeling/layer/basic.py
stevezheng23/sequence_labeling_tf
train
18
5c8c027969dfdcea5c18ff866fccdcdefabfaefe
[ "NF = NoiseFigure(value=list((l.noise.value for l in self.chain)))\ngain = PhysicalDimension(value=list((l.gain.dB().value for l in self.chain))[:-1], scale='dB')\nreturn friis(NF, gain)", "gain = np.zeros(self.chain[0].gain.shape)\nfor l in self.chain:\n gain += l.gain.dB().value\nprint(gain)\nreturn sum(gain...
<|body_start_0|> NF = NoiseFigure(value=list((l.noise.value for l in self.chain))) gain = PhysicalDimension(value=list((l.gain.dB().value for l in self.chain))[:-1], scale='dB') return friis(NF, gain) <|end_body_0|> <|body_start_1|> gain = np.zeros(self.chain[0].gain.shape) for ...
class used to size rf line-up
RFLineUp
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RFLineUp: """class used to size rf line-up""" def NF(self): """return the noise figure of the global line-up.""" <|body_0|> def gain(self): """return the gain of the global line-up.""" <|body_1|> <|end_skeleton|> <|body_start_0|> NF = NoiseFigur...
stack_v2_sparse_classes_75kplus_train_065013
2,133
permissive
[ { "docstring": "return the noise figure of the global line-up.", "name": "NF", "signature": "def NF(self)" }, { "docstring": "return the gain of the global line-up.", "name": "gain", "signature": "def gain(self)" } ]
2
null
Implement the Python class `RFLineUp` described below. Class description: class used to size rf line-up Method signatures and docstrings: - def NF(self): return the noise figure of the global line-up. - def gain(self): return the gain of the global line-up.
Implement the Python class `RFLineUp` described below. Class description: class used to size rf line-up Method signatures and docstrings: - def NF(self): return the noise figure of the global line-up. - def gain(self): return the gain of the global line-up. <|skeleton|> class RFLineUp: """class used to size rf l...
da7e40005c67202ccd99f19cf49d90fa771e3fcf
<|skeleton|> class RFLineUp: """class used to size rf line-up""" def NF(self): """return the noise figure of the global line-up.""" <|body_0|> def gain(self): """return the gain of the global line-up.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RFLineUp: """class used to size rf line-up""" def NF(self): """return the noise figure of the global line-up.""" NF = NoiseFigure(value=list((l.noise.value for l in self.chain))) gain = PhysicalDimension(value=list((l.gain.dB().value for l in self.chain))[:-1], scale='dB') ...
the_stack_v2_python_sparse
passive_auto_design/system/rf_line_up.py
Patarimi/PassiveAutoDesign
train
1
cecc99a6ef1afc631b2c50575e8da470a7efecd6
[ "assert config_path.parent.exists(), f'directory {config_path.parent} does not exist'\n\ndef convert_dict(data):\n for key, val in data.items():\n if isinstance(val, pathlib.Path):\n data[key] = str(val)\n if isinstance(val, dict):\n data[key] = convert_dict(val)\n return d...
<|body_start_0|> assert config_path.parent.exists(), f'directory {config_path.parent} does not exist' def convert_dict(data): for key, val in data.items(): if isinstance(val, pathlib.Path): data[key] = str(val) if isinstance(val, dict): ...
YamlConfig
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class YamlConfig: def save(self, config_path: pathlib.Path): """Export config as YAML file""" <|body_0|> def load(cls, config_path: pathlib.Path): """Load config from YAML file""" <|body_1|> <|end_skeleton|> <|body_start_0|> assert config_path.parent.exis...
stack_v2_sparse_classes_75kplus_train_065014
1,564
no_license
[ { "docstring": "Export config as YAML file", "name": "save", "signature": "def save(self, config_path: pathlib.Path)" }, { "docstring": "Load config from YAML file", "name": "load", "signature": "def load(cls, config_path: pathlib.Path)" } ]
2
null
Implement the Python class `YamlConfig` described below. Class description: Implement the YamlConfig class. Method signatures and docstrings: - def save(self, config_path: pathlib.Path): Export config as YAML file - def load(cls, config_path: pathlib.Path): Load config from YAML file
Implement the Python class `YamlConfig` described below. Class description: Implement the YamlConfig class. Method signatures and docstrings: - def save(self, config_path: pathlib.Path): Export config as YAML file - def load(cls, config_path: pathlib.Path): Load config from YAML file <|skeleton|> class YamlConfig: ...
e3381c67988f607f2ebb684ed88d3864dee2f38c
<|skeleton|> class YamlConfig: def save(self, config_path: pathlib.Path): """Export config as YAML file""" <|body_0|> def load(cls, config_path: pathlib.Path): """Load config from YAML file""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class YamlConfig: def save(self, config_path: pathlib.Path): """Export config as YAML file""" assert config_path.parent.exists(), f'directory {config_path.parent} does not exist' def convert_dict(data): for key, val in data.items(): if isinstance(val, pathlib.Pat...
the_stack_v2_python_sparse
gan_based_anomaly_detection/src/utils/yaml_config.py
TMdiesel/pytorch-implementation
train
0
4c172779b2a28c3498570c131f46fec27394a61e
[ "self.molecule = mol_to_mol_graph(molecule)\nif isinstance(job_type, str):\n if job_type.lower() not in job_type_mapping:\n raise ValueError('Job type {} unknown!'.format(job_type))\n self.job_type = job_type_mapping[job_type.lower()]\nelse:\n self.job_type = job_type\nif isinstance(path, Path):\n ...
<|body_start_0|> self.molecule = mol_to_mol_graph(molecule) if isinstance(job_type, str): if job_type.lower() not in job_type_mapping: raise ValueError('Job type {} unknown!'.format(job_type)) self.job_type = job_type_mapping[job_type.lower()] else: ...
A helper class to prepare and execute Jaguar calculations.
JaguarJob
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JaguarJob: """A helper class to prepare and execute Jaguar calculations.""" def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJobType], path: Union[str, Path], schrodinger_dir: Optional[Union[str, Path]]='SCHRODINGER', job_name: Optional[str]=None, num_c...
stack_v2_sparse_classes_75kplus_train_065015
30,590
no_license
[ { "docstring": ":param molecule: :param job_type: :param path: :param schrodinger_dir: :param job_name: :param num_cores: :param host: :param save_scratch: :param input_params:", "name": "__init__", "signature": "def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJob...
3
stack_v2_sparse_classes_30k_train_053757
Implement the Python class `JaguarJob` described below. Class description: A helper class to prepare and execute Jaguar calculations. Method signatures and docstrings: - def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJobType], path: Union[str, Path], schrodinger_dir: Optional[...
Implement the Python class `JaguarJob` described below. Class description: A helper class to prepare and execute Jaguar calculations. Method signatures and docstrings: - def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJobType], path: Union[str, Path], schrodinger_dir: Optional[...
c21e4eb86d9118365e17166c852f3ba6d36dd674
<|skeleton|> class JaguarJob: """A helper class to prepare and execute Jaguar calculations.""" def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJobType], path: Union[str, Path], schrodinger_dir: Optional[Union[str, Path]]='SCHRODINGER', job_name: Optional[str]=None, num_c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JaguarJob: """A helper class to prepare and execute Jaguar calculations.""" def __init__(self, molecule: Union[Molecule, MoleculeGraph], job_type: Union[str, JaguarJobType], path: Union[str, Path], schrodinger_dir: Optional[Union[str, Path]]='SCHRODINGER', job_name: Optional[str]=None, num_cores: Optiona...
the_stack_v2_python_sparse
mpcat/automate/generate_calcs.py
espottesmith/MPcat
train
10
4c598df0b0989bdf2e546d04e5be15b20a622175
[ "serialized = []\n\ndef preorder(node):\n if not node:\n return\n serialized.append(str(node.val))\n for child in node.children:\n preorder(child)\n serialized.append('#')\npreorder(root)\nreturn ' '.join(serialized)", "tokens = deque(data.split())\nif len(tokens) == 0:\n return None\...
<|body_start_0|> serialized = [] def preorder(node): if not node: return serialized.append(str(node.val)) for child in node.children: preorder(child) serialized.append('#') preorder(root) return ' '.join(ser...
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus_train_065016
1,306
permissive
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root: 'Node') -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def des...
2
stack_v2_sparse_classes_30k_train_012061
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
fd4cf122cfd4920f3bd8dce40ba7487a170a1b57
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" serialized = [] def preorder(node): if not node: return serialized.append(str(node.val)) for child in node.childre...
the_stack_v2_python_sparse
0428_Serialize_and_Deserialize_N-ary_Tree.py
coldmanck/leetcode-python
train
6
86ad00ff5a24d6fef6a809e9f9e237c02c2d0648
[ "self.coord_names = tuple(coord_names)\nself.name = name\nself.coord_dtype = coord_dtype", "if name is None:\n name = self.name\nif coord_dtype is None:\n coord_dtype = self.coord_dtype\nif N > len(self.coord_names):\n raise CoordSysMakerError('Not enough axis names (have %d, you asked for %d)' % (len(se...
<|body_start_0|> self.coord_names = tuple(coord_names) self.name = name self.coord_dtype = coord_dtype <|end_body_0|> <|body_start_1|> if name is None: name = self.name if coord_dtype is None: coord_dtype = self.coord_dtype if N > len(self.coord_n...
Class to create similar coordinate maps of different dimensions
CoordSysMaker
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoordSysMaker: """Class to create similar coordinate maps of different dimensions""" def __init__(self, coord_names, name='', coord_dtype=np.float64): """Create a coordsys maker with given axis `coord_names` Parameters ---------- coord_names : iterable A sequence of coordinate names....
stack_v2_sparse_classes_75kplus_train_065017
16,745
permissive
[ { "docstring": "Create a coordsys maker with given axis `coord_names` Parameters ---------- coord_names : iterable A sequence of coordinate names. name : string, optional The name of the coordinate system coord_dtype : np.dtype, optional The dtype of the coord_names. This should be a built-in numpy scalar dtype...
2
null
Implement the Python class `CoordSysMaker` described below. Class description: Class to create similar coordinate maps of different dimensions Method signatures and docstrings: - def __init__(self, coord_names, name='', coord_dtype=np.float64): Create a coordsys maker with given axis `coord_names` Parameters --------...
Implement the Python class `CoordSysMaker` described below. Class description: Class to create similar coordinate maps of different dimensions Method signatures and docstrings: - def __init__(self, coord_names, name='', coord_dtype=np.float64): Create a coordsys maker with given axis `coord_names` Parameters --------...
7eede02471567487e454016c1e7cf637d3afac9e
<|skeleton|> class CoordSysMaker: """Class to create similar coordinate maps of different dimensions""" def __init__(self, coord_names, name='', coord_dtype=np.float64): """Create a coordsys maker with given axis `coord_names` Parameters ---------- coord_names : iterable A sequence of coordinate names....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CoordSysMaker: """Class to create similar coordinate maps of different dimensions""" def __init__(self, coord_names, name='', coord_dtype=np.float64): """Create a coordsys maker with given axis `coord_names` Parameters ---------- coord_names : iterable A sequence of coordinate names. name : strin...
the_stack_v2_python_sparse
nipy/core/reference/coordinate_system.py
nipy/nipy
train
275
aa9d56bc710b5079229c14ed8db5ca34a28e85b1
[ "node = TreeNode(5)\nleftNode = TreeNode(4)\nrightNode = TreeNode(5)\nnode.left = leftNode\nnode.right = rightNode\nthirdLevelLeftNode1 = TreeNode(1)\nthirdLevelLeftNode2 = TreeNode(1)\nthirdLevelRightNode1 = TreeNode(5)\nleftNode.left = thirdLevelLeftNode1\nleftNode.right = thirdLevelLeftNode2\nrightNode.right = t...
<|body_start_0|> node = TreeNode(5) leftNode = TreeNode(4) rightNode = TreeNode(5) node.left = leftNode node.right = rightNode thirdLevelLeftNode1 = TreeNode(1) thirdLevelLeftNode2 = TreeNode(1) thirdLevelRightNode1 = TreeNode(5) leftNode.left = th...
TestSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSolution: def test_LongestUnivalueCase1(self): """5 / 4 5 / \\ / 1 1 5""" <|body_0|> def test_LongestUnivalueCase2(self): """1 / 4 5 / \\ / 4 4 5""" <|body_1|> def test_LongestUnivalueCase3(self): """5 / 5 5 / \\ / 5 4 5""" <|body_2|>...
stack_v2_sparse_classes_75kplus_train_065018
2,303
no_license
[ { "docstring": "5 / 4 5 / \\\\ / 1 1 5", "name": "test_LongestUnivalueCase1", "signature": "def test_LongestUnivalueCase1(self)" }, { "docstring": "1 / 4 5 / \\\\ / 4 4 5", "name": "test_LongestUnivalueCase2", "signature": "def test_LongestUnivalueCase2(self)" }, { "docstring": "...
3
stack_v2_sparse_classes_30k_train_031701
Implement the Python class `TestSolution` described below. Class description: Implement the TestSolution class. Method signatures and docstrings: - def test_LongestUnivalueCase1(self): 5 / 4 5 / \\ / 1 1 5 - def test_LongestUnivalueCase2(self): 1 / 4 5 / \\ / 4 4 5 - def test_LongestUnivalueCase3(self): 5 / 5 5 / \\ ...
Implement the Python class `TestSolution` described below. Class description: Implement the TestSolution class. Method signatures and docstrings: - def test_LongestUnivalueCase1(self): 5 / 4 5 / \\ / 1 1 5 - def test_LongestUnivalueCase2(self): 1 / 4 5 / \\ / 4 4 5 - def test_LongestUnivalueCase3(self): 5 / 5 5 / \\ ...
7fa160362ebb58e7286b490012542baa2d51e5c9
<|skeleton|> class TestSolution: def test_LongestUnivalueCase1(self): """5 / 4 5 / \\ / 1 1 5""" <|body_0|> def test_LongestUnivalueCase2(self): """1 / 4 5 / \\ / 4 4 5""" <|body_1|> def test_LongestUnivalueCase3(self): """5 / 5 5 / \\ / 5 4 5""" <|body_2|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestSolution: def test_LongestUnivalueCase1(self): """5 / 4 5 / \\ / 1 1 5""" node = TreeNode(5) leftNode = TreeNode(4) rightNode = TreeNode(5) node.left = leftNode node.right = rightNode thirdLevelLeftNode1 = TreeNode(1) thirdLevelLeftNode2 = Tr...
the_stack_v2_python_sparse
tree/test_longestUnivaluePath.py
gerrycfchang/leetcode-python
train
2
1a9cbfbf24c4b3ced7a45dad5323f6f11d355e85
[ "self.cache = {}\nself.head = Node(None, None)\nself.tail = Node(None, None)\nself.head.next = self.tail\nself.tail.pre = self.head\nself.cap = capacity\nself.size = 0", "if key not in self.cache:\n return -1\nnode = self.cache[key]\nval = node.val\nself.remove_node(node)\nself.add_to_first(node)\nreturn val",...
<|body_start_0|> self.cache = {} self.head = Node(None, None) self.tail = Node(None, None) self.head.next = self.tail self.tail.pre = self.head self.cap = capacity self.size = 0 <|end_body_0|> <|body_start_1|> if key not in self.cache: return ...
Hash Map + Doubly Linked List
LRUCache
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: """Hash Map + Doubly Linked List""" def __init__(self, capacity: int): """cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail""" <|body_0|> def get(self, key: int) -> int: """1 - Key does not exist....
stack_v2_sparse_classes_75kplus_train_065019
2,890
permissive
[ { "docstring": "cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail", "name": "__init__", "signature": "def __init__(self, capacity: int)" }, { "docstring": "1 - Key does not exist. 2 - Find the Key-Node pair in self.cache. 3 - Remove this n...
5
null
Implement the Python class `LRUCache` described below. Class description: Hash Map + Doubly Linked List Method signatures and docstrings: - def __init__(self, capacity: int): cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail - def get(self, key: int) -> int: 1 ...
Implement the Python class `LRUCache` described below. Class description: Hash Map + Doubly Linked List Method signatures and docstrings: - def __init__(self, capacity: int): cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail - def get(self, key: int) -> int: 1 ...
3c18b8809c5a21a62903060eef659654e0595036
<|skeleton|> class LRUCache: """Hash Map + Doubly Linked List""" def __init__(self, capacity: int): """cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail""" <|body_0|> def get(self, key: int) -> int: """1 - Key does not exist....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: """Hash Map + Doubly Linked List""" def __init__(self, capacity: int): """cache - dictionary cache[key] = Node(val) DLL - doubly linked list head <-> node <-> node <-> ... <-> tail""" self.cache = {} self.head = Node(None, None) self.tail = Node(None, None) ...
the_stack_v2_python_sparse
OOD/146. LRU Cache.py
xli1110/LC
train
2
9a70ad1cdb033df60a45c8d3b1c29a795994e93d
[ "self.exclusive_maximum = exclusive_maximum\nself.exclusive_minimum = exclusive_minimum\nself.id = id\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nexclusive_maximum = dictionary.get('exclusiveMaximum')\nexclusive_minimum = dictionary.get('exclusiveMinimum')\nid =...
<|body_start_0|> self.exclusive_maximum = exclusive_maximum self.exclusive_minimum = exclusive_minimum self.id = id self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None exclusive_maximum = dicti...
Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here.
Attributes
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Attributes: """Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here.""" def __init__(self, exclusive_maxi...
stack_v2_sparse_classes_75kplus_train_065020
2,258
permissive
[ { "docstring": "Constructor for the Attributes class", "name": "__init__", "signature": "def __init__(self, exclusive_maximum=None, exclusive_minimum=None, id=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A ...
2
null
Implement the Python class `Attributes` described below. Class description: Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here. M...
Implement the Python class `Attributes` described below. Class description: Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here. M...
49acc3d416a1dde7ea43b178d070484baf1b7f2b
<|skeleton|> class Attributes: """Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here.""" def __init__(self, exclusive_maxi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Attributes: """Implementation of the 'Attributes' model. TODO: type model description here. Attributes: exclusive_maximum (bool): TODO: type description here. exclusive_minimum (bool): TODO: type description here. id (string): TODO: type description here.""" def __init__(self, exclusive_maximum=None, exc...
the_stack_v2_python_sparse
PYTHON_GENERIC_LIB/tester/models/attributes.py
MaryamAdnan3/Tester1
train
0
165e7c10fdf95aba4c92114f8754229b6432d980
[ "self.log = TastLogger(self.__class__.__name__)\nself.log.debug('LocalEndpoint: Creating new %s instance...' % self.__class__.__name__)\nsuper(LocalEndpoint, self).__init__(fqdn, username, password, type, version)\nself.viewer_type = viewer_type\nself.viewer_id = viewer_id\nself.connection_interface = None\nself._l...
<|body_start_0|> self.log = TastLogger(self.__class__.__name__) self.log.debug('LocalEndpoint: Creating new %s instance...' % self.__class__.__name__) super(LocalEndpoint, self).__init__(fqdn, username, password, type, version) self.viewer_type = viewer_type self.viewer_id = view...
LocalEndpoint class provides functions for managing local PCoIP endpoint.
LocalEndpoint
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LocalEndpoint: """LocalEndpoint class provides functions for managing local PCoIP endpoint.""" def __init__(self, fqdn, username, password, type, version, viewer_type, viewer_id): """Arguments: fqdn: same as for Endpoint username: same as for Endpoint password: same as for Endpoint t...
stack_v2_sparse_classes_75kplus_train_065021
6,754
no_license
[ { "docstring": "Arguments: fqdn: same as for Endpoint username: same as for Endpoint password: same as for Endpoint type: one of LocalEndpointType values version: same as for Endpoint viewer_type: 'kvmoip' or 'dp-dvi' viewer_id: type specific, for 'kvmoip' switch it is fqdn or ipaddr of the kvmoip device", ...
3
stack_v2_sparse_classes_30k_train_007983
Implement the Python class `LocalEndpoint` described below. Class description: LocalEndpoint class provides functions for managing local PCoIP endpoint. Method signatures and docstrings: - def __init__(self, fqdn, username, password, type, version, viewer_type, viewer_id): Arguments: fqdn: same as for Endpoint userna...
Implement the Python class `LocalEndpoint` described below. Class description: LocalEndpoint class provides functions for managing local PCoIP endpoint. Method signatures and docstrings: - def __init__(self, fqdn, username, password, type, version, viewer_type, viewer_id): Arguments: fqdn: same as for Endpoint userna...
f199aae9467c80b57c43070728d4939f405c347a
<|skeleton|> class LocalEndpoint: """LocalEndpoint class provides functions for managing local PCoIP endpoint.""" def __init__(self, fqdn, username, password, type, version, viewer_type, viewer_id): """Arguments: fqdn: same as for Endpoint username: same as for Endpoint password: same as for Endpoint t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LocalEndpoint: """LocalEndpoint class provides functions for managing local PCoIP endpoint.""" def __init__(self, fqdn, username, password, type, version, viewer_type, viewer_id): """Arguments: fqdn: same as for Endpoint username: same as for Endpoint password: same as for Endpoint type: one of L...
the_stack_v2_python_sparse
factory/endpoint/endpoint-001/local_endpoint.py
dragan-nikolic/python_ex
train
0
fadf50b0e0f72d673f9251da18ea61435d646376
[ "code = ''\nfor i in range(self.dimensions):\n code += '{neighbor}{i} = {coord}{i}{delta};\\n'.format(neighbor=neighbor_prefix, i=i, coord=coord_prefix, delta=self._delta2str[self._neighbor_deltas[index][i]])\nreturn code", "cell_index = self.topology.lattice.coord_to_index_code(coord_prefix)\ncell_index += ' ...
<|body_start_0|> code = '' for i in range(self.dimensions): code += '{neighbor}{i} = {coord}{i}{delta};\n'.format(neighbor=neighbor_prefix, i=i, coord=coord_prefix, delta=self._delta2str[self._neighbor_deltas[index][i]]) return code <|end_body_0|> <|body_start_1|> cell_index...
The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should correctly set ``num_neighbors`` and ``_neighbor_deltas`` attributes.
OrthogonalNeighborhood
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrthogonalNeighborhood: """The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should correctly set ``num_neighbors`` and ``_...
stack_v2_sparse_classes_75kplus_train_065022
6,400
permissive
[ { "docstring": "Generate the C code to obtain neighbor coordinates by its index. See :meth:`Neighborhood.neighbor_coords` for details.", "name": "neighbor_coords", "signature": "def neighbor_coords(self, index, coord_prefix, neighbor_prefix)" }, { "docstring": "Generate the C code to obtain a ne...
2
null
Implement the Python class `OrthogonalNeighborhood` described below. Class description: The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should ...
Implement the Python class `OrthogonalNeighborhood` described below. Class description: The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should ...
a5f736f5478205316898aaa810df9eab949b55f7
<|skeleton|> class OrthogonalNeighborhood: """The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should correctly set ``num_neighbors`` and ``_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OrthogonalNeighborhood: """The base class for neighborhoods on an orthogonal lattice. It is implementing all necessary :class:`Neighborhood` abstract methods, the only thing you should override is :meth:`dimensions` setter. In :meth:`dimensions`, you should correctly set ``num_neighbors`` and ``_neighbor_delt...
the_stack_v2_python_sparse
xentica/core/topology/neighborhood.py
irthomasthomas/xentica
train
0
ca7badec766cb7eb514a64eeacb031c96540450b
[ "m = len(triangle)\ndp = [[float('inf')] * (m + 1) for _ in range(m + 1)]\ndp[0][1] = 0\nfor i in range(1, m + 1):\n for j in range(1, i + 1):\n dp[i][j] = min(dp[i - 1][j] + triangle[i - 1][j - 1], dp[i - 1][j - 1] + triangle[i - 1][j - 1])\nreturn min(dp[-1])", "m = len(triangle)\ndp = [float('inf')] ...
<|body_start_0|> m = len(triangle) dp = [[float('inf')] * (m + 1) for _ in range(m + 1)] dp[0][1] = 0 for i in range(1, m + 1): for j in range(1, i + 1): dp[i][j] = min(dp[i - 1][j] + triangle[i - 1][j - 1], dp[i - 1][j - 1] + triangle[i - 1][j - 1]) r...
Soluton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Soluton: def minimumTotal(self, triangle: list) -> int: """dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j-1_最短回文串.py] + tri[i-1_最短回文串.py][j-1_最短回文串.py]) dp[0][j] = 'inf' dp[i][0] = 'inf' dp[0][0] ...
stack_v2_sparse_classes_75kplus_train_065023
1,782
no_license
[ { "docstring": "dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j-1_最短回文串.py] + tri[i-1_最短回文串.py][j-1_最短回文串.py]) dp[0][j] = 'inf' dp[i][0] = 'inf' dp[0][0] = 0 res = max(dp[-1_最短回文串.py]) 空间 O(m^2) 时间 O(m)", "name": "min...
2
stack_v2_sparse_classes_30k_train_003647
Implement the Python class `Soluton` described below. Class description: Implement the Soluton class. Method signatures and docstrings: - def minimumTotal(self, triangle: list) -> int: dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串....
Implement the Python class `Soluton` described below. Class description: Implement the Soluton class. Method signatures and docstrings: - def minimumTotal(self, triangle: list) -> int: dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串....
57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb
<|skeleton|> class Soluton: def minimumTotal(self, triangle: list) -> int: """dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j-1_最短回文串.py] + tri[i-1_最短回文串.py][j-1_最短回文串.py]) dp[0][j] = 'inf' dp[i][0] = 'inf' dp[0][0] ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Soluton: def minimumTotal(self, triangle: list) -> int: """dp dp[i][j] 从triangle[0][0] 到 triangle[i][j] 最小路径 dp[i][j] = min(dp[i-1_最短回文串.py][j] + tri[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j-1_最短回文串.py] + tri[i-1_最短回文串.py][j-1_最短回文串.py]) dp[0][j] = 'inf' dp[i][0] = 'inf' dp[0][0] = 0 res = max(...
the_stack_v2_python_sparse
4_LEETCODE/2_DP/网格问题/120._三角形最小路径和.py
fzingithub/SwordRefers2Offer
train
1
55985167491ac63bb4049ec33e7dbf677eb205fb
[ "if not isinstance(value, list):\n raise XRPLBinaryCodecException(f'Invalid type to construct a Path: expected list, received {value.__class__.__name__}.')\nbuffer: bytes = b''\nfor PathStep_dict in value:\n pathstep = PathStep.from_value(PathStep_dict)\n buffer += bytes(pathstep)\nreturn Path(buffer)", ...
<|body_start_0|> if not isinstance(value, list): raise XRPLBinaryCodecException(f'Invalid type to construct a Path: expected list, received {value.__class__.__name__}.') buffer: bytes = b'' for PathStep_dict in value: pathstep = PathStep.from_value(PathStep_dict) ...
Class for serializing/deserializing Paths.
Path
[ "ISC", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Path: """Class for serializing/deserializing Paths.""" def from_value(cls: Type[Path], value: List[Dict[str, str]]) -> Path: """Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to construct a Path object from. Returns: The Path constructed f...
stack_v2_sparse_classes_75kplus_train_065024
9,067
permissive
[ { "docstring": "Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to construct a Path object from. Returns: The Path constructed from value. Raises: XRPLBinaryCodecException: If the supplied value is of the wrong type.", "name": "from_value", "signature": "def f...
3
stack_v2_sparse_classes_30k_train_025605
Implement the Python class `Path` described below. Class description: Class for serializing/deserializing Paths. Method signatures and docstrings: - def from_value(cls: Type[Path], value: List[Dict[str, str]]) -> Path: Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to cons...
Implement the Python class `Path` described below. Class description: Class for serializing/deserializing Paths. Method signatures and docstrings: - def from_value(cls: Type[Path], value: List[Dict[str, str]]) -> Path: Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to cons...
e5bbdf458ad83e6670a4ebf3df63e17fed8b099f
<|skeleton|> class Path: """Class for serializing/deserializing Paths.""" def from_value(cls: Type[Path], value: List[Dict[str, str]]) -> Path: """Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to construct a Path object from. Returns: The Path constructed f...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Path: """Class for serializing/deserializing Paths.""" def from_value(cls: Type[Path], value: List[Dict[str, str]]) -> Path: """Construct a Path from an array of dictionaries describing PathSteps. Args: value: The array to construct a Path object from. Returns: The Path constructed from value. Ra...
the_stack_v2_python_sparse
xrpl/core/binarycodec/types/path_set.py
yyolk/xrpl-py
train
1
3c26419e5d29474b3dff3181b455a9518d5c97ad
[ "storage = get_storage()\nauth0_id = get_auth0_id_of_user(email)\nuser_id = storage.read_user_id(auth0_id)\nreturn super().post(user_id, role_id)", "storage = get_storage()\nauth0_id = get_auth0_id_of_user(email)\ntry:\n user_id = storage.read_user_id(auth0_id)\nexcept StorageAuthError:\n return ('', 204)\n...
<|body_start_0|> storage = get_storage() auth0_id = get_auth0_id_of_user(email) user_id = storage.read_user_id(auth0_id) return super().post(user_id, role_id) <|end_body_0|> <|body_start_1|> storage = get_storage() auth0_id = get_auth0_id_of_user(email) try: ...
UserRolesManagementByEmailView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRolesManagementByEmailView: def post(self, email, role_id): """--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref...
stack_v2_sparse_classes_75kplus_train_065025
12,608
permissive
[ { "docstring": "--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/responses/404-NotFound'", "name": "post", "signatur...
2
stack_v2_sparse_classes_30k_train_029085
Implement the Python class `UserRolesManagementByEmailView` described below. Class description: Implement the UserRolesManagementByEmailView class. Method signatures and docstrings: - def post(self, email, role_id): --- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Rol...
Implement the Python class `UserRolesManagementByEmailView` described below. Class description: Implement the UserRolesManagementByEmailView class. Method signatures and docstrings: - def post(self, email, role_id): --- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Rol...
280800c73eb7cfd49029462b352887e78f1ff91b
<|skeleton|> class UserRolesManagementByEmailView: def post(self, email, role_id): """--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserRolesManagementByEmailView: def post(self, email, role_id): """--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/component...
the_stack_v2_python_sparse
sfa_api/users.py
SolarArbiter/solarforecastarbiter-api
train
9
58ac35541d30e1e96a6a242ea29e29c3f8cba894
[ "super().__init__()\nassert len(transforms_list) > 0, 'Argument transforms_list cannot be empty.'\nassert num_sample_op > 0, 'Need to sample at least one transform.'\nassert num_sample_op <= len(transforms_list), 'Argument num_sample_op cannot be greater than number of available transforms.'\nif transforms_prob is ...
<|body_start_0|> super().__init__() assert len(transforms_list) > 0, 'Argument transforms_list cannot be empty.' assert num_sample_op > 0, 'Need to sample at least one transform.' assert num_sample_op <= len(transforms_list), 'Argument num_sample_op cannot be greater than number of avail...
Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.
OpSampler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, rando...
stack_v2_sparse_classes_75kplus_train_065026
10,994
permissive
[ { "docstring": "Args: transforms_list (List[Callable]): A list of tuples of all available transforms to sample from. transforms_prob (Optional[List[float]]): The probabilities associated with each transform in transforms_list. If not provided, the sampler assumes a uniform distribution over all transforms. They...
2
stack_v2_sparse_classes_30k_train_033148
Implement the Python class `OpSampler` described below. Class description: Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input. Method signatures and docstrings: - def __init__(self, transforms_list: List[Callable], tran...
Implement the Python class `OpSampler` described below. Class description: Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input. Method signatures and docstrings: - def __init__(self, transforms_list: List[Callable], tran...
16f2abf2f8aa174915316007622bbb260215dee8
<|skeleton|> class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, rando...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OpSampler: """Given a list of transforms with weights, OpSampler applies weighted sampling to select n transforms, which are then applied sequentially to the input.""" def __init__(self, transforms_list: List[Callable], transforms_prob: Optional[List[float]]=None, num_sample_op: int=1, randomly_sample_de...
the_stack_v2_python_sparse
pytorchvideo/transforms/transforms.py
xchani/pytorchvideo
train
0
2d697450b617fd6843744cacf27a082f64bdceed
[ "def buildChildTree(preIndex, inIndex, length):\n if length == 0:\n return None\n root = TreeNode(preorder[preIndex])\n count = 0\n while inorder[inIndex + count] != preorder[preIndex]:\n count += 1\n root.left = buildChildTree(preIndex + 1, inIndex, count)\n root.right = buildChildT...
<|body_start_0|> def buildChildTree(preIndex, inIndex, length): if length == 0: return None root = TreeNode(preorder[preIndex]) count = 0 while inorder[inIndex + count] != preorder[preIndex]: count += 1 root.left = build...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def buildTree2(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_1|...
stack_v2_sparse_classes_75kplus_train_065027
1,314
permissive
[ { "docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode", "name": "buildTree", "signature": "def buildTree(self, preorder, inorder)" }, { "docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode", "name": "buildTree2", "signature": "de...
2
stack_v2_sparse_classes_30k_train_054573
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def buildTree2(self, preorder, inorder): :type preorder: List[int] :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def buildTree2(self, preorder, inorder): :type preorder: List[int] :...
c8bf33af30569177c5276ffcd72a8d93ba4c402a
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def buildTree2(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_1|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def buildTree(self, preorder, inorder): """:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" def buildChildTree(preIndex, inIndex, length): if length == 0: return None root = TreeNode(preorder[preIndex]) count =...
the_stack_v2_python_sparse
101-200/101-110/105-binaryTreeFromPreInOrder/binaryTreeFromPreInOrder.py
xuychen/Leetcode
train
0
677988a15d69f2bb63e8f51085cdde6de1ec7860
[ "start = timezone.now()\ntest_case = rfactories.TestCaseF.create()\nrfactories.TestCaseStepF.create(testcase=test_case)\nrfactories.TestCaseStepF.create(testcase=test_case)\ntest_case.run(test_case.testrun)\nself.assertEqual(2, rmodels.TestCaseStep.run.call_count)\nself.assertObjectUpdated(test_case, start_date__gt...
<|body_start_0|> start = timezone.now() test_case = rfactories.TestCaseF.create() rfactories.TestCaseStepF.create(testcase=test_case) rfactories.TestCaseStepF.create(testcase=test_case) test_case.run(test_case.testrun) self.assertEqual(2, rmodels.TestCaseStep.run.call_cou...
TestCaseModelTestCase
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCaseModelTestCase: def test_run_runs_all_test_steps(self): """Test case should run all TestCaseSteps and mark self as success.""" <|body_0|> def test_run_without_test_steps(self): """Test case should be runnable without TestCaseSteps (and should be success).""" ...
stack_v2_sparse_classes_75kplus_train_065028
27,107
permissive
[ { "docstring": "Test case should run all TestCaseSteps and mark self as success.", "name": "test_run_runs_all_test_steps", "signature": "def test_run_runs_all_test_steps(self)" }, { "docstring": "Test case should be runnable without TestCaseSteps (and should be success).", "name": "test_run_...
4
stack_v2_sparse_classes_30k_train_001615
Implement the Python class `TestCaseModelTestCase` described below. Class description: Implement the TestCaseModelTestCase class. Method signatures and docstrings: - def test_run_runs_all_test_steps(self): Test case should run all TestCaseSteps and mark self as success. - def test_run_without_test_steps(self): Test c...
Implement the Python class `TestCaseModelTestCase` described below. Class description: Implement the TestCaseModelTestCase class. Method signatures and docstrings: - def test_run_runs_all_test_steps(self): Test case should run all TestCaseSteps and mark self as success. - def test_run_without_test_steps(self): Test c...
57f5e7d16185d91a06fc3ad9ecd26fbef1c0a84d
<|skeleton|> class TestCaseModelTestCase: def test_run_runs_all_test_steps(self): """Test case should run all TestCaseSteps and mark self as success.""" <|body_0|> def test_run_without_test_steps(self): """Test case should be runnable without TestCaseSteps (and should be success).""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestCaseModelTestCase: def test_run_runs_all_test_steps(self): """Test case should run all TestCaseSteps and mark self as success.""" start = timezone.now() test_case = rfactories.TestCaseF.create() rfactories.TestCaseStepF.create(testcase=test_case) rfactories.TestCase...
the_stack_v2_python_sparse
fortuitus/frunner/tests.py
elegion/djangodash2012
train
0
46f3766c8d9dfc196e8bc12f4beda75ccde47c95
[ "if not root:\n return 'null'\nmessage = []\n\ndef build_message(root):\n if root is None:\n message.append('null')\n else:\n message.append(str(root.val))\n build_message(root.left)\n build_message(root.right)\nbuild_message(root)\nreturn ','.join(message)", "queue = collecti...
<|body_start_0|> if not root: return 'null' message = [] def build_message(root): if root is None: message.append('null') else: message.append(str(root.val)) build_message(root.left) build_messag...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_065029
1,635
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_031047
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
9d0ff0f8705451947a6605ab5ef92bb3e27a7147
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return 'null' message = [] def build_message(root): if root is None: message.append('null') else: ...
the_stack_v2_python_sparse
premium/amazon/design/serialize_and_deserialize_bst.py
rayt579/leetcode
train
0
43879ca3aef1ae28c37716e2c2f4fd66486cf481
[ "\"\"\"找出所有的pair, 如果符合条件,计数器加1 O(n^2)\"\"\"\ncount = 0\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if abs(nums[i] - nums[j]) == k:\n count += 1\nreturn count", "\"\"\"\n 思路:如果k不等于零的话,那就是nums和nums数组每个数加k集合的交,如果k等于零的话,那就统计数组中相同的数字即可\n 区分开k=0的情况\n \...
<|body_start_0|> """找出所有的pair, 如果符合条件,计数器加1 O(n^2)""" count = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): if abs(nums[i] - nums[j]) == k: count += 1 return count <|end_body_0|> <|body_start_1|> """ ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findPairs_simple(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def findPairs_map(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> def findPairs_pointer(self, nums, k): ...
stack_v2_sparse_classes_75kplus_train_065030
2,289
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "findPairs_simple", "signature": "def findPairs_simple(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "findPairs_map", "signature": "def findPairs_map(self, nums, k)" }...
3
stack_v2_sparse_classes_30k_train_006789
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPairs_simple(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findPairs_map(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findP...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findPairs_simple(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findPairs_map(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findP...
a0f270c1adce25be11df92877813037f2e73e28b
<|skeleton|> class Solution: def findPairs_simple(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def findPairs_map(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> def findPairs_pointer(self, nums, k): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findPairs_simple(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" """找出所有的pair, 如果符合条件,计数器加1 O(n^2)""" count = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): if abs(nums[i] - nums[j]) == k: ...
the_stack_v2_python_sparse
leetcode/532_k_diff_pairs_in_an_array.py
lvraikkonen/GoodCode
train
0
33edaf0aab6fb21a88a46bc8dd88fc8ae98f76c9
[ "c = Company(name='PCT')\np = annualTimePeriod(1, start_period='2012')\nc.set_current_period(p)\nc.capital_program.generate_expenditures()\nself.assertEqual(c.capital_program.expenditures.cost_of_sales, 1000)\nself.assertEqual(c.capital_program.expenditures.interest, 1000)", "c = Company(name='PCT')\np = annualTi...
<|body_start_0|> c = Company(name='PCT') p = annualTimePeriod(1, start_period='2012') c.set_current_period(p) c.capital_program.generate_expenditures() self.assertEqual(c.capital_program.expenditures.cost_of_sales, 1000) self.assertEqual(c.capital_program.expenditures.int...
Tests for determining if the Company correctly calculates the period expenditures for projects
ProjectExpendituresTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectExpendituresTests: """Tests for determining if the Company correctly calculates the period expenditures for projects""" def testSingleCapitalProjectExpenditures(self): """For a single capital project, the Company should correctly calculate the expenditures for the current peri...
stack_v2_sparse_classes_75kplus_train_065031
12,467
no_license
[ { "docstring": "For a single capital project, the Company should correctly calculate the expenditures for the current period", "name": "testSingleCapitalProjectExpenditures", "signature": "def testSingleCapitalProjectExpenditures(self)" }, { "docstring": "For a given list of capital projects, th...
5
stack_v2_sparse_classes_30k_train_013388
Implement the Python class `ProjectExpendituresTests` described below. Class description: Tests for determining if the Company correctly calculates the period expenditures for projects Method signatures and docstrings: - def testSingleCapitalProjectExpenditures(self): For a single capital project, the Company should ...
Implement the Python class `ProjectExpendituresTests` described below. Class description: Tests for determining if the Company correctly calculates the period expenditures for projects Method signatures and docstrings: - def testSingleCapitalProjectExpenditures(self): For a single capital project, the Company should ...
5a49c7c9885f453828b5e43cd27564e3f4c95b23
<|skeleton|> class ProjectExpendituresTests: """Tests for determining if the Company correctly calculates the period expenditures for projects""" def testSingleCapitalProjectExpenditures(self): """For a single capital project, the Company should correctly calculate the expenditures for the current peri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProjectExpendituresTests: """Tests for determining if the Company correctly calculates the period expenditures for projects""" def testSingleCapitalProjectExpenditures(self): """For a single capital project, the Company should correctly calculate the expenditures for the current period""" ...
the_stack_v2_python_sparse
company_test.py
SundropFuels/project-finance
train
0
14bf3295d4b8eb60dfc5643d85db80b743727066
[ "stats = kwargs['stats']\nif day == 0 or not stats:\n return '<td class=\"noday\">&nbsp;</td>'\nstat = next((stat for stat in stats if stat.date == dt.date(kwargs['theyear'], kwargs['themonth'], day)), None)\nif not stat:\n return '<td class=\"noday\">&nbsp;</td>'\nparams = dict(defaults.units, **stat.dict)\n...
<|body_start_0|> stats = kwargs['stats'] if day == 0 or not stats: return '<td class="noday">&nbsp;</td>' stat = next((stat for stat in stats if stat.date == dt.date(kwargs['theyear'], kwargs['themonth'], day)), None) if not stat: return '<td class="noday">&nbsp;<...
Генератор html-календаря с погодой
CalendarMaker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CalendarMaker: """Генератор html-календаря с погодой""" def formatday(self, day, weekday, **kwargs): """Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html ...
stack_v2_sparse_classes_75kplus_train_065032
11,050
no_license
[ { "docstring": "Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html код ячейки календаря с прогнозом", "name": "formatday", "signature": "def formatday(self, day, weekday, **kw...
5
stack_v2_sparse_classes_30k_train_016200
Implement the Python class `CalendarMaker` described below. Class description: Генератор html-календаря с погодой Method signatures and docstrings: - def formatday(self, day, weekday, **kwargs): Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётс...
Implement the Python class `CalendarMaker` described below. Class description: Генератор html-календаря с погодой Method signatures and docstrings: - def formatday(self, day, weekday, **kwargs): Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётс...
d2c0014dffccadb8232a1034e4ea9b427016a1d1
<|skeleton|> class CalendarMaker: """Генератор html-календаря с погодой""" def formatday(self, day, weekday, **kwargs): """Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CalendarMaker: """Генератор html-календаря с погодой""" def formatday(self, day, weekday, **kwargs): """Возвращает HTML код ячейки календаря :param day: день месяца :param weekday: день недели :param kwargs: в кваргах передаётся stats - список объектов класса Stats :return: str Html код ячейки ка...
the_stack_v2_python_sparse
lesson_016/engine/image_maker.py
glotyuids/skillbox_learning
train
0
606fe49355ebb3a7d8390a051094369338d7ae8e
[ "metadata_status = Status('Extracted submission metadata.', 'Extracting submission metadata.', 'white')\nmetadata_status.start()\nskeleton = {'scrape_settings': {'n_results': int(limit) if int(limit) > 0 else 'all', 'style': 'structured' if not args.raw else 'raw', 'url': url}, 'data': {'submission_metadata': {'aut...
<|body_start_0|> metadata_status = Status('Extracted submission metadata.', 'Extracting submission metadata.', 'white') metadata_status.start() skeleton = {'scrape_settings': {'n_results': int(limit) if int(limit) > 0 else 'all', 'style': 'structured' if not args.raw else 'raw', 'url': url}, 'da...
Methods for writing scraped comments to CSV or JSON.
Write
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Write: """Methods for writing scraped comments to CSV or JSON.""" def _make_json_skeleton(args, limit, submission, url): """Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace Namespace object containing all arguments that were ...
stack_v2_sparse_classes_75kplus_train_065033
14,112
permissive
[ { "docstring": "Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace Namespace object containing all arguments that were defined in the CLI limit: str Integer of string type denoting n_results or RAW format submission: PRAW submission object url: str String...
3
stack_v2_sparse_classes_30k_train_006348
Implement the Python class `Write` described below. Class description: Methods for writing scraped comments to CSV or JSON. Method signatures and docstrings: - def _make_json_skeleton(args, limit, submission, url): Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Names...
Implement the Python class `Write` described below. Class description: Methods for writing scraped comments to CSV or JSON. Method signatures and docstrings: - def _make_json_skeleton(args, limit, submission, url): Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Names...
9f8cf3a3adb9aa5079dfc7bfd7832b53358ee40f
<|skeleton|> class Write: """Methods for writing scraped comments to CSV or JSON.""" def _make_json_skeleton(args, limit, submission, url): """Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace Namespace object containing all arguments that were ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Write: """Methods for writing scraped comments to CSV or JSON.""" def _make_json_skeleton(args, limit, submission, url): """Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace Namespace object containing all arguments that were defined in th...
the_stack_v2_python_sparse
urs/praw_scrapers/static_scrapers/Comments.py
shilezi/URS
train
0
0396aee9be9fb2f95172367c6f72288641864231
[ "self.main_bin = Queue()\nfor num in num_list:\n self.main_bin.enqueue(num)\nself.bin_0 = Queue()\nself.bin_1 = Queue()\nself.bin_2 = Queue()\nself.bin_3 = Queue()\nself.bin_4 = Queue()\nself.bin_5 = Queue()\nself.bin_6 = Queue()\nself.bin_7 = Queue()\nself.bin_8 = Queue()\nself.bin_9 = Queue()", "while self.m...
<|body_start_0|> self.main_bin = Queue() for num in num_list: self.main_bin.enqueue(num) self.bin_0 = Queue() self.bin_1 = Queue() self.bin_2 = Queue() self.bin_3 = Queue() self.bin_4 = Queue() self.bin_5 = Queue() self.bin_6 = Queue() ...
RadixSort
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RadixSort: def __init__(self, num_list): """Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:""" <|body_0|> def radix_sort(self): """Combin...
stack_v2_sparse_classes_75kplus_train_065034
4,261
no_license
[ { "docstring": "Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:", "name": "__init__", "signature": "def __init__(self, num_list)" }, { "docstring": "Combines the Radi...
4
stack_v2_sparse_classes_30k_train_034067
Implement the Python class `RadixSort` described below. Class description: Implement the RadixSort class. Method signatures and docstrings: - def __init__(self, num_list): Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 di...
Implement the Python class `RadixSort` described below. Class description: Implement the RadixSort class. Method signatures and docstrings: - def __init__(self, num_list): Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 di...
b36aa897a83a21560a5e80674dd10f5a00d97fa4
<|skeleton|> class RadixSort: def __init__(self, num_list): """Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:""" <|body_0|> def radix_sort(self): """Combin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RadixSort: def __init__(self, num_list): """Sort a number list using a radix sort, takes a list of ints and sorts them from smallest to largest. Will not work if numbers are larger than 3 digits. :param num_list: :return:""" self.main_bin = Queue() for num in num_list: self...
the_stack_v2_python_sparse
DataStructure/week 4/radix_speed.py
Himanshudhir50/Himanshudhir50.github.io
train
0
0102b4a85f0076319eaef6bd0a742fb0d22167ff
[ "dev = qml.device('default.qubit', wires=3)\nparams = [1.0, 1.0, 1.0]\nwith JacobianTape() as tape:\n qml.RX(params[0], wires=[0])\n qml.RY(params[1], wires=[1])\n qml.RZ(params[2], wires=[2])\n qml.CNOT(wires=[0, 1])\n qml.probs(wires=0)\n qml.probs(wires=[1, 2])\nres = tape.jacobian(dev)\nassert...
<|body_start_0|> dev = qml.device('default.qubit', wires=3) params = [1.0, 1.0, 1.0] with JacobianTape() as tape: qml.RX(params[0], wires=[0]) qml.RY(params[1], wires=[1]) qml.RZ(params[2], wires=[2]) qml.CNOT(wires=[0, 1]) qml.probs(wi...
Integration tests for the Jacobian method
TestJacobianIntegration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestJacobianIntegration: """Integration tests for the Jacobian method""" def test_ragged_output(self): """Test that the Jacobian is correctly returned for a tape with ragged output""" <|body_0|> def test_single_expectation_value(self, tol): """Tests correct outpu...
stack_v2_sparse_classes_75kplus_train_065035
25,459
permissive
[ { "docstring": "Test that the Jacobian is correctly returned for a tape with ragged output", "name": "test_ragged_output", "signature": "def test_ragged_output(self)" }, { "docstring": "Tests correct output shape and evaluation for a tape with a single expval output", "name": "test_single_ex...
5
stack_v2_sparse_classes_30k_train_007932
Implement the Python class `TestJacobianIntegration` described below. Class description: Integration tests for the Jacobian method Method signatures and docstrings: - def test_ragged_output(self): Test that the Jacobian is correctly returned for a tape with ragged output - def test_single_expectation_value(self, tol)...
Implement the Python class `TestJacobianIntegration` described below. Class description: Integration tests for the Jacobian method Method signatures and docstrings: - def test_ragged_output(self): Test that the Jacobian is correctly returned for a tape with ragged output - def test_single_expectation_value(self, tol)...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class TestJacobianIntegration: """Integration tests for the Jacobian method""" def test_ragged_output(self): """Test that the Jacobian is correctly returned for a tape with ragged output""" <|body_0|> def test_single_expectation_value(self, tol): """Tests correct outpu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestJacobianIntegration: """Integration tests for the Jacobian method""" def test_ragged_output(self): """Test that the Jacobian is correctly returned for a tape with ragged output""" dev = qml.device('default.qubit', wires=3) params = [1.0, 1.0, 1.0] with JacobianTape() a...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1349/after/test_jacobian_tape.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
90aa90e677a5de86568e842f6e8e083faeac00c4
[ "avatar = self.cleaned_data.get('avatar', None)\nif avatar is not None:\n avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2)\n if avatar_size > settings.MAX_FILE_SIZES['avatar']:\n raise forms.ValidationError(_('Image file too large'))\nreturn avatar", "user = info.context.user\ntouched = Fals...
<|body_start_0|> avatar = self.cleaned_data.get('avatar', None) if avatar is not None: avatar_size = len(avatar) * 3 / 4 - avatar.count('=', -2) if avatar_size > settings.MAX_FILE_SIZES['avatar']: raise forms.ValidationError(_('Image file too large')) retu...
For used by profile settings mutation.
ProfileSettingsForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileSettingsForm: """For used by profile settings mutation.""" def clean_avatar(self) -> str: """Add some custom validation to our avatar field""" <|body_0|> def save(self, info, commit: bool=True) -> User: """Saves the changes made to the database (if any)"""...
stack_v2_sparse_classes_75kplus_train_065036
10,299
no_license
[ { "docstring": "Add some custom validation to our avatar field", "name": "clean_avatar", "signature": "def clean_avatar(self) -> str" }, { "docstring": "Saves the changes made to the database (if any)", "name": "save", "signature": "def save(self, info, commit: bool=True) -> User" } ]
2
stack_v2_sparse_classes_30k_val_002901
Implement the Python class `ProfileSettingsForm` described below. Class description: For used by profile settings mutation. Method signatures and docstrings: - def clean_avatar(self) -> str: Add some custom validation to our avatar field - def save(self, info, commit: bool=True) -> User: Saves the changes made to the...
Implement the Python class `ProfileSettingsForm` described below. Class description: For used by profile settings mutation. Method signatures and docstrings: - def clean_avatar(self) -> str: Add some custom validation to our avatar field - def save(self, info, commit: bool=True) -> User: Saves the changes made to the...
fe24d0bd08952647d27940a336bd0504af1bae0c
<|skeleton|> class ProfileSettingsForm: """For used by profile settings mutation.""" def clean_avatar(self) -> str: """Add some custom validation to our avatar field""" <|body_0|> def save(self, info, commit: bool=True) -> User: """Saves the changes made to the database (if any)"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileSettingsForm: """For used by profile settings mutation.""" def clean_avatar(self) -> str: """Add some custom validation to our avatar field""" avatar = self.cleaned_data.get('avatar', None) if avatar is not None: avatar_size = len(avatar) * 3 / 4 - avatar.count(...
the_stack_v2_python_sparse
accounts/graphql/mutations.py
ApyMajul/Zola-Backend
train
0
5d8454bfa5f13c22b42d77e0a410eb3b9bcbe75a
[ "self.log = LogHandler(logger=logger)\ntry:\n self._wavemeterdll = ctypes.windll.LoadLibrary('wlmData.dll')\nexcept:\n msg_str = 'High-Finesse WS7 Wavemeter is not properly installed on this computer'\n self.log.error(msg_str)\n raise WavemeterError(msg_str)\nself._wavemeterdll.GetWLMVersion.restype = c...
<|body_start_0|> self.log = LogHandler(logger=logger) try: self._wavemeterdll = ctypes.windll.LoadLibrary('wlmData.dll') except: msg_str = 'High-Finesse WS7 Wavemeter is not properly installed on this computer' self.log.error(msg_str) raise Wavemet...
Hardware class to control High Finesse Wavemeter.
Driver
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Driver: """Hardware class to control High Finesse Wavemeter.""" def __init__(self, logger=None): """Instantiate wavemeter :param logger: instance of LogClient class (optional)""" <|body_0|> def get_wavelength(self, channel=1, units='Frequency (THz)'): """Returns ...
stack_v2_sparse_classes_75kplus_train_065037
2,446
permissive
[ { "docstring": "Instantiate wavemeter :param logger: instance of LogClient class (optional)", "name": "__init__", "signature": "def __init__(self, logger=None)" }, { "docstring": "Returns the wavelength in specified units for a given channel :param channel: Channel number from 1-8 :param units: ...
2
stack_v2_sparse_classes_30k_train_039570
Implement the Python class `Driver` described below. Class description: Hardware class to control High Finesse Wavemeter. Method signatures and docstrings: - def __init__(self, logger=None): Instantiate wavemeter :param logger: instance of LogClient class (optional) - def get_wavelength(self, channel=1, units='Freque...
Implement the Python class `Driver` described below. Class description: Hardware class to control High Finesse Wavemeter. Method signatures and docstrings: - def __init__(self, logger=None): Instantiate wavemeter :param logger: instance of LogClient class (optional) - def get_wavelength(self, channel=1, units='Freque...
c8794a342d30119a6be93b2dd30ea61b5c946d8a
<|skeleton|> class Driver: """Hardware class to control High Finesse Wavemeter.""" def __init__(self, logger=None): """Instantiate wavemeter :param logger: instance of LogClient class (optional)""" <|body_0|> def get_wavelength(self, channel=1, units='Frequency (THz)'): """Returns ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Driver: """Hardware class to control High Finesse Wavemeter.""" def __init__(self, logger=None): """Instantiate wavemeter :param logger: instance of LogClient class (optional)""" self.log = LogHandler(logger=logger) try: self._wavemeterdll = ctypes.windll.LoadLibrary('...
the_stack_v2_python_sparse
pylabnet/hardware/wavemeter/high_finesse_ws7.py
lukingroup/pylabnet
train
15
2e84eef0e9d645b22303d95301b8a63f355bc663
[ "res = super(account_voucher, self).proforma_voucher()\ncommission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)])\nif commission_payment_rcs:\n commission_payment_rcs.wkf_done()\nreturn res", "res = super(account_voucher, self).cancel_voucher()\ncm_obj = self.env['commissio...
<|body_start_0|> res = super(account_voucher, self).proforma_voucher() commission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)]) if commission_payment_rcs: commission_payment_rcs.wkf_done() return res <|end_body_0|> <|body_start_1|> ...
account_voucher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class account_voucher: def proforma_voucher(self): """Surcharge pour lier l'écriture comptable du paiement à la commission""" <|body_0|> def cancel_voucher(self): """Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est ter...
stack_v2_sparse_classes_75kplus_train_065038
6,577
no_license
[ { "docstring": "Surcharge pour lier l'écriture comptable du paiement à la commission", "name": "proforma_voucher", "signature": "def proforma_voucher(self)" }, { "docstring": "Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est terminée", "...
2
stack_v2_sparse_classes_30k_train_010028
Implement the Python class `account_voucher` described below. Class description: Implement the account_voucher class. Method signatures and docstrings: - def proforma_voucher(self): Surcharge pour lier l'écriture comptable du paiement à la commission - def cancel_voucher(self): Surchage de la fonction d'annulation du...
Implement the Python class `account_voucher` described below. Class description: Implement the account_voucher class. Method signatures and docstrings: - def proforma_voucher(self): Surcharge pour lier l'écriture comptable du paiement à la commission - def cancel_voucher(self): Surchage de la fonction d'annulation du...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class account_voucher: def proforma_voucher(self): """Surcharge pour lier l'écriture comptable du paiement à la commission""" <|body_0|> def cancel_voucher(self): """Surchage de la fonction d'annulation du paiement Permet de remettre la commission à valider si elle est ter...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class account_voucher: def proforma_voucher(self): """Surcharge pour lier l'écriture comptable du paiement à la commission""" res = super(account_voucher, self).proforma_voucher() commission_payment_rcs = self.env['commission.payment'].search([('payment_id', '=', self.id)]) if commis...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/commission/account_invoice.py
kazacube-mziouadi/ceci
train
0
0bce7840dfef2323601c70fe40f26e8002036161
[ "if week < 0:\n raise ValueError('Invalid week number')\nif second >= cls.SECONDS_PER_WEEK:\n raise ValueError('Bad second number')\nweekday, daysec = divmod(second + cls.GPS_LEAP_OFFSET, cls.SECONDS_PER_DAY)\ndaynum = week * cls.NUM_WEEKDAYS + weekday\ndays, seconds = xdatetime.TAIDaySecsToUTCDaySecs(daynum ...
<|body_start_0|> if week < 0: raise ValueError('Invalid week number') if second >= cls.SECONDS_PER_WEEK: raise ValueError('Bad second number') weekday, daysec = divmod(second + cls.GPS_LEAP_OFFSET, cls.SECONDS_PER_DAY) daynum = week * cls.NUM_WEEKDAYS + weekday ...
Date/time object.
datetime
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class datetime: """Date/time object.""" def from_gps_week_sec(cls, week, second=0, nanosecond=0): """Create new datetime object from GPS week, second and nanosecond.""" <|body_0|> def gps_week_sec_nano(self, roundofs=0): """Get GPS week, second, and nanosecond from dat...
stack_v2_sparse_classes_75kplus_train_065039
3,139
no_license
[ { "docstring": "Create new datetime object from GPS week, second and nanosecond.", "name": "from_gps_week_sec", "signature": "def from_gps_week_sec(cls, week, second=0, nanosecond=0)" }, { "docstring": "Get GPS week, second, and nanosecond from datetime object.", "name": "gps_week_sec_nano",...
2
stack_v2_sparse_classes_30k_train_000002
Implement the Python class `datetime` described below. Class description: Date/time object. Method signatures and docstrings: - def from_gps_week_sec(cls, week, second=0, nanosecond=0): Create new datetime object from GPS week, second and nanosecond. - def gps_week_sec_nano(self, roundofs=0): Get GPS week, second, an...
Implement the Python class `datetime` described below. Class description: Date/time object. Method signatures and docstrings: - def from_gps_week_sec(cls, week, second=0, nanosecond=0): Create new datetime object from GPS week, second and nanosecond. - def gps_week_sec_nano(self, roundofs=0): Get GPS week, second, an...
1a6471dfbd7ec27f3d9f42b49173d18761a8f5aa
<|skeleton|> class datetime: """Date/time object.""" def from_gps_week_sec(cls, week, second=0, nanosecond=0): """Create new datetime object from GPS week, second and nanosecond.""" <|body_0|> def gps_week_sec_nano(self, roundofs=0): """Get GPS week, second, and nanosecond from dat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class datetime: """Date/time object.""" def from_gps_week_sec(cls, week, second=0, nanosecond=0): """Create new datetime object from GPS week, second and nanosecond.""" if week < 0: raise ValueError('Invalid week number') if second >= cls.SECONDS_PER_WEEK: raise ...
the_stack_v2_python_sparse
fwgnss/systems/xdatetime.py
fhgwright/fwgnss
train
2
ae6d48bd9082c413d186669848a66600f5efa740
[ "super(CriticModel, self).__init__()\nself.seed = torch.manual_seed(seed)\nself.fcs1 = nn.Linear(state_size, fc1_units)\nself.fc2 = nn.Linear(fc1_units + action_size, fc2_units)\nself.fc3 = nn.Linear(fc2_units, fc3_units)\nself.fc4 = nn.Linear(fc3_units, 1)", "xs = F.leaky_relu(self.fcs1(state))\nx = torch.cat((x...
<|body_start_0|> super(CriticModel, self).__init__() self.seed = torch.manual_seed(seed) self.fcs1 = nn.Linear(state_size, fc1_units) self.fc2 = nn.Linear(fc1_units + action_size, fc2_units) self.fc3 = nn.Linear(fc2_units, fc3_units) self.fc4 = nn.Linear(fc3_units, 1) <|e...
CriticModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CriticModel: def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128): """estimate Q value""" <|body_0|> def forward(self, state, action): """Params: input: [state, action]""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_75kplus_train_065040
2,012
no_license
[ { "docstring": "estimate Q value", "name": "__init__", "signature": "def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128)" }, { "docstring": "Params: input: [state, action]", "name": "forward", "signature": "def forward(self, state, action)" } ...
2
null
Implement the Python class `CriticModel` described below. Class description: Implement the CriticModel class. Method signatures and docstrings: - def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128): estimate Q value - def forward(self, state, action): Params: input: [state, ...
Implement the Python class `CriticModel` described below. Class description: Implement the CriticModel class. Method signatures and docstrings: - def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128): estimate Q value - def forward(self, state, action): Params: input: [state, ...
df85d6b4a22b7904c45139a358a606b92406cd1f
<|skeleton|> class CriticModel: def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128): """estimate Q value""" <|body_0|> def forward(self, state, action): """Params: input: [state, action]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CriticModel: def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=256, fc3_units=128): """estimate Q value""" super(CriticModel, self).__init__() self.seed = torch.manual_seed(seed) self.fcs1 = nn.Linear(state_size, fc1_units) self.fc2 = nn.Linear(...
the_stack_v2_python_sparse
DDPG/model.py
jiemingChen/RL
train
0
519d8d428a05e407267b3acf7b29ef3992a0bb32
[ "if matrix == [] or matrix[0] == []:\n return []\nrows = len(matrix)\ncolomns = len(matrix[0])\ntotal = rows * colomns\nvisitied = [[False] * colomns for _ in range(rows)]\nans = [0] * total\ndirections = [[0, 1], [1, 0], [0, -1], [-1, 0]]\ndirec_idx = 0\nrow, colomn = (0, 0)\nfor i in range(total):\n ans[i] ...
<|body_start_0|> if matrix == [] or matrix[0] == []: return [] rows = len(matrix) colomns = len(matrix[0]) total = rows * colomns visitied = [[False] * colomns for _ in range(rows)] ans = [0] * total directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def spiralOrder(self, matrix): """方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每个元素表示该位置 是否被访问过。当一个元素被访问时,将 visited extit{visited}visited 中的对应位置的元素设为已访问。 如何判断路径是否结束?由于矩阵中的每个元素都被...
stack_v2_sparse_classes_75kplus_train_065041
5,333
no_license
[ { "docstring": "方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每个元素表示该位置 是否被访问过。当一个元素被访问时,将 visited extit{visited}visited 中的对应位置的元素设为已访问。 如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路 径,将该路径...
2
stack_v2_sparse_classes_30k_train_007517
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def spiralOrder(self, matrix): 方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def spiralOrder(self, matrix): 方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每...
85f71621c54f6b0029f3a2746f022f89dd7419d9
<|skeleton|> class Solution: def spiralOrder(self, matrix): """方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每个元素表示该位置 是否被访问过。当一个元素被访问时,将 visited extit{visited}visited 中的对应位置的元素设为已访问。 如何判断路径是否结束?由于矩阵中的每个元素都被...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def spiralOrder(self, matrix): """方法一:模拟 可以模拟螺旋矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,则顺时针旋转,进入下一个方向。 判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited extit{visited}visited,其中的每个元素表示该位置 是否被访问过。当一个元素被访问时,将 visited extit{visited}visited 中的对应位置的元素设为已访问。 如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为...
the_stack_v2_python_sparse
LeetCode/Offer/顺时针打印矩阵.py
XyK0907/for_work
train
0
e7b347ad603ff2baca675f7b5c22c06d00aa1673
[ "self.repo_path = repo_path\nself.logger = logger\nself.secret = secret", "assert command and len(command)\ncommand = ['git'] + list(command)\nif self.logger:\n command_str = ' '.join(map(pipes.quote, command))\n if self.secret:\n command_str = command_str.replace(self.secret, 'xxx')\n self.logger...
<|body_start_0|> self.repo_path = repo_path self.logger = logger self.secret = secret <|end_body_0|> <|body_start_1|> assert command and len(command) command = ['git'] + list(command) if self.logger: command_str = ' '.join(map(pipes.quote, command)) ...
Helper class for running git commands
GitCommand
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GitCommand: """Helper class for running git commands""" def __init__(self, repo_path, secret=None): """:param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' wh...
stack_v2_sparse_classes_75kplus_train_065042
3,785
no_license
[ { "docstring": ":param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' when logging.", "name": "__init__", "signature": "def __init__(self, repo_path, secret=None)" }, { "d...
3
stack_v2_sparse_classes_30k_train_013153
Implement the Python class `GitCommand` described below. Class description: Helper class for running git commands Method signatures and docstrings: - def __init__(self, repo_path, secret=None): :param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. ...
Implement the Python class `GitCommand` described below. Class description: Helper class for running git commands Method signatures and docstrings: - def __init__(self, repo_path, secret=None): :param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. ...
8ef71a98892473434dbd903647a11b6903b3c92a
<|skeleton|> class GitCommand: """Helper class for running git commands""" def __init__(self, repo_path, secret=None): """:param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' wh...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GitCommand: """Helper class for running git commands""" def __init__(self, repo_path, secret=None): """:param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' when logging.""...
the_stack_v2_python_sparse
vcssync/mozvcssync/gitutil.py
mjzffr/version-control-tools
train
1
66c4659fd093b940f682fe026b124b960fad6512
[ "self.language = language\nself.compiler = language.get_compiler()\nself.plugin_stub = language.plugin_stub", "if not os.path.exists(self.language.get_build_directory()):\n os.makedirs(self.language.get_build_directory())\nif not os.path.exists(self.language.get_output_directory()):\n os.makedirs(self.langu...
<|body_start_0|> self.language = language self.compiler = language.get_compiler() self.plugin_stub = language.plugin_stub <|end_body_0|> <|body_start_1|> if not os.path.exists(self.language.get_build_directory()): os.makedirs(self.language.get_build_directory()) if n...
Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object
Builder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Builder: """Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object""" def __init__(self, language): """Constructor for Python Builder. Args: language: A Language object""" <|body_0|> def prep(self): """Performs any pre-co...
stack_v2_sparse_classes_75kplus_train_065043
1,494
no_license
[ { "docstring": "Constructor for Python Builder. Args: language: A Language object", "name": "__init__", "signature": "def __init__(self, language)" }, { "docstring": "Performs any pre-compile stage prep work for plugin.", "name": "prep", "signature": "def prep(self)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_045074
Implement the Python class `Builder` described below. Class description: Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object Method signatures and docstrings: - def __init__(self, language): Constructor for Python Builder. Args: language: A Language object - def prep(self)...
Implement the Python class `Builder` described below. Class description: Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object Method signatures and docstrings: - def __init__(self, language): Constructor for Python Builder. Args: language: A Language object - def prep(self)...
b3fd3ebb4f63957c0cb6a9f1577d8556dc554bda
<|skeleton|> class Builder: """Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object""" def __init__(self, language): """Constructor for Python Builder. Args: language: A Language object""" <|body_0|> def prep(self): """Performs any pre-co...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Builder: """Object which builds Python plugins. Attributes: plugin_stub: madz.plugin.PythonPluginStub object""" def __init__(self, language): """Constructor for Python Builder. Args: language: A Language object""" self.language = language self.compiler = language.get_compiler() ...
the_stack_v2_python_sparse
madz/language/python/build.py
OffByOneStudios/massive-dangerzone
train
0
90b61c67022ddea582804ac8952d825dac68f539
[ "items = []\nfilter_shared = request.GET.get('filter_shared', False)\nif request.GET.get('all_projects') == 'true':\n result = api.neutron.network_list(request, **request.GET)\n rest_utils.ensure_tenant_name(request, result)\n for item in result:\n item_dict = item.to_dict()\n if hasattr(item...
<|body_start_0|> items = [] filter_shared = request.GET.get('filter_shared', False) if request.GET.get('all_projects') == 'true': result = api.neutron.network_list(request, **request.GET) rest_utils.ensure_tenant_name(request, result) for item in result: ...
API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html
Networks
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Networks: """API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html""" def get(self, request): """Get a list of networks for a project The listing result is an object with property "items". Each item is a network.""" <|body_0|> def post(self, ...
stack_v2_sparse_classes_75kplus_train_065044
30,067
permissive
[ { "docstring": "Get a list of networks for a project The listing result is an object with property \"items\". Each item is a network.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a network :param admin_state_up (optional): The administrative state of the netwo...
2
stack_v2_sparse_classes_30k_train_040872
Implement the Python class `Networks` described below. Class description: API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html Method signatures and docstrings: - def get(self, request): Get a list of networks for a project The listing result is an object with property "items". Each item...
Implement the Python class `Networks` described below. Class description: API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html Method signatures and docstrings: - def get(self, request): Get a list of networks for a project The listing result is an object with property "items". Each item...
9524f1952461c83db485d5d1702c350b158d7ce0
<|skeleton|> class Networks: """API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html""" def get(self, request): """Get a list of networks for a project The listing result is an object with property "items". Each item is a network.""" <|body_0|> def post(self, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Networks: """API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html""" def get(self, request): """Get a list of networks for a project The listing result is an object with property "items". Each item is a network.""" items = [] filter_shared = request.G...
the_stack_v2_python_sparse
easystack_dashboard/api/rest/neutron.py
oksbsb/horizon-acc
train
0
001ede22b8ae447983de1d08f2d81ee5f4159f76
[ "super(Local, self).__init__()\nself.name = 'Local Storage'\nself._logger = logging.getLogger(__name__)\nself._path = ''\nself._filename = ''", "if not isinstance(data, dict):\n raise TypeError('incorrect data type to store, dict required')\nif not os.path.isfile(self._filename):\n with open(self._filename,...
<|body_start_0|> super(Local, self).__init__() self.name = 'Local Storage' self._logger = logging.getLogger(__name__) self._path = '' self._filename = '' <|end_body_0|> <|body_start_1|> if not isinstance(data, dict): raise TypeError('incorrect data type to st...
Storage API Provides abstract class for various storage options to implement as plugin to storage api
Local
[ "CC-BY-4.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Local: """Storage API Provides abstract class for various storage options to implement as plugin to storage api""" def __init__(self): """Initialization function""" <|body_0|> def store(self, data): """stores ``data``, ``data`` should be a dict :param data: dict ...
stack_v2_sparse_classes_75kplus_train_065045
3,869
permissive
[ { "docstring": "Initialization function", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "stores ``data``, ``data`` should be a dict :param data: dict object to store", "name": "store", "signature": "def store(self, data)" }, { "docstring": "Load all requ...
3
stack_v2_sparse_classes_30k_train_031782
Implement the Python class `Local` described below. Class description: Storage API Provides abstract class for various storage options to implement as plugin to storage api Method signatures and docstrings: - def __init__(self): Initialization function - def store(self, data): stores ``data``, ``data`` should be a di...
Implement the Python class `Local` described below. Class description: Storage API Provides abstract class for various storage options to implement as plugin to storage api Method signatures and docstrings: - def __init__(self): Initialization function - def store(self, data): stores ``data``, ``data`` should be a di...
4743d6120a9afe077e3666e3128e16808cb04c09
<|skeleton|> class Local: """Storage API Provides abstract class for various storage options to implement as plugin to storage api""" def __init__(self): """Initialization function""" <|body_0|> def store(self, data): """stores ``data``, ``data`` should be a dict :param data: dict ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Local: """Storage API Provides abstract class for various storage options to implement as plugin to storage api""" def __init__(self): """Initialization function""" super(Local, self).__init__() self.name = 'Local Storage' self._logger = logging.getLogger(__name__) ...
the_stack_v2_python_sparse
sdv/docker/sdvstate/tools/result_api/storage/local/local.py
adi0509/cirv-sdv
train
0
9c0b18fb5510ad478e35e98030b0a2faefea1264
[ "self.h = Heap()\nself.hash_map = {}\nself.ts_generator = 0\nself.cap = capacity", "if key in self.hash_map:\n self.hash_map[key].freq += 1\n self.hash_map[key].ts = self.ts_generator\n self.ts_generator += 1\n self.h.heapupdate(self.hash_map[key].idx)\n return self.hash_map[key].v\nelse:\n retu...
<|body_start_0|> self.h = Heap() self.hash_map = {} self.ts_generator = 0 self.cap = capacity <|end_body_0|> <|body_start_1|> if key in self.hash_map: self.hash_map[key].freq += 1 self.hash_map[key].ts = self.ts_generator self.ts_generator += ...
LFUCache
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: 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_065046
3,971
permissive
[ { "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
stack_v2_sparse_classes_30k_train_052796
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache 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 `LFUCache` described below. Class description: Implement the LFUCache 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...
fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f
<|skeleton|> class LFUCache: 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 LFUCache: def __init__(self, capacity): """:type capacity: int""" self.h = Heap() self.hash_map = {} self.ts_generator = 0 self.cap = capacity def get(self, key): """:type key: int :rtype: int""" if key in self.hash_map: self.hash_map[ke...
the_stack_v2_python_sparse
460.LFU-Cache.py
mickey0524/leetcode
train
27
dd4173abacb17f666c625341dd484862c3420e71
[ "if not isinstance(p, float):\n raise TypeError(f'Please pass float, not {type(p)}.')\nself._p = np.clip(p, 0.0, 1.0)", "verify_aligned_info(sequence)\naligned_seq, non_active_sites, active_sites, all_seqs = extract_active_sites_info(sequence)\norder = list(range(len(active_sites)))\nfor pos in range(len(order...
<|body_start_0|> if not isinstance(p, float): raise TypeError(f'Please pass float, not {type(p)}.') self._p = np.clip(p, 0.0, 1.0) <|end_body_0|> <|body_start_1|> verify_aligned_info(sequence) aligned_seq, non_active_sites, active_sites, all_seqs = extract_active_sites_info(...
Augment a protein sequence by randomly swapping neighboring subsequences.
ProteinAugmentSwapSubstrs
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProteinAugmentSwapSubstrs: """Augment a protein sequence by randomly swapping neighboring subsequences.""" def __init__(self, p: float=0.2) -> None: """Args: p (float): Probability that any substr switches places with its "neighbour".""" <|body_0|> def __call__(self, seq...
stack_v2_sparse_classes_75kplus_train_065047
11,629
permissive
[ { "docstring": "Args: p (float): Probability that any substr switches places with its \"neighbour\".", "name": "__init__", "signature": "def __init__(self, p: float=0.2) -> None" }, { "docstring": "Apply the transform. Args: sequence (str): an aligned sequence (example: abCDefGHi). Returns: str:...
2
stack_v2_sparse_classes_30k_train_000422
Implement the Python class `ProteinAugmentSwapSubstrs` described below. Class description: Augment a protein sequence by randomly swapping neighboring subsequences. Method signatures and docstrings: - def __init__(self, p: float=0.2) -> None: Args: p (float): Probability that any substr switches places with its "neig...
Implement the Python class `ProteinAugmentSwapSubstrs` described below. Class description: Augment a protein sequence by randomly swapping neighboring subsequences. Method signatures and docstrings: - def __init__(self, p: float=0.2) -> None: Args: p (float): Probability that any substr switches places with its "neig...
27ca3f8c5b5463cd081be5abdea04f5bfa076f39
<|skeleton|> class ProteinAugmentSwapSubstrs: """Augment a protein sequence by randomly swapping neighboring subsequences.""" def __init__(self, p: float=0.2) -> None: """Args: p (float): Probability that any substr switches places with its "neighbour".""" <|body_0|> def __call__(self, seq...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProteinAugmentSwapSubstrs: """Augment a protein sequence by randomly swapping neighboring subsequences.""" def __init__(self, p: float=0.2) -> None: """Args: p (float): Probability that any substr switches places with its "neighbour".""" if not isinstance(p, float): raise Type...
the_stack_v2_python_sparse
pytoda/proteins/transforms.py
PaccMann/paccmann_datasets
train
22
83e8f2578846eaf00ecb799a95af1d26ee238427
[ "self.all_smb_mount_paths = all_smb_mount_paths\nself.enable_filer_audit_log = enable_filer_audit_log\nself.enable_smb_encryption = enable_smb_encryption\nself.enable_smb_view_discovery = enable_smb_view_discovery\nself.enforce_smb_encryption = enforce_smb_encryption\nself.nfs_mount_path = nfs_mount_path\nself.path...
<|body_start_0|> self.all_smb_mount_paths = all_smb_mount_paths self.enable_filer_audit_log = enable_filer_audit_log self.enable_smb_encryption = enable_smb_encryption self.enable_smb_view_discovery = enable_smb_view_discovery self.enforce_smb_encryption = enforce_smb_encryption ...
Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be used to mount this Share as a SMB share. If Active Directory has multip...
Share
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Share: """Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be used to mount this Share as a SMB shar...
stack_v2_sparse_classes_75kplus_train_065048
7,179
permissive
[ { "docstring": "Constructor for the Share class", "name": "__init__", "signature": "def __init__(self, all_smb_mount_paths=None, enable_filer_audit_log=None, enable_smb_encryption=None, enable_smb_view_discovery=None, enforce_smb_encryption=None, nfs_mount_path=None, path=None, s3_access_path=None, shar...
2
null
Implement the Python class `Share` described below. Class description: Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be...
Implement the Python class `Share` described below. Class description: Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class Share: """Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be used to mount this Share as a SMB shar...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Share: """Implementation of the 'Share' model. Specifies the share details when request is made for list of shares filtered by ShareName parameter. Attributes: all_smb_mount_paths (list of string): Array of SMB Paths. Specifies the possible paths that can be used to mount this Share as a SMB share. If Active ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/share.py
cohesity/management-sdk-python
train
24
aa878c3ff2d54b82730fa2cf385a742cd5efb16e
[ "snap = super(ScrollArea, self).snapshot()\nsnap['horizontal_policy'] = self.horizontal_policy\nsnap['vertical_policy'] = self.vertical_policy\nsnap['widget_resizable'] = self.widget_resizable\nreturn snap", "super(ScrollArea, self).bind()\nattrs = ('horizontal_policy', 'vertical_policy', 'widget_resizable')\nsel...
<|body_start_0|> snap = super(ScrollArea, self).snapshot() snap['horizontal_policy'] = self.horizontal_policy snap['vertical_policy'] = self.vertical_policy snap['widget_resizable'] = self.widget_resizable return snap <|end_body_0|> <|body_start_1|> super(ScrollArea, sel...
A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget.
ScrollArea
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScrollArea: """A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget.""" def snapshot(self): """Return a dictionary which contains all the state necessary to initialize a client widget.""" <|body_0|> def bin...
stack_v2_sparse_classes_75kplus_train_065049
2,901
permissive
[ { "docstring": "Return a dictionary which contains all the state necessary to initialize a client widget.", "name": "snapshot", "signature": "def snapshot(self)" }, { "docstring": "Bind the change handlers for this widget.", "name": "bind", "signature": "def bind(self)" }, { "doc...
3
null
Implement the Python class `ScrollArea` described below. Class description: A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget. Method signatures and docstrings: - def snapshot(self): Return a dictionary which contains all the state necessary to initi...
Implement the Python class `ScrollArea` described below. Class description: A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget. Method signatures and docstrings: - def snapshot(self): Return a dictionary which contains all the state necessary to initi...
424bba29219de58fe9e47196de6763de8b2009f2
<|skeleton|> class ScrollArea: """A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget.""" def snapshot(self): """Return a dictionary which contains all the state necessary to initialize a client widget.""" <|body_0|> def bin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScrollArea: """A widget which displays a single child in a scrollable area. A ScrollArea has at most a single child Container widget.""" def snapshot(self): """Return a dictionary which contains all the state necessary to initialize a client widget.""" snap = super(ScrollArea, self).snaps...
the_stack_v2_python_sparse
enaml/widgets/scroll_area.py
enthought/enaml
train
17
2061194404c40d47ff3ad902b784e6df77e60d7f
[ "if not root:\n return 'x'\nreturn ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])", "self.data = input_data\nif self.data[0] == 'x':\n return None\nnode = TreeNode(self.data[:self.data.find(',')], None, None)\nnode.left = self.deserialize(self.data[self.data.find(',') + 1:]...
<|body_start_0|> if not root: return 'x' return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)]) <|end_body_0|> <|body_start_1|> self.data = input_data if self.data[0] == 'x': return None node = TreeNode(self.data[:self.dat...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, input_data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_75kplus_train_065050
4,141
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_047129
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, input_data): Decodes your encoded data to tree. :type data: str :...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, input_data): Decodes your encoded data to tree. :type data: str :...
c875ff69ed2b5dfaa5b2d7f37354456542f1ceea
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, input_data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return 'x' return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)]) def deserialize(self, input_data): """Dec...
the_stack_v2_python_sparse
DailyChallenge/LC_297.py
linxixu-1/Leetcode
train
0
cf559b5c0966fc31016507766b68fecc09144653
[ "self.app = QtWidgets.QApplication(sys.argv)\nself.set_color_theme(self.app, 'light')\nMainWindow = QtWidgets.QMainWindow()\nself.main_ui = Ui_Segmentation()\nself.main_ui.setupUi(MainWindow)\nself.source_dir_opener = FileDialog()\nself.main_ui.centralwidget.setFocusPolicy(Qt.NoFocus)\nself.main_app = MicroTomograp...
<|body_start_0|> self.app = QtWidgets.QApplication(sys.argv) self.set_color_theme(self.app, 'light') MainWindow = QtWidgets.QMainWindow() self.main_ui = Ui_Segmentation() self.main_ui.setupUi(MainWindow) self.source_dir_opener = FileDialog() self.main_ui.centralwi...
Main
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Main: def __init__(self): """Initializes program. Starts app, creates window and implements functions accessible via action bar.""" <|body_0|> def set_color_theme(self, app, color): """Set ui color scheme to either dark or bright Args: app: PyQt App the color scheme ...
stack_v2_sparse_classes_75kplus_train_065051
27,085
no_license
[ { "docstring": "Initializes program. Starts app, creates window and implements functions accessible via action bar.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Set ui color scheme to either dark or bright Args: app: PyQt App the color scheme is applied to color: St...
5
null
Implement the Python class `Main` described below. Class description: Implement the Main class. Method signatures and docstrings: - def __init__(self): Initializes program. Starts app, creates window and implements functions accessible via action bar. - def set_color_theme(self, app, color): Set ui color scheme to ei...
Implement the Python class `Main` described below. Class description: Implement the Main class. Method signatures and docstrings: - def __init__(self): Initializes program. Starts app, creates window and implements functions accessible via action bar. - def set_color_theme(self, app, color): Set ui color scheme to ei...
fb462691e14a650a0d55cd059721b13ece589105
<|skeleton|> class Main: def __init__(self): """Initializes program. Starts app, creates window and implements functions accessible via action bar.""" <|body_0|> def set_color_theme(self, app, color): """Set ui color scheme to either dark or bright Args: app: PyQt App the color scheme ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Main: def __init__(self): """Initializes program. Starts app, creates window and implements functions accessible via action bar.""" self.app = QtWidgets.QApplication(sys.argv) self.set_color_theme(self.app, 'light') MainWindow = QtWidgets.QMainWindow() self.main_ui = Ui...
the_stack_v2_python_sparse
segmentation_cpg/segmentation.py
elerator/capillary_effects_aluminum
train
0
cc2b11a5423c0a22227250d7864cb64f00955fb1
[ "self.filepath = bpy.path.abspath('//')\nself.current_filename = bpy.path.display_name_from_filepath(bpy.data.filepath)\nself.current_filename = current_filename.rsplit('.', 1)\nself.does_file_exist = None\nself.file_exists = True\nself.next_numeric = 0\nself.new_filename = ''\nself.new_suffix = ''\nself.non_numeri...
<|body_start_0|> self.filepath = bpy.path.abspath('//') self.current_filename = bpy.path.display_name_from_filepath(bpy.data.filepath) self.current_filename = current_filename.rsplit('.', 1) self.does_file_exist = None self.file_exists = True self.next_numeric = 0 ...
Save incremental version of file
SaveIncrementalFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SaveIncrementalFile: """Save incremental version of file""" def __init__(self): """Initialize""" <|body_0|> def execute(self): """Execute""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.filepath = bpy.path.abspath('//') self.current...
stack_v2_sparse_classes_75kplus_train_065052
44,083
no_license
[ { "docstring": "Initialize", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Execute", "name": "execute", "signature": "def execute(self)" } ]
2
stack_v2_sparse_classes_30k_train_041172
Implement the Python class `SaveIncrementalFile` described below. Class description: Save incremental version of file Method signatures and docstrings: - def __init__(self): Initialize - def execute(self): Execute
Implement the Python class `SaveIncrementalFile` described below. Class description: Save incremental version of file Method signatures and docstrings: - def __init__(self): Initialize - def execute(self): Execute <|skeleton|> class SaveIncrementalFile: """Save incremental version of file""" def __init__(se...
0788f00283d7c8c083aa5d554eb1f32c201adbd6
<|skeleton|> class SaveIncrementalFile: """Save incremental version of file""" def __init__(self): """Initialize""" <|body_0|> def execute(self): """Execute""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SaveIncrementalFile: """Save incremental version of file""" def __init__(self): """Initialize""" self.filepath = bpy.path.abspath('//') self.current_filename = bpy.path.display_name_from_filepath(bpy.data.filepath) self.current_filename = current_filename.rsplit('.', 1) ...
the_stack_v2_python_sparse
repos/blender_addons/internal/2.7.x/addon_customprops_preset.py
BlenderCN-Org/working_files
train
0
d192ee19acfa1fe7574c69fb686e5ffc6437a772
[ "self.destination_module_globals = globals()\nself.family = family\nif not isinstance(self.family, list) and (not isinstance(self.family, tuple)):\n self.family = [family]", "for family in self.family:\n new_klass, klass_name = self._create_interface(klass, family)\n self.destination_module_globals[klass...
<|body_start_0|> self.destination_module_globals = globals() self.family = family if not isinstance(self.family, list) and (not isinstance(self.family, tuple)): self.family = [family] <|end_body_0|> <|body_start_1|> for family in self.family: new_klass, klass_nam...
Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().
DeepLearningDecorator
[ "LicenseRef-scancode-cecill-b-en" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepLearningDecorator: """Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().""" def __init__(self, family): ...
stack_v2_sparse_classes_75kplus_train_065053
8,565
permissive
[ { "docstring": "Initialize the ValidationDecorator class. Parameters ---------- family: str or list of str the families associated to the network.", "name": "__init__", "signature": "def __init__(self, family)" }, { "docstring": "Create the validator. Parameters ---------- function: callable the...
3
stack_v2_sparse_classes_30k_train_019719
Implement the Python class `DeepLearningDecorator` described below. Class description: Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals(). ...
Implement the Python class `DeepLearningDecorator` described below. Class description: Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals(). ...
7a807ed690929563ce36086eaf0998d0e8856aea
<|skeleton|> class DeepLearningDecorator: """Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().""" def __init__(self, family): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeepLearningDecorator: """Decorator to determine the networks that need to be warped in the Deep Leanring interface environment. In order to make the class publicly accessible, we assign the result of the function to a variable dynamically using globals().""" def __init__(self, family): """Initia...
the_stack_v2_python_sparse
pynet/interfaces.py
Duplums/pynet
train
0
e34e31f941b5e0cb939b7b8e9a1e51d6a1af2a2c
[ "self.attributes = attributes\nself.end_of_range = end_of_range\nself.range_type = range_type\nself.start_of_range = start_of_range", "if dictionary is None:\n return None\nattributes = cohesity_management_sdk.models.oracle_archive_log_info_oracle_archive_log_range_range_attributes.OracleArchiveLogInfo_OracleA...
<|body_start_0|> self.attributes = attributes self.end_of_range = end_of_range self.range_type = range_type self.start_of_range = start_of_range <|end_body_0|> <|body_start_1|> if dictionary is None: return None attributes = cohesity_management_sdk.models.ora...
Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End value of the range range_type (int): Type of range provided. start_of_rang...
OracleArchiveLogInfo_OracleArchiveLogRange
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OracleArchiveLogInfo_OracleArchiveLogRange: """Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End valu...
stack_v2_sparse_classes_75kplus_train_065054
2,708
permissive
[ { "docstring": "Constructor for the OracleArchiveLogInfo_OracleArchiveLogRange class", "name": "__init__", "signature": "def __init__(self, attributes=None, end_of_range=None, range_type=None, start_of_range=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dict...
2
stack_v2_sparse_classes_30k_train_010143
Implement the Python class `OracleArchiveLogInfo_OracleArchiveLogRange` described below. Class description: Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description ...
Implement the Python class `OracleArchiveLogInfo_OracleArchiveLogRange` described below. Class description: Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class OracleArchiveLogInfo_OracleArchiveLogRange: """Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End valu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OracleArchiveLogInfo_OracleArchiveLogRange: """Implementation of the 'OracleArchiveLogInfo_OracleArchiveLogRange' model. TODO: type description here. Attributes: attributes (OracleArchiveLogInfo_OracleArchiveLogRange_RangeAttributes): TODO: Type description here. end_of_range (long|int): End value of the rang...
the_stack_v2_python_sparse
cohesity_management_sdk/models/oracle_archive_log_info_oracle_archive_log_range.py
cohesity/management-sdk-python
train
24
e47423e500ba0d60b033720a408bc2bd0fe7fb33
[ "super().__init__()\nself.out_channels = out_channels if out_channels is not None else in_channels\nmixer_name = mixer_kwargs['token_mixer']\nself.patch_embed = ContiguousEmbed(**embed_kwargs, flatten=not RESHAPE_LOOKUP[mixer_name])\nself.proj_dim = self.patch_embed.proj_dim\nself.mixer = TokenMixerBlock(**mixer_kw...
<|body_start_0|> super().__init__() self.out_channels = out_channels if out_channels is not None else in_channels mixer_name = mixer_kwargs['token_mixer'] self.patch_embed = ContiguousEmbed(**embed_kwargs, flatten=not RESHAPE_LOOKUP[mixer_name]) self.proj_dim = self.patch_embed.p...
MetaFormer
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetaFormer: def __init__(self, in_channels: int, embed_kwargs: Dict[str, Any], mixer_kwargs: Dict[str, Any], mlp_kwargs: Dict[str, Any], out_channels: int=None, layer_scale: bool=False, dropout: float=0.0, **kwargs) -> None: """Create a generic Metaformer block with any token-mixer avail...
stack_v2_sparse_classes_75kplus_train_065055
6,927
permissive
[ { "docstring": "Create a generic Metaformer block with any token-mixer available. Input shape: (B, in_channels, H, W) Output shape: (B, out_channels, H, W) Parameters ---------- in_channels : int Number of input channels. embed_kwargs : Dict[str, Any] Key-word arguments for the patch embedding block. mixer_kwar...
2
stack_v2_sparse_classes_30k_val_001089
Implement the Python class `MetaFormer` described below. Class description: Implement the MetaFormer class. Method signatures and docstrings: - def __init__(self, in_channels: int, embed_kwargs: Dict[str, Any], mixer_kwargs: Dict[str, Any], mlp_kwargs: Dict[str, Any], out_channels: int=None, layer_scale: bool=False, ...
Implement the Python class `MetaFormer` described below. Class description: Implement the MetaFormer class. Method signatures and docstrings: - def __init__(self, in_channels: int, embed_kwargs: Dict[str, Any], mixer_kwargs: Dict[str, Any], mlp_kwargs: Dict[str, Any], out_channels: int=None, layer_scale: bool=False, ...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class MetaFormer: def __init__(self, in_channels: int, embed_kwargs: Dict[str, Any], mixer_kwargs: Dict[str, Any], mlp_kwargs: Dict[str, Any], out_channels: int=None, layer_scale: bool=False, dropout: float=0.0, **kwargs) -> None: """Create a generic Metaformer block with any token-mixer avail...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetaFormer: def __init__(self, in_channels: int, embed_kwargs: Dict[str, Any], mixer_kwargs: Dict[str, Any], mlp_kwargs: Dict[str, Any], out_channels: int=None, layer_scale: bool=False, dropout: float=0.0, **kwargs) -> None: """Create a generic Metaformer block with any token-mixer available. Input sh...
the_stack_v2_python_sparse
cellseg_models_pytorch/modules/metaformer.py
okunator/cellseg_models.pytorch
train
43
b944d90d4784de8c2f92b8ac1bae26e5718db186
[ "super(jfcEncoderNet, self).__init__()\ndense = []\nfor i in range(num_layers):\n input_dim = np.product(in_dim) if i == 0 else hidden_dim\n dense.extend([nn.Linear(input_dim, hidden_dim), nn.Tanh()])\nself.dense = nn.Sequential(*dense)\nself.reshape_ = hidden_dim\nself.fc11 = nn.Linear(self.reshape_, latent_...
<|body_start_0|> super(jfcEncoderNet, self).__init__() dense = [] for i in range(num_layers): input_dim = np.product(in_dim) if i == 0 else hidden_dim dense.extend([nn.Linear(input_dim, hidden_dim), nn.Tanh()]) self.dense = nn.Sequential(*dense) self.resha...
Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by default) num_layers: number of NN layers...
jfcEncoderNet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class jfcEncoderNet: """Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by...
stack_v2_sparse_classes_75kplus_train_065056
28,462
permissive
[ { "docstring": "Initializes network parameters", "name": "__init__", "signature": "def __init__(self, in_dim: Tuple[int], latent_dim: int=2, discrete_dim: List=[1], num_layers: int=2, hidden_dim: int=32, **kwargs: bool) -> None" }, { "docstring": "Forward pass", "name": "forward", "signa...
2
stack_v2_sparse_classes_30k_train_041921
Implement the Python class `jfcEncoderNet` described below. Class description: Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent...
Implement the Python class `jfcEncoderNet` described below. Class description: Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent...
6d187296074143d017ca8fc60302364cd946b180
<|skeleton|> class jfcEncoderNet: """Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class jfcEncoderNet: """Encoder/inference network (for variational autoencoder) Args: in_dim: Input dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions (the first 3 latent dimensions are angle & translations by default) num...
the_stack_v2_python_sparse
atomai/nets/ed.py
pycroscopy/atomai
train
157
14111f31d02a5272747019078e08e245fbab4399
[ "log.msg('connectionLost')\nlog.err(reason)\nreactor.callLater(5, shutdown)", "defer = DBPOOL.runInteraction(real_parser, data)\ndefer.addCallback(write_memcache)\ndefer.addErrback(common.email_error, data)\ndefer.addErrback(log.err)" ]
<|body_start_0|> log.msg('connectionLost') log.err(reason) reactor.callLater(5, shutdown) <|end_body_0|> <|body_start_1|> defer = DBPOOL.runInteraction(real_parser, data) defer.addCallback(write_memcache) defer.addErrback(common.email_error, data) defer.addErrbac...
I receive products from ldmbridge and process them 1 by 1 :)
MyProductIngestor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyProductIngestor: """I receive products from ldmbridge and process them 1 by 1 :)""" def connectionLost(self, reason): """called when the connection is lost""" <|body_0|> def process_data(self, data): """Process the product""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_065057
3,601
permissive
[ { "docstring": "called when the connection is lost", "name": "connectionLost", "signature": "def connectionLost(self, reason)" }, { "docstring": "Process the product", "name": "process_data", "signature": "def process_data(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_044281
Implement the Python class `MyProductIngestor` described below. Class description: I receive products from ldmbridge and process them 1 by 1 :) Method signatures and docstrings: - def connectionLost(self, reason): called when the connection is lost - def process_data(self, data): Process the product
Implement the Python class `MyProductIngestor` described below. Class description: I receive products from ldmbridge and process them 1 by 1 :) Method signatures and docstrings: - def connectionLost(self, reason): called when the connection is lost - def process_data(self, data): Process the product <|skeleton|> cla...
e9ca4c4ad0a6e5a6e6479a84d86fd21ad2a0be00
<|skeleton|> class MyProductIngestor: """I receive products from ldmbridge and process them 1 by 1 :)""" def connectionLost(self, reason): """called when the connection is lost""" <|body_0|> def process_data(self, data): """Process the product""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyProductIngestor: """I receive products from ldmbridge and process them 1 by 1 :)""" def connectionLost(self, reason): """called when the connection is lost""" log.msg('connectionLost') log.err(reason) reactor.callLater(5, shutdown) def process_data(self, data): ...
the_stack_v2_python_sparse
parsers/afos_dump.py
xlia/pyWWA
train
0
5613767004b318d3177e27172d8585b4c7d3a669
[ "VoxelTimeSeries.__init__(self, overlay, overlayList, displayCtx, plotCanvas)\nself.parentTs = parentTs\nself.contrast = contrast\nself.fitType = fitType\nself.idx = idx", "opts = self.displayCtx.getOpts(self.overlay)\ncoords = opts.getVoxel()\nif coords is None:\n return None\nreturn self.overlay.partialFit(s...
<|body_start_0|> VoxelTimeSeries.__init__(self, overlay, overlayList, displayCtx, plotCanvas) self.parentTs = parentTs self.contrast = contrast self.fitType = fitType self.idx = idx <|end_body_0|> <|body_start_1|> opts = self.displayCtx.getOpts(self.overlay) coor...
A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.
FEATPartialFitTimeSeries
[ "Apache-2.0", "CC-BY-3.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FEATPartialFitTimeSeries: """A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.""" def __init__(self, overlay, overlayList, displayCtx...
stack_v2_sparse_classes_75kplus_train_065058
29,239
permissive
[ { "docstring": "Create a ``FEATPartialFitTimeSeries``. :arg overlay: The :class:`.FEATImage` instance to extract the data from. :arg overlayList: The :class:`.OverlayList` instance. :arg displayCtx: The :class:`.DisplayContext` instance. :arg plotCanvas: The :class:`TimeSeriesPanel` which owns this ``FEATPartia...
2
null
Implement the Python class `FEATPartialFitTimeSeries` described below. Class description: A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class. Method signatures a...
Implement the Python class `FEATPartialFitTimeSeries` described below. Class description: A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class. Method signatures a...
37b45d034d60660b6de3e4bdf5dd6349ed6d853b
<|skeleton|> class FEATPartialFitTimeSeries: """A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.""" def __init__(self, overlay, overlayList, displayCtx...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FEATPartialFitTimeSeries: """A :class:`VoxelTimeSeries` class which represents the partial model fit of an EV or contrast from a FEAT analysis at a specific voxel. Instances of this class are created by the :class:`FEATTimeSeries` class.""" def __init__(self, overlay, overlayList, displayCtx, plotCanvas,...
the_stack_v2_python_sparse
fsleyes/plotting/timeseries.py
CGSchwarzMayo/fsleyes
train
0
9796a40d6b3946ffeeb4989b72535ce12509c877
[ "super(HopeNet, self).__init__()\nself.inplanes = 64\nself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\nself.bn1 = nn.BatchNorm2d(64)\nself.relu = nn.ReLU(inplace=True)\nself.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\nself.layer1 = self._make_layer(block, 64, layers[0])...
<|body_start_0|> super(HopeNet, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1...
Implements HopeNet, used for estimating the head pose from media (images and videos).
HopeNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HopeNet: """Implements HopeNet, used for estimating the head pose from media (images and videos).""" def __init__(self, block, layers, n_bins): """Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of lay...
stack_v2_sparse_classes_75kplus_train_065059
9,784
no_license
[ { "docstring": "Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of layer sizes for each ``block`` object. n_bins : int The number of bins in the yaw, pitch, and roll outputs. Increase this number to have a finer estimate. Returns...
3
stack_v2_sparse_classes_30k_train_014650
Implement the Python class `HopeNet` described below. Class description: Implements HopeNet, used for estimating the head pose from media (images and videos). Method signatures and docstrings: - def __init__(self, block, layers, n_bins): Instantiates a HopeNet object used for estimating head pose from media. Paramete...
Implement the Python class `HopeNet` described below. Class description: Implements HopeNet, used for estimating the head pose from media (images and videos). Method signatures and docstrings: - def __init__(self, block, layers, n_bins): Instantiates a HopeNet object used for estimating head pose from media. Paramete...
a7c30481822ecb945e3ff6ad184d104361a40ed1
<|skeleton|> class HopeNet: """Implements HopeNet, used for estimating the head pose from media (images and videos).""" def __init__(self, block, layers, n_bins): """Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of lay...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HopeNet: """Implements HopeNet, used for estimating the head pose from media (images and videos).""" def __init__(self, block, layers, n_bins): """Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of layer sizes for ...
the_stack_v2_python_sparse
cheapfake/hopenet/models.py
hu-simon/cheapfake
train
0
fed2ef5e3435f98360094a247a05bcc1b7fade80
[ "super().__init__(self.PROBLEM_NAME)\nself.input_graph = input_graph\nself.source = source", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\ndistance = [float('Inf')] * self.input_graph.get_vertices_count()\ndistance[self.source] = 0\nadjacency_list = self.input_graph.get_adjacency_list()\nfor _ in ra...
<|body_start_0|> super().__init__(self.PROBLEM_NAME) self.input_graph = input_graph self.source = source <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) distance = [float('Inf')] * self.input_graph.get_vertices_count() distance[s...
ShortestPathBellmanFordAlgorithm
ShortestPathBellmanFordAlgorithm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShortestPathBellmanFordAlgorithm: """ShortestPathBellmanFordAlgorithm""" def __init__(self, input_graph, source): """Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths source: vertex Returns: None Raises: None""" <|b...
stack_v2_sparse_classes_75kplus_train_065060
2,813
no_license
[ { "docstring": "Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths source: vertex Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, input_graph, source)" }, { "docstring": "Solve the problem Note: O(VE) (...
2
stack_v2_sparse_classes_30k_train_008939
Implement the Python class `ShortestPathBellmanFordAlgorithm` described below. Class description: ShortestPathBellmanFordAlgorithm Method signatures and docstrings: - def __init__(self, input_graph, source): Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths...
Implement the Python class `ShortestPathBellmanFordAlgorithm` described below. Class description: ShortestPathBellmanFordAlgorithm Method signatures and docstrings: - def __init__(self, input_graph, source): Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class ShortestPathBellmanFordAlgorithm: """ShortestPathBellmanFordAlgorithm""" def __init__(self, input_graph, source): """Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths source: vertex Returns: None Raises: None""" <|b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ShortestPathBellmanFordAlgorithm: """ShortestPathBellmanFordAlgorithm""" def __init__(self, input_graph, source): """Compute Shortest Path (Bellman Ford's Algorithm) Args: input_graph: Graph for which to find the shortest paths source: vertex Returns: None Raises: None""" super().__init__...
the_stack_v2_python_sparse
python/problems/graphs/shortest_path_bellman_ford.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
9ad523a355f031dd2ff4c99b8e61cc6a9cdd1ec3
[ "super(Router, self).__init__()\nself.key_function = key_function\nself.routing_table = routing_table", "k = self.key_function(msg)\nkey = k[0] if isinstance(k, (tuple, list)) else k\nreturn self.routing_table[key]", "k = self.key_function(msg)\nif isinstance(k, (tuple, list)):\n key, args, kwargs = {1: tupl...
<|body_start_0|> super(Router, self).__init__() self.key_function = key_function self.routing_table = routing_table <|end_body_0|> <|body_start_1|> k = self.key_function(msg) key = k[0] if isinstance(k, (tuple, list)) else k return self.routing_table[key] <|end_body_1|> ...
Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler function.
Router
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Router: """Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler function.""" def __init__(self, key_func...
stack_v2_sparse_classes_75kplus_train_065061
40,889
permissive
[ { "docstring": ":param key_function: A function that takes one argument (the message) and returns one of the following: - a key to the routing table - a 1-tuple (key,) - a 2-tuple (key, (positional, arguments, ...)) - a 3-tuple (key, (positional, arguments, ...), {keyword: arguments, ...}) Extra arguments, if r...
3
stack_v2_sparse_classes_30k_train_032460
Implement the Python class `Router` described below. Class description: Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler functi...
Implement the Python class `Router` described below. Class description: Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler functi...
979ec1c7d50786939eb65ff779e3e03be950d595
<|skeleton|> class Router: """Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler function.""" def __init__(self, key_func...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Router: """Map a message to a handler function, using a **key function** and a **routing table** (dictionary). A *key function* digests a message down to a value. This value is treated as a key to the *routing table* to look up a corresponding handler function.""" def __init__(self, key_function, routing...
the_stack_v2_python_sparse
amanobot/helper.py
AmanoTeam/amanobot
train
25
1182017ca6457de74cef9da88f0af5c1d32bf68c
[ "if len(arr) == arr[-1]:\n return arr[-1] + k\ncnt = 0\nfor i in range(1, arr[-1]):\n if i not in arr:\n cnt += 1\n if cnt == k:\n return i\nreturn arr[-1] + (k - cnt)", "for i in range(len(arr)):\n distance = arr[i] - i\n if k < distance:\n return arr[i] - (distance - k)\nretu...
<|body_start_0|> if len(arr) == arr[-1]: return arr[-1] + k cnt = 0 for i in range(1, arr[-1]): if i not in arr: cnt += 1 if cnt == k: return i return arr[-1] + (k - cnt) <|end_body_0|> <|body_start_1|> for i in...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findKthPositive(self, arr, k): """:type arr: List[int] :type k: int :rtype: int""" <|body_0|> def findKthPositive(self, arr, k): """:type arr: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(ar...
stack_v2_sparse_classes_75kplus_train_065062
750
no_license
[ { "docstring": ":type arr: List[int] :type k: int :rtype: int", "name": "findKthPositive", "signature": "def findKthPositive(self, arr, k)" }, { "docstring": ":type arr: List[int] :type k: int :rtype: int", "name": "findKthPositive", "signature": "def findKthPositive(self, arr, k)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int - def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int - def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int <|skeleton|> ...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def findKthPositive(self, arr, k): """:type arr: List[int] :type k: int :rtype: int""" <|body_0|> def findKthPositive(self, arr, k): """:type arr: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findKthPositive(self, arr, k): """:type arr: List[int] :type k: int :rtype: int""" if len(arr) == arr[-1]: return arr[-1] + k cnt = 0 for i in range(1, arr[-1]): if i not in arr: cnt += 1 if cnt == k: ...
the_stack_v2_python_sparse
1539_Kth_Missing_Positive_Number.py
bingli8802/leetcode
train
0
f77b6a9e7797025c53c119de9cf16e45322e76a9
[ "url_parsing = urlparse(url)\nallowed = ['docs.google', 'onedrive.live', 'pdf']\nif url_parsing.scheme and url_parsing.netloc:\n if not any((match in url for match in allowed)):\n pass\nelse:\n return 0\nreturn 1", "now = datetime.datetime.now()\nif int(now.year) - int(date.year) < 0:\n return 0\n...
<|body_start_0|> url_parsing = urlparse(url) allowed = ['docs.google', 'onedrive.live', 'pdf'] if url_parsing.scheme and url_parsing.netloc: if not any((match in url for match in allowed)): pass else: return 0 return 1 <|end_body_0|> <|bod...
Validator for common fields of material model
MaterialValidator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaterialValidator: """Validator for common fields of material model""" def validate_material_link(cls, url): """Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url is either not valid or broken. -1 -> Provided url should ...
stack_v2_sparse_classes_75kplus_train_065063
1,681
permissive
[ { "docstring": "Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url is either not valid or broken. -1 -> Provided url should lead to pdf or doc file.", "name": "validate_material_link", "signature": "def validate_material_link(cls, url)" }...
2
null
Implement the Python class `MaterialValidator` described below. Class description: Validator for common fields of material model Method signatures and docstrings: - def validate_material_link(cls, url): Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url ...
Implement the Python class `MaterialValidator` described below. Class description: Validator for common fields of material model Method signatures and docstrings: - def validate_material_link(cls, url): Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url ...
70638c121ea85ff0e6a650c5f2641b0b3b04d6d0
<|skeleton|> class MaterialValidator: """Validator for common fields of material model""" def validate_material_link(cls, url): """Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url is either not valid or broken. -1 -> Provided url should ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MaterialValidator: """Validator for common fields of material model""" def validate_material_link(cls, url): """Validates material's link that it presents a vaild, pdf file not a broken url. 1 -> All is good. 0 -> Provided url is either not valid or broken. -1 -> Provided url should lead to pdf o...
the_stack_v2_python_sparse
cms/validators.py
Ibrahem3amer/bala7
train
0
2daa2037932cee130dc8a01ea030622a8b29e20d
[ "region = Region.query.filter_by(id=id).first()\nif region is None:\n return ({'message': 'Region does not exist'}, 404)\nreturn region_schema.dump(region)", "req = api.payload\nregion = Region.query.filter_by(id=id).first()\nif region is None:\n return ({'message': 'Region does not exist'}, 404)\ntry:\n ...
<|body_start_0|> region = Region.query.filter_by(id=id).first() if region is None: return ({'message': 'Region does not exist'}, 404) return region_schema.dump(region) <|end_body_0|> <|body_start_1|> req = api.payload region = Region.query.filter_by(id=id).first() ...
SingleRegion
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SingleRegion: def get(self, id): """Get Region by id""" <|body_0|> def put(self, id): """Update a Region""" <|body_1|> def delete(self, id): """Delete a Region by id""" <|body_2|> <|end_skeleton|> <|body_start_0|> region = Regio...
stack_v2_sparse_classes_75kplus_train_065064
3,943
no_license
[ { "docstring": "Get Region by id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update a Region", "name": "put", "signature": "def put(self, id)" }, { "docstring": "Delete a Region by id", "name": "delete", "signature": "def delete(self, id)" } ]
3
stack_v2_sparse_classes_30k_train_036834
Implement the Python class `SingleRegion` described below. Class description: Implement the SingleRegion class. Method signatures and docstrings: - def get(self, id): Get Region by id - def put(self, id): Update a Region - def delete(self, id): Delete a Region by id
Implement the Python class `SingleRegion` described below. Class description: Implement the SingleRegion class. Method signatures and docstrings: - def get(self, id): Get Region by id - def put(self, id): Update a Region - def delete(self, id): Delete a Region by id <|skeleton|> class SingleRegion: def get(self...
ae78fff9888b0f68d9403d7f65cba086dabb3802
<|skeleton|> class SingleRegion: def get(self, id): """Get Region by id""" <|body_0|> def put(self, id): """Update a Region""" <|body_1|> def delete(self, id): """Delete a Region by id""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SingleRegion: def get(self, id): """Get Region by id""" region = Region.query.filter_by(id=id).first() if region is None: return ({'message': 'Region does not exist'}, 404) return region_schema.dump(region) def put(self, id): """Update a Region""" ...
the_stack_v2_python_sparse
api/v1/regions.py
mythril-io/flask-api
train
0
99af2325f23ead0a1ce015fa615ae957c2d1d0e5
[ "orders_serializer = OrdersSerializer(data=request.data)\nif orders_serializer.is_valid():\n logging.debug('The order is valid with the data {}'.format(request.data))\n order_object = orders_serializer.save()\n json_response = json.dumps({'order_id': order_object.id}, separators=(':', ','))\n return Res...
<|body_start_0|> orders_serializer = OrdersSerializer(data=request.data) if orders_serializer.is_valid(): logging.debug('The order is valid with the data {}'.format(request.data)) order_object = orders_serializer.save() json_response = json.dumps({'order_id': order_ob...
This is the CRUD for Order models.
CRUDOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CRUDOrder: """This is the CRUD for Order models.""" def post(self, request, format=None): """Insert a order in a database""" <|body_0|> def get(self, request, format=None): """Get all orders in database""" <|body_1|> def delete(self, request, format=...
stack_v2_sparse_classes_75kplus_train_065065
2,875
no_license
[ { "docstring": "Insert a order in a database", "name": "post", "signature": "def post(self, request, format=None)" }, { "docstring": "Get all orders in database", "name": "get", "signature": "def get(self, request, format=None)" }, { "docstring": "Delete a order in the database",...
4
null
Implement the Python class `CRUDOrder` described below. Class description: This is the CRUD for Order models. Method signatures and docstrings: - def post(self, request, format=None): Insert a order in a database - def get(self, request, format=None): Get all orders in database - def delete(self, request, format=None...
Implement the Python class `CRUDOrder` described below. Class description: This is the CRUD for Order models. Method signatures and docstrings: - def post(self, request, format=None): Insert a order in a database - def get(self, request, format=None): Get all orders in database - def delete(self, request, format=None...
de3f616a28574816f4570b28ae9abb8fcd22188b
<|skeleton|> class CRUDOrder: """This is the CRUD for Order models.""" def post(self, request, format=None): """Insert a order in a database""" <|body_0|> def get(self, request, format=None): """Get all orders in database""" <|body_1|> def delete(self, request, format=...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CRUDOrder: """This is the CRUD for Order models.""" def post(self, request, format=None): """Insert a order in a database""" orders_serializer = OrdersSerializer(data=request.data) if orders_serializer.is_valid(): logging.debug('The order is valid with the data {}'.for...
the_stack_v2_python_sparse
tasker/Orders/views/order.py
Desenho-2018-2/Tasker
train
0
3a8b2cf6d3f36cfe05234b8088f2db3fb8254e99
[ "self._logger = logger\nself._no_run = False\nif not is_exe(exe_path):\n self._logger.error('No trim_quality script available (exiting)')\n sys.exit(1)\nself._exe_path = exe_path\nself.format = 'fastq'", "self.__build_cmd(infname, outdir)\nmsg = ['Running...', '\\t%s' % self._cmd]\nfor m in msg:\n self._...
<|body_start_0|> self._logger = logger self._no_run = False if not is_exe(exe_path): self._logger.error('No trim_quality script available (exiting)') sys.exit(1) self._exe_path = exe_path self.format = 'fastq' <|end_body_0|> <|body_start_1|> self....
Class for working with trim_quality
Trim_Quality
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trim_Quality: """Class for working with trim_quality""" def __init__(self, exe_path, logger): """Instantiate with location of executable""" <|body_0|> def run(self, infname, outdir): """Run trim_quality on the passed file""" <|body_1|> def __build_cm...
stack_v2_sparse_classes_75kplus_train_065066
3,597
permissive
[ { "docstring": "Instantiate with location of executable", "name": "__init__", "signature": "def __init__(self, exe_path, logger)" }, { "docstring": "Run trim_quality on the passed file", "name": "run", "signature": "def run(self, infname, outdir)" }, { "docstring": "Build a comma...
3
stack_v2_sparse_classes_30k_train_033833
Implement the Python class `Trim_Quality` described below. Class description: Class for working with trim_quality Method signatures and docstrings: - def __init__(self, exe_path, logger): Instantiate with location of executable - def run(self, infname, outdir): Run trim_quality on the passed file - def __build_cmd(se...
Implement the Python class `Trim_Quality` described below. Class description: Class for working with trim_quality Method signatures and docstrings: - def __init__(self, exe_path, logger): Instantiate with location of executable - def run(self, infname, outdir): Run trim_quality on the passed file - def __build_cmd(se...
a3c64198aad3709a5c4d969f48ae0af11fdc25db
<|skeleton|> class Trim_Quality: """Class for working with trim_quality""" def __init__(self, exe_path, logger): """Instantiate with location of executable""" <|body_0|> def run(self, infname, outdir): """Run trim_quality on the passed file""" <|body_1|> def __build_cm...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Trim_Quality: """Class for working with trim_quality""" def __init__(self, exe_path, logger): """Instantiate with location of executable""" self._logger = logger self._no_run = False if not is_exe(exe_path): self._logger.error('No trim_quality script available ...
the_stack_v2_python_sparse
metapy/pycits/seq_crumbs.py
peterthorpe5/public_scripts
train
35
fd13c3e8ec5c1d0a9671f41c60fd35fcc20f2be9
[ "node = self.generic_visit(node)\nif isinstance(node.func, ast.Name):\n fc_name = node.func.id\n new_name = fc_name\n integer = self.parse_integer.search(fc_name)\n if integer is not None:\n size = int(integer.groups()[0])\n new_name = 'ExprInt'\n node.func.id = new_name\n no...
<|body_start_0|> node = self.generic_visit(node) if isinstance(node.func, ast.Name): fc_name = node.func.id new_name = fc_name integer = self.parse_integer.search(fc_name) if integer is not None: size = int(integer.groups()[0]) ...
AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))
MiasmTransformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit...
stack_v2_sparse_classes_75kplus_train_065067
12,978
no_license
[ { "docstring": "iX(Y) -> ExprIntX(Y), 'X'(Y) -> ExprOp('X', Y), ('X' % Y)(Z) -> ExprOp('X' % Y, Z)", "name": "visit_Call", "signature": "def visit_Call(self, node)" }, { "docstring": "memX[Y] -> ExprMem(Y, X)", "name": "visit_Subscript", "signature": "def visit_Subscript(self, node)" }...
4
stack_v2_sparse_classes_30k_train_013439
Implement the Python class `MiasmTransformer` described below. Class description: AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.siz...
Implement the Python class `MiasmTransformer` described below. Class description: AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.siz...
b71431045339a2e031950d2f8d99bfce30a44e99
<|skeleton|> class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MiasmTransformer: """AST visitor translating DSL to Miasm expression memX[Y] -> ExprMem(Y, X) iX(Y) -> ExprIntX(Y) X if Y else Z -> ExprCond(Y, X, Z) 'X'(Y) -> ExprOp('X', Y) ('X' % Y)(Z) -> ExprOp('X' % Y, Z) {a, b} -> ExprCompose(((a, 0, a.size), (b, a.size, a.size + b.size)))""" def visit_Call(self, n...
the_stack_v2_python_sparse
miasm2/core/sembuilder.py
buptsseGJ/VulSeeker
train
97
92b7e85c3726232f52a212ba133965134926bb68
[ "try:\n from pynao import tddft_iter\nexcept ModuleNotFoundError as err:\n msg = 'running lrtddft with Siesta calculator requires pynao package'\n raise ModuleNotFoundError(msg) from err\nself.initialize = initialize\nself.lrtddft_params = kw\nself.tddft = None\nif 'iter_broadening' in self.lrtddft_params:...
<|body_start_0|> try: from pynao import tddft_iter except ModuleNotFoundError as err: msg = 'running lrtddft with Siesta calculator requires pynao package' raise ModuleNotFoundError(msg) from err self.initialize = initialize self.lrtddft_params = kw ...
Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)
SiestaLRTDDFT
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SiestaLRTDDFT: """Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)""" def __init__(self, in...
stack_v2_sparse_classes_75kplus_train_065068
6,483
no_license
[ { "docstring": "Parameters ---------- initialize: bool To initialize the tddft calculations before calculating the polarizability Can be useful to calculate multiple frequency range without the need to recalculate the kernel kw: dictionary keywords for the tddft_iter function from PyNAO", "name": "__init__"...
3
stack_v2_sparse_classes_30k_train_045978
Implement the Python class `SiestaLRTDDFT` described below. Class description: Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/referen...
Implement the Python class `SiestaLRTDDFT` described below. Class description: Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/referen...
6299b76c0504c5a7f7e94271aba9907a8ce77719
<|skeleton|> class SiestaLRTDDFT: """Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)""" def __init__(self, in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SiestaLRTDDFT: """Interface for linear response TDDFT for Siesta via [PyNAO](https://mbarbry.website.fr.to/pynao/doc/html/) When using PyNAO please cite the papers indicated at in the PyNAO [documentation](https://mbarbry.website.fr.to/pynao/doc/html/references.html)""" def __init__(self, initialize=Fals...
the_stack_v2_python_sparse
venv/Lib/site-packages/ase/calculators/siesta/siesta_lrtddft.py
Pratiksha1317/e-shop
train
0
2e52af42e6fbe8e48b25fb304ed057549e216a5e
[ "cursor = '0'\nwhile cursor != 0:\n cursor, data = await self.scan(cursor=cursor, match=match, count=count)\n for item in data:\n yield item", "cursor = '0'\nwhile cursor != 0:\n cursor, data = await self.sscan(name, cursor=cursor, match=match, count=count)\n for item in data:\n yield it...
<|body_start_0|> cursor = '0' while cursor != 0: cursor, data = await self.scan(cursor=cursor, match=match, count=count) for item in data: yield item <|end_body_0|> <|body_start_1|> cursor = '0' while cursor != 0: cursor, data = await ...
convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6
IterCommandMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IterCommandMixin: """convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6""" async def scan_iter(self, match=None, count=None): """Make an iterator using the SCAN command so that the client doesn't need to remember ...
stack_v2_sparse_classes_75kplus_train_065069
3,468
permissive
[ { "docstring": "Make an iterator using the SCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns", "name": "scan_iter", "signature": "async def scan_iter(self, match=None, c...
4
stack_v2_sparse_classes_30k_train_003474
Implement the Python class `IterCommandMixin` described below. Class description: convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6 Method signatures and docstrings: - async def scan_iter(self, match=None, count=None): Make an iterator using the ...
Implement the Python class `IterCommandMixin` described below. Class description: convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6 Method signatures and docstrings: - async def scan_iter(self, match=None, count=None): Make an iterator using the ...
3a7f80bf41bf9df6f9d4d97a2327368bcc1941cb
<|skeleton|> class IterCommandMixin: """convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6""" async def scan_iter(self, match=None, count=None): """Make an iterator using the SCAN command so that the client doesn't need to remember ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IterCommandMixin: """convenient function of scan iter, make it a class separately because yield can not be used in async function in Python3.6""" async def scan_iter(self, match=None, count=None): """Make an iterator using the SCAN command so that the client doesn't need to remember the cursor po...
the_stack_v2_python_sparse
aredis/commands/iter.py
DalavanCloud/aredis
train
1
3bc21c1ce1f351aec8aac44b3f4194ef74e94be0
[ "super(focal_loss, self).__init__()\nself.size_average = size_average\nif isinstance(alpha, list):\n assert len(alpha) == num_classes\n self.alpha = torch.Tensor(alpha)\nelse:\n assert alpha < 1\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += 1 - alpha\nself.ga...
<|body_start_0|> super(focal_loss, self).__init__() self.size_average = size_average if isinstance(alpha, list): assert len(alpha) == num_classes self.alpha = torch.Tensor(alpha) else: assert alpha < 1 self.alpha = torch.zeros(num_classes) ...
focal_loss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class focal_loss: def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): """focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样...
stack_v2_sparse_classes_75kplus_train_065070
12,665
no_license
[ { "docstring": "focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainnet中设置为2 :param num_classes: 类别数量 :param size_average: 损失计算方式,默认取均值", "name": "__...
2
stack_v2_sparse_classes_30k_train_046986
Implement the Python class `focal_loss` described below. Class description: Implement the focal_loss class. Method signatures and docstrings: - def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表...
Implement the Python class `focal_loss` described below. Class description: Implement the focal_loss class. Method signatures and docstrings: - def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表...
3d3e07974a8ba1ffb7c79765aaf37cdb435a611f
<|skeleton|> class focal_loss: def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): """focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class focal_loss: def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): """focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainn...
the_stack_v2_python_sparse
code_zjx_round2/model/model_axial.py
Waterbearbear/spark-competition
train
0
c704ba7e09d5b635926f3f81fe2620e89f8f5c84
[ "self.src = src\nself.dst = dst\nself.smtp = None\nself.default_message = 'Your post processsing job has completed successfully'\nself.default_status = 'SUCCEESS'", "if not msg:\n msg = self.default_message\nif not status:\n status = self.default_status\nself.smtp = smtplib.SMTP('localhost')\nmessage = MIME...
<|body_start_0|> self.src = src self.dst = dst self.smtp = None self.default_message = 'Your post processsing job has completed successfully' self.default_status = 'SUCCEESS' <|end_body_0|> <|body_start_1|> if not msg: msg = self.default_message if no...
A simple class for sending email
Mailer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" <|body_0|> def send(self, status=None...
stack_v2_sparse_classes_75kplus_train_065071
1,584
permissive
[ { "docstring": "Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address", "name": "__init__", "signature": "def __init__(self, src, dst)" }, { "docstring": "Send the email with contents = msg and subje...
2
stack_v2_sparse_classes_30k_train_048454
Implement the Python class `Mailer` described below. Class description: A simple class for sending email Method signatures and docstrings: - def __init__(self, src, dst): Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email addr...
Implement the Python class `Mailer` described below. Class description: A simple class for sending email Method signatures and docstrings: - def __init__(self, src, dst): Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email addr...
84110cab08f7897d1489a6dc925258580a5d2bff
<|skeleton|> class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" <|body_0|> def send(self, status=None...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" self.src = src self.dst = dst self.smtp...
the_stack_v2_python_sparse
processflow/lib/mailer.py
E3SM-Project/processflow
train
4
66fc6764c600ab9ad1a83a1a09c2a72f350c8f5a
[ "self.enable_logging = enable_logging\nself.user_emails = user_emails\nself._config_for_bp = False", "if self._config_for_bp:\n gca_model_monitoring = gca_model_monitoring_v1beta1\nelse:\n gca_model_monitoring = gca_model_monitoring_v1\nuser_email_alert_config = gca_model_monitoring.ModelMonitoringAlertConf...
<|body_start_0|> self.enable_logging = enable_logging self.user_emails = user_emails self._config_for_bp = False <|end_body_0|> <|body_start_1|> if self._config_for_bp: gca_model_monitoring = gca_model_monitoring_v1beta1 else: gca_model_monitoring = gca_m...
EmailAlertConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailAlertConfig: def __init__(self, user_emails: List[str]=[], enable_logging: Optional[bool]=False): """Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email addresses to send the alert to. enable_logging (bool): Optional. Defaults to False. Streams detected anomal...
stack_v2_sparse_classes_75kplus_train_065072
2,668
permissive
[ { "docstring": "Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email addresses to send the alert to. enable_logging (bool): Optional. Defaults to False. Streams detected anomalies to Cloud Logging. The anomalies will be put into json payload encoded from proto [google.cloud.aiplatform.logg...
2
stack_v2_sparse_classes_30k_train_033477
Implement the Python class `EmailAlertConfig` described below. Class description: Implement the EmailAlertConfig class. Method signatures and docstrings: - def __init__(self, user_emails: List[str]=[], enable_logging: Optional[bool]=False): Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email ad...
Implement the Python class `EmailAlertConfig` described below. Class description: Implement the EmailAlertConfig class. Method signatures and docstrings: - def __init__(self, user_emails: List[str]=[], enable_logging: Optional[bool]=False): Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email ad...
76b95b92c1d3b87c72d754d8c02b1bca652b9a27
<|skeleton|> class EmailAlertConfig: def __init__(self, user_emails: List[str]=[], enable_logging: Optional[bool]=False): """Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email addresses to send the alert to. enable_logging (bool): Optional. Defaults to False. Streams detected anomal...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EmailAlertConfig: def __init__(self, user_emails: List[str]=[], enable_logging: Optional[bool]=False): """Initializer for EmailAlertConfig. Args: user_emails (List[str]): The email addresses to send the alert to. enable_logging (bool): Optional. Defaults to False. Streams detected anomalies to Cloud L...
the_stack_v2_python_sparse
google/cloud/aiplatform/model_monitoring/alert.py
googleapis/python-aiplatform
train
418
71b4ba13e85dad5800089b4efe0d300d5185f144
[ "names = set()\nconnections = list()\nwith open(filename, 'r') as myfile:\n for line in myfile.readlines():\n con = line.strip().split(',')\n connections.append(con)\n names.add(con[0])\n names.add(con[1])\nself.names = sorted(list(names))\nn = len(self.names)\nself.n = n\nA = np.zero...
<|body_start_0|> names = set() connections = list() with open(filename, 'r') as myfile: for line in myfile.readlines(): con = line.strip().split(',') connections.append(con) names.add(con[0]) names.add(con[1]) se...
Predict links between nodes of a network.
LinkPredictor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkPredictor: """Predict links between nodes of a network.""" def __init__(self, filename='social_network.csv'): """Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data.""" <|body_0|>...
stack_v2_sparse_classes_75kplus_train_065073
6,778
no_license
[ { "docstring": "Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data.", "name": "__init__", "signature": "def __init__(self, filename='social_network.csv')" }, { "docstring": "Predict the next link, eithe...
3
stack_v2_sparse_classes_30k_train_044198
Implement the Python class `LinkPredictor` described below. Class description: Predict links between nodes of a network. Method signatures and docstrings: - def __init__(self, filename='social_network.csv'): Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The na...
Implement the Python class `LinkPredictor` described below. Class description: Predict links between nodes of a network. Method signatures and docstrings: - def __init__(self, filename='social_network.csv'): Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The na...
6e969de3a8337b0bd9bb4ba7abac722ab5c065ab
<|skeleton|> class LinkPredictor: """Predict links between nodes of a network.""" def __init__(self, filename='social_network.csv'): """Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data.""" <|body_0|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LinkPredictor: """Predict links between nodes of a network.""" def __init__(self, filename='social_network.csv'): """Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data.""" names = set() c...
the_stack_v2_python_sparse
Class/ACME_Volume_1-Python/DrazinInverse/drazin.py
scj1420/Class-Projects-Research
train
0
c0c6aea8e298c52e99e367bcb4a56fb04d49abbc
[ "super().__init__(task_params, num_shards)\nloss_fn_name = self.task_params.get('main_loss', None)\nif loss_fn_name is None:\n if self.dataset.meta_data['num_classes'] == 1:\n loss_fn_name = 'sigmoid_cross_entropy'\n else:\n loss_fn_name = 'categorical_cross_entropy'\nself.main_loss_fn = functoo...
<|body_start_0|> super().__init__(task_params, num_shards) loss_fn_name = self.task_params.get('main_loss', None) if loss_fn_name is None: if self.dataset.meta_data['num_classes'] == 1: loss_fn_name = 'sigmoid_cross_entropy' else: loss_fn_n...
Classification Task.
ClassificationTask
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassificationTask: """Classification Task.""" def __init__(self, task_params, num_shards): """Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_065074
44,080
permissive
[ { "docstring": "Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over.", "name": "__init__", "signature": "def __init__(self, task_params, num_shards)" }, { "docstring": "Calculates met...
3
stack_v2_sparse_classes_30k_train_038313
Implement the Python class `ClassificationTask` described below. Class description: Classification Task. Method signatures and docstrings: - def __init__(self, task_params, num_shards): Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of devi...
Implement the Python class `ClassificationTask` described below. Class description: Classification Task. Method signatures and docstrings: - def __init__(self, task_params, num_shards): Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of devi...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ClassificationTask: """Classification Task.""" def __init__(self, task_params, num_shards): """Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ClassificationTask: """Classification Task.""" def __init__(self, task_params, num_shards): """Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over.""" super().__init__(task_par...
the_stack_v2_python_sparse
gift/tasks/task.py
Jimmy-INL/google-research
train
1
1db7c70561305e5cfdb03827c0d88d10e90df498
[ "super().__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.ffn = point_wise_feed_forward_network(dm, hidden)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.dropout1 = tf.keras.layers.Dropout(drop_rate)\nself.dropou...
<|body_start_0|> super().__init__() self.mha = MultiHeadAttention(dm, h) self.ffn = point_wise_feed_forward_network(dm, hidden) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06) self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06) self.dro...
class Encoder
EncoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderBlock: """class Encoder""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Init""" <|body_0|> def call(self, x, training, mask=None): """call method""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__() self.mha ...
stack_v2_sparse_classes_75kplus_train_065075
8,707
no_license
[ { "docstring": "Init", "name": "__init__", "signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)" }, { "docstring": "call method", "name": "call", "signature": "def call(self, x, training, mask=None)" } ]
2
stack_v2_sparse_classes_30k_train_048527
Implement the Python class `EncoderBlock` described below. Class description: class Encoder Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Init - def call(self, x, training, mask=None): call method
Implement the Python class `EncoderBlock` described below. Class description: class Encoder Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Init - def call(self, x, training, mask=None): call method <|skeleton|> class EncoderBlock: """class Encoder""" def __init__(self,...
e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58
<|skeleton|> class EncoderBlock: """class Encoder""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Init""" <|body_0|> def call(self, x, training, mask=None): """call method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EncoderBlock: """class Encoder""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Init""" super().__init__() self.mha = MultiHeadAttention(dm, h) self.ffn = point_wise_feed_forward_network(dm, hidden) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilo...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
AndrewMiranda/holbertonschool-machine_learning-1
train
0
4c0cc5bfc4be026c8692210a441330302f70c42b
[ "\"\"\"在初始化冰激凌的属性\"\"\"\nsuper().__init__(restaurant_name, cuisine_type)\nself.flavors = ['酸甜', '草莓味', '芒果味', '西瓜味']", "displays = self.flavors\nprint('冰激凌的口味有:')\nfor a in displays:\n print(a)" ]
<|body_start_0|> """在初始化冰激凌的属性""" super().__init__(restaurant_name, cuisine_type) self.flavors = ['酸甜', '草莓味', '芒果味', '西瓜味'] <|end_body_0|> <|body_start_1|> displays = self.flavors print('冰激凌的口味有:') for a in displays: print(a) <|end_body_1|>
冰激凌小店的日常
IceCreamStand
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IceCreamStand: """冰激凌小店的日常""" def __init__(self, restaurant_name, cuisine_type): """初始化父类的属性""" <|body_0|> def display(self): """显示各种冰激凌""" <|body_1|> <|end_skeleton|> <|body_start_0|> """在初始化冰激凌的属性""" super().__init__(restaurant_name, c...
stack_v2_sparse_classes_75kplus_train_065076
1,650
no_license
[ { "docstring": "初始化父类的属性", "name": "__init__", "signature": "def __init__(self, restaurant_name, cuisine_type)" }, { "docstring": "显示各种冰激凌", "name": "display", "signature": "def display(self)" } ]
2
stack_v2_sparse_classes_30k_train_007958
Implement the Python class `IceCreamStand` described below. Class description: 冰激凌小店的日常 Method signatures and docstrings: - def __init__(self, restaurant_name, cuisine_type): 初始化父类的属性 - def display(self): 显示各种冰激凌
Implement the Python class `IceCreamStand` described below. Class description: 冰激凌小店的日常 Method signatures and docstrings: - def __init__(self, restaurant_name, cuisine_type): 初始化父类的属性 - def display(self): 显示各种冰激凌 <|skeleton|> class IceCreamStand: """冰激凌小店的日常""" def __init__(self, restaurant_name, cuisine_ty...
0e18c1711a07bd8583a9f74eacfb0b48b5a76216
<|skeleton|> class IceCreamStand: """冰激凌小店的日常""" def __init__(self, restaurant_name, cuisine_type): """初始化父类的属性""" <|body_0|> def display(self): """显示各种冰激凌""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IceCreamStand: """冰激凌小店的日常""" def __init__(self, restaurant_name, cuisine_type): """初始化父类的属性""" """在初始化冰激凌的属性""" super().__init__(restaurant_name, cuisine_type) self.flavors = ['酸甜', '草莓味', '芒果味', '西瓜味'] def display(self): """显示各种冰激凌""" displays = self...
the_stack_v2_python_sparse
Python_World/9-6.py
qyl1006/MyGitHub
train
0
b723536260d0739ea6a1b67fc29f591d07cd3c5f
[ "super().__init__()\nself.receiver = RCReceiver(read_pin_config(mock_bbio=mock_bbio))\nself.keep_reading = True\nself.read_interval = read_interval()", "while True:\n self.receiver.send_inputs()\n sleep(self.read_interval)" ]
<|body_start_0|> super().__init__() self.receiver = RCReceiver(read_pin_config(mock_bbio=mock_bbio)) self.keep_reading = True self.read_interval = read_interval() <|end_body_0|> <|body_start_1|> while True: self.receiver.send_inputs() sleep(self.read_inte...
A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.
RCInputThread
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RCInputThread: """A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.""" def __init__(self, mock_bbio=None): """Builds a new RC input thread.""...
stack_v2_sparse_classes_75kplus_train_065077
849
permissive
[ { "docstring": "Builds a new RC input thread.", "name": "__init__", "signature": "def __init__(self, mock_bbio=None)" }, { "docstring": "Starts a regular input read interval.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_003988
Implement the Python class `RCInputThread` described below. Class description: A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension. Method signatures and docstrings: - def __init...
Implement the Python class `RCInputThread` described below. Class description: A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension. Method signatures and docstrings: - def __init...
b5d75cb82e4bc3e9c4e428a288c6ac98a4aa2c52
<|skeleton|> class RCInputThread: """A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.""" def __init__(self, mock_bbio=None): """Builds a new RC input thread.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RCInputThread: """A separate thread to manage reading the RC inputs and broadcasting the data to the system. Should accept multiple boat configurations, and should be general enough to allow for easy extension.""" def __init__(self, mock_bbio=None): """Builds a new RC input thread.""" sup...
the_stack_v2_python_sparse
src/rc_input/rc_input_thread.py
vt-sailbot/sailbot-21
train
5
eef5af9c32764e1c1601a983e0d6fb66b5681b91
[ "super().__init__(**kwargs)\nself.factory = factory\nself.activity = activity", "challenge_translations = self.get_yaml_translations(CHALLENGES_FILENAME, required_fields=['question'])\nfor challenge_order_number, challenge_data in challenge_translations.items():\n translations = self.get_blank_translation_dict...
<|body_start_0|> super().__init__(**kwargs) self.factory = factory self.activity = activity <|end_body_0|> <|body_start_1|> challenge_translations = self.get_yaml_translations(CHALLENGES_FILENAME, required_fields=['question']) for challenge_order_number, challenge_data in challe...
Custom loader for loading activity challenges.
ChallengeLoader
[ "LicenseRef-scancode-secret-labs-2011", "MIT", "OFL-1.1", "LGPL-2.0-or-later", "AGPL-3.0-only", "CC-BY-4.0", "Apache-2.0", "BSD-3-Clause", "CC-BY-SA-4.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChallengeLoader: """Custom loader for loading activity challenges.""" def __init__(self, factory, activity, **kwargs): """Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). activty: Object of related activity m...
stack_v2_sparse_classes_75kplus_train_065078
2,892
permissive
[ { "docstring": "Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). activty: Object of related activity model (Activity).", "name": "__init__", "signature": "def __init__(self, factory, activity, **kwargs)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_val_001879
Implement the Python class `ChallengeLoader` described below. Class description: Custom loader for loading activity challenges. Method signatures and docstrings: - def __init__(self, factory, activity, **kwargs): Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loade...
Implement the Python class `ChallengeLoader` described below. Class description: Custom loader for loading activity challenges. Method signatures and docstrings: - def __init__(self, factory, activity, **kwargs): Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loade...
363e281ff17cefdef0ec61078b1718eef2eaf71a
<|skeleton|> class ChallengeLoader: """Custom loader for loading activity challenges.""" def __init__(self, factory, activity, **kwargs): """Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). activty: Object of related activity m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ChallengeLoader: """Custom loader for loading activity challenges.""" def __init__(self, factory, activity, **kwargs): """Create the loader for loading activity challenges. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). activty: Object of related activity model (Activit...
the_stack_v2_python_sparse
csunplugged/at_home/management/commands/_ChallengeLoader.py
uccser/cs-unplugged
train
200
e38b23625f8c0e790bd69312e37441d8b1528afe
[ "super(MacAppFirewallParser, self).__init__()\nself._last_month = 0\nself._previous_structure = None\nself._year_use = 0", "time_elements_tuple = self._GetValueFromStructure(structure, 'date_time')\nmonth, day, hours, minutes, seconds = time_elements_tuple\nmonth = timelib.MONTH_DICT.get(month.lower(), 0)\nif mon...
<|body_start_0|> super(MacAppFirewallParser, self).__init__() self._last_month = 0 self._previous_structure = None self._year_use = 0 <|end_body_0|> <|body_start_1|> time_elements_tuple = self._GetValueFromStructure(structure, 'date_time') month, day, hours, minutes, sec...
Parser for MacOS Application firewall log (appfirewall.log) files.
MacAppFirewallParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MacAppFirewallParser: """Parser for MacOS Application firewall log (appfirewall.log) files.""" def __init__(self): """Initializes a parser.""" <|body_0|> def _GetTimeElementsTuple(self, structure): """Retrieves a time elements tuple from the structure. Args: stru...
stack_v2_sparse_classes_75kplus_train_065079
8,331
permissive
[ { "docstring": "Initializes a parser.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Retrieves a time elements tuple from the structure. Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Returns: tuple: containing: year ...
5
null
Implement the Python class `MacAppFirewallParser` described below. Class description: Parser for MacOS Application firewall log (appfirewall.log) files. Method signatures and docstrings: - def __init__(self): Initializes a parser. - def _GetTimeElementsTuple(self, structure): Retrieves a time elements tuple from the ...
Implement the Python class `MacAppFirewallParser` described below. Class description: Parser for MacOS Application firewall log (appfirewall.log) files. Method signatures and docstrings: - def __init__(self): Initializes a parser. - def _GetTimeElementsTuple(self, structure): Retrieves a time elements tuple from the ...
c69b2952b608cfce47ff8fd0d1409d856be35cb1
<|skeleton|> class MacAppFirewallParser: """Parser for MacOS Application firewall log (appfirewall.log) files.""" def __init__(self): """Initializes a parser.""" <|body_0|> def _GetTimeElementsTuple(self, structure): """Retrieves a time elements tuple from the structure. Args: stru...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MacAppFirewallParser: """Parser for MacOS Application firewall log (appfirewall.log) files.""" def __init__(self): """Initializes a parser.""" super(MacAppFirewallParser, self).__init__() self._last_month = 0 self._previous_structure = None self._year_use = 0 ...
the_stack_v2_python_sparse
plaso/parsers/mac_appfirewall.py
cyb3rfox/plaso
train
3
96d4e8f8ac1033e53caf9f17c9320fa125744395
[ "threading.Thread.__init__(self)\nself.client: socket.socket = client\nself.address = address", "request = self.client.recv(1024)\ntry:\n request = Request.decode(request)\nexcept:\n response = Response(status=400)\nelse:\n response = self.respond(request)\nself.client.send(response.encode())\nself.clien...
<|body_start_0|> threading.Thread.__init__(self) self.client: socket.socket = client self.address = address <|end_body_0|> <|body_start_1|> request = self.client.recv(1024) try: request = Request.decode(request) except: response = Response(status=...
ServerThread
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerThread: def __init__(self, client, address): """Constructor""" <|body_0|> def run(self): """Serve client's request.""" <|body_1|> def respond(self, request: Request) -> Response: """Respond to a HTTP request. :param request: The request. :r...
stack_v2_sparse_classes_75kplus_train_065080
7,546
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, client, address)" }, { "docstring": "Serve client's request.", "name": "run", "signature": "def run(self)" }, { "docstring": "Respond to a HTTP request. :param request: The request. :return: The co...
3
null
Implement the Python class `ServerThread` described below. Class description: Implement the ServerThread class. Method signatures and docstrings: - def __init__(self, client, address): Constructor - def run(self): Serve client's request. - def respond(self, request: Request) -> Response: Respond to a HTTP request. :p...
Implement the Python class `ServerThread` described below. Class description: Implement the ServerThread class. Method signatures and docstrings: - def __init__(self, client, address): Constructor - def run(self): Serve client's request. - def respond(self, request: Request) -> Response: Respond to a HTTP request. :p...
aad20f17ab99f86fb30dbc1f4d13ce5fab6633d2
<|skeleton|> class ServerThread: def __init__(self, client, address): """Constructor""" <|body_0|> def run(self): """Serve client's request.""" <|body_1|> def respond(self, request: Request) -> Response: """Respond to a HTTP request. :param request: The request. :r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServerThread: def __init__(self, client, address): """Constructor""" threading.Thread.__init__(self) self.client: socket.socket = client self.address = address def run(self): """Serve client's request.""" request = self.client.recv(1024) try: ...
the_stack_v2_python_sparse
CSCI_4760/pj01/web_server.py
dsluo-archive/notes
train
0
59285e5510e2cefdddc5a6a1d28d19b35b5559c6
[ "self.entity_description = description\nself._tc_object = tc_object\nself._update_devices = update_devices\nself._attr_name = f'{tc_object.name} {description.name}'", "self._update_devices()\nsensor_type = self.entity_description.key\nif sensor_type == 'battery':\n self._attr_native_value = self._tc_object.bat...
<|body_start_0|> self.entity_description = description self._tc_object = tc_object self._update_devices = update_devices self._attr_name = f'{tc_object.name} {description.name}' <|end_body_0|> <|body_start_1|> self._update_devices() sensor_type = self.entity_description....
Representation of a ThinkingCleaner Sensor.
ThinkingCleanerSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" <|body_0|> def update(self) -> None: """Update the sensor."...
stack_v2_sparse_classes_75kplus_train_065081
3,910
permissive
[ { "docstring": "Initialize the ThinkingCleaner.", "name": "__init__", "signature": "def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None" }, { "docstring": "Update the sensor.", "name": "update", "signature": "def update(self) -> None" } ]
2
stack_v2_sparse_classes_30k_train_031553
Implement the Python class `ThinkingCleanerSensor` described below. Class description: Representation of a ThinkingCleaner Sensor. Method signatures and docstrings: - def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner. - def update(self) -> None...
Implement the Python class `ThinkingCleanerSensor` described below. Class description: Representation of a ThinkingCleaner Sensor. Method signatures and docstrings: - def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner. - def update(self) -> None...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" <|body_0|> def update(self) -> None: """Update the sensor."...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThinkingCleanerSensor: """Representation of a ThinkingCleaner Sensor.""" def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: """Initialize the ThinkingCleaner.""" self.entity_description = description self._tc_object = tc_object sel...
the_stack_v2_python_sparse
homeassistant/components/thinkingcleaner/sensor.py
home-assistant/core
train
35,501
df0c8cf3c3c37c68ee71c47f57af1675f15ec9dc
[ "args = args or {}\nkwargs = kwargs or {}\ncall_args = getcallargs(self.run, *args, **kwargs)\nif isinstance(call_args.get('self'), celery.Task):\n del call_args['self']\nkeys = sorted(self.mutex_lock_keys) if type(self.mutex_lock_keys) is list else [self.mutex_lock_keys]\naccum = []\nfor key in keys:\n accum...
<|body_start_0|> args = args or {} kwargs = kwargs or {} call_args = getcallargs(self.run, *args, **kwargs) if isinstance(call_args.get('self'), celery.Task): del call_args['self'] keys = sorted(self.mutex_lock_keys) if type(self.mutex_lock_keys) is list else [self.mu...
Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of exceptions that would finish the schedule after the task returns. mutex_max_exec_time...
RepeatableMutexTask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RepeatableMutexTask: """Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of exceptions that would finish the sched...
stack_v2_sparse_classes_75kplus_train_065082
12,527
no_license
[ { "docstring": "Build a lock key based on the task name and its arguments", "name": "get_key", "signature": "def get_key(self, args, kwargs)" }, { "docstring": "Lock the given redis key, making another instances of the task with the same arguments unable to run. If the lock already exists, excep...
5
null
Implement the Python class `RepeatableMutexTask` described below. Class description: Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of...
Implement the Python class `RepeatableMutexTask` described below. Class description: Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of...
d2366c4a22a83ef28f008520f862a2f2cd8a29c6
<|skeleton|> class RepeatableMutexTask: """Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of exceptions that would finish the sched...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RepeatableMutexTask: """Represents repeatable task that can be run only once. Any additional calls to the task would be rejected. Class-wise arguments: continue_exceptions -- Set of exceptions that shouldn't break the schedule. terminate_exceptions -- Set of exceptions that would finish the schedule after the...
the_stack_v2_python_sparse
source/matrix_bot/tasks.py
a13xmt/matrixstats.org
train
8
0b906215988f6c1c66143f05efc138ea77e4a0c8
[ "album_list = []\nmethod_uri = '/getalbums/{{service_token}}/' + library_id\nif include_inactive:\n method_uri += '/IncludeInactive'\nxml_root = _client.get_xml(method_uri)\nalbums = xml_root.find('albums').getchildren()\nfor album_element in albums:\n album = Album._from_xml(album_element, _client=_client)\n...
<|body_start_0|> album_list = [] method_uri = '/getalbums/{{service_token}}/' + library_id if include_inactive: method_uri += '/IncludeInactive' xml_root = _client.get_xml(method_uri) albums = xml_root.find('albums').getchildren() for album_element in albums: ...
Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query`
AlbumQuery
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlbumQuery: """Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query`""" def get_albums_for_library(self, library_id, _client, include_inactive=False): """Gets all of the albums for a particular library. :par...
stack_v2_sparse_classes_75kplus_train_065083
3,756
permissive
[ { "docstring": "Gets all of the albums for a particular library. :param library_id: The Harvest Media library identifer :param _client: An initialized instance of :class:`harvestmedia.api.client.Client`", "name": "get_albums_for_library", "signature": "def get_albums_for_library(self, library_id, _clien...
2
stack_v2_sparse_classes_30k_train_019043
Implement the Python class `AlbumQuery` described below. Class description: Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query` Method signatures and docstrings: - def get_albums_for_library(self, library_id, _client, include_inactive=Fals...
Implement the Python class `AlbumQuery` described below. Class description: Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query` Method signatures and docstrings: - def get_albums_for_library(self, library_id, _client, include_inactive=Fals...
f2aa8d4b4296fefdc5b66905d22c8fe7de970dd8
<|skeleton|> class AlbumQuery: """Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query`""" def get_albums_for_library(self, library_id, _client, include_inactive=False): """Gets all of the albums for a particular library. :par...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlbumQuery: """Performs calls for the :class:`Album` model, also useful in a static context. Available at `Album.query` or `album_instance.query`""" def get_albums_for_library(self, library_id, _client, include_inactive=False): """Gets all of the albums for a particular library. :param library_id...
the_stack_v2_python_sparse
harvestmedia/api/album.py
ralfonso/harvestmedia
train
1
e5f1d88083142ba4c6047d8dfdb5e94c92dc5330
[ "super(SmallUpSampler, self).__init__()\nself.conv = conv(n_feats, upsize * upsize * n_feats, 3, has_bias)\nself.reshape = P.Reshape()\nself.upsize = upsize\nself.pixelsf = _pixelsf_", "x = self.conv(x)\noutput = self.pixelsf(x, self.upsize)\nreturn output" ]
<|body_start_0|> super(SmallUpSampler, self).__init__() self.conv = conv(n_feats, upsize * upsize * n_feats, 3, has_bias) self.reshape = P.Reshape() self.upsize = upsize self.pixelsf = _pixelsf_ <|end_body_0|> <|body_start_1|> x = self.conv(x) output = self.pixel...
edsr
SmallUpSampler
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmallUpSampler: """edsr""" def __init__(self, conv, upsize, n_feats, has_bias=True): """edsr""" <|body_0|> def construct(self, x): """edsr""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(SmallUpSampler, self).__init__() self.conv =...
stack_v2_sparse_classes_75kplus_train_065084
5,893
permissive
[ { "docstring": "edsr", "name": "__init__", "signature": "def __init__(self, conv, upsize, n_feats, has_bias=True)" }, { "docstring": "edsr", "name": "construct", "signature": "def construct(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_053866
Implement the Python class `SmallUpSampler` described below. Class description: edsr Method signatures and docstrings: - def __init__(self, conv, upsize, n_feats, has_bias=True): edsr - def construct(self, x): edsr
Implement the Python class `SmallUpSampler` described below. Class description: edsr Method signatures and docstrings: - def __init__(self, conv, upsize, n_feats, has_bias=True): edsr - def construct(self, x): edsr <|skeleton|> class SmallUpSampler: """edsr""" def __init__(self, conv, upsize, n_feats, has_b...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class SmallUpSampler: """edsr""" def __init__(self, conv, upsize, n_feats, has_bias=True): """edsr""" <|body_0|> def construct(self, x): """edsr""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SmallUpSampler: """edsr""" def __init__(self, conv, upsize, n_feats, has_bias=True): """edsr""" super(SmallUpSampler, self).__init__() self.conv = conv(n_feats, upsize * upsize * n_feats, 3, has_bias) self.reshape = P.Reshape() self.upsize = upsize self.pix...
the_stack_v2_python_sparse
research/cv/csd/src/edsr_model.py
mindspore-ai/models
train
301
de2c7fe33201066931f0976c53c663619b00fe22
[ "self.port = config['logging']['port'] or logging.handlers.DEFAULT_TCP_LOGGING_PORT\nself.host = 'localhost'\nself.config = config\nself.multi = multi", "if self.multi:\n logger = MultiFileLogger(self.config)\nelse:\n logger = SingleFileLogger(self.config, 'mistamover')\ntcpserver = LogReceiver.LogRecordSoc...
<|body_start_0|> self.port = config['logging']['port'] or logging.handlers.DEFAULT_TCP_LOGGING_PORT self.host = 'localhost' self.config = config self.multi = multi <|end_body_0|> <|body_start_1|> if self.multi: logger = MultiFileLogger(self.config) else: ...
A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger
LoggerServer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoggerServer: """A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger""" def __init__(self, config, multi=True): """instantiate with GlobalConfig / DatasetConfig object set "multi" to True/False depending whether...
stack_v2_sparse_classes_75kplus_train_065085
5,340
permissive
[ { "docstring": "instantiate with GlobalConfig / DatasetConfig object set \"multi\" to True/False depending whether single file or multi file logging is wanted", "name": "__init__", "signature": "def __init__(self, config, multi=True)" }, { "docstring": "Main loop.", "name": "serve", "sig...
2
stack_v2_sparse_classes_30k_train_006383
Implement the Python class `LoggerServer` described below. Class description: A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger Method signatures and docstrings: - def __init__(self, config, multi=True): instantiate with GlobalConfig / Dataset...
Implement the Python class `LoggerServer` described below. Class description: A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger Method signatures and docstrings: - def __init__(self, config, multi=True): instantiate with GlobalConfig / Dataset...
37ad31c4c66658c4c77340efc783040f94df3f3f
<|skeleton|> class LoggerServer: """A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger""" def __init__(self, config, multi=True): """instantiate with GlobalConfig / DatasetConfig object set "multi" to True/False depending whether...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LoggerServer: """A top level logger server, which will receive messages on a port and pass them to either SingleFileLogger or MultiFileLogger""" def __init__(self, config, multi=True): """instantiate with GlobalConfig / DatasetConfig object set "multi" to True/False depending whether single file ...
the_stack_v2_python_sparse
lib/LoggerServer.py
cedadev/mistamover
train
0
58781760828835a42cfa4ecf36cc6f3df265ab28
[ "html = helpers.get_content(url)\nif not html:\n return None\nsoup = BeautifulSoup(html)\na = soup.find('title')\nk = a.text.split('-')\nheadline = k[0]\ndate = k[1]\nc = soup.findAll('p', attrs={'class': 'zn-body__paragraph'})\nbody = ''\nfor paragraph in c:\n try:\n body += paragraph.text.decode('utf...
<|body_start_0|> html = helpers.get_content(url) if not html: return None soup = BeautifulSoup(html) a = soup.find('title') k = a.text.split('-') headline = k[0] date = k[1] c = soup.findAll('p', attrs={'class': 'zn-body__paragraph'}) b...
Methods for interacting with the CNN website.
CNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CNN: """Methods for interacting with the CNN website.""" def get_article(self, url): """Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at that url.""" <|body_0|> def get_query_result...
stack_v2_sparse_classes_75kplus_train_065086
1,861
no_license
[ { "docstring": "Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at that url.", "name": "get_article", "signature": "def get_article(self, url)" }, { "docstring": "Implementation for keyword searches from CNN....
2
stack_v2_sparse_classes_30k_train_038950
Implement the Python class `CNN` described below. Class description: Methods for interacting with the CNN website. Method signatures and docstrings: - def get_article(self, url): Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at ...
Implement the Python class `CNN` described below. Class description: Methods for interacting with the CNN website. Method signatures and docstrings: - def get_article(self, url): Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at ...
b1adf7d582eb78623a44611dc07749823da84d5f
<|skeleton|> class CNN: """Methods for interacting with the CNN website.""" def get_article(self, url): """Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at that url.""" <|body_0|> def get_query_result...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CNN: """Methods for interacting with the CNN website.""" def get_article(self, url): """Implementation for getting an article from CNN. Args: url: A URL in the www.cnn.* domain. Returns: The Article representing the article at that url.""" html = helpers.get_content(url) if not ht...
the_stack_v2_python_sparse
analysis/scraping/cnn.py
pandrewhk/perspectives
train
0
bc07131ea149006a74120c4bfb2dedbaef8abd60
[ "try:\n for field in dataclasses.fields(self):\n setattr(self, field.name, field.type(env_file))\nexcept ValidationError as err:\n config_field = None\n first_error = err.errors()[0]\n loc: str = first_error['loc'][0]\n if loc != '__root__':\n settings_model = cast(BaseSettings, err.mod...
<|body_start_0|> try: for field in dataclasses.fields(self): setattr(self, field.name, field.type(env_file)) except ValidationError as err: config_field = None first_error = err.errors()[0] loc: str = first_error['loc'][0] if lo...
Globally manage environment variables configuration options.
Settings
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configura...
stack_v2_sparse_classes_75kplus_train_065087
6,638
permissive
[ { "docstring": "Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configuration option is not valid.", "name": "__init__", "signature": "def __init__(self, env_file: Optional[Path]=None) -> None" }, { "docstrin...
2
stack_v2_sparse_classes_30k_train_021855
Implement the Python class `Settings` described below. Class description: Globally manage environment variables configuration options. Method signatures and docstrings: - def __init__(self, env_file: Optional[Path]=None) -> None: Checks the validity of each configuration option. Args: env_file: Path to a file definin...
Implement the Python class `Settings` described below. Class description: Globally manage environment variables configuration options. Method signatures and docstrings: - def __init__(self, env_file: Optional[Path]=None) -> None: Checks the validity of each configuration option. Args: env_file: Path to a file definin...
9e3370a7656b415058acf2d39a690a72f6eb343f
<|skeleton|> class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configura...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Settings: """Globally manage environment variables configuration options.""" def __init__(self, env_file: Optional[Path]=None) -> None: """Checks the validity of each configuration option. Args: env_file: Path to a file defining environment variables. Raises: ConfigError: A configuration option i...
the_stack_v2_python_sparse
src/opcua_webhmi_bridge/config.py
renovate-tests/opcua-webhmi-bridge
train
0
d74496e1b176070fcd5d91b200a480c79cf17240
[ "self.pairs = pairs\nself.change_types = change_types\nself.func = None\nself.funcname = None", "assert isinstance(func, FunctionType), 'func must be a function'\nself.func = func\nreturn self", "clone = type(self)(self.pairs, self.change_types)\nclone.func = self.func\nreturn clone" ]
<|body_start_0|> self.pairs = pairs self.change_types = change_types self.func = None self.funcname = None <|end_body_0|> <|body_start_1|> assert isinstance(func, FunctionType), 'func must be a function' self.func = func return self <|end_body_1|> <|body_start_2...
An object used to temporarily store observe decorator state.
ObserveHandler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObserveHandler: """An object used to temporarily store observe decorator state.""" def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None: """Initialize an ObserveHandler. Parameters ---------- pairs : list The list of 2-tuples whi...
stack_v2_sparse_classes_75kplus_train_065088
5,816
permissive
[ { "docstring": "Initialize an ObserveHandler. Parameters ---------- pairs : list The list of 2-tuples which stores the pair information for the observers.", "name": "__init__", "signature": "def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None" },...
3
stack_v2_sparse_classes_30k_train_007015
Implement the Python class `ObserveHandler` described below. Class description: An object used to temporarily store observe decorator state. Method signatures and docstrings: - def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None: Initialize an ObserveHandler. Pa...
Implement the Python class `ObserveHandler` described below. Class description: An object used to temporarily store observe decorator state. Method signatures and docstrings: - def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None: Initialize an ObserveHandler. Pa...
761a52821d8c77b5718216256963682d11599c1e
<|skeleton|> class ObserveHandler: """An object used to temporarily store observe decorator state.""" def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None: """Initialize an ObserveHandler. Parameters ---------- pairs : list The list of 2-tuples whi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ObserveHandler: """An object used to temporarily store observe decorator state.""" def __init__(self, pairs: List[Tuple[str, Optional[str]]], change_types: ChangeType=ChangeType.ANY) -> None: """Initialize an ObserveHandler. Parameters ---------- pairs : list The list of 2-tuples which stores the...
the_stack_v2_python_sparse
atom/meta/observation.py
nucleic/atom
train
251
fb31f14f3ff2b131f0fd7567f3d88a9125495202
[ "assert isinstance(nb_topics, int)\nassert nb_topics > 0\nself.nb_topics = nb_topics", "vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')\nbow = vectorizer.fit_transform(dataset.data)\nself.lda_model = LatentDirichletAllocation(n_components=self.nb_topics, random_state=0)\nX = self...
<|body_start_0|> assert isinstance(nb_topics, int) assert nb_topics > 0 self.nb_topics = nb_topics <|end_body_0|> <|body_start_1|> vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english') bow = vectorizer.fit_transform(dataset.data) self.lda_mode...
BOW_TopicModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BOW_TopicModel: def __init__(self, nb_topics=10): """Class constructor. Args: nb_topics (int, optional): Number of topics for LDA.""" <|body_0|> def extract_features(self, dataset): """Extract features using Bag-of-Words and then LDA (topic models). Each document is ...
stack_v2_sparse_classes_75kplus_train_065089
8,035
no_license
[ { "docstring": "Class constructor. Args: nb_topics (int, optional): Number of topics for LDA.", "name": "__init__", "signature": "def __init__(self, nb_topics=10)" }, { "docstring": "Extract features using Bag-of-Words and then LDA (topic models). Each document is represented as a n-dimensional ...
2
stack_v2_sparse_classes_30k_train_042590
Implement the Python class `BOW_TopicModel` described below. Class description: Implement the BOW_TopicModel class. Method signatures and docstrings: - def __init__(self, nb_topics=10): Class constructor. Args: nb_topics (int, optional): Number of topics for LDA. - def extract_features(self, dataset): Extract feature...
Implement the Python class `BOW_TopicModel` described below. Class description: Implement the BOW_TopicModel class. Method signatures and docstrings: - def __init__(self, nb_topics=10): Class constructor. Args: nb_topics (int, optional): Number of topics for LDA. - def extract_features(self, dataset): Extract feature...
bfe9f8cb6eb7341c156131c62eaba96dbfe0adbb
<|skeleton|> class BOW_TopicModel: def __init__(self, nb_topics=10): """Class constructor. Args: nb_topics (int, optional): Number of topics for LDA.""" <|body_0|> def extract_features(self, dataset): """Extract features using Bag-of-Words and then LDA (topic models). Each document is ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BOW_TopicModel: def __init__(self, nb_topics=10): """Class constructor. Args: nb_topics (int, optional): Number of topics for LDA.""" assert isinstance(nb_topics, int) assert nb_topics > 0 self.nb_topics = nb_topics def extract_features(self, dataset): """Extract f...
the_stack_v2_python_sparse
feature_extraction/feature_extraction.py
LLNL/al_nlp
train
11
034b92b1e5caa2de4d4956e9849ba3439745074e
[ "super(RandPointCNN, self).__init__()\nself.pointcnn = PointCNN(cin, cout, dims, K, D, P)\nself.P = P\nif self.P > 0:\n self.sampler = FurthestPointSampler(self.P)", "pts, fts = x\nif 0 < self.P < pts.size()[1]:\n rep_pts = self.sampler(pts)\nelse:\n rep_pts = pts\nrep_pts_fts = self.pointcnn((rep_pts, p...
<|body_start_0|> super(RandPointCNN, self).__init__() self.pointcnn = PointCNN(cin, cout, dims, K, D, P) self.P = P if self.P > 0: self.sampler = FurthestPointSampler(self.P) <|end_body_0|> <|body_start_1|> pts, fts = x if 0 < self.P < pts.size()[1]: ...
PointCNN with randomly subsampled representative points.
RandPointCNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandPointCNN: """PointCNN with randomly subsampled representative points.""" def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None: """See documentation for PointCNN.""" <|body_0|> def execute(self, x): """Given a point cloud, and its...
stack_v2_sparse_classes_75kplus_train_065090
18,458
no_license
[ { "docstring": "See documentation for PointCNN.", "name": "__init__", "signature": "def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None" }, { "docstring": "Given a point cloud, and its corresponding features, return a new set of randomly-sampled representative poin...
2
null
Implement the Python class `RandPointCNN` described below. Class description: PointCNN with randomly subsampled representative points. Method signatures and docstrings: - def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None: See documentation for PointCNN. - def execute(self, x): Given a...
Implement the Python class `RandPointCNN` described below. Class description: PointCNN with randomly subsampled representative points. Method signatures and docstrings: - def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None: See documentation for PointCNN. - def execute(self, x): Given a...
c0018e21ee1a93c0d9df2dde25144585d6e3ab49
<|skeleton|> class RandPointCNN: """PointCNN with randomly subsampled representative points.""" def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None: """See documentation for PointCNN.""" <|body_0|> def execute(self, x): """Given a point cloud, and its...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandPointCNN: """PointCNN with randomly subsampled representative points.""" def __init__(self, cin: int, cout: int, dims: int, K: int, D: int, P: int) -> None: """See documentation for PointCNN.""" super(RandPointCNN, self).__init__() self.pointcnn = PointCNN(cin, cout, dims, K, ...
the_stack_v2_python_sparse
ops/layers.py
xiaoxTM/jittor-pcl
train
0
6be83c96ffb945d97afdd6436caff882fe536388
[ "super(BerkJones, self).__init__()\nassert 'direction' in kwargs.keys()\nassert 'alpha' in kwargs.keys()\nself.kwargs = kwargs", "assert 'alpha' in self.kwargs.keys(), 'Warning: calling bj score without alpha'\nalpha = self.kwargs['alpha']\nif q < alpha:\n q = alpha\nassert q > 0, 'Warning: calling compute_sco...
<|body_start_0|> super(BerkJones, self).__init__() assert 'direction' in kwargs.keys() assert 'alpha' in kwargs.keys() self.kwargs = kwargs <|end_body_0|> <|body_start_1|> assert 'alpha' in self.kwargs.keys(), 'Warning: calling bj score without alpha' alpha = self.kwargs...
BerkJones
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BerkJones: def __init__(self, **kwargs): """Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring functions do not make parametric assumptions about the model or outcome [1]. kwargs must contain 'di...
stack_v2_sparse_classes_75kplus_train_065091
4,161
permissive
[ { "docstring": "Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring functions do not make parametric assumptions about the model or outcome [1]. kwargs must contain 'direction (str)' - direction of the severity; could be...
4
null
Implement the Python class `BerkJones` described below. Class description: Implement the BerkJones class. Method signatures and docstrings: - def __init__(self, **kwargs): Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring fu...
Implement the Python class `BerkJones` described below. Class description: Implement the BerkJones class. Method signatures and docstrings: - def __init__(self, **kwargs): Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring fu...
0ddf84fbe456feef0570dfe0d714d6656a18d9ca
<|skeleton|> class BerkJones: def __init__(self, **kwargs): """Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring functions do not make parametric assumptions about the model or outcome [1]. kwargs must contain 'di...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BerkJones: def __init__(self, **kwargs): """Berk-Jones score function is a non parametric expectatation based scan statistic that also satisfies the ALTSS property; Non-parametric scoring functions do not make parametric assumptions about the model or outcome [1]. kwargs must contain 'direction (str)'...
the_stack_v2_python_sparse
aif360/metrics/mdss/ScoringFunctions/BerkJones.py
SumaiyaSaima05/AIF360
train
1
afbf0983e90d9efac98652276eec985fadbb9700
[ "super(RelativePosition, self).__init__()\nself.num_units = num_units\nself.device = device\nself.max_relative_position = max_relative_position\nself.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))\nnn.init.xavier_uniform_(self.embeddings_table)", "range_vec_q = torch.arang...
<|body_start_0|> super(RelativePosition, self).__init__() self.num_units = num_units self.device = device self.max_relative_position = max_relative_position self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units)) nn.init.xavier_uniform...
RelativePosition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelativePosition: def __init__(self, num_units, max_relative_position, device=None): """:param num_units: d_a :param max_relative_position: k""" <|body_0|> def forward(self, length_q, length_k): """for self-att: length_q == length_k == length_x return: embeddings: le...
stack_v2_sparse_classes_75kplus_train_065092
1,268
no_license
[ { "docstring": ":param num_units: d_a :param max_relative_position: k", "name": "__init__", "signature": "def __init__(self, num_units, max_relative_position, device=None)" }, { "docstring": "for self-att: length_q == length_k == length_x return: embeddings: length_q x length_k x d_a", "name...
2
stack_v2_sparse_classes_30k_train_017706
Implement the Python class `RelativePosition` described below. Class description: Implement the RelativePosition class. Method signatures and docstrings: - def __init__(self, num_units, max_relative_position, device=None): :param num_units: d_a :param max_relative_position: k - def forward(self, length_q, length_k): ...
Implement the Python class `RelativePosition` described below. Class description: Implement the RelativePosition class. Method signatures and docstrings: - def __init__(self, num_units, max_relative_position, device=None): :param num_units: d_a :param max_relative_position: k - def forward(self, length_q, length_k): ...
1bfff12c6b03f64f57d118b435c0040431befcdf
<|skeleton|> class RelativePosition: def __init__(self, num_units, max_relative_position, device=None): """:param num_units: d_a :param max_relative_position: k""" <|body_0|> def forward(self, length_q, length_k): """for self-att: length_q == length_k == length_x return: embeddings: le...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RelativePosition: def __init__(self, num_units, max_relative_position, device=None): """:param num_units: d_a :param max_relative_position: k""" super(RelativePosition, self).__init__() self.num_units = num_units self.device = device self.max_relative_position = max_rel...
the_stack_v2_python_sparse
nag/modules/relative_position.py
liu-hz18/Non-Autoregressive-Neural-Dialogue-Generation
train
0
433543da97e5ffe525fb8081ad2d368aa34e01bf
[ "self.spectrum = spectrum\nself.possiblePeptides = []\nself.aaMass = {'G': 57, 'A': 71, 'S': 87, 'P': 97, 'V': 99, 'T': 101, 'C': 103, 'I': 113, 'L': 113, 'N': 114, 'D': 115, 'K': 128, 'Q': 128, 'E': 129, 'M': 131, 'H': 137, 'F': 147, 'R': 156, 'Y': 163, 'W': 186}\nself.aaList = list(self.aaMass)", "sortedSpectru...
<|body_start_0|> self.spectrum = spectrum self.possiblePeptides = [] self.aaMass = {'G': 57, 'A': 71, 'S': 87, 'P': 97, 'V': 99, 'T': 101, 'C': 103, 'I': 113, 'L': 113, 'N': 114, 'D': 115, 'K': 128, 'Q': 128, 'E': 129, 'M': 131, 'H': 137, 'F': 147, 'R': 156, 'Y': 163, 'W': 186} self.aaLi...
Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum.
TheoPepCyclic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TheoPepCyclic: """Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum.""" def __init__(self, spectrum): """Create a constructor to hold impo...
stack_v2_sparse_classes_75kplus_train_065093
7,890
no_license
[ { "docstring": "Create a constructor to hold important data and tables.", "name": "__init__", "signature": "def __init__(self, spectrum)" }, { "docstring": "Create possible peptide strings given the input spectrum", "name": "matchTheoretical", "signature": "def matchTheoretical(self)" ...
6
null
Implement the Python class `TheoPepCyclic` described below. Class description: Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum. Method signatures and docstrings: - def __...
Implement the Python class `TheoPepCyclic` described below. Class description: Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum. Method signatures and docstrings: - def __...
efe83914cbe193c151504a1b2fe81b8b53055816
<|skeleton|> class TheoPepCyclic: """Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum.""" def __init__(self, spectrum): """Create a constructor to hold impo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TheoPepCyclic: """Program to find a Cyclic Peptide with a Theoretical Spectrum Matching an Ideal Spectrum given A collection of (possibly repeated) integers Spectrum corresponding to an ideal experimental spectrum.""" def __init__(self, spectrum): """Create a constructor to hold important data an...
the_stack_v2_python_sparse
cyclicPepTheoIdeal.py
zmmason/BINF
train
6
e936fa99361410dd4af805eacb81c0ed88056446
[ "tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file)\nif reserved_tokens is None:\n reserved_tokens = RESERVED_TOKENS\nself.subtoken_list = _load_vocab_file(vocab_file, reserved_tokens)\nself.alphabet = _generate_alphabet_dict(self.subtoken_list)\nself.subtoken_to_id_dict = _list_to...
<|body_start_0|> tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file) if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS self.subtoken_list = _load_vocab_file(vocab_file, reserved_tokens) self.alphabet = _generate_alphabet_dict(self.sub...
Encodes and decodes strings to/from integer IDs.
Subtokenizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subtokenizer: """Encodes and decodes strings to/from integer IDs.""" def __init__(self, vocab_file, reserved_tokens=None): """Initializes class, creating a vocab file if data_files is provided.""" <|body_0|> def init_from_files(vocab_file, files, target_vocab_size, thres...
stack_v2_sparse_classes_75kplus_train_065094
22,774
permissive
[ { "docstring": "Initializes class, creating a vocab file if data_files is provided.", "name": "__init__", "signature": "def __init__(self, vocab_file, reserved_tokens=None)" }, { "docstring": "Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of voc...
6
stack_v2_sparse_classes_30k_train_005548
Implement the Python class `Subtokenizer` described below. Class description: Encodes and decodes strings to/from integer IDs. Method signatures and docstrings: - def __init__(self, vocab_file, reserved_tokens=None): Initializes class, creating a vocab file if data_files is provided. - def init_from_files(vocab_file,...
Implement the Python class `Subtokenizer` described below. Class description: Encodes and decodes strings to/from integer IDs. Method signatures and docstrings: - def __init__(self, vocab_file, reserved_tokens=None): Initializes class, creating a vocab file if data_files is provided. - def init_from_files(vocab_file,...
9304c9f59fde013f158ac338fc80171c0e8cda5d
<|skeleton|> class Subtokenizer: """Encodes and decodes strings to/from integer IDs.""" def __init__(self, vocab_file, reserved_tokens=None): """Initializes class, creating a vocab file if data_files is provided.""" <|body_0|> def init_from_files(vocab_file, files, target_vocab_size, thres...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Subtokenizer: """Encodes and decodes strings to/from integer IDs.""" def __init__(self, vocab_file, reserved_tokens=None): """Initializes class, creating a vocab file if data_files is provided.""" tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file) if...
the_stack_v2_python_sparse
models/language_translation/tensorflow/transformer_mlperf/inference/int8/transformer/utils/tokenizer.py
IntelAI/models
train
609
582bb4478416b2b8adee7f63908cb3a9f47d2224
[ "self.cfg = ConfigParser.ConfigParser()\nself.configfile = configfile\nself.profile_name = profile_name\nself.args = args\nif self.profile_name != 'default':\n self.profile_name = 'profile ' + profile_name\nself.options = {'action': 'create', 'audit': 'NoopAudit', 'audit_output': None, 'output': 'BaseOutput', 'p...
<|body_start_0|> self.cfg = ConfigParser.ConfigParser() self.configfile = configfile self.profile_name = profile_name self.args = args if self.profile_name != 'default': self.profile_name = 'profile ' + profile_name self.options = {'action': 'create', 'audit':...
Config class responsible to assemble config from files, defaults and command line arguments.
PMCFConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PMCFConfig: """Config class responsible to assemble config from files, defaults and command line arguments.""" def __init__(self, configfile, profile_name, args): """Constructor :param configfile: Path to configuration file :type configfile: str. :param profile_name: Profile in confi...
stack_v2_sparse_classes_75kplus_train_065095
3,945
permissive
[ { "docstring": "Constructor :param configfile: Path to configuration file :type configfile: str. :param profile_name: Profile in configuration file :type profile_name: str. :param args: command line arguments :type args: dict.", "name": "__init__", "signature": "def __init__(self, configfile, profile_na...
3
null
Implement the Python class `PMCFConfig` described below. Class description: Config class responsible to assemble config from files, defaults and command line arguments. Method signatures and docstrings: - def __init__(self, configfile, profile_name, args): Constructor :param configfile: Path to configuration file :ty...
Implement the Python class `PMCFConfig` described below. Class description: Config class responsible to assemble config from files, defaults and command line arguments. Method signatures and docstrings: - def __init__(self, configfile, profile_name, args): Constructor :param configfile: Path to configuration file :ty...
ce504286546c78fdd28145d8c413635e5df6f2bc
<|skeleton|> class PMCFConfig: """Config class responsible to assemble config from files, defaults and command line arguments.""" def __init__(self, configfile, profile_name, args): """Constructor :param configfile: Path to configuration file :type configfile: str. :param profile_name: Profile in confi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PMCFConfig: """Config class responsible to assemble config from files, defaults and command line arguments.""" def __init__(self, configfile, profile_name, args): """Constructor :param configfile: Path to configuration file :type configfile: str. :param profile_name: Profile in configuration file...
the_stack_v2_python_sparse
pmcf/config/config.py
ktechmidas/pmcf
train
0
078188bde352e46d3c871a6e7fee54c9afae3677
[ "user = User.objects.get(pk=int(request.data['id']))\nif models.MovieRating.objects.filter(rating_user=user.movie_user, movie=Movie.objects.get(pk=int(request.data['movie']))).exists():\n movie_rating = models.MovieRating.objects.get(rating_user=user.movie_user, movie=Movie.objects.get(pk=int(request.data['movie...
<|body_start_0|> user = User.objects.get(pk=int(request.data['id'])) if models.MovieRating.objects.filter(rating_user=user.movie_user, movie=Movie.objects.get(pk=int(request.data['movie']))).exists(): movie_rating = models.MovieRating.objects.get(rating_user=user.movie_user, movie=Movie.obje...
MovieRatingViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovieRatingViewSet: def new(self, request): """Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param request: /movies/ratings/new/ -- 'id': int (user id), 'movie': int (movieId), 'rating': float :return Response w...
stack_v2_sparse_classes_75kplus_train_065096
4,372
no_license
[ { "docstring": "Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param request: /movies/ratings/new/ -- 'id': int (user id), 'movie': int (movieId), 'rating': float :return Response with status", "name": "new", "signature": "def n...
2
null
Implement the Python class `MovieRatingViewSet` described below. Class description: Implement the MovieRatingViewSet class. Method signatures and docstrings: - def new(self, request): Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param reque...
Implement the Python class `MovieRatingViewSet` described below. Class description: Implement the MovieRatingViewSet class. Method signatures and docstrings: - def new(self, request): Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param reque...
0f9bbea2eef25a58bf80433ae8c8960684bdfbfa
<|skeleton|> class MovieRatingViewSet: def new(self, request): """Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param request: /movies/ratings/new/ -- 'id': int (user id), 'movie': int (movieId), 'rating': float :return Response w...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MovieRatingViewSet: def new(self, request): """Adds a new rating for the user on the given media. Updates the user model embedding which updates the user's predictions. :param request: /movies/ratings/new/ -- 'id': int (user id), 'movie': int (movieId), 'rating': float :return Response with status""" ...
the_stack_v2_python_sparse
MediaRecommendationServer/app/ratings/views.py
sorennelson/MediaRecommendation
train
0
0041e6accad1eebd88a6aebd56eec5978ba9b777
[ "low, high = (0, len(nums) - 1)\nwhile low <= high:\n mid = low + (high - low) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n high = mid - 1\n else:\n low = mid + 1\nreturn None", "if len(nums) <= 1:\n return 0\nlow, high = (0, len(nums) - 1)\nwhile lo...
<|body_start_0|> low, high = (0, len(nums) - 1) while low <= high: mid = low + (high - low) // 2 if nums[mid] == target: return mid elif nums[mid] > target: high = mid - 1 else: low = mid + 1 return N...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def binary_search(self, nums, target): """二分查找 :param nums: :param target: :return:""" <|body_0|> def find_rotate_index(self, nums): """二分法查找分割点 :param nums: :return:""" <|body_1|> def search(self, nums, target): """:type nums: List[int...
stack_v2_sparse_classes_75kplus_train_065097
2,319
no_license
[ { "docstring": "二分查找 :param nums: :param target: :return:", "name": "binary_search", "signature": "def binary_search(self, nums, target)" }, { "docstring": "二分法查找分割点 :param nums: :return:", "name": "find_rotate_index", "signature": "def find_rotate_index(self, nums)" }, { "docstr...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def binary_search(self, nums, target): 二分查找 :param nums: :param target: :return: - def find_rotate_index(self, nums): 二分法查找分割点 :param nums: :return: - def search(self, nums, targ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def binary_search(self, nums, target): 二分查找 :param nums: :param target: :return: - def find_rotate_index(self, nums): 二分法查找分割点 :param nums: :return: - def search(self, nums, targ...
3b13b36f37eb364410b3b5b4f10a1808d8b1111e
<|skeleton|> class Solution: def binary_search(self, nums, target): """二分查找 :param nums: :param target: :return:""" <|body_0|> def find_rotate_index(self, nums): """二分法查找分割点 :param nums: :return:""" <|body_1|> def search(self, nums, target): """:type nums: List[int...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def binary_search(self, nums, target): """二分查找 :param nums: :param target: :return:""" low, high = (0, len(nums) - 1) while low <= high: mid = low + (high - low) // 2 if nums[mid] == target: return mid elif nums[mid] > targe...
the_stack_v2_python_sparse
leetcode/33.py
yanggelinux/algorithm-data-structure
train
0
2fda368ca43c860a7eb63f90972ade3e30a66517
[ "ana_id = super(hr_department, self).create(vals)\nif self.manager_id.id != False and self.analytic_account_id.id != False:\n self.analytic_account_id.write({'user_id': self.manager_id.user_id.id})\nreturn ana_id", "ana_id = super(hr_department, self).write(vals)\nif self.manager_id.id != False and self.analyt...
<|body_start_0|> ana_id = super(hr_department, self).create(vals) if self.manager_id.id != False and self.analytic_account_id.id != False: self.analytic_account_id.write({'user_id': self.manager_id.user_id.id}) return ana_id <|end_body_0|> <|body_start_1|> ana_id = super(hr_...
inherit hr.department model
hr_department
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class hr_department: """inherit hr.department model""" def create(self, vals): """override create function to set resposeble of department's analytic account equals to department's manager""" <|body_0|> def write(self, vals): """override write function to set resposebl...
stack_v2_sparse_classes_75kplus_train_065098
926
no_license
[ { "docstring": "override create function to set resposeble of department's analytic account equals to department's manager", "name": "create", "signature": "def create(self, vals)" }, { "docstring": "override write function to set resposeble of department's analytic account equals to department'...
2
stack_v2_sparse_classes_30k_train_033948
Implement the Python class `hr_department` described below. Class description: inherit hr.department model Method signatures and docstrings: - def create(self, vals): override create function to set resposeble of department's analytic account equals to department's manager - def write(self, vals): override write func...
Implement the Python class `hr_department` described below. Class description: inherit hr.department model Method signatures and docstrings: - def create(self, vals): override create function to set resposeble of department's analytic account equals to department's manager - def write(self, vals): override write func...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class hr_department: """inherit hr.department model""" def create(self, vals): """override create function to set resposeble of department's analytic account equals to department's manager""" <|body_0|> def write(self, vals): """override write function to set resposebl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class hr_department: """inherit hr.department model""" def create(self, vals): """override create function to set resposeble of department's analytic account equals to department's manager""" ana_id = super(hr_department, self).create(vals) if self.manager_id.id != False and self.analyt...
the_stack_v2_python_sparse
v_11/EBS-SVN/trunk/account_budget_ebs/models/departmentAccount_custom.py
musabahmed/baba
train
0
b39ab5d569f8cafa772dd4f557213bc1879d4603
[ "self._GoalFrameId = '/map'\nself._GoalsFilePath = filePath\nwith open(filePath, 'r') as file:\n goals = []\n while True:\n goal = self._ReadNextGoalSection(file)\n if goal is None:\n break\n goals.append(goal)\n file.readline()\nreturn (self._GoalFrameId, goals)", "fo...
<|body_start_0|> self._GoalFrameId = '/map' self._GoalsFilePath = filePath with open(filePath, 'r') as file: goals = [] while True: goal = self._ReadNextGoalSection(file) if goal is None: break goals.appe...
Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 nsecs: 0 id: '' goal: target_pose: header: seq: ...
RecordedGoalsParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecordedGoalsParser: """Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 n...
stack_v2_sparse_classes_75kplus_train_065099
11,034
permissive
[ { "docstring": "Parses the specified file and returns the extracted frame id and the array of goal poses: (frame_id, [(x,y,theta)])", "name": "Parse", "signature": "def Parse(self, filePath)" }, { "docstring": "Reads a section of the file that needs to be structured like this: header: seq: 5 sta...
3
stack_v2_sparse_classes_30k_val_002574
Implement the Python class `RecordedGoalsParser` described below. Class description: Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316...
Implement the Python class `RecordedGoalsParser` described below. Class description: Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316...
48d9144293d1b604969ca1208fb813939e935ed9
<|skeleton|> class RecordedGoalsParser: """Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 n...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RecordedGoalsParser: """Helper class for extracting goals from a text file that contains the output of the ros topic /move_base/goal: rostopic echo /move_base/goal > ./goals.txt Content looks like this: header: seq: 5 stamp: secs: 1327888889 nsecs: 905062316 frame_id: '' goal_id: stamp: secs: 0 nsecs: 0 id: '...
the_stack_v2_python_sparse
Chapter09/chefbot_code/chefbot_bringup/scripts/bkup_working/GoalsSequencer.py
PacktPublishing/ROS-Robotics-Projects
train
149