blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
5399b121ec372865fd963a3fbe863b425e656ae2
[ "if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelse:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n ...
<|body_start_0|> if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = float(lambtha) else: if not isinstance(data, list): raise TypeError('data must be a list') if len(data) <...
Poisson
Poisson
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poisson: """Poisson""" def __init__(self, data=None, lambtha=1.0): """Constructor""" <|body_0|> def pmf(self, k): """Calculates PMF""" <|body_1|> def cdf(self, k): """calculate CDF""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_000500
1,184
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "Calculates PMF", "name": "pmf", "signature": "def pmf(self, k)" }, { "docstring": "calculate CDF", "name": "cdf", "signature": "def cdf(self, k)"...
3
null
Implement the Python class `Poisson` described below. Class description: Poisson Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Constructor - def pmf(self, k): Calculates PMF - def cdf(self, k): calculate CDF
Implement the Python class `Poisson` described below. Class description: Poisson Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Constructor - def pmf(self, k): Calculates PMF - def cdf(self, k): calculate CDF <|skeleton|> class Poisson: """Poisson""" def __init__(self, data=...
ff1af62484620b599cc3813068770db03b37036d
<|skeleton|> class Poisson: """Poisson""" def __init__(self, data=None, lambtha=1.0): """Constructor""" <|body_0|> def pmf(self, k): """Calculates PMF""" <|body_1|> def cdf(self, k): """calculate CDF""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Poisson: """Poisson""" def __init__(self, data=None, lambtha=1.0): """Constructor""" if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = float(lambtha) else: if not isinstance(dat...
the_stack_v2_python_sparse
math/0x03-probability/poisson.py
paurbano/holbertonschool-machine_learning
train
0
13b9428e0f046efdfffb52c2e296efe195138dba
[ "for rule_cls in self.rules:\n rule = rule_cls()\n logging.info(f'Running: {rule}')\n for result in rule.evaluate(oi):\n yield result", "rule_dict = {rule.__name__: rule for rule in RULES}\nself.rules = [rule_dict[name] for name in rule_names]\nlogging.info(f'Set rules: {self.rules}')" ]
<|body_start_0|> for rule_cls in self.rules: rule = rule_cls() logging.info(f'Running: {rule}') for result in rule.evaluate(oi): yield result <|end_body_0|> <|body_start_1|> rule_dict = {rule.__name__: rule for rule in RULES} self.rules = [rul...
RuleRunner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RuleRunner: def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]: """Run all rules :param oi: :return:""" <|body_0|> def set_rules(self, rule_names: Iterable[str]) -> None: """Set the rules to run :param rules: :return:""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_000501
1,313
permissive
[ { "docstring": "Run all rules :param oi: :return:", "name": "run", "signature": "def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]" }, { "docstring": "Set the rules to run :param rules: :return:", "name": "set_rules", "signature": "def set_rules(self, rule_names: It...
2
null
Implement the Python class `RuleRunner` described below. Class description: Implement the RuleRunner class. Method signatures and docstrings: - def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]: Run all rules :param oi: :return: - def set_rules(self, rule_names: Iterable[str]) -> None: Set the r...
Implement the Python class `RuleRunner` described below. Class description: Implement the RuleRunner class. Method signatures and docstrings: - def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]: Run all rules :param oi: :return: - def set_rules(self, rule_names: Iterable[str]) -> None: Set the r...
8d2a124f7af66fe2e796f9e0ece55585438796a5
<|skeleton|> class RuleRunner: def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]: """Run all rules :param oi: :return:""" <|body_0|> def set_rules(self, rule_names: Iterable[str]) -> None: """Set the rules to run :param rules: :return:""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RuleRunner: def run(self, oi: BasicOntologyInterface) -> Iterable[ValidationResult]: """Run all rules :param oi: :return:""" for rule_cls in self.rules: rule = rule_cls() logging.info(f'Running: {rule}') for result in rule.evaluate(oi): yield...
the_stack_v2_python_sparse
src/oaklib/utilities/validation/rule_runner.py
INCATools/ontology-access-kit
train
67
6ddbd8d7ed307d91d245ff2505927accb29986a4
[ "result = []\nself.restore(s, 4, '', result)\nreturn result", "if seg_no == 1:\n if int(s) > 255 or (s[0] == '0' and len(s) > 1):\n return None\n else:\n cur_ip += '.' + s\n ip_list.append(cur_ip[1:])\n return s\nfor i in range(0, len(s) - seg_no + 1):\n ip_seg = s[0:i + 1]\n ...
<|body_start_0|> result = [] self.restore(s, 4, '', result) return result <|end_body_0|> <|body_start_1|> if seg_no == 1: if int(s) > 255 or (s[0] == '0' and len(s) > 1): return None else: cur_ip += '.' + s ip_list....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def restoreIpAddresses(self, s): """使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]""" <|body_0|> def restore(self, s, seg_no, cur_ip, ip_list): """递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param...
stack_v2_sparse_classes_36k_train_000502
1,787
no_license
[ { "docstring": "使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]", "name": "restoreIpAddresses", "signature": "def restoreIpAddresses(self, s)" }, { "docstring": "递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param ip_list: 最终结果存放列表 :retur...
2
stack_v2_sparse_classes_30k_train_002267
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restoreIpAddresses(self, s): 使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str] - def restore(self, s, seg_no, cur_ip, ip_list): 递归主体 :param s: 字符串 :param seg_...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def restoreIpAddresses(self, s): 使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str] - def restore(self, s, seg_no, cur_ip, ip_list): 递归主体 :param s: 字符串 :param seg_...
68a09a1ea2fb5083d62d8188c7ef213b2cc315cd
<|skeleton|> class Solution: def restoreIpAddresses(self, s): """使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]""" <|body_0|> def restore(self, s, seg_no, cur_ip, ip_list): """递归主体 :param s: 字符串 :param seg_no: 当前ip片段的idx :param cur_ip: 当前ip,用于传递当前以及restore好的ip :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def restoreIpAddresses(self, s): """使用递归:每次递归确定第n个地址段的所有可能,在第4个地址段结束递归 :type s: str :rtype: List[str]""" result = [] self.restore(s, 4, '', result) return result def restore(self, s, seg_no, cur_ip, ip_list): """递归主体 :param s: 字符串 :param seg_no: 当前ip片段的id...
the_stack_v2_python_sparse
leetcode081-100/leetcode93-restore-ip-addresses.py
linshuang/code4fun
train
0
7c60bf82e61a98ea3d96b025467db0fa5af6974b
[ "for frame in g.app.windowList:\n if frame.c != c:\n frame.c.close()", "result: list[str] = []\nif not getattr(g.app.gui, 'frameFactory', None):\n return result\nmf = getattr(g.app.gui.frameFactory, 'masterFrame', None)\nif mf:\n outlines = [mf.widget(i).leo_c for i in range(mf.count())]\nelse:\n ...
<|body_start_0|> for frame in g.app.windowList: if frame.c != c: frame.c.close() <|end_body_0|> <|body_start_1|> result: list[str] = [] if not getattr(g.app.gui, 'frameFactory', None): return result mf = getattr(g.app.gui.frameFactory, 'masterFram...
A class managing session data and related commands.
SessionManager
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionManager: """A class managing session data and related commands.""" def clear_session(self, c: Cmdr) -> None: """Close all tabs except the presently selected tab.""" <|body_0|> def get_session(self) -> list[str]: """Return a list of UNLs for open tabs.""" ...
stack_v2_sparse_classes_36k_train_000503
6,641
permissive
[ { "docstring": "Close all tabs except the presently selected tab.", "name": "clear_session", "signature": "def clear_session(self, c: Cmdr) -> None" }, { "docstring": "Return a list of UNLs for open tabs.", "name": "get_session", "signature": "def get_session(self) -> list[str]" }, {...
6
null
Implement the Python class `SessionManager` described below. Class description: A class managing session data and related commands. Method signatures and docstrings: - def clear_session(self, c: Cmdr) -> None: Close all tabs except the presently selected tab. - def get_session(self) -> list[str]: Return a list of UNL...
Implement the Python class `SessionManager` described below. Class description: A class managing session data and related commands. Method signatures and docstrings: - def clear_session(self, c: Cmdr) -> None: Close all tabs except the presently selected tab. - def get_session(self) -> list[str]: Return a list of UNL...
a3f6c3ebda805dc40cd93123948f153a26eccee5
<|skeleton|> class SessionManager: """A class managing session data and related commands.""" def clear_session(self, c: Cmdr) -> None: """Close all tabs except the presently selected tab.""" <|body_0|> def get_session(self) -> list[str]: """Return a list of UNLs for open tabs.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionManager: """A class managing session data and related commands.""" def clear_session(self, c: Cmdr) -> None: """Close all tabs except the presently selected tab.""" for frame in g.app.windowList: if frame.c != c: frame.c.close() def get_session(self...
the_stack_v2_python_sparse
leo/core/leoSessions.py
leo-editor/leo-editor
train
1,671
28f1c2035d5bd40880fc34bf9ced71900512d0f4
[ "filterInputValue = request.GET.get('filterInputValue', '')\nfilterDbType = request.GET.get('filterDbType[]', '')\nfilterDbType = json.loads(filterDbType) if len(filterDbType) > 2 else None\nobj = DataSourceConfig.objects.filter()\nif filterInputValue:\n obj = obj.filter(host__contains=filterInputValue)\nif filt...
<|body_start_0|> filterInputValue = request.GET.get('filterInputValue', '') filterDbType = request.GET.get('filterDbType[]', '') filterDbType = json.loads(filterDbType) if len(filterDbType) > 2 else None obj = DataSourceConfig.objects.filter() if filterInputValue: obj...
DataSourceConfigList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataSourceConfigList: def get(self, request, *args, **kwargs): """数据源列表""" <|body_0|> def put(self, request, *args, **kwargs): """编辑数据源""" <|body_1|> def post(self, request, *args, **kwargs): """创建数据源""" <|body_2|> def delete(self, r...
stack_v2_sparse_classes_36k_train_000504
9,325
no_license
[ { "docstring": "数据源列表", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "编辑数据源", "name": "put", "signature": "def put(self, request, *args, **kwargs)" }, { "docstring": "创建数据源", "name": "post", "signature": "def post(self, request, ...
4
stack_v2_sparse_classes_30k_val_000568
Implement the Python class `DataSourceConfigList` described below. Class description: Implement the DataSourceConfigList class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 数据源列表 - def put(self, request, *args, **kwargs): 编辑数据源 - def post(self, request, *args, **kwargs): 创建数据源 - def de...
Implement the Python class `DataSourceConfigList` described below. Class description: Implement the DataSourceConfigList class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 数据源列表 - def put(self, request, *args, **kwargs): 编辑数据源 - def post(self, request, *args, **kwargs): 创建数据源 - def de...
f2523d6e51cde1b53ac6f453f8066b4b90c523b9
<|skeleton|> class DataSourceConfigList: def get(self, request, *args, **kwargs): """数据源列表""" <|body_0|> def put(self, request, *args, **kwargs): """编辑数据源""" <|body_1|> def post(self, request, *args, **kwargs): """创建数据源""" <|body_2|> def delete(self, r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataSourceConfigList: def get(self, request, *args, **kwargs): """数据源列表""" filterInputValue = request.GET.get('filterInputValue', '') filterDbType = request.GET.get('filterDbType[]', '') filterDbType = json.loads(filterDbType) if len(filterDbType) > 2 else None obj = Da...
the_stack_v2_python_sparse
api/db/rest/dataSourceConfig.py
zhuzhanhao1/backend
train
0
fb4049d8db8793c5d605768946086fd310732a59
[ "permutations = set([('K', 'K', 'R'), ('K', 'R', 'K'), ('R', 'K', 'K')])\nresult = board.possible_ordered_sequences({'K': 2, 'Q': 0, 'R': 1, 'B': 0, 'N': 0})\nself.assertEqual(permutations, set(result))", "matrix = [[0] * 3 for _ in itertools.repeat(None, 3)]\ncorner_uleft_boundaries = [1, 2, 5]\nresult = board.p...
<|body_start_0|> permutations = set([('K', 'K', 'R'), ('K', 'R', 'K'), ('R', 'K', 'K')]) result = board.possible_ordered_sequences({'K': 2, 'Q': 0, 'R': 1, 'B': 0, 'N': 0}) self.assertEqual(permutations, set(result)) <|end_body_0|> <|body_start_1|> matrix = [[0] * 3 for _ in itertools.r...
Class of chess main application - board module testing
BoardApplicationTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BoardApplicationTest: """Class of chess main application - board module testing""" def test_permutations(self): """Tests possible ordered sequences in permutation""" <|body_0|> def test_boundaries(self): """Tests boundaries checking""" <|body_1|> def...
stack_v2_sparse_classes_36k_train_000505
6,418
permissive
[ { "docstring": "Tests possible ordered sequences in permutation", "name": "test_permutations", "signature": "def test_permutations(self)" }, { "docstring": "Tests boundaries checking", "name": "test_boundaries", "signature": "def test_boundaries(self)" }, { "docstring": "Tests ch...
5
stack_v2_sparse_classes_30k_val_000332
Implement the Python class `BoardApplicationTest` described below. Class description: Class of chess main application - board module testing Method signatures and docstrings: - def test_permutations(self): Tests possible ordered sequences in permutation - def test_boundaries(self): Tests boundaries checking - def tes...
Implement the Python class `BoardApplicationTest` described below. Class description: Class of chess main application - board module testing Method signatures and docstrings: - def test_permutations(self): Tests possible ordered sequences in permutation - def test_boundaries(self): Tests boundaries checking - def tes...
7470479e352bf6fa28215e745af8c42dc20d7a1f
<|skeleton|> class BoardApplicationTest: """Class of chess main application - board module testing""" def test_permutations(self): """Tests possible ordered sequences in permutation""" <|body_0|> def test_boundaries(self): """Tests boundaries checking""" <|body_1|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BoardApplicationTest: """Class of chess main application - board module testing""" def test_permutations(self): """Tests possible ordered sequences in permutation""" permutations = set([('K', 'K', 'R'), ('K', 'R', 'K'), ('R', 'K', 'K')]) result = board.possible_ordered_sequences({...
the_stack_v2_python_sparse
challenges/chess/tests.py
williamlagos/python-coding
train
0
46372296cede8dc8ccb262e21bf6c4d0dab8ad95
[ "self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nb_min, b_max = bounds\nself.X_s = np.linspace(b_min, b_max, num=ac_samples).reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize", "mu, sigma = self.gp.predict(self.X_s)\nif self.minimize is True:\n f_plus = np.amin(self.gp.Y)\n imp = f_plus - mu - ...
<|body_start_0|> self.f = f self.gp = GP(X_init, Y_init, l, sigma_f) b_min, b_max = bounds self.X_s = np.linspace(b_min, b_max, num=ac_samples).reshape(-1, 1) self.xsi = xsi self.minimize = minimize <|end_body_0|> <|body_start_1|> mu, sigma = self.gp.predict(self...
Bayesian optimization on a noiseless 1D Gaussian process:
BayesianOptimization
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BayesianOptimization: """Bayesian optimization on a noiseless 1D Gaussian process:""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """- f is the black-box function to be optimized - X_init is a numpy.ndarray of shape (t, 1) repre...
stack_v2_sparse_classes_36k_train_000506
4,224
no_license
[ { "docstring": "- f is the black-box function to be optimized - X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function - Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init - t is the number ...
3
null
Implement the Python class `BayesianOptimization` described below. Class description: Bayesian optimization on a noiseless 1D Gaussian process: Method signatures and docstrings: - def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): - f is the black-box function to be op...
Implement the Python class `BayesianOptimization` described below. Class description: Bayesian optimization on a noiseless 1D Gaussian process: Method signatures and docstrings: - def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): - f is the black-box function to be op...
e10b4e9b6f3fa00639e6e9e5b35f0cdb43a339a3
<|skeleton|> class BayesianOptimization: """Bayesian optimization on a noiseless 1D Gaussian process:""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """- f is the black-box function to be optimized - X_init is a numpy.ndarray of shape (t, 1) repre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BayesianOptimization: """Bayesian optimization on a noiseless 1D Gaussian process:""" def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): """- f is the black-box function to be optimized - X_init is a numpy.ndarray of shape (t, 1) representing the i...
the_stack_v2_python_sparse
unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py
HeimerR/holbertonschool-machine_learning
train
0
4bc8f0bfb6cdb80d47c3f0545e559fbf01850196
[ "self.coef_ = None\nself.intercept_ = None\nself._theta = None", "assert X_train.shape[0] == y_train.shape[0], 'The size of X_train must be equal to the size of y_train'\nX_b = np.vstack([np.ones((len(X_train), 1)), X_train])\nself._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)\nself.coef_ = self....
<|body_start_0|> self.coef_ = None self.intercept_ = None self._theta = None <|end_body_0|> <|body_start_1|> assert X_train.shape[0] == y_train.shape[0], 'The size of X_train must be equal to the size of y_train' X_b = np.vstack([np.ones((len(X_train), 1)), X_train]) sel...
LinearRegression
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearRegression: def __int__(self): """构造方法""" <|body_0|> def fit_nomal(self, X_train, y_train): """根据训练数据集X_train, y_train训练Linear Regression模型""" <|body_1|> def predict(self, X_predict): """给定待预测数据集X_predict,返回表示X_predict的结果向量""" <|bod...
stack_v2_sparse_classes_36k_train_000507
1,092
no_license
[ { "docstring": "构造方法", "name": "__int__", "signature": "def __int__(self)" }, { "docstring": "根据训练数据集X_train, y_train训练Linear Regression模型", "name": "fit_nomal", "signature": "def fit_nomal(self, X_train, y_train)" }, { "docstring": "给定待预测数据集X_predict,返回表示X_predict的结果向量", "na...
3
stack_v2_sparse_classes_30k_train_004580
Implement the Python class `LinearRegression` described below. Class description: Implement the LinearRegression class. Method signatures and docstrings: - def __int__(self): 构造方法 - def fit_nomal(self, X_train, y_train): 根据训练数据集X_train, y_train训练Linear Regression模型 - def predict(self, X_predict): 给定待预测数据集X_predict,返回...
Implement the Python class `LinearRegression` described below. Class description: Implement the LinearRegression class. Method signatures and docstrings: - def __int__(self): 构造方法 - def fit_nomal(self, X_train, y_train): 根据训练数据集X_train, y_train训练Linear Regression模型 - def predict(self, X_predict): 给定待预测数据集X_predict,返回...
517ac7b7992a686fa5370b6fda8b62663735853c
<|skeleton|> class LinearRegression: def __int__(self): """构造方法""" <|body_0|> def fit_nomal(self, X_train, y_train): """根据训练数据集X_train, y_train训练Linear Regression模型""" <|body_1|> def predict(self, X_predict): """给定待预测数据集X_predict,返回表示X_predict的结果向量""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearRegression: def __int__(self): """构造方法""" self.coef_ = None self.intercept_ = None self._theta = None def fit_nomal(self, X_train, y_train): """根据训练数据集X_train, y_train训练Linear Regression模型""" assert X_train.shape[0] == y_train.shape[0], 'The size of X...
the_stack_v2_python_sparse
MachineLearning/PlayML/LinearRegression.py
CharlesBird/Resources
train
1
83a70ed2d61353c68c47156f851f49936d5fc15c
[ "self.job_id = job_id\nself.num_machines_failed = num_machines_failed\nself.num_machines_passed = num_machines_passed\nself.num_machines_total = num_machines_total\nself.registering_app = registering_app\nself.state = state", "if dictionary is None:\n return None\njob_id = dictionary.get('jobId')\nnum_machines...
<|body_start_0|> self.job_id = job_id self.num_machines_failed = num_machines_failed self.num_machines_passed = num_machines_passed self.num_machines_total = num_machines_total self.registering_app = registering_app self.state = state <|end_body_0|> <|body_start_1|> ...
Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_passed (int): Number of machines on which task is started. num_machines_total (int): Number ...
BulkInstallAppTaskInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BulkInstallAppTaskInfo: """Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_passed (int): Number of machines on which ...
stack_v2_sparse_classes_36k_train_000508
3,321
permissive
[ { "docstring": "Constructor for the BulkInstallAppTaskInfo class", "name": "__init__", "signature": "def __init__(self, job_id=None, num_machines_failed=None, num_machines_passed=None, num_machines_total=None, registering_app=None, state=None)" }, { "docstring": "Creates an instance of this mode...
2
stack_v2_sparse_classes_30k_train_007332
Implement the Python class `BulkInstallAppTaskInfo` described below. Class description: Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_pas...
Implement the Python class `BulkInstallAppTaskInfo` described below. Class description: Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_pas...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class BulkInstallAppTaskInfo: """Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_passed (int): Number of machines on which ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BulkInstallAppTaskInfo: """Implementation of the 'BulkInstallAppTaskInfo' model. Parameters for a bulk install app task. Attributes: job_id (string): Job id of the task. num_machines_failed (int): Number of machines on which task is started. num_machines_passed (int): Number of machines on which task is start...
the_stack_v2_python_sparse
cohesity_management_sdk/models/bulk_install_app_task_info.py
cohesity/management-sdk-python
train
24
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae
[ "q = quantity.Inertia(1.0, 'kg*m^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'kg*m^2')", "q = quantity.Inertia(1.0, 'amu*angstrom^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si * constants.Na * 1e+23...
<|body_start_0|> q = quantity.Inertia(1.0, 'kg*m^2') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06) self.assertEqual(q.units, 'kg*m^2') <|end_body_0|> <|body_start_1|> q = quantity.Inertia(1.0, 'amu*angstrom^2') self.assertAl...
Contains unit tests of the Inertia unit type object.
TestInertia
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestInertia: """Contains unit tests of the Inertia unit type object.""" def test_kg_m2(self): """Test the creation of a moment of inertia quantity with units of kg*m^2.""" <|body_0|> def test_amu_angstrom2(self): """Test the creation of a moment of inertia quanti...
stack_v2_sparse_classes_36k_train_000509
33,010
permissive
[ { "docstring": "Test the creation of a moment of inertia quantity with units of kg*m^2.", "name": "test_kg_m2", "signature": "def test_kg_m2(self)" }, { "docstring": "Test the creation of a moment of inertia quantity with units of amu*angstrom^2.", "name": "test_amu_angstrom2", "signatur...
2
stack_v2_sparse_classes_30k_train_009005
Implement the Python class `TestInertia` described below. Class description: Contains unit tests of the Inertia unit type object. Method signatures and docstrings: - def test_kg_m2(self): Test the creation of a moment of inertia quantity with units of kg*m^2. - def test_amu_angstrom2(self): Test the creation of a mom...
Implement the Python class `TestInertia` described below. Class description: Contains unit tests of the Inertia unit type object. Method signatures and docstrings: - def test_kg_m2(self): Test the creation of a moment of inertia quantity with units of kg*m^2. - def test_amu_angstrom2(self): Test the creation of a mom...
0937b2e0a955dcf21b79674a4e89f43941c0dd85
<|skeleton|> class TestInertia: """Contains unit tests of the Inertia unit type object.""" def test_kg_m2(self): """Test the creation of a moment of inertia quantity with units of kg*m^2.""" <|body_0|> def test_amu_angstrom2(self): """Test the creation of a moment of inertia quanti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestInertia: """Contains unit tests of the Inertia unit type object.""" def test_kg_m2(self): """Test the creation of a moment of inertia quantity with units of kg*m^2.""" q = quantity.Inertia(1.0, 'kg*m^2') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q....
the_stack_v2_python_sparse
rmgpy/quantityTest.py
vrlambert/RMG-Py
train
1
699dada0f6978149a95a3e76b18be7ba86887adb
[ "loss = self.compute_loss(data)\nloss['total'] = loss['total'].item()\nreturn loss", "\"\"\"load input and ground-truth data\"\"\"\ndata = self.to_device(data)\n'network forwarding'\nest_data = self.net(data)\n'computer losses'\nloss = self.net.loss(est_data, data[1])\nreturn loss" ]
<|body_start_0|> loss = self.compute_loss(data) loss['total'] = loss['total'].item() return loss <|end_body_0|> <|body_start_1|> """load input and ground-truth data""" data = self.to_device(data) 'network forwarding' est_data = self.net(data) 'computer lo...
Trainer object for pano3d.
Trainer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trainer: """Trainer object for pano3d.""" def eval_step(self, data): """performs a step in evaluation :param data (dict): data dictionary :return:""" <|body_0|> def compute_loss(self, data): """compute the overall loss. :param data (dict): data dictionary :return...
stack_v2_sparse_classes_36k_train_000510
778
permissive
[ { "docstring": "performs a step in evaluation :param data (dict): data dictionary :return:", "name": "eval_step", "signature": "def eval_step(self, data)" }, { "docstring": "compute the overall loss. :param data (dict): data dictionary :return:", "name": "compute_loss", "signature": "def...
2
null
Implement the Python class `Trainer` described below. Class description: Trainer object for pano3d. Method signatures and docstrings: - def eval_step(self, data): performs a step in evaluation :param data (dict): data dictionary :return: - def compute_loss(self, data): compute the overall loss. :param data (dict): da...
Implement the Python class `Trainer` described below. Class description: Trainer object for pano3d. Method signatures and docstrings: - def eval_step(self, data): performs a step in evaluation :param data (dict): data dictionary :return: - def compute_loss(self, data): compute the overall loss. :param data (dict): da...
8628c19b8113a64d529def5447a207a77143f916
<|skeleton|> class Trainer: """Trainer object for pano3d.""" def eval_step(self, data): """performs a step in evaluation :param data (dict): data dictionary :return:""" <|body_0|> def compute_loss(self, data): """compute the overall loss. :param data (dict): data dictionary :return...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trainer: """Trainer object for pano3d.""" def eval_step(self, data): """performs a step in evaluation :param data (dict): data dictionary :return:""" loss = self.compute_loss(data) loss['total'] = loss['total'].item() return loss def compute_loss(self, data): ...
the_stack_v2_python_sparse
models/pano3d/training.py
TrendingTechnology/DeepPanoContext
train
0
a639412340c7c976da22e0ae2f1cb875ddf94df8
[ "r = Round.query.get(round_id)\nif r is not None:\n return r.reports_data()\nabort(404, 'Unknown round_id')", "r = Round.query.get(round_id)\nif r is not None:\n r.heat_list_published = not r.heat_list_published\n db.session.commit()\n return OK\nabort(404, 'Unknown round_id')", "r = Round.query.get...
<|body_start_0|> r = Round.query.get(round_id) if r is not None: return r.reports_data() abort(404, 'Unknown round_id') <|end_body_0|> <|body_start_1|> r = Round.query.get(round_id) if r is not None: r.heat_list_published = not r.heat_list_published ...
RoundAPIReports
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoundAPIReports: def get(self, round_id): """Get reports data""" <|body_0|> def patch(self, round_id): """Publishes or hides the heat list""" <|body_1|> def post(self, round_id): """Returns data to print reports""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_36k_train_000511
25,303
no_license
[ { "docstring": "Get reports data", "name": "get", "signature": "def get(self, round_id)" }, { "docstring": "Publishes or hides the heat list", "name": "patch", "signature": "def patch(self, round_id)" }, { "docstring": "Returns data to print reports", "name": "post", "sig...
3
null
Implement the Python class `RoundAPIReports` described below. Class description: Implement the RoundAPIReports class. Method signatures and docstrings: - def get(self, round_id): Get reports data - def patch(self, round_id): Publishes or hides the heat list - def post(self, round_id): Returns data to print reports
Implement the Python class `RoundAPIReports` described below. Class description: Implement the RoundAPIReports class. Method signatures and docstrings: - def get(self, round_id): Get reports data - def patch(self, round_id): Publishes or hides the heat list - def post(self, round_id): Returns data to print reports <...
079b109fd13683a31d1d632faa5ab72cf0e78ddf
<|skeleton|> class RoundAPIReports: def get(self, round_id): """Get reports data""" <|body_0|> def patch(self, round_id): """Publishes or hides the heat list""" <|body_1|> def post(self, round_id): """Returns data to print reports""" <|body_2|> <|end_skele...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoundAPIReports: def get(self, round_id): """Get reports data""" r = Round.query.get(round_id) if r is not None: return r.reports_data() abort(404, 'Unknown round_id') def patch(self, round_id): """Publishes or hides the heat list""" r = Round.q...
the_stack_v2_python_sparse
backend/apis/round/apis.py
AlenAlic/DANCE
train
0
ed407e708913b85db248b3493889e67babb38946
[ "self.lsa_components = lsa_components\nself.tfidf_parameters = tfidf_parameters\nself._tfv = TfidfVectorizer(**self.tfidf_parameters)\nself._svd = TruncatedSVD(self.lsa_components)", "X.fillna('NA', inplace=True)\ntfidf_output_csr = self._tfv.fit_transform(X, y)\nself._svd.fit(tfidf_output_csr)\nprint('LSA explai...
<|body_start_0|> self.lsa_components = lsa_components self.tfidf_parameters = tfidf_parameters self._tfv = TfidfVectorizer(**self.tfidf_parameters) self._svd = TruncatedSVD(self.lsa_components) <|end_body_0|> <|body_start_1|> X.fillna('NA', inplace=True) tfidf_output_csr...
This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.
LSAVectorizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_...
stack_v2_sparse_classes_36k_train_000512
14,227
no_license
[ { "docstring": "This is the class' constructor. Parameters ---------- lsa_components : positive integer Number of components we want to keep. tfidf_parameters : dict (default = {\"analyzer\": \"word\", \"ngram_range\": (1, 1), \"min_df\": 10}) Dict containing parameters of TfidfVectorizer used in this class. Ea...
3
stack_v2_sparse_classes_30k_train_005892
Implement the Python class `LSAVectorizer` described below. Class description: This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis. Method signatures and docstrings: - def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): T...
Implement the Python class `LSAVectorizer` described below. Class description: This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis. Method signatures and docstrings: - def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): T...
ba9a7a15a3ae8b65cb09044489ee1d907a702909
<|skeleton|> class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LSAVectorizer: """This class defines a Scikit-Learn transformer that implements a Latent Semantic Analysis.""" def __init__(self, lsa_components, tfidf_parameters={'analyzer': 'word', 'ngram_range': (1, 1), 'min_df': 10}): """This is the class' constructor. Parameters ---------- lsa_components : ...
the_stack_v2_python_sparse
python_code/M5_Forecasting_Accuracy/m5_forecasting_accuracy/preprocessing/text_encoders.py
ThomasSELECK/src
train
0
07cc42e856cb84f94e6c47e852905cb2d90d0d75
[ "class EntryCount:\n\n def __init__(self):\n self.value = 0\n\n def add_function(self, items):\n items = list(items)\n for _ in items:\n self.value += 1\n return items\n\n def remove_function(self, items):\n items = list(items)\n for _ in items:\n ...
<|body_start_0|> class EntryCount: def __init__(self): self.value = 0 def add_function(self, items): items = list(items) for _ in items: self.value += 1 return items def remove_function(sel...
Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/removed.
EnforcerHidirSpec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnforcerHidirSpec: """Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/removed.""" def ENFORCER_HIDIR(Enforc...
stack_v2_sparse_classes_36k_train_000513
5,334
no_license
[ { "docstring": "Build a hierarchical directory. `add_function(added)` is a function that is called whenever a new (or replacement) key:value pair is added, and it should expect `added` to be a `iterable<tuple<key1, key2, ..., value>>` as an argument. The return of `add_function(added)` should be an `iterable<tu...
6
stack_v2_sparse_classes_30k_train_015464
Implement the Python class `EnforcerHidirSpec` described below. Class description: Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/rem...
Implement the Python class `EnforcerHidirSpec` described below. Class description: Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/rem...
47c1512bc2d593dd33ac55ec6137d035fff2e2a9
<|skeleton|> class EnforcerHidirSpec: """Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/removed.""" def ENFORCER_HIDIR(Enforc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnforcerHidirSpec: """Hierarchical directory. An extension of python `dict` allowing N hierarchically-ordered key types to be used to organize and access a set of values. Contains enforcement hooks that call functions whenever items are added/overwritten/removed.""" def ENFORCER_HIDIR(EnforcerHidir, dict...
the_stack_v2_python_sparse
structpy/collection/enforcer/enforcer_hidir_spec.py
jdfinch/structpy
train
0
40a96bfe0a1328d123da5121b4fac09389faa053
[ "self._client_creator = client_creator\nself._sso_region = sso_region\nself._role_name = role_name\nself._account_id = account_id\nself._start_url = start_url\nself._token_loader = token_loader\nsuper().__init__(cache, expiry_window_seconds)", "args = {'startUrl': self._start_url, 'roleName': self._role_name, 'ac...
<|body_start_0|> self._client_creator = client_creator self._sso_region = sso_region self._role_name = role_name self._account_id = account_id self._start_url = start_url self._token_loader = token_loader super().__init__(cache, expiry_window_seconds) <|end_body_0...
AWS SSO credential fetcher.
SSOCredentialFetcher
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SSOCredentialFetcher: """AWS SSO credential fetcher.""" def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None): """Instantiate class.""" <|body_0|> def _create_cache_key(self): "...
stack_v2_sparse_classes_36k_train_000514
11,021
permissive
[ { "docstring": "Instantiate class.", "name": "__init__", "signature": "def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None)" }, { "docstring": "Create a predictable cache key for the current configuration. The...
4
stack_v2_sparse_classes_30k_train_012195
Implement the Python class `SSOCredentialFetcher` described below. Class description: AWS SSO credential fetcher. Method signatures and docstrings: - def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None): Instantiate class. - def _c...
Implement the Python class `SSOCredentialFetcher` described below. Class description: AWS SSO credential fetcher. Method signatures and docstrings: - def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None): Instantiate class. - def _c...
0763b06aee07d2cf3f037a49ca0cb81a048c5deb
<|skeleton|> class SSOCredentialFetcher: """AWS SSO credential fetcher.""" def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None): """Instantiate class.""" <|body_0|> def _create_cache_key(self): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SSOCredentialFetcher: """AWS SSO credential fetcher.""" def __init__(self, start_url, sso_region, role_name, account_id, client_creator, token_loader=None, cache=None, expiry_window_seconds=None): """Instantiate class.""" self._client_creator = client_creator self._sso_region = ss...
the_stack_v2_python_sparse
runway/aws_sso_botocore/credentials.py
onicagroup/runway
train
156
5d24e7300c299defa3e0714caaca629c734027bc
[ "ret, queue = ([], [root])\nfor node in queue:\n if node is None:\n ret.append('null')\n else:\n ret.append(str(node.val))\n queue += [node.left, node.right]\nreturn ','.join(ret)", "vals = data.split(',')\nif len(vals) == 0 or vals[0] == 'null':\n return None\ndummy = root = TreeNod...
<|body_start_0|> ret, queue = ([], [root]) for node in queue: if node is None: ret.append('null') else: ret.append(str(node.val)) queue += [node.left, node.right] return ','.join(ret) <|end_body_0|> <|body_start_1|> ...
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_36k_train_000515
1,378
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_019944
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:...
1a0dbcabb0f454a4fdcc31af9b919f5d30664335
<|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_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" ret, queue = ([], [root]) for node in queue: if node is None: ret.append('null') else: ret.append(str(node.val)) ...
the_stack_v2_python_sparse
297. Serialize and Deserialize Binary Tree.py
haomingchan0811/Leetcode
train
0
65363130424ad565487f772538a11a377156418c
[ "self.head = MyLinkedListNode()\nself.tail = MyLinkedListNode()\nself.head.next = self.tail\nself.tail.prev = self.head\nself.size = 0", "def getFromHead(m):\n p = self.head\n while m > 0:\n m -= 1\n p = p.next\n return p.next.val\n\ndef getFromTail(m):\n p = self.tail\n while m > 0:\...
<|body_start_0|> self.head = MyLinkedListNode() self.tail = MyLinkedListNode() self.head.next = self.tail self.tail.prev = self.head self.size = 0 <|end_body_0|> <|body_start_1|> def getFromHead(m): p = self.head while m > 0: m -= ...
MyLinkedList
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here. Running Time: O(1)""" <|body_0|> def get(self, index: int) -> int: """Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)"""...
stack_v2_sparse_classes_36k_train_000516
3,989
permissive
[ { "docstring": "Initialize your data structure here. Running Time: O(1)", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)", "name": "get", "si...
6
stack_v2_sparse_classes_30k_train_012347
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. Running Time: O(1) - def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If ...
Implement the Python class `MyLinkedList` described below. Class description: Implement the MyLinkedList class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. Running Time: O(1) - def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If ...
4a508a982b125a3a90ea893ae70863df7c99cc70
<|skeleton|> class MyLinkedList: def __init__(self): """Initialize your data structure here. Running Time: O(1)""" <|body_0|> def get(self, index: int) -> int: """Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyLinkedList: def __init__(self): """Initialize your data structure here. Running Time: O(1)""" self.head = MyLinkedListNode() self.tail = MyLinkedListNode() self.head.next = self.tail self.tail.prev = self.head self.size = 0 def get(self, index: int) -> in...
the_stack_v2_python_sparse
solutions/707_design_linked_list.py
YiqunPeng/leetcode_pro
train
0
4fd718677ac2b8cab8337a38a0288803db112ef7
[ "self.name: str = name\nif isinstance(yaml, dict):\n path = yaml.get('path', None)\n self.path: Optional[Path] = None if path is None else Path(path)\n self.groups: Optional[List[str]] = yaml.get('groups', None)\n defaults = yaml.get('defaults', None)\n self.defaults: Optional[Defaults] = None if def...
<|body_start_0|> self.name: str = name if isinstance(yaml, dict): path = yaml.get('path', None) self.path: Optional[Path] = None if path is None else Path(path) self.groups: Optional[List[str]] = yaml.get('groups', None) defaults = yaml.get('defaults', Non...
clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group projects :ivar bool _has_projects_key: Whether the projects were listed under t...
Section
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Section: """clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group projects :ivar bool _has_projects_key: Wheth...
stack_v2_sparse_classes_36k_train_000517
2,522
permissive
[ { "docstring": "Group __init__ :param str name: Section name :param Union[dict, List[Project]] yaml: Parsed YAML python object for group :raise UnknownTypeError:", "name": "__init__", "signature": "def __init__(self, name: str, yaml: Union[dict, List[Project]])" }, { "docstring": "Return python ...
2
stack_v2_sparse_classes_30k_train_002449
Implement the Python class `Section` described below. Class description: clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group proje...
Implement the Python class `Section` described below. Class description: clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group proje...
1438fc8b1bb7379de66142ffcb0e20b459b59159
<|skeleton|> class Section: """clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group projects :ivar bool _has_projects_key: Wheth...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Section: """clowder yaml Section model class :ivar str name: Section name :ivar Optional[Path] path: Section path prefix :ivar Optional[List[str]] groups: Group names :ivar Optional[Defaults] defaults: Group defaults :ivar List[Project] projects: Group projects :ivar bool _has_projects_key: Whether the projec...
the_stack_v2_python_sparse
clowder/model/section.py
JrGoodle/clowder
train
17
fc0a960b86f0d98bf58a4f1720137d78acd42a85
[ "self.end_time_usecs = end_time_usecs\nself.error = error\nself.indexing_task_end_time_usecs = indexing_task_end_time_usecs\nself.indexing_task_start_time_usecs = indexing_task_start_time_usecs\nself.indexing_task_status = indexing_task_status\nself.indexing_task_uid = indexing_task_uid\nself.latest_expiry_time_use...
<|body_start_0|> self.end_time_usecs = end_time_usecs self.error = error self.indexing_task_end_time_usecs = indexing_task_end_time_usecs self.indexing_task_start_time_usecs = indexing_task_start_time_usecs self.indexing_task_status = indexing_task_status self.indexing_ta...
Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is creating an index of the Job Runs that occurred between the startTimeUsecs and this endTimeUsec...
RemoteRestoreIndexingStatus
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoteRestoreIndexingStatus: """Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is creating an index of the Job Runs that o...
stack_v2_sparse_classes_36k_train_000518
5,666
permissive
[ { "docstring": "Constructor for the RemoteRestoreIndexingStatus class", "name": "__init__", "signature": "def __init__(self, end_time_usecs=None, error=None, indexing_task_end_time_usecs=None, indexing_task_start_time_usecs=None, indexing_task_status=None, indexing_task_uid=None, latest_expiry_time_usec...
2
stack_v2_sparse_classes_30k_train_014543
Implement the Python class `RemoteRestoreIndexingStatus` described below. Class description: Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is c...
Implement the Python class `RemoteRestoreIndexingStatus` described below. Class description: Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is c...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RemoteRestoreIndexingStatus: """Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is creating an index of the Job Runs that o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RemoteRestoreIndexingStatus: """Implementation of the 'RemoteRestoreIndexingStatus' model. Specifies the status of an indexing task. Attributes: end_time_usecs (long|int): Specifies the end time of the time range that is being indexed. The indexing task is creating an index of the Job Runs that occurred betwe...
the_stack_v2_python_sparse
cohesity_management_sdk/models/remote_restore_indexing_status.py
cohesity/management-sdk-python
train
24
4eeb5f3a039348c101787a022a52a2da53770be0
[ "super(AuViSubNet, self).__init__()\nself.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)\nself.dropout = nn.Dropout(dropout)\nself.linear_1 = nn.Linear(hidden_size, out_size)", "_, final_states = self.rnn(x)\nh = self.dropout(final_states...
<|body_start_0|> super(AuViSubNet, self).__init__() self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True) self.dropout = nn.Dropout(dropout) self.linear_1 = nn.Linear(hidden_size, out_size) <|end_body_0|> <|body_s...
AuViSubNet
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuViSubNet: def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): """Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usa...
stack_v2_sparse_classes_36k_train_000519
7,016
permissive
[ { "docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usage of bidirectional LSTM Output: (return value in forward) a tensor of shape (batch_size, out_size)", "name": "__init__...
2
null
Implement the Python class `AuViSubNet` described below. Class description: Implement the AuViSubNet class. Method signatures and docstrings: - def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden layer dimension num_lay...
Implement the Python class `AuViSubNet` described below. Class description: Implement the AuViSubNet class. Method signatures and docstrings: - def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden layer dimension num_lay...
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class AuViSubNet: def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): """Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuViSubNet: def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): """Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usage of bidirect...
the_stack_v2_python_sparse
PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/multiTask/SELF_MM.py
Ascend/ModelZoo-PyTorch
train
23
f20f0af2f9ca6055ceea9018f6b906a10c7a6fb9
[ "self.sign_request = sign_request\nself.reminder = reminder\nself.signature_receipt = signature_receipt\nself.final_receipt = final_receipt\nself.canceled_receipt = canceled_receipt\nself.expired_receipt = expired_receipt\nself.additional_properties = additional_properties", "if dictionary is None:\n return No...
<|body_start_0|> self.sign_request = sign_request self.reminder = reminder self.signature_receipt = signature_receipt self.final_receipt = final_receipt self.canceled_receipt = canceled_receipt self.expired_receipt = expired_receipt self.additional_properties = ad...
Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications notifying the signer that they have a new ...
Notification
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Notification: """Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications no...
stack_v2_sparse_classes_36k_train_000520
5,007
permissive
[ { "docstring": "Constructor for the Notification class", "name": "__init__", "signature": "def __init__(self, sign_request=None, reminder=None, signature_receipt=None, final_receipt=None, canceled_receipt=None, expired_receipt=None, additional_properties={})" }, { "docstring": "Creates an instan...
2
null
Implement the Python class `Notification` described below. Class description: Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here y...
Implement the Python class `Notification` described below. Class description: Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here y...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class Notification: """Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications no...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Notification: """Implementation of the 'Notification' model. Setup your own notification texts, and specify specail settings. Info: you also has to setup notifications on the signers you want to notify. Attributes: sign_request (SignatureSignRequest): Here you can setup email/sms notifications notifying the s...
the_stack_v2_python_sparse
idfy_rest_client/models/notification.py
dealflowteam/Idfy
train
0
dc9944f1b1b3472fa50b0dc82455fb8e8d0c7f07
[ "self.small = []\nself.large = []\nself.size = 0", "heappush(self.small, -1 * heappushpop(self.large, num))\nself.size += 1\nwhile len(self.large) < len(self.small):\n heappush(self.large, -1 * heappop(self.small))", "if self.size % 2:\n return float(self.large[0])\nelse:\n return float(self.large[0] +...
<|body_start_0|> self.small = [] self.large = [] self.size = 0 <|end_body_0|> <|body_start_1|> heappush(self.small, -1 * heappushpop(self.large, num)) self.size += 1 while len(self.large) < len(self.small): heappush(self.large, -1 * heappop(self.small)) <|end...
MedianFinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MedianFinder: def __init__(self): """Initialize your data structure here.""" <|body_0|> def addNum(self, num): """Adds a num into the data structure. :type num: int :rtype: void""" <|body_1|> def findMedian(self): """Returns the median of current...
stack_v2_sparse_classes_36k_train_000521
1,833
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Adds a num into the data structure. :type num: int :rtype: void", "name": "addNum", "signature": "def addNum(self, num)" }, { "docstring": "Returns the ...
3
stack_v2_sparse_classes_30k_train_008004
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void - def findMedian(self): ...
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void - def findMedian(self): ...
b4da922c4e8406c486760639b71e3ec50283ca43
<|skeleton|> class MedianFinder: def __init__(self): """Initialize your data structure here.""" <|body_0|> def addNum(self, num): """Adds a num into the data structure. :type num: int :rtype: void""" <|body_1|> def findMedian(self): """Returns the median of current...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MedianFinder: def __init__(self): """Initialize your data structure here.""" self.small = [] self.large = [] self.size = 0 def addNum(self, num): """Adds a num into the data structure. :type num: int :rtype: void""" heappush(self.small, -1 * heappushpop(sel...
the_stack_v2_python_sparse
old_session/session_1/_295/_295_find_median_from_data_stream.py
YJL33/LeetCode
train
3
02235ddd5cedb1ef5fdb9338c3e95e5f26785162
[ "self.buffer_capacity = max_size\nself.num_states = num_states\nself.num_actions = num_actions\nself.clear()", "index = self.size % self.buffer_capacity\nself.state_buffer[index] = obs_tuple[0]\nself.action_buffer[index] = obs_tuple[1]\nself.next_state_buffer[index] = obs_tuple[2]\nself.reward_buffer[index] = obs...
<|body_start_0|> self.buffer_capacity = max_size self.num_states = num_states self.num_actions = num_actions self.clear() <|end_body_0|> <|body_start_1|> index = self.size % self.buffer_capacity self.state_buffer[index] = obs_tuple[0] self.action_buffer[index] = ...
Replay buffer class to store experiences for a reinforcement learning agent.
ReplayBuffer
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplayBuffer: """Replay buffer class to store experiences for a reinforcement learning agent.""" def __init__(self, max_size, num_states, num_actions): """Replay buffer class to store experiences for a reinforcement learning agent. Parameters ---------- max_size: int maximum number o...
stack_v2_sparse_classes_36k_train_000522
3,252
permissive
[ { "docstring": "Replay buffer class to store experiences for a reinforcement learning agent. Parameters ---------- max_size: int maximum number of experiences to store in the repleay buffer. When adding experiences beyond this limit, the first entry is deleted. num_state: int the dimension of the state space nu...
4
stack_v2_sparse_classes_30k_train_014608
Implement the Python class `ReplayBuffer` described below. Class description: Replay buffer class to store experiences for a reinforcement learning agent. Method signatures and docstrings: - def __init__(self, max_size, num_states, num_actions): Replay buffer class to store experiences for a reinforcement learning ag...
Implement the Python class `ReplayBuffer` described below. Class description: Replay buffer class to store experiences for a reinforcement learning agent. Method signatures and docstrings: - def __init__(self, max_size, num_states, num_actions): Replay buffer class to store experiences for a reinforcement learning ag...
2dab162a3a7bd33632fd36924b2bfb289249ffa3
<|skeleton|> class ReplayBuffer: """Replay buffer class to store experiences for a reinforcement learning agent.""" def __init__(self, max_size, num_states, num_actions): """Replay buffer class to store experiences for a reinforcement learning agent. Parameters ---------- max_size: int maximum number o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReplayBuffer: """Replay buffer class to store experiences for a reinforcement learning agent.""" def __init__(self, max_size, num_states, num_actions): """Replay buffer class to store experiences for a reinforcement learning agent. Parameters ---------- max_size: int maximum number of experiences...
the_stack_v2_python_sparse
software/python/simple_pendulum/reinforcement_learning/ddpg/replay_buffer.py
dfki-ric-underactuated-lab/torque_limited_simple_pendulum
train
37
db7182ba59e04cfd998c29f48c614622a6c75a89
[ "auth_string = self.get_auth_string(url)\nif not auth_string:\n return {}\nb64_auth = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')\nreturn {'Authorization': 'Basic %s' % b64_auth}", "username, password = self.get_username_password(url)\nif username and password:\n return '%s:%s' % (username...
<|body_start_0|> auth_string = self.get_auth_string(url) if not auth_string: return {} b64_auth = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8') return {'Authorization': 'Basic %s' % b64_auth} <|end_body_0|> <|body_start_1|> username, password = self.g...
A base for downloaders to add an HTTP basic auth header
BasicAuthDownloader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicAuthDownloader: """A base for downloaders to add an HTTP basic auth header""" def build_auth_header(self, url): """Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header ...
stack_v2_sparse_classes_36k_train_000523
2,100
permissive
[ { "docstring": "Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header name as the key and the value as the value. Both are unicode strings.", "name": "build_auth_header", "signature": "def build...
3
stack_v2_sparse_classes_30k_train_005319
Implement the Python class `BasicAuthDownloader` described below. Class description: A base for downloaders to add an HTTP basic auth header Method signatures and docstrings: - def build_auth_header(self, url): Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the ...
Implement the Python class `BasicAuthDownloader` described below. Class description: A base for downloaders to add an HTTP basic auth header Method signatures and docstrings: - def build_auth_header(self, url): Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the ...
9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20
<|skeleton|> class BasicAuthDownloader: """A base for downloaders to add an HTTP basic auth header""" def build_auth_header(self, url): """Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasicAuthDownloader: """A base for downloaders to add an HTTP basic auth header""" def build_auth_header(self, url): """Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header name as the k...
the_stack_v2_python_sparse
app/lib/package_control/downloaders/basic_auth_downloader.py
june07/packagecontrol.io
train
1
b3b36ac73791afcdd0a65a650e929c9fad049b48
[ "tz_info = timezone.get_default_timezone()\narr_date_from = datetime.strptime(str_date, '%Y-%m-%d').replace(tzinfo=tz_info)\narr_date_to = arr_date_from + timedelta(days=settings.BOOKING_DATE_RANGE_GAP)\nqueryset['departure_date__gte'] = arr_date_from\nqueryset['departure_date__lte'] = arr_date_to", "queryset = {...
<|body_start_0|> tz_info = timezone.get_default_timezone() arr_date_from = datetime.strptime(str_date, '%Y-%m-%d').replace(tzinfo=tz_info) arr_date_to = arr_date_from + timedelta(days=settings.BOOKING_DATE_RANGE_GAP) queryset['departure_date__gte'] = arr_date_from queryset['depar...
Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger
BookingShipSelectForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BookingShipSelectForm: """Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger""" def get_departure_date_query(self, queryset, str_date): """Departure date filter - timezne awar...
stack_v2_sparse_classes_36k_train_000524
13,644
no_license
[ { "docstring": "Departure date filter - timezne aware datetime object - time gap which defined beforehand in settings", "name": "get_departure_date_query", "signature": "def get_departure_date_query(self, queryset, str_date)" }, { "docstring": "Dynamically create queryset for schedule field", ...
2
stack_v2_sparse_classes_30k_train_003082
Implement the Python class `BookingShipSelectForm` described below. Class description: Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger Method signatures and docstrings: - def get_departure_date_query(self, ...
Implement the Python class `BookingShipSelectForm` described below. Class description: Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger Method signatures and docstrings: - def get_departure_date_query(self, ...
e01ac10772f484e83209c47484a2af2ad595e7f1
<|skeleton|> class BookingShipSelectForm: """Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger""" def get_departure_date_query(self, queryset, str_date): """Departure date filter - timezne awar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BookingShipSelectForm: """Booking ship select form - filter queryset based on data from directions and dates which user provided - check if schedules vessel can carry cargo or passenger""" def get_departure_date_query(self, queryset, str_date): """Departure date filter - timezne aware datetime ob...
the_stack_v2_python_sparse
port_app/booking/forms.py
vugarrahim/vugarrahim.github.io
train
0
0eeaeedb2129fc779778f6a1118801a8342b47ac
[ "n = len(nums)\nl = r = 1\noutput = [1] * n\nfor i in range(n):\n output[i] *= l\n l *= nums[i]\nfor i in range(n - 1, -1, -1):\n output[i] *= r\n r *= nums[i]\nreturn output", "result = [1] * len(nums)\nfor i, n in enumerate(nums):\n for j in range(len(result)):\n if i != j:\n re...
<|body_start_0|> n = len(nums) l = r = 1 output = [1] * n for i in range(n): output[i] *= l l *= nums[i] for i in range(n - 1, -1, -1): output[i] *= r r *= nums[i] return output <|end_body_0|> <|body_start_1|> resul...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def productExceptSelf(self, nums): """This is so cool. :type nums: List[int] :rtype: List[int]""" <|body_0|> def productExceptSelfSlow(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_000525
909
no_license
[ { "docstring": "This is so cool. :type nums: List[int] :rtype: List[int]", "name": "productExceptSelf", "signature": "def productExceptSelf(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "productExceptSelfSlow", "signature": "def productExceptSelfSlow(s...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def productExceptSelf(self, nums): This is so cool. :type nums: List[int] :rtype: List[int] - def productExceptSelfSlow(self, nums): :type nums: List[int] :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def productExceptSelf(self, nums): This is so cool. :type nums: List[int] :rtype: List[int] - def productExceptSelfSlow(self, nums): :type nums: List[int] :rtype: List[int] <|sk...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def productExceptSelf(self, nums): """This is so cool. :type nums: List[int] :rtype: List[int]""" <|body_0|> def productExceptSelfSlow(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def productExceptSelf(self, nums): """This is so cool. :type nums: List[int] :rtype: List[int]""" n = len(nums) l = r = 1 output = [1] * n for i in range(n): output[i] *= l l *= nums[i] for i in range(n - 1, -1, -1): ...
the_stack_v2_python_sparse
random/product_of_array_except_self.py
hwc1824/LeetCodeSolution
train
0
4d3407e399f277451b0f08880eb9c75e5689f085
[ "super(TrainableInitialState, self).__init__(name=name)\nwarnings.simplefilter('always', DeprecationWarning)\nwarnings.warn('Use the trainable flag in initial_state instead.', DeprecationWarning, stacklevel=2)\nif mask is not None:\n flat_mask = nest.flatten(mask)\n if not all([isinstance(m, bool) for m in fl...
<|body_start_0|> super(TrainableInitialState, self).__init__(name=name) warnings.simplefilter('always', DeprecationWarning) warnings.warn('Use the trainable flag in initial_state instead.', DeprecationWarning, stacklevel=2) if mask is not None: flat_mask = nest.flatten(mask) ...
Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a boolean mask that indicates which parts of the ini...
TrainableInitialState
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TrainableInitialState: """Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a b...
stack_v2_sparse_classes_36k_train_000526
14,770
permissive
[ { "docstring": "Constructs the Module that introduces a trainable state in the graph. It receives an initial state that will be used as the initial values for the trainable variables that the module contains, and optionally a mask that indicates the parts of the initial state that should be learnable. Args: ini...
2
stack_v2_sparse_classes_30k_train_004122
Implement the Python class `TrainableInitialState` described below. Class description: Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable....
Implement the Python class `TrainableInitialState` described below. Class description: Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable....
4e28fdf2ffd0eaefc0d23049106609421c9290b0
<|skeleton|> class TrainableInitialState: """Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TrainableInitialState: """Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a boolean mask t...
the_stack_v2_python_sparse
sunset/sunset/python/modules/rnn_core.py
SynthAI/SynthAI
train
3
8850ed7fa96daf7095108fc25b586e7021bb3b2f
[ "if not nums:\n return\nsize = len(nums)\nk = k % size\nif not k:\n return\nremain = size - k\nfor i in range(remain // 2):\n nums[i], nums[remain - 1 - i] = (nums[remain - 1 - i], nums[i])\nfor i in range(k // 2):\n nums[i + remain], nums[size - 1 - i] = (nums[size - 1 - i], nums[i + remain])\nfor i in...
<|body_start_0|> if not nums: return size = len(nums) k = k % size if not k: return remain = size - k for i in range(remain // 2): nums[i], nums[remain - 1 - i] = (nums[remain - 1 - i], nums[i]) for i in range(k // 2): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate1(self, nums: List[int], k: int) -> None: """Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O(1)""" <|body_0|> def rotate2(self, nums: List[int], k: int) -> None: """Cac...
stack_v2_sparse_classes_36k_train_000527
1,450
no_license
[ { "docstring": "Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O(1)", "name": "rotate1", "signature": "def rotate1(self, nums: List[int], k: int) -> None" }, { "docstring": "Cache the first size - k numbers and replace...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate1(self, nums: List[int], k: int) -> None: Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate1(self, nums: List[int], k: int) -> None: Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O...
c14d8829c95f61ff6691816e8c0de76b9319f389
<|skeleton|> class Solution: def rotate1(self, nums: List[int], k: int) -> None: """Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O(1)""" <|body_0|> def rotate2(self, nums: List[int], k: int) -> None: """Cac...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate1(self, nums: List[int], k: int) -> None: """Reverse solution. Reverse the first n-k and remaining k elements separately, then reverse the whole array. Time: O(n) Space: O(1)""" if not nums: return size = len(nums) k = k % size if not k: ...
the_stack_v2_python_sparse
easy/rotate-array/solution.py
hsuanhauliu/leetcode-solutions
train
0
46ff90bfd962e82e37c05f3d42574d4675c1dde3
[ "cnst = mdl_const()\nret_list = []\nret_srate = 0\nfiletype_arg = [('CSV/MAT (*.csv, *.mat)', '*.csv *.mat')]\nf_name = filedialog.askopenfilename(initialdir=cnst.fout_dflt_dir, title='Open data file: ', filetypes=filetype_arg)\ncsv_pat = re.compile('^(.)+(.csv)$')\nmat_pat = re.compile('^(.)+(.mat)$')\nif csv_pat....
<|body_start_0|> cnst = mdl_const() ret_list = [] ret_srate = 0 filetype_arg = [('CSV/MAT (*.csv, *.mat)', '*.csv *.mat')] f_name = filedialog.askopenfilename(initialdir=cnst.fout_dflt_dir, title='Open data file: ', filetypes=filetype_arg) csv_pat = re.compile('^(.)+(.csv...
This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31
ctrl_fileio
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ctrl_fileio: """This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31""" def parse_data_file(): """Generate a data list and sampling rate based on a opened MAT or CSV file. Prompts the user for a file to open. Args: None Returns: ...
stack_v2_sparse_classes_36k_train_000528
4,838
no_license
[ { "docstring": "Generate a data list and sampling rate based on a opened MAT or CSV file. Prompts the user for a file to open. Args: None Returns: data_list: List of data samples data_srate: Sampling rate of data file", "name": "parse_data_file", "signature": "def parse_data_file()" }, { "docstr...
5
stack_v2_sparse_classes_30k_train_000684
Implement the Python class `ctrl_fileio` described below. Class description: This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31 Method signatures and docstrings: - def parse_data_file(): Generate a data list and sampling rate based on a opened MAT or CSV file. ...
Implement the Python class `ctrl_fileio` described below. Class description: This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31 Method signatures and docstrings: - def parse_data_file(): Generate a data list and sampling rate based on a opened MAT or CSV file. ...
30ac8bb8ad1a6dbfa7c2181949f468213a6ae717
<|skeleton|> class ctrl_fileio: """This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31""" def parse_data_file(): """Generate a data list and sampling rate based on a opened MAT or CSV file. Prompts the user for a file to open. Args: None Returns: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ctrl_fileio: """This class defines control logic for file output and input functions. of the front end. @author: sdmay18-31""" def parse_data_file(): """Generate a data list and sampling rate based on a opened MAT or CSV file. Prompts the user for a file to open. Args: None Returns: data_list: Li...
the_stack_v2_python_sparse
src/front_end/ctrl_fileio.py
tdemps/CyDAQ
train
0
e2eb4a37cd3c8df8707e807565c967bec31a68db
[ "self.min_num = min_num\nself.max_num = max_num\nself.choice = choice\nself.target = random.randint(min_num, max_num)", "choice = self.choice\nwhile choice > 0:\n try:\n num = int(input('请输入猜测数字:'))\n except ValueError as e:\n print('请输入有效数字')\n continue\n choice -= 1\n if self.ta...
<|body_start_0|> self.min_num = min_num self.max_num = max_num self.choice = choice self.target = random.randint(min_num, max_num) <|end_body_0|> <|body_start_1|> choice = self.choice while choice > 0: try: num = int(input('请输入猜测数字:')) ...
GuessNumGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GuessNumGame: def __init__(self, min_num, max_num, choice): """:param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数""" <|body_0|> def guess(self): """猜字方法 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.min_num = min_num ...
stack_v2_sparse_classes_36k_train_000529
1,573
no_license
[ { "docstring": ":param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数", "name": "__init__", "signature": "def __init__(self, min_num, max_num, choice)" }, { "docstring": "猜字方法 :return:", "name": "guess", "signature": "def guess(self)" } ]
2
stack_v2_sparse_classes_30k_train_019080
Implement the Python class `GuessNumGame` described below. Class description: Implement the GuessNumGame class. Method signatures and docstrings: - def __init__(self, min_num, max_num, choice): :param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数 - def guess(self): 猜字方法 :return:
Implement the Python class `GuessNumGame` described below. Class description: Implement the GuessNumGame class. Method signatures and docstrings: - def __init__(self, min_num, max_num, choice): :param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数 - def guess(self): 猜字方法 :return: <|skeleton|> class GuessNumGam...
dbc54dd1017cdeacc79bc8d0856d17bb7033b11f
<|skeleton|> class GuessNumGame: def __init__(self, min_num, max_num, choice): """:param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数""" <|body_0|> def guess(self): """猜字方法 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GuessNumGame: def __init__(self, min_num, max_num, choice): """:param min_num: 最小值 :param max_num: 最大值 :param choice: 猜测次数""" self.min_num = min_num self.max_num = max_num self.choice = choice self.target = random.randint(min_num, max_num) def guess(self): ...
the_stack_v2_python_sparse
code/exercises/guess_number_game.py
Glepooek/python-learning-notes
train
2
84ce86af7df9dbf15895ab7178cd2b9880c9f3bf
[ "if graph.is_directed():\n raise ValueError('the graph is directed')\nif not is_connected(graph):\n raise ValueError('the graph is not connected')\nself.graph = graph\nself.color = dict(((node, None) for node in self.graph.iternodes()))\nself._color_list = [False] * self.graph.v()", "try:\n algorithm = B...
<|body_start_0|> if graph.is_directed(): raise ValueError('the graph is directed') if not is_connected(graph): raise ValueError('the graph is not connected') self.graph = graph self.color = dict(((node, None) for node in self.graph.iternodes())) self._colo...
Find sp-graph node coloring.
SPNodeColoring
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SPNodeColoring: """Find sp-graph node coloring.""" def __init__(self, graph): """The algorithm initialization.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> def _greedy_color(self, source): """Give node the smallest pos...
stack_v2_sparse_classes_36k_train_000530
1,800
permissive
[ { "docstring": "The algorithm initialization.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self)" }, { "docstring": "Give node the smallest possible color.", "name": "_greedy_co...
3
stack_v2_sparse_classes_30k_val_000504
Implement the Python class `SPNodeColoring` described below. Class description: Find sp-graph node coloring. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization. - def run(self): Executable pseudocode. - def _greedy_color(self, source): Give node the smallest possible color.
Implement the Python class `SPNodeColoring` described below. Class description: Find sp-graph node coloring. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization. - def run(self): Executable pseudocode. - def _greedy_color(self, source): Give node the smallest possible color. <...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class SPNodeColoring: """Find sp-graph node coloring.""" def __init__(self, graph): """The algorithm initialization.""" <|body_0|> def run(self): """Executable pseudocode.""" <|body_1|> def _greedy_color(self, source): """Give node the smallest pos...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SPNodeColoring: """Find sp-graph node coloring.""" def __init__(self, graph): """The algorithm initialization.""" if graph.is_directed(): raise ValueError('the graph is directed') if not is_connected(graph): raise ValueError('the graph is not connected') ...
the_stack_v2_python_sparse
graphtheory/seriesparallel/spnodecolor.py
kgashok/graphs-dict
train
0
c1067a5fc296d1851e30c9e59564f53ebcfa0ac8
[ "input_file = self.get_data(self.test_dir, 'jw00001001001_01101_00001_MIRIMAGE_jump.fits')\nresult = RampFitStep.call(input_file, save_opt=True, opt_name='rampfit1_opt_out.fits')\noutput_file = result[0].save(path=result[0].meta.filename.replace('jump', 'rampfit'))\nint_output = result[1].save(path=result[1].meta.f...
<|body_start_0|> input_file = self.get_data(self.test_dir, 'jw00001001001_01101_00001_MIRIMAGE_jump.fits') result = RampFitStep.call(input_file, save_opt=True, opt_name='rampfit1_opt_out.fits') output_file = result[0].save(path=result[0].meta.filename.replace('jump', 'rampfit')) int_outp...
TestMIRIRampFit
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestMIRIRampFit: def test_ramp_fit_miri1(self): """Regression test of ramp_fit step performed on MIRI data.""" <|body_0|> def test_ramp_fit_miri2(self): """Regression test of ramp_fit step performed on MIRI data.""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_000531
20,238
permissive
[ { "docstring": "Regression test of ramp_fit step performed on MIRI data.", "name": "test_ramp_fit_miri1", "signature": "def test_ramp_fit_miri1(self)" }, { "docstring": "Regression test of ramp_fit step performed on MIRI data.", "name": "test_ramp_fit_miri2", "signature": "def test_ramp_...
2
stack_v2_sparse_classes_30k_train_011204
Implement the Python class `TestMIRIRampFit` described below. Class description: Implement the TestMIRIRampFit class. Method signatures and docstrings: - def test_ramp_fit_miri1(self): Regression test of ramp_fit step performed on MIRI data. - def test_ramp_fit_miri2(self): Regression test of ramp_fit step performed ...
Implement the Python class `TestMIRIRampFit` described below. Class description: Implement the TestMIRIRampFit class. Method signatures and docstrings: - def test_ramp_fit_miri1(self): Regression test of ramp_fit step performed on MIRI data. - def test_ramp_fit_miri2(self): Regression test of ramp_fit step performed ...
e3a5b2d8bb50d92ccca46cd3bbd6585d5238000a
<|skeleton|> class TestMIRIRampFit: def test_ramp_fit_miri1(self): """Regression test of ramp_fit step performed on MIRI data.""" <|body_0|> def test_ramp_fit_miri2(self): """Regression test of ramp_fit step performed on MIRI data.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestMIRIRampFit: def test_ramp_fit_miri1(self): """Regression test of ramp_fit step performed on MIRI data.""" input_file = self.get_data(self.test_dir, 'jw00001001001_01101_00001_MIRIMAGE_jump.fits') result = RampFitStep.call(input_file, save_opt=True, opt_name='rampfit1_opt_out.fits'...
the_stack_v2_python_sparse
jwst/tests_nightly/general/miri/test_miri_steps_single.py
mperrin/jwst
train
0
918261500212eee0d6652e9ecd3db267f8bf8eea
[ "self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself.ap_dict = dict()\nself._THRESHOLD = 3", "if pkt.haslayer(scapy.Dot11) and pkt.haslayer(scapy.Dot11Beacon):\n if int(pkt[scapy.Dot11].subtype) == 8:\n bssid = pkt[scapy.Dot11].addr2\n time_stamp = pkt[scapy.Dot11Beacon].timestamp\n...
<|body_start_0|> self.logger = logger.SecureTeaLogger(__name__, debug=debug) self.ap_dict = dict() self._THRESHOLD = 3 <|end_body_0|> <|body_start_1|> if pkt.haslayer(scapy.Dot11) and pkt.haslayer(scapy.Dot11Beacon): if int(pkt[scapy.Dot11].subtype) == 8: bss...
FakeAccessPoint class.
FakeAccessPoint
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FakeAccessPoint: """FakeAccessPoint class.""" def __init__(self, debug=False): """Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" <|body_0|> def detect_fake_ap(self, pkt): """Detect fake access point by o...
stack_v2_sparse_classes_36k_train_000532
2,870
permissive
[ { "docstring": "Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None", "name": "__init__", "signature": "def __init__(self, debug=False)" }, { "docstring": "Detect fake access point by observing their time stamps. A genuine access point broadcas...
2
null
Implement the Python class `FakeAccessPoint` described below. Class description: FakeAccessPoint class. Method signatures and docstrings: - def __init__(self, debug=False): Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None - def detect_fake_ap(self, pkt): Detect f...
Implement the Python class `FakeAccessPoint` described below. Class description: FakeAccessPoint class. Method signatures and docstrings: - def __init__(self, debug=False): Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None - def detect_fake_ap(self, pkt): Detect f...
43dec187e5848b9ced8a6b4957b6e9028d4d43cd
<|skeleton|> class FakeAccessPoint: """FakeAccessPoint class.""" def __init__(self, debug=False): """Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" <|body_0|> def detect_fake_ap(self, pkt): """Detect fake access point by o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FakeAccessPoint: """FakeAccessPoint class.""" def __init__(self, debug=False): """Initialize FakeAccessPoint class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" self.logger = logger.SecureTeaLogger(__name__, debug=debug) self.ap_dict = dict() se...
the_stack_v2_python_sparse
securetea/lib/ids/r2l_rules/wireless/fake_access.py
rejahrehim/SecureTea-Project
train
1
d6947ba6ed412b7d17be54151f4d96c1a409169b
[ "if df is None:\n return False\ndf.to_csv(filename, float_format='%f')\nreturn True", "df = pd.read_csv(filename, index_col=0)\ntimestamps = df[info.colname_timestamps]\ndf.drop(info.colname_timestamps, axis=1)\nreturn (timestamps, df)" ]
<|body_start_0|> if df is None: return False df.to_csv(filename, float_format='%f') return True <|end_body_0|> <|body_start_1|> df = pd.read_csv(filename, index_col=0) timestamps = df[info.colname_timestamps] df.drop(info.colname_timestamps, axis=1) r...
Handle feeling files.
FeelFileHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeelFileHandler: """Handle feeling files.""" def save_data(cls, filename, df): """Save a feelings dataframe to a .csv""" <|body_0|> def load_data(cls, filename): """Read the feelings from csv.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if d...
stack_v2_sparse_classes_36k_train_000533
950
no_license
[ { "docstring": "Save a feelings dataframe to a .csv", "name": "save_data", "signature": "def save_data(cls, filename, df)" }, { "docstring": "Read the feelings from csv.", "name": "load_data", "signature": "def load_data(cls, filename)" } ]
2
stack_v2_sparse_classes_30k_train_008164
Implement the Python class `FeelFileHandler` described below. Class description: Handle feeling files. Method signatures and docstrings: - def save_data(cls, filename, df): Save a feelings dataframe to a .csv - def load_data(cls, filename): Read the feelings from csv.
Implement the Python class `FeelFileHandler` described below. Class description: Handle feeling files. Method signatures and docstrings: - def save_data(cls, filename, df): Save a feelings dataframe to a .csv - def load_data(cls, filename): Read the feelings from csv. <|skeleton|> class FeelFileHandler: """Handl...
38cbb8d55cec730a03899692a37273f0817875eb
<|skeleton|> class FeelFileHandler: """Handle feeling files.""" def save_data(cls, filename, df): """Save a feelings dataframe to a .csv""" <|body_0|> def load_data(cls, filename): """Read the feelings from csv.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeelFileHandler: """Handle feeling files.""" def save_data(cls, filename, df): """Save a feelings dataframe to a .csv""" if df is None: return False df.to_csv(filename, float_format='%f') return True def load_data(cls, filename): """Read the feelin...
the_stack_v2_python_sparse
backend/filesystem/feel.py
pdpino/muse-player
train
0
d48cfdcf7c832d7ab459c0a1e9f7d98a1398e882
[ "super(AtributoItemCadenaForm, self).__init__(*args, **kwargs)\nself.plantilla = plantilla\nself.nombre = 'valor_' + str(counter)\nself.fields[self.nombre] = forms.CharField()\nself.fields[self.nombre].label = self.plantilla.nombre\nself.fields[self.nombre].required = self.plantilla.requerido", "valor = self.clea...
<|body_start_0|> super(AtributoItemCadenaForm, self).__init__(*args, **kwargs) self.plantilla = plantilla self.nombre = 'valor_' + str(counter) self.fields[self.nombre] = forms.CharField() self.fields[self.nombre].label = self.plantilla.nombre self.fields[self.nombre].req...
Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str
AtributoItemCadenaForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AtributoItemCadenaForm: """Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str""" def __init__(self, *args, plantilla=None, counter=None, **kwargs): ""...
stack_v2_sparse_classes_36k_train_000534
12,403
no_license
[ { "docstring": "Constructor del form AtributoItemCadenaForm. Argumentos: - plantilla: AtributoCadena", "name": "__init__", "signature": "def __init__(self, *args, plantilla=None, counter=None, **kwargs)" }, { "docstring": "Método que valida que la longitud de la cadena no supere la especificada ...
2
null
Implement the Python class `AtributoItemCadenaForm` described below. Class description: Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str Method signatures and docstrings: - def __ini...
Implement the Python class `AtributoItemCadenaForm` described below. Class description: Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str Method signatures and docstrings: - def __ini...
423e79d437b8666f9508b4b0eeb2be67533b8b2d
<|skeleton|> class AtributoItemCadenaForm: """Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str""" def __init__(self, *args, plantilla=None, counter=None, **kwargs): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AtributoItemCadenaForm: """Form que permite crear y editar atributos dinamicos del tipo 'Cadena'. Validaciones: - La longitud del texto no debe superar la especificada en la plantilla del atributo. Campos: - str""" def __init__(self, *args, plantilla=None, counter=None, **kwargs): """Constructor ...
the_stack_v2_python_sparse
gestion_de_item/forms.py
jbust97/proyecto_is2
train
0
25c6377bf1a7101a2c8440f6ea06152f0e8bb476
[ "if not root:\n return []\nqueue = [(root, 0)]\nvalues = defaultdict(list)\nwhile queue:\n cur, height = queue.pop(0)\n values[height].append(cur.val)\n if cur.left:\n queue.append((cur.left, height + 1))\n if cur.right:\n queue.append((cur.right, height + 1))\nres = []\niter = True\nfo...
<|body_start_0|> if not root: return [] queue = [(root, 0)] values = defaultdict(list) while queue: cur, height = queue.pop(0) values[height].append(cur.val) if cur.left: queue.append((cur.left, height + 1)) if c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def zigzagLevelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root:...
stack_v2_sparse_classes_36k_train_000535
2,087
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "zigzagLevelOrder", "signature": "def zigzagLevelOrder(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "zigzagLevelOrder2", "signature": "def zigzagLevelOrder2(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_010986
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def zigzagLevelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def zigzagLevelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def zigzagLevelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] - def zigzagLevelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]] <|skeleton|> cla...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def zigzagLevelOrder2(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def zigzagLevelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" if not root: return [] queue = [(root, 0)] values = defaultdict(list) while queue: cur, height = queue.pop(0) values[height].append(cur.val...
the_stack_v2_python_sparse
103. Binary Tree Zigzag Level Order Traversal/zigzag.py
Macielyoung/LeetCode
train
1
d8e7010bbe6d8e80e80cfc2e9c932ab339a73f27
[ "if file_:\n source = ImageFile(file_)\nelse:\n return None\nfor key, value in list(self.default_options.items()):\n options.setdefault(key, value)\nname = self._get_thumbnail_filename(source, geometry_string, options)\nthumbnail = ImageFile(name, default.storage)\nreturn thumbnail", "base_url = 'thumbs'...
<|body_start_0|> if file_: source = ImageFile(file_) else: return None for key, value in list(self.default_options.items()): options.setdefault(key, value) name = self._get_thumbnail_filename(source, geometry_string, options) thumbnail = ImageF...
S3Backend
[ "MIT", "CC-BY-SA-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" ...
stack_v2_sparse_classes_36k_train_000536
1,764
permissive
[ { "docstring": "Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.", "name": "get_thumbnail", "signature": "def get_thumbnail(self, file_, geometry_st...
2
stack_v2_sparse_classes_30k_train_009516
Implement the Python class `S3Backend` described below. Class description: Implement the S3Backend class. Method signatures and docstrings: - def get_thumbnail(self, file_, geometry_string, **options): Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation...
Implement the Python class `S3Backend` described below. Class description: Implement the S3Backend class. Method signatures and docstrings: - def get_thumbnail(self, file_, geometry_string, **options): Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation...
db3f037c356a586b0eb6b9d5430ce12aa1ea7119
<|skeleton|> class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" if file_: ...
the_stack_v2_python_sparse
electionleaflets/apps/core/s3_thumbnail_store.py
DemocracyClub/electionleaflets
train
9
e92b53172eb81cfbab8f376daba44ae22013ce8b
[ "self.list = []\nself.window = size\nself.sum = 0", "if len(self.list) == self.window:\n self.sum -= self.list.pop(0)\nself.sum += val\nself.list.append(val)\nreturn self.sum / len(self.list)" ]
<|body_start_0|> self.list = [] self.window = size self.sum = 0 <|end_body_0|> <|body_start_1|> if len(self.list) == self.window: self.sum -= self.list.pop(0) self.sum += val self.list.append(val) return self.sum / len(self.list) <|end_body_1|>
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.list = [] self.window = ...
stack_v2_sparse_classes_36k_train_000537
725
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
null
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
baa6927a137765e4d7fe2d020863bca6988a1cf7
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.list = [] self.window = size self.sum = 0 def next(self, val): """:type val: int :rtype: float""" if len(self.list) == self.window: self.sum...
the_stack_v2_python_sparse
346. Moving Average from Data Stream.py
Jingwei4CMU/Leetcode
train
0
710fea9c8cb9ca215d255f212994b7883675edf2
[ "self.__logger = get_logger(__name__)\nself.__logger.info('Creating decorator ')\nself.__topics_receive__ = []\nself.__topics_send__ = []\nself.__connection__ = None\nself.cls = None", "self.__logger.info('Adding host')\nparent = self\n\ndef inner(cls):\n parent.__logger.info(f'Creating class: {cls}')\n\n c...
<|body_start_0|> self.__logger = get_logger(__name__) self.__logger.info('Creating decorator ') self.__topics_receive__ = [] self.__topics_send__ = [] self.__connection__ = None self.cls = None <|end_body_0|> <|body_start_1|> self.__logger.info('Adding host') ...
Wrap pykafka functions. Define the decorators and hold the comunication data
KafkaDecorator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KafkaDecorator: """Wrap pykafka functions. Define the decorators and hold the comunication data""" def __init__(self): """Create a KafkaDecorator.""" <|body_0|> def host(self, *args, **kargs): """Set the conenction data. Create a new version of the decorated clas...
stack_v2_sparse_classes_36k_train_000538
5,207
permissive
[ { "docstring": "Create a KafkaDecorator.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Set the conenction data. Create a new version of the decorated class that inherits from kafka_client_decorators.client.Client class Parameters ---------- *args A list of arguments ...
5
stack_v2_sparse_classes_30k_train_009288
Implement the Python class `KafkaDecorator` described below. Class description: Wrap pykafka functions. Define the decorators and hold the comunication data Method signatures and docstrings: - def __init__(self): Create a KafkaDecorator. - def host(self, *args, **kargs): Set the conenction data. Create a new version ...
Implement the Python class `KafkaDecorator` described below. Class description: Wrap pykafka functions. Define the decorators and hold the comunication data Method signatures and docstrings: - def __init__(self): Create a KafkaDecorator. - def host(self, *args, **kargs): Set the conenction data. Create a new version ...
f2c958df88c5698148aae4c5314dd39e31e995c3
<|skeleton|> class KafkaDecorator: """Wrap pykafka functions. Define the decorators and hold the comunication data""" def __init__(self): """Create a KafkaDecorator.""" <|body_0|> def host(self, *args, **kargs): """Set the conenction data. Create a new version of the decorated clas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KafkaDecorator: """Wrap pykafka functions. Define the decorators and hold the comunication data""" def __init__(self): """Create a KafkaDecorator.""" self.__logger = get_logger(__name__) self.__logger.info('Creating decorator ') self.__topics_receive__ = [] self.__...
the_stack_v2_python_sparse
kafka_client_decorators/decorators.py
cdsedson/kafka-decorator
train
1
9de96cdb4557ff0680805d7ceb2086485f2e0b52
[ "self.fasta = fasta\nself.output = output\nself.window_size = window_size\nself.max_bp_span = max_bp_span\nself.avg_bp_prob_cutoff = avg_bp_prob_cutoff\nself.complexity = complexity\nself.nbits = nbits\nself.njobs = njobs\nself.verbose = verbose", "if self.verbose:\n print('Folding sequences using RNAplfold -W...
<|body_start_0|> self.fasta = fasta self.output = output self.window_size = window_size self.max_bp_span = max_bp_span self.avg_bp_prob_cutoff = avg_bp_prob_cutoff self.complexity = complexity self.nbits = nbits self.njobs = njobs self.verbose = ve...
Compute the RNA features.
RNAVectorizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNAVectorizer: """Compute the RNA features.""" def __init__(self, fasta, output, window_size=150, max_bp_span=40, avg_bp_prob_cutoff=0.4, complexity=2, nbits=10, njobs=-1, verbose=True): """Constructor. Parameters ---------- fasta : str Fasta file containing the RNA sequences. output...
stack_v2_sparse_classes_36k_train_000539
6,638
permissive
[ { "docstring": "Constructor. Parameters ---------- fasta : str Fasta file containing the RNA sequences. output : str Name of the output file. The output file is an HDF5 containing a pandas DataFrame, in which the columns are the RNA names and the rows are the EDeN features. window_size : int (default : 150) Win...
4
stack_v2_sparse_classes_30k_train_008628
Implement the Python class `RNAVectorizer` described below. Class description: Compute the RNA features. Method signatures and docstrings: - def __init__(self, fasta, output, window_size=150, max_bp_span=40, avg_bp_prob_cutoff=0.4, complexity=2, nbits=10, njobs=-1, verbose=True): Constructor. Parameters ---------- fa...
Implement the Python class `RNAVectorizer` described below. Class description: Compute the RNA features. Method signatures and docstrings: - def __init__(self, fasta, output, window_size=150, max_bp_span=40, avg_bp_prob_cutoff=0.4, complexity=2, nbits=10, njobs=-1, verbose=True): Constructor. Parameters ---------- fa...
840007ae9da2bb89ba5a60769e3bc885579c0a39
<|skeleton|> class RNAVectorizer: """Compute the RNA features.""" def __init__(self, fasta, output, window_size=150, max_bp_span=40, avg_bp_prob_cutoff=0.4, complexity=2, nbits=10, njobs=-1, verbose=True): """Constructor. Parameters ---------- fasta : str Fasta file containing the RNA sequences. output...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNAVectorizer: """Compute the RNA features.""" def __init__(self, fasta, output, window_size=150, max_bp_span=40, avg_bp_prob_cutoff=0.4, complexity=2, nbits=10, njobs=-1, verbose=True): """Constructor. Parameters ---------- fasta : str Fasta file containing the RNA sequences. output : str Name o...
the_stack_v2_python_sparse
rnacommender/rnafeatures.py
xflicsu/RNAcommender
train
0
e8d632942b51977f54ed57e3b3dbe11fa8b4f67c
[ "def input_fn():\n return ({'age': tf.constant([1]), 'language': tf.SparseTensor(values=['english'], indices=[[0, 0]], shape=[1, 1])}, tf.constant([[1]]))\nlanguage = tf.contrib.layers.sparse_column_with_hash_bucket('language', 100)\nage = tf.contrib.layers.real_valued_column('age')\ntarget_column = layers.multi...
<|body_start_0|> def input_fn(): return ({'age': tf.constant([1]), 'language': tf.SparseTensor(values=['english'], indices=[[0, 0]], shape=[1, 1])}, tf.constant([[1]])) language = tf.contrib.layers.sparse_column_with_hash_bucket('language', 100) age = tf.contrib.layers.real_valued_co...
ComposableModelTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ComposableModelTest: def testLinearModel(self): """Tests that loss goes down with training.""" <|body_0|> def testDNNModel(self): """Tests multi-class classification using matrix data as input.""" <|body_1|> <|end_skeleton|> <|body_start_0|> def inp...
stack_v2_sparse_classes_36k_train_000540
4,936
permissive
[ { "docstring": "Tests that loss goes down with training.", "name": "testLinearModel", "signature": "def testLinearModel(self)" }, { "docstring": "Tests multi-class classification using matrix data as input.", "name": "testDNNModel", "signature": "def testDNNModel(self)" } ]
2
stack_v2_sparse_classes_30k_train_012610
Implement the Python class `ComposableModelTest` described below. Class description: Implement the ComposableModelTest class. Method signatures and docstrings: - def testLinearModel(self): Tests that loss goes down with training. - def testDNNModel(self): Tests multi-class classification using matrix data as input.
Implement the Python class `ComposableModelTest` described below. Class description: Implement the ComposableModelTest class. Method signatures and docstrings: - def testLinearModel(self): Tests that loss goes down with training. - def testDNNModel(self): Tests multi-class classification using matrix data as input. ...
6d39eeb66c63a6f0f7895befc588c9eb1dd105f9
<|skeleton|> class ComposableModelTest: def testLinearModel(self): """Tests that loss goes down with training.""" <|body_0|> def testDNNModel(self): """Tests multi-class classification using matrix data as input.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ComposableModelTest: def testLinearModel(self): """Tests that loss goes down with training.""" def input_fn(): return ({'age': tf.constant([1]), 'language': tf.SparseTensor(values=['english'], indices=[[0, 0]], shape=[1, 1])}, tf.constant([[1]])) language = tf.contrib.layer...
the_stack_v2_python_sparse
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/composable_model_test.py
Lab603/PicEncyclopedias
train
6
d3d0fa5a5fb275115480ca085ef2a4ca5c824bfb
[ "lines = read_file('globalbss.info')\n\ndef mapper(l):\n items = l.strip().split()\n return (items[0][1:].upper(), items[1])\nreturn map(mapper, lines)", "u_fl = filter(lambda f: not f.is_lib, fl)\nif docfg:\n _cg = cg()\n _cg.set_funcs(fl)\n il = _cg.visit(il)\nil = re.adjust_loclabel(il)\nre.reas...
<|body_start_0|> lines = read_file('globalbss.info') def mapper(l): items = l.strip().split() return (items[0][1:].upper(), items[1]) return map(mapper, lines) <|end_body_0|> <|body_start_1|> u_fl = filter(lambda f: not f.is_lib, fl) if docfg: ...
Code analysis skeleton
Analysis
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Analysis: """Code analysis skeleton""" def global_bss(): """Load external bss variable information""" <|body_0|> def analyze(il, fl, re, docfg=False): """Analyze code :param il: instruction list :param fl: function list :param re: symbol reconstruction object :pa...
stack_v2_sparse_classes_36k_train_000541
1,907
no_license
[ { "docstring": "Load external bss variable information", "name": "global_bss", "signature": "def global_bss()" }, { "docstring": "Analyze code :param il: instruction list :param fl: function list :param re: symbol reconstruction object :param docfg: True to evaluate call graph and cfg :return: [...
3
stack_v2_sparse_classes_30k_train_016310
Implement the Python class `Analysis` described below. Class description: Code analysis skeleton Method signatures and docstrings: - def global_bss(): Load external bss variable information - def analyze(il, fl, re, docfg=False): Analyze code :param il: instruction list :param fl: function list :param re: symbol reco...
Implement the Python class `Analysis` described below. Class description: Code analysis skeleton Method signatures and docstrings: - def global_bss(): Load external bss variable information - def analyze(il, fl, re, docfg=False): Analyze code :param il: instruction list :param fl: function list :param re: symbol reco...
aff27a9f7281e76e935a5b085160038767363eed
<|skeleton|> class Analysis: """Code analysis skeleton""" def global_bss(): """Load external bss variable information""" <|body_0|> def analyze(il, fl, re, docfg=False): """Analyze code :param il: instruction list :param fl: function list :param re: symbol reconstruction object :pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Analysis: """Code analysis skeleton""" def global_bss(): """Load external bss variable information""" lines = read_file('globalbss.info') def mapper(l): items = l.strip().split() return (items[0][1:].upper(), items[1]) return map(mapper, lines) ...
the_stack_v2_python_sparse
src/analysis/analysis_process.py
jimwangzx/adversarial-example----GNN-malware-Uroboros-ELF-
train
0
96c6d3bdf363067247f1825a28e290fb28febc1f
[ "self.maxDiff = None\nuser = User.objects.create(username='cristina@gmail.com', email='cristina@gmail.com', password='password')\nresponse = self.client.post(path=f'/api/v1/user/{user.id}/address/', data=json.dumps({'first_name': 'first_name', 'last_name': 'last_name', 'street_address': 'street_address', 'apt_nr': ...
<|body_start_0|> self.maxDiff = None user = User.objects.create(username='cristina@gmail.com', email='cristina@gmail.com', password='password') response = self.client.post(path=f'/api/v1/user/{user.id}/address/', data=json.dumps({'first_name': 'first_name', 'last_name': 'last_name', 'street_addr...
AddressCreationTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddressCreationTest: def test_create_address(self): """tests that the address information is saved to the database.""" <|body_0|> def test_create_unique_address(self): """tests that if the address already exists 200 status code is returned and the address is not adde...
stack_v2_sparse_classes_36k_train_000542
7,789
no_license
[ { "docstring": "tests that the address information is saved to the database.", "name": "test_create_address", "signature": "def test_create_address(self)" }, { "docstring": "tests that if the address already exists 200 status code is returned and the address is not added to the database.", "...
2
null
Implement the Python class `AddressCreationTest` described below. Class description: Implement the AddressCreationTest class. Method signatures and docstrings: - def test_create_address(self): tests that the address information is saved to the database. - def test_create_unique_address(self): tests that if the addres...
Implement the Python class `AddressCreationTest` described below. Class description: Implement the AddressCreationTest class. Method signatures and docstrings: - def test_create_address(self): tests that the address information is saved to the database. - def test_create_unique_address(self): tests that if the addres...
d84bdedc9ed011dc009cd1b6d42eed1925ccc977
<|skeleton|> class AddressCreationTest: def test_create_address(self): """tests that the address information is saved to the database.""" <|body_0|> def test_create_unique_address(self): """tests that if the address already exists 200 status code is returned and the address is not adde...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddressCreationTest: def test_create_address(self): """tests that the address information is saved to the database.""" self.maxDiff = None user = User.objects.create(username='cristina@gmail.com', email='cristina@gmail.com', password='password') response = self.client.post(path...
the_stack_v2_python_sparse
backend/user/tests.py
Code-Institute-Submissions/vintage-earrings
train
0
b235ca9b860ca7079725ddb4aab103380ac70aaf
[ "Questionnaire.__init__(self, df)\nself.names = ['stai_state', 'stai_trait']\nself.labels = ['STAI anxiety questionnaire - state', 'STAI anxiety questionnaire - trait']\nself.values = {'stai_state': {}, 'stai_trait': {}}\nself.code_dic = stai\nself.new_df = pd.DataFrame(0, index=self.df.index, columns=self.names)",...
<|body_start_0|> Questionnaire.__init__(self, df) self.names = ['stai_state', 'stai_trait'] self.labels = ['STAI anxiety questionnaire - state', 'STAI anxiety questionnaire - trait'] self.values = {'stai_state': {}, 'stai_trait': {}} self.code_dic = stai self.new_df = pd....
A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trait_calc() helper funtion for calculating the STATE/TRAIT score
Stai
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stai: """A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trait_calc() helper funtion for calculating...
stack_v2_sparse_classes_36k_train_000543
2,702
no_license
[ { "docstring": "Init the following arguments: names = the new columns' names (after grading) labels = labels for the columns to be written in the SPSS output file values = explanation for the value for SPSS columns - empty for this questionaire code_dic = a dictionary from each pharse to a number Parameters ---...
3
stack_v2_sparse_classes_30k_train_014059
Implement the Python class `Stai` described below. Class description: A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trai...
Implement the Python class `Stai` described below. Class description: A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trai...
26b8a2847d7202b61e67e2cd0074278a46a9f8f3
<|skeleton|> class Stai: """A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trait_calc() helper funtion for calculating...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Stai: """A class used to represent an the Spielberg‏ Anxiety Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculates the grading of the questionnaire state_trait_calc() helper funtion for calculating the STATE/TR...
the_stack_v2_python_sparse
Questionnaires/Stai.py
TechnionENIC/ENIC_scoring_program
train
0
77d8723cd663e9ab9e74c203ccad8ad6582ab89d
[ "if not s:\n return True\ns = s.lower()\nnum = len(s)\ni = 0\nj = num - 1\nwhile j - i >= 1:\n if not (s[i] >= 'a' and s[i] <= 'z' or (s[i] >= 'A' and s[i] <= 'Z') or (s[i] >= '0' and s[i] <= '9')):\n i += 1\n continue\n if not (s[j] >= 'a' and s[j] <= 'z' or (s[j] >= 'A' and s[j] <= 'Z') or ...
<|body_start_0|> if not s: return True s = s.lower() num = len(s) i = 0 j = num - 1 while j - i >= 1: if not (s[i] >= 'a' and s[i] <= 'z' or (s[i] >= 'A' and s[i] <= 'Z') or (s[i] >= '0' and s[i] <= '9')): i += 1 con...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, s): """:type s: str :rtype: bool""" <|body_0|> def isPalindrome2(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not s: return True s = s.lower() ...
stack_v2_sparse_classes_36k_train_000544
1,152
no_license
[ { "docstring": ":type s: str :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, s)" }, { "docstring": ":type s: str :rtype: bool", "name": "isPalindrome2", "signature": "def isPalindrome2(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_015157
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, s): :type s: str :rtype: bool - def isPalindrome2(self, s): :type s: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, s): :type s: str :rtype: bool - def isPalindrome2(self, s): :type s: str :rtype: bool <|skeleton|> class Solution: def isPalindrome(self, s): ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def isPalindrome(self, s): """:type s: str :rtype: bool""" <|body_0|> def isPalindrome2(self, s): """:type s: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, s): """:type s: str :rtype: bool""" if not s: return True s = s.lower() num = len(s) i = 0 j = num - 1 while j - i >= 1: if not (s[i] >= 'a' and s[i] <= 'z' or (s[i] >= 'A' and s[i] <= 'Z') or (s[i...
the_stack_v2_python_sparse
125. Valid Palindrome/palindrome.py
Macielyoung/LeetCode
train
1
39d736d0fed6ec7343728649d5e8fb31174cdbb6
[ "if isinstance(symbol, (SymbolAtom,)):\n return True\nelif containsAnonymousList(symbol):\n return False\nelif containsOr(symbol):\n return False\nelse:\n return True", "if isinstance(symbol, (SymbolAtom,)):\n return False\nelif isinstance(symbol, (SymbolList,)):\n return True\nelse:\n while ...
<|body_start_0|> if isinstance(symbol, (SymbolAtom,)): return True elif containsAnonymousList(symbol): return False elif containsOr(symbol): return False else: return True <|end_body_0|> <|body_start_1|> if isinstance(symbol, (Symb...
generated source for class GdlValidator
GdlValidator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GdlValidator: """generated source for class GdlValidator""" def validate(self, symbol): """generated source for method validate""" <|body_0|> def containsAnonymousList(self, symbol): """generated source for method containsAnonymousList""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_000545
3,334
permissive
[ { "docstring": "generated source for method validate", "name": "validate", "signature": "def validate(self, symbol)" }, { "docstring": "generated source for method containsAnonymousList", "name": "containsAnonymousList", "signature": "def containsAnonymousList(self, symbol)" }, { ...
3
null
Implement the Python class `GdlValidator` described below. Class description: generated source for class GdlValidator Method signatures and docstrings: - def validate(self, symbol): generated source for method validate - def containsAnonymousList(self, symbol): generated source for method containsAnonymousList - def ...
Implement the Python class `GdlValidator` described below. Class description: generated source for class GdlValidator Method signatures and docstrings: - def validate(self, symbol): generated source for method validate - def containsAnonymousList(self, symbol): generated source for method containsAnonymousList - def ...
4e6e6e876c3a4294cd711647051da2d9c1836b60
<|skeleton|> class GdlValidator: """generated source for class GdlValidator""" def validate(self, symbol): """generated source for method validate""" <|body_0|> def containsAnonymousList(self, symbol): """generated source for method containsAnonymousList""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GdlValidator: """generated source for class GdlValidator""" def validate(self, symbol): """generated source for method validate""" if isinstance(symbol, (SymbolAtom,)): return True elif containsAnonymousList(symbol): return False elif containsOr(sym...
the_stack_v2_python_sparse
ggpy/cruft/autocode/GdlValidator.py
hobson/ggpy
train
1
fe04cfdc4e7d304ec81da5b2f41c3572dca0f4d3
[ "options = super()._default_run_options()\noptions.meas_level = MeasLevel.KERNELED\noptions.meas_return = MeasReturnType.SINGLE\nreturn options", "options = super()._default_experiment_options()\noptions.n_states = 2\noptions.schedules = None\nreturn options", "super().__init__(physical_qubits, analysis=MultiSt...
<|body_start_0|> options = super()._default_run_options() options.meas_level = MeasLevel.KERNELED options.meas_return = MeasReturnType.SINGLE return options <|end_body_0|> <|body_start_1|> options = super()._default_experiment_options() options.n_states = 2 optio...
An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For, e.g., :math:`n=4` the circuits are of the form .. parsed-literal:: Circuit preparing :math...
MultiStateDiscrimination
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiStateDiscrimination: """An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For, e.g., :math:`n=4` the circuits are of ...
stack_v2_sparse_classes_36k_train_000546
5,401
permissive
[ { "docstring": "Default option values for the experiment :meth:`run` method.", "name": "_default_run_options", "signature": "def _default_run_options(cls) -> Options" }, { "docstring": "Default values for the number of states if none is given. Experiment Options: n_states (int): The number of st...
4
null
Implement the Python class `MultiStateDiscrimination` described below. Class description: An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For,...
Implement the Python class `MultiStateDiscrimination` described below. Class description: An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For,...
a387675a3fe817cef05b968bbf3e05799a09aaae
<|skeleton|> class MultiStateDiscrimination: """An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For, e.g., :math:`n=4` the circuits are of ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiStateDiscrimination: """An experiment that discriminates between the first :math:`n` energy states. # section: overview The experiment creates :math:`n` circuits that prepare, respectively, the energy states :math:`|0\\rangle,\\cdots,|n-1\\rangle`. For, e.g., :math:`n=4` the circuits are of the form .. p...
the_stack_v2_python_sparse
qiskit_experiments/library/characterization/multi_state_discrimination.py
oliverdial/qiskit-experiments
train
0
68edf807f129b92d99d60602870d197e2db17fb0
[ "try:\n user = User.objects.get(pk=pk)\n serializer = UserSerializer(user, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)", "users = User.objects.all().order_by('-is_staff')\nserializer = UserSerializer(users, many=True, c...
<|body_start_0|> try: user = User.objects.get(pk=pk) serializer = UserSerializer(user, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) <|end_body_0|> <|body_start_1|> users ...
UserViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserViewSet: def retrieve(self, request, pk=None): """Handle GET requests for single user returns: Response -- JSON serialized user""" <|body_0|> def list(self, request): """Handle GET requests to get all users Returns: Response -- JSON serialized list of users""" ...
stack_v2_sparse_classes_36k_train_000547
1,271
no_license
[ { "docstring": "Handle GET requests for single user returns: Response -- JSON serialized user", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "Handle GET requests to get all users Returns: Response -- JSON serialized list of users", "name": "list",...
2
stack_v2_sparse_classes_30k_train_021049
Implement the Python class `UserViewSet` described below. Class description: Implement the UserViewSet class. Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single user returns: Response -- JSON serialized user - def list(self, request): Handle GET requests to get al...
Implement the Python class `UserViewSet` described below. Class description: Implement the UserViewSet class. Method signatures and docstrings: - def retrieve(self, request, pk=None): Handle GET requests for single user returns: Response -- JSON serialized user - def list(self, request): Handle GET requests to get al...
bd996853f6bd9a95d15115248300e6d801c0dc47
<|skeleton|> class UserViewSet: def retrieve(self, request, pk=None): """Handle GET requests for single user returns: Response -- JSON serialized user""" <|body_0|> def list(self, request): """Handle GET requests to get all users Returns: Response -- JSON serialized list of users""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserViewSet: def retrieve(self, request, pk=None): """Handle GET requests for single user returns: Response -- JSON serialized user""" try: user = User.objects.get(pk=pk) serializer = UserSerializer(user, context={'request': request}) return Response(seriali...
the_stack_v2_python_sparse
capstoneapi/views/user.py
jeaninebeckle/backend-capstone-api
train
0
17d6169090f2bcd7b73f08bb21894e3c940a14ee
[ "nodes_gpu = max(1, int(ceil(ngpus / cls.gpus_per_node)))\nnodes_cpu = max(1, int(ceil(ncpus / cls.cores_per_node)))\nif nodes_gpu >= nodes_cpu:\n check_utilization(nodes_gpu, ngpus, cls.gpus_per_node, threshold, 'compute')\n return nodes_gpu\ncheck_utilization(nodes_cpu, ncpus, cls.cores_per_node, threshold,...
<|body_start_0|> nodes_gpu = max(1, int(ceil(ngpus / cls.gpus_per_node))) nodes_cpu = max(1, int(ceil(ncpus / cls.cores_per_node))) if nodes_gpu >= nodes_cpu: check_utilization(nodes_gpu, ngpus, cls.gpus_per_node, threshold, 'compute') return nodes_gpu check_utili...
Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html
FrontierEnvironment
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrontierEnvironment: """Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html""" def calc_num_nodes(cls, ngpus, ncpus, threshold): """Compute the number of nodes needed to meet the resource request. Also raise an error when th...
stack_v2_sparse_classes_36k_train_000548
10,994
permissive
[ { "docstring": "Compute the number of nodes needed to meet the resource request. Also raise an error when the requested resource do not come close to saturating the asked for nodes.", "name": "calc_num_nodes", "signature": "def calc_num_nodes(cls, ngpus, ncpus, threshold)" }, { "docstring": "Get...
2
stack_v2_sparse_classes_30k_train_007621
Implement the Python class `FrontierEnvironment` described below. Class description: Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html Method signatures and docstrings: - def calc_num_nodes(cls, ngpus, ncpus, threshold): Compute the number of nodes needed ...
Implement the Python class `FrontierEnvironment` described below. Class description: Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html Method signatures and docstrings: - def calc_num_nodes(cls, ngpus, ncpus, threshold): Compute the number of nodes needed ...
845865c5f34135243ac21800495c46c915662c64
<|skeleton|> class FrontierEnvironment: """Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html""" def calc_num_nodes(cls, ngpus, ncpus, threshold): """Compute the number of nodes needed to meet the resource request. Also raise an error when th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrontierEnvironment: """Environment profile for the Frontier supercomputer. https://docs.olcf.ornl.gov/systems/frontier_user_guide.html""" def calc_num_nodes(cls, ngpus, ncpus, threshold): """Compute the number of nodes needed to meet the resource request. Also raise an error when the requested r...
the_stack_v2_python_sparse
flow/environments/incite.py
glotzerlab/signac-flow
train
54
5bb00eab175218c14123f30ae3f02272492d26f3
[ "self.username = username\npassword = password.encode('utf8')\nself.password = md5(password).hexdigest()\nself.soft_id = soft_id\nself.base_params = {'user': self.username, 'pass2': self.password, 'softid': self.soft_id}\nself.headers = {'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8',...
<|body_start_0|> self.username = username password = password.encode('utf8') self.password = md5(password).hexdigest() self.soft_id = soft_id self.base_params = {'user': self.username, 'pass2': self.password, 'softid': self.soft_id} self.headers = {'Accept-Encoding': 'gzi...
Chaojiying
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chaojiying: def __init__(self, username, password, soft_id): """:param username: :param password: :param soft_id:""" <|body_0|> def PostPic(self, im, codetype): """:param im: 图片字节 :param codetype: 题目类型 参考 http://www.chaojiying.com/price.html :return:""" <|bod...
stack_v2_sparse_classes_36k_train_000549
7,494
no_license
[ { "docstring": ":param username: :param password: :param soft_id:", "name": "__init__", "signature": "def __init__(self, username, password, soft_id)" }, { "docstring": ":param im: 图片字节 :param codetype: 题目类型 参考 http://www.chaojiying.com/price.html :return:", "name": "PostPic", "signature...
3
stack_v2_sparse_classes_30k_train_013176
Implement the Python class `Chaojiying` described below. Class description: Implement the Chaojiying class. Method signatures and docstrings: - def __init__(self, username, password, soft_id): :param username: :param password: :param soft_id: - def PostPic(self, im, codetype): :param im: 图片字节 :param codetype: 题目类型 参考...
Implement the Python class `Chaojiying` described below. Class description: Implement the Chaojiying class. Method signatures and docstrings: - def __init__(self, username, password, soft_id): :param username: :param password: :param soft_id: - def PostPic(self, im, codetype): :param im: 图片字节 :param codetype: 题目类型 参考...
a9705ebc3a6f95160ad9571d48675bc59876bd32
<|skeleton|> class Chaojiying: def __init__(self, username, password, soft_id): """:param username: :param password: :param soft_id:""" <|body_0|> def PostPic(self, im, codetype): """:param im: 图片字节 :param codetype: 题目类型 参考 http://www.chaojiying.com/price.html :return:""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Chaojiying: def __init__(self, username, password, soft_id): """:param username: :param password: :param soft_id:""" self.username = username password = password.encode('utf8') self.password = md5(password).hexdigest() self.soft_id = soft_id self.base_params = {...
the_stack_v2_python_sparse
codes/Module_4/lecture_23/lecture_23_1.py
Gedanke/Reptile_study_notes
train
5
b0097f8c7c50f1f2c852f612e3ad08f171c752af
[ "app.config['TESTING'] = True\nself.client = app.test_client()\nconnect_to_db(app, 'postgresql:///testdb')\ndb.drop_all()\ndb.create_all()\ncreate_test_data()", "db.session.remove()\ndb.drop_all()\ndb.engine.dispose()", "result = self.client.get('/')\nself.assertIn(b'IM_Melon', result.data)\nself.assertEqual(re...
<|body_start_0|> app.config['TESTING'] = True self.client = app.test_client() connect_to_db(app, 'postgresql:///testdb') db.drop_all() db.create_all() create_test_data() <|end_body_0|> <|body_start_1|> db.session.remove() db.drop_all() db.engine.d...
Flask tests.
FlaskTestBasic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FlaskTestBasic: """Flask tests.""" def setUp(self): """Run code before every test""" <|body_0|> def tearDown(self): """Run this at the end of every test.""" <|body_1|> def test_index(self): """Test homepage""" <|body_2|> def test...
stack_v2_sparse_classes_36k_train_000550
4,379
no_license
[ { "docstring": "Run code before every test", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Run this at the end of every test.", "name": "tearDown", "signature": "def tearDown(self)" }, { "docstring": "Test homepage", "name": "test_index", "signature":...
4
stack_v2_sparse_classes_30k_train_011683
Implement the Python class `FlaskTestBasic` described below. Class description: Flask tests. Method signatures and docstrings: - def setUp(self): Run code before every test - def tearDown(self): Run this at the end of every test. - def test_index(self): Test homepage - def test_addnewmelon(self): Test add new melon p...
Implement the Python class `FlaskTestBasic` described below. Class description: Flask tests. Method signatures and docstrings: - def setUp(self): Run code before every test - def tearDown(self): Run this at the end of every test. - def test_index(self): Test homepage - def test_addnewmelon(self): Test add new melon p...
81f76323e660a97e46b479099ab02591be6ce4e4
<|skeleton|> class FlaskTestBasic: """Flask tests.""" def setUp(self): """Run code before every test""" <|body_0|> def tearDown(self): """Run this at the end of every test.""" <|body_1|> def test_index(self): """Test homepage""" <|body_2|> def test...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FlaskTestBasic: """Flask tests.""" def setUp(self): """Run code before every test""" app.config['TESTING'] = True self.client = app.test_client() connect_to_db(app, 'postgresql:///testdb') db.drop_all() db.create_all() create_test_data() def te...
the_stack_v2_python_sparse
test.py
kioshi87/IM_Melon
train
6
010a5eda3d42169112042145140e28c0d5d19a12
[ "try:\n userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender}\nexcept AttributeError as e:\n detailForm = DetailForm()\nelse:\n detailForm = DetailForm(userDetail)\nreturn render(request, 'usermgr/user/userdetail.html', locals())...
<|body_start_0|> try: userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender} except AttributeError as e: detailForm = DetailForm() else: detailForm = DetailForm(userDetail) re...
处理用户信息相关请求
UserDetail
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserDetail: """处理用户信息相关请求""" def get(self, request): """处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面""" <|body_0|> def post(self, request): """处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_000551
12,349
no_license
[ { "docstring": "处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面", "name": "get", "signature": "def get(self, request)" }, { "docstring": "处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果", "name": "post", "signature": "def post(self, request)"...
3
stack_v2_sparse_classes_30k_train_013263
Implement the Python class `UserDetail` described below. Class description: 处理用户信息相关请求 Method signatures and docstrings: - def get(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面 - def post(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果 - ...
Implement the Python class `UserDetail` described below. Class description: 处理用户信息相关请求 Method signatures and docstrings: - def get(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面 - def post(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果 - ...
26c49e8f525ca57dca27f8de53d15bcab24d00e4
<|skeleton|> class UserDetail: """处理用户信息相关请求""" def get(self, request): """处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面""" <|body_0|> def post(self, request): """处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserDetail: """处理用户信息相关请求""" def get(self, request): """处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面""" try: userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender} ex...
the_stack_v2_python_sparse
iframe_api/views.py
A35-Zhou/Rental-House-Manager
train
0
f461c7d0144dcee17906fbafed05a10af8fb7723
[ "self.interpreter = interpreter\nassert os.path.isfile(interpreter) and os.path.exists(interpreter), \"'%s' is not a valid interpreter path\" % interpreter\nself.paths = paths\nself.flags = flags\nself.environ = environ", "rt_env = self._runtime_environment(self.paths)\narg_string = ''\nif len(args):\n arg_str...
<|body_start_0|> self.interpreter = interpreter assert os.path.isfile(interpreter) and os.path.exists(interpreter), "'%s' is not a valid interpreter path" % interpreter self.paths = paths self.flags = flags self.environ = environ <|end_body_0|> <|body_start_1|> rt_env = ...
For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard libraries if these are installed in non-st...
MayaPyManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MayaPyManager: """For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard l...
stack_v2_sparse_classes_36k_train_000552
9,665
permissive
[ { "docstring": "Create a MayaPyManager for ths supplied interpreter and paths Arguments: - intepreter is a disk path to a maya python interpreter - environ is a dictionary of environment variables. If no dictionary is provided, intepreter will use os.environ. - paths is an array of strings. It will completely r...
6
null
Implement the Python class `MayaPyManager` described below. Class description: For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions m...
Implement the Python class `MayaPyManager` described below. Class description: For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions m...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class MayaPyManager: """For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MayaPyManager: """For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard libraries if t...
the_stack_v2_python_sparse
dockerized-gists/2c712a91155c7e1c4c15/snippet.py
gistable/gistable
train
76
1ca63ad43b40cf7cde85bc1e26fb8a38c12bc5aa
[ "if not persno:\n from cdb import auth\n persno = auth.persno\nif not Subscription.ByKeys(object_id, persno):\n fields = clss.MakeChangeControlAttributes()\n fields['channel_cdb_object_id'] = object_id\n fields['personalnummer'] = persno\n Subscription.Create(**fields)", "if not persno:\n fro...
<|body_start_0|> if not persno: from cdb import auth persno = auth.persno if not Subscription.ByKeys(object_id, persno): fields = clss.MakeChangeControlAttributes() fields['channel_cdb_object_id'] = object_id fields['personalnummer'] = persno ...
Subscription
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subscription: def subscribeToChannel(clss, object_id, persno=''): """Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``None``. If not the entry will be generated.""" <|body_0|> def unsubscribeFromChannel(clss...
stack_v2_sparse_classes_36k_train_000553
19,136
no_license
[ { "docstring": "Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``None``. If not the entry will be generated.", "name": "subscribeToChannel", "signature": "def subscribeToChannel(clss, object_id, persno='')" }, { "docstring": "Ch...
3
null
Implement the Python class `Subscription` described below. Class description: Implement the Subscription class. Method signatures and docstrings: - def subscribeToChannel(clss, object_id, persno=''): Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``N...
Implement the Python class `Subscription` described below. Class description: Implement the Subscription class. Method signatures and docstrings: - def subscribeToChannel(clss, object_id, persno=''): Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``N...
6bc932c67bc8d93b873838ae6d9fb8d33c72234d
<|skeleton|> class Subscription: def subscribeToChannel(clss, object_id, persno=''): """Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``None``. If not the entry will be generated.""" <|body_0|> def unsubscribeFromChannel(clss...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Subscription: def subscribeToChannel(clss, object_id, persno=''): """Checks whether there is a subscription entry for the user identified by `persno` or the active user if `persno` is ``None``. If not the entry will be generated.""" if not persno: from cdb import auth p...
the_stack_v2_python_sparse
site-packages/cs.activitystream-15.3.1.4-py2.7.egg/cs/activitystream/objects.py
prachipainuly-rbei/devops-poc
train
0
447f5b04de5b3b0eb3204f9c86f10d609ea98244
[ "dummy = ListNode(0)\ndummy.next = head\nfirst = head\nlength = 0\nwhile first:\n first = first.next\n length += 1\nlength -= n\nfirst = dummy\nwhile length:\n length -= 1\n first = first.next\nfirst.next = first.next.next\nreturn dummy.next", "first = head\nsecond = first\nwhile n:\n n -= 1\n f...
<|body_start_0|> dummy = ListNode(0) dummy.next = head first = head length = 0 while first: first = first.next length += 1 length -= n first = dummy while length: length -= 1 first = first.next first....
LinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkedList: def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': """Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:""" <|body_0|> def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode': """Appr...
stack_v2_sparse_classes_36k_train_000554
1,555
no_license
[ { "docstring": "Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:", "name": "remove_nth_node_", "signature": "def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode'" }, { "docstring": "Approach: Single Pass Time Complexity: O(N) Space Com...
2
null
Implement the Python class `LinkedList` described below. Class description: Implement the LinkedList class. Method signatures and docstrings: - def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return: - def remo...
Implement the Python class `LinkedList` described below. Class description: Implement the LinkedList class. Method signatures and docstrings: - def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return: - def remo...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class LinkedList: def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': """Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:""" <|body_0|> def remove_nth_node(self, head: 'ListNode', n: int) -> 'ListNode': """Appr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinkedList: def remove_nth_node_(self, head: 'ListNode', n: int) -> 'ListNode': """Approach: Two Pass Time Complexity: O(N) Space Complexity: O(1) :param head: :param n: :return:""" dummy = ListNode(0) dummy.next = head first = head length = 0 while first: ...
the_stack_v2_python_sparse
revisited__2021/linked_list/remove_nth_node_from_end_of_list.py
Shiv2157k/leet_code
train
1
970f76aece79528ddec4777e1ca655789b89319e
[ "if not prices:\n return 0\nminPirce = prices[0]\nmaxProfit = 0\nfor price in prices[1:]:\n maxProfit = max(maxProfit, price - minPirce)\n minPirce = min(minPirce, price)\nreturn maxProfit", "if not prices:\n return 0\nsold, hold = (0, -prices[0])\nfor price in prices:\n prev_sold = sold\n prev_...
<|body_start_0|> if not prices: return 0 minPirce = prices[0] maxProfit = 0 for price in prices[1:]: maxProfit = max(maxProfit, price - minPirce) minPirce = min(minPirce, price) return maxProfit <|end_body_0|> <|body_start_1|> if not p...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit_121(self, prices: List[int]) -> int: """https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 *****解题思路...
stack_v2_sparse_classes_36k_train_000555
4,200
no_license
[ { "docstring": "https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 *****解题思路****** 假设当前在第 i 天,令 minPrice 表示前 i-1 天的最低价格;令 maxProfit 表示前 i-1 天的最大收益。 ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_121(self, prices: List[int]) -> int: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_121(self, prices: List[int]) -> int: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天...
42fc5de91fa724c901243b1e6bcf5641e03c2791
<|skeleton|> class Solution: def maxProfit_121(self, prices: List[int]) -> int: """https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 *****解题思路...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit_121(self, prices: List[int]) -> int: """https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 *****解题思路****** 假设当前在第 ...
the_stack_v2_python_sparse
buy_sell_stock/stock_problems.py
tianyunzqs/LeetCodePractise
train
1
a8d17d8474c2cd59bb8f179790019c23345cd4e9
[ "map_table = {}\nfor i in range(len(s)):\n a = s[i]\n b = t[i]\n if not map_table.keys().__contains__(a):\n if map_table.values().__contains__(b):\n return False\n map_table[a] = b\n elif map_table[a] != b:\n return False\nprint(map_table)\nreturn True", "m1 = [0] * 256...
<|body_start_0|> map_table = {} for i in range(len(s)): a = s[i] b = t[i] if not map_table.keys().__contains__(a): if map_table.values().__contains__(b): return False map_table[a] = b elif map_table[a] !=...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isIsomorphic1(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> map_table = {} for i in ...
stack_v2_sparse_classes_36k_train_000556
1,064
no_license
[ { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isIsomorphic1", "signature": "def isIsomorphic1(self, s, t)" }, { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isIsomorphic", "signature": "def isIsomorphic(self, s, t)" } ]
2
stack_v2_sparse_classes_30k_train_001043
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic1(self, s, t): :type s: str :type t: str :rtype: bool - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic1(self, s, t): :type s: str :type t: str :rtype: bool - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool <|skeleton|> class Solution: de...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def isIsomorphic1(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isIsomorphic1(self, s, t): """:type s: str :type t: str :rtype: bool""" map_table = {} for i in range(len(s)): a = s[i] b = t[i] if not map_table.keys().__contains__(a): if map_table.values().__contains__(b): ...
the_stack_v2_python_sparse
python/leetcode/205_Isomorphic_Strings.py
bobcaoge/my-code
train
0
3bc09cf9ba1759b2ce86e0ec6614c0821f9f04c4
[ "base_mapping = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I'}\nbase = [1000, 500, 100, 50, 10, 5, 1]\nroman = ''\nn = len(base)\nfor i, b in enumerate(base):\n result = num // b\n if result > 0:\n roman += base_mapping[b] * result\n num = num % b\n if num == 0:\n break\...
<|body_start_0|> base_mapping = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I'} base = [1000, 500, 100, 50, 10, 5, 1] roman = '' n = len(base) for i, b in enumerate(base): result = num // b if result > 0: roman += base_map...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def intToRoman(self, num): """:type num: int :rtype: str""" <|body_0|> def intToRoman_opt(self, num): """:type num: int :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> base_mapping = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10:...
stack_v2_sparse_classes_36k_train_000557
1,314
no_license
[ { "docstring": ":type num: int :rtype: str", "name": "intToRoman", "signature": "def intToRoman(self, num)" }, { "docstring": ":type num: int :rtype: str", "name": "intToRoman_opt", "signature": "def intToRoman_opt(self, num)" } ]
2
stack_v2_sparse_classes_30k_train_012257
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intToRoman(self, num): :type num: int :rtype: str - def intToRoman_opt(self, num): :type num: int :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def intToRoman(self, num): :type num: int :rtype: str - def intToRoman_opt(self, num): :type num: int :rtype: str <|skeleton|> class Solution: def intToRoman(self, num): ...
84c81fd17c652141d3d194da3481a7241c2accf6
<|skeleton|> class Solution: def intToRoman(self, num): """:type num: int :rtype: str""" <|body_0|> def intToRoman_opt(self, num): """:type num: int :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def intToRoman(self, num): """:type num: int :rtype: str""" base_mapping = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I'} base = [1000, 500, 100, 50, 10, 5, 1] roman = '' n = len(base) for i, b in enumerate(base): result ...
the_stack_v2_python_sparse
leetcode/12-integer to roman.py
harvey103565/OI-Algorithm-wareh
train
0
b89cc1a4b7aee8abf2c5c25ddf4889d97bb242cc
[ "mobile = attrs.get('mobile')\nif not re.match('1[3-9]\\\\d{9}$', mobile):\n raise serializers.ValidationError('手机号不合法。')\nif attrs.get('password') != attrs.get('password2'):\n raise serializers.ValidationError('两次输入密码不一致。')\nredis_conn = get_redis_connection('default')\nreal_sms_code = redis_conn.get('sms_%s...
<|body_start_0|> mobile = attrs.get('mobile') if not re.match('1[3-9]\\d{9}$', mobile): raise serializers.ValidationError('手机号不合法。') if attrs.get('password') != attrs.get('password2'): raise serializers.ValidationError('两次输入密码不一致。') redis_conn = get_redis_connecti...
用户注册序列化器
UserRegisterSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRegisterSerializer: """用户注册序列化器""" def validate(self, attrs): """验证数据 :param attrs: :return:""" <|body_0|> def create(self, validated_data): """重写父类create方法 :param validated_data: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> mobi...
stack_v2_sparse_classes_36k_train_000558
3,402
no_license
[ { "docstring": "验证数据 :param attrs: :return:", "name": "validate", "signature": "def validate(self, attrs)" }, { "docstring": "重写父类create方法 :param validated_data: :return:", "name": "create", "signature": "def create(self, validated_data)" } ]
2
stack_v2_sparse_classes_30k_val_000142
Implement the Python class `UserRegisterSerializer` described below. Class description: 用户注册序列化器 Method signatures and docstrings: - def validate(self, attrs): 验证数据 :param attrs: :return: - def create(self, validated_data): 重写父类create方法 :param validated_data: :return:
Implement the Python class `UserRegisterSerializer` described below. Class description: 用户注册序列化器 Method signatures and docstrings: - def validate(self, attrs): 验证数据 :param attrs: :return: - def create(self, validated_data): 重写父类create方法 :param validated_data: :return: <|skeleton|> class UserRegisterSerializer: "...
c7a57b6ac23885a6db682899d9360017708d084a
<|skeleton|> class UserRegisterSerializer: """用户注册序列化器""" def validate(self, attrs): """验证数据 :param attrs: :return:""" <|body_0|> def create(self, validated_data): """重写父类create方法 :param validated_data: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserRegisterSerializer: """用户注册序列化器""" def validate(self, attrs): """验证数据 :param attrs: :return:""" mobile = attrs.get('mobile') if not re.match('1[3-9]\\d{9}$', mobile): raise serializers.ValidationError('手机号不合法。') if attrs.get('password') != attrs.get('passwo...
the_stack_v2_python_sparse
backend/backend/apps/users/serializers.py
chenya1123236324/AutomationTestPlat
train
1
707da0130932e982e2f8b26796b7c38235ff10d3
[ "Thread.__init__(self)\nself.server = server\nself.width = os.get_terminal_size().columns\nself.terminal_size = shutil.get_terminal_size(fallback=(120, 50))", "while True:\n connection_socket, addr = self.server.server_socket.accept()\n connection_socket.send(('\\n' + PrettyPrint.pretty_print('CONCORD'.cent...
<|body_start_0|> Thread.__init__(self) self.server = server self.width = os.get_terminal_size().columns self.terminal_size = shutil.get_terminal_size(fallback=(120, 50)) <|end_body_0|> <|body_start_1|> while True: connection_socket, addr = self.server.server_socket.a...
Class of thread responsible for handling incoming users
ControllerConnections
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ControllerConnections: """Class of thread responsible for handling incoming users""" def __init__(self, server) -> None: """Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: None""" <|body_0|> def run(self) -> None: ...
stack_v2_sparse_classes_36k_train_000559
1,771
permissive
[ { "docstring": "Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: None", "name": "__init__", "signature": "def __init__(self, server) -> None" }, { "docstring": "Responsible for running the thread :returns: None", "name": "run", "signat...
2
null
Implement the Python class `ControllerConnections` described below. Class description: Class of thread responsible for handling incoming users Method signatures and docstrings: - def __init__(self, server) -> None: Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: N...
Implement the Python class `ControllerConnections` described below. Class description: Class of thread responsible for handling incoming users Method signatures and docstrings: - def __init__(self, server) -> None: Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: N...
6720d1789a366bfd7943b81c7c84cb0941c66e80
<|skeleton|> class ControllerConnections: """Class of thread responsible for handling incoming users""" def __init__(self, server) -> None: """Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: None""" <|body_0|> def run(self) -> None: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ControllerConnections: """Class of thread responsible for handling incoming users""" def __init__(self, server) -> None: """Initializes the ControllerConnections class instance's attributes :param server: server obj :returns: None""" Thread.__init__(self) self.server = server ...
the_stack_v2_python_sparse
src/controllers/controller_connections.py
WebisD/chat-irc-protocol
train
0
07c9fd457e74a8c5c769b629ec0a457a7a27efed
[ "if numRows == 0:\n return []\n\ndef recurse(rows, triangle):\n if rows == 0:\n return triangle\n triangle.append(self.calculate(triangle[-1]))\n return recurse(rows - 1, triangle)\nreturn recurse(numRows - 1, [[1]])", "if numRows == 0:\n return []\noutput = [[1]]\nfor i in range(numRows - 1...
<|body_start_0|> if numRows == 0: return [] def recurse(rows, triangle): if rows == 0: return triangle triangle.append(self.calculate(triangle[-1])) return recurse(rows - 1, triangle) return recurse(numRows - 1, [[1]]) <|end_body_0...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generate(self, numRows: int) -> List[List[int]]: """Recursive solution""" <|body_0|> def generate_iterative(self, numRows: int) -> List[List[int]]: """Iterative for-loop solution; O(n) linear time complexity,""" <|body_1|> def calculate(sel...
stack_v2_sparse_classes_36k_train_000560
1,594
no_license
[ { "docstring": "Recursive solution", "name": "generate", "signature": "def generate(self, numRows: int) -> List[List[int]]" }, { "docstring": "Iterative for-loop solution; O(n) linear time complexity,", "name": "generate_iterative", "signature": "def generate_iterative(self, numRows: int...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows: int) -> List[List[int]]: Recursive solution - def generate_iterative(self, numRows: int) -> List[List[int]]: Iterative for-loop solution; O(n) linear ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generate(self, numRows: int) -> List[List[int]]: Recursive solution - def generate_iterative(self, numRows: int) -> List[List[int]]: Iterative for-loop solution; O(n) linear ...
286677fc7be84f8f8a8754c785a39d07a2c5604a
<|skeleton|> class Solution: def generate(self, numRows: int) -> List[List[int]]: """Recursive solution""" <|body_0|> def generate_iterative(self, numRows: int) -> List[List[int]]: """Iterative for-loop solution; O(n) linear time complexity,""" <|body_1|> def calculate(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def generate(self, numRows: int) -> List[List[int]]: """Recursive solution""" if numRows == 0: return [] def recurse(rows, triangle): if rows == 0: return triangle triangle.append(self.calculate(triangle[-1])) r...
the_stack_v2_python_sparse
arrays/pascals-triangle/pascals_triangle.py
mich-chen/code-challenges
train
3
faa69b4d569abd0831d5c39cc203e7352f3ff2eb
[ "super(RequeueJobsBulk, self).__init__('requeue_jobs_bulk')\nself.current_job_id = None\nself.started = None\nself.ended = None\nself.error_categories = None\nself.error_ids = None\nself.job_ids = None\nself.job_type_ids = None\nself.priority = None\nself.status = None\nself.job_type_names = None\nself.batch_ids = ...
<|body_start_0|> super(RequeueJobsBulk, self).__init__('requeue_jobs_bulk') self.current_job_id = None self.started = None self.ended = None self.error_categories = None self.error_ids = None self.job_ids = None self.job_type_ids = None self.priori...
Command message that performs a bulk re-queue operation
RequeueJobsBulk
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequeueJobsBulk: """Command message that performs a bulk re-queue operation""" def __init__(self): """Constructor""" <|body_0|> def to_json(self): """See :meth:`messaging.messages.message.CommandMessage.to_json`""" <|body_1|> def from_json(json_dict)...
stack_v2_sparse_classes_36k_train_000561
8,523
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "See :meth:`messaging.messages.message.CommandMessage.to_json`", "name": "to_json", "signature": "def to_json(self)" }, { "docstring": "See :meth:`messaging.messages.message.Comm...
4
null
Implement the Python class `RequeueJobsBulk` described below. Class description: Command message that performs a bulk re-queue operation Method signatures and docstrings: - def __init__(self): Constructor - def to_json(self): See :meth:`messaging.messages.message.CommandMessage.to_json` - def from_json(json_dict): Se...
Implement the Python class `RequeueJobsBulk` described below. Class description: Command message that performs a bulk re-queue operation Method signatures and docstrings: - def __init__(self): Constructor - def to_json(self): See :meth:`messaging.messages.message.CommandMessage.to_json` - def from_json(json_dict): Se...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class RequeueJobsBulk: """Command message that performs a bulk re-queue operation""" def __init__(self): """Constructor""" <|body_0|> def to_json(self): """See :meth:`messaging.messages.message.CommandMessage.to_json`""" <|body_1|> def from_json(json_dict)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequeueJobsBulk: """Command message that performs a bulk re-queue operation""" def __init__(self): """Constructor""" super(RequeueJobsBulk, self).__init__('requeue_jobs_bulk') self.current_job_id = None self.started = None self.ended = None self.error_categ...
the_stack_v2_python_sparse
scale/queue/messages/requeue_jobs_bulk.py
kfconsultant/scale
train
0
26902aa755d009427e4904aaa1f93905bf2e2470
[ "height = 0\nwhile root:\n height += 1\n root = root.left\nreturn height", "if not root:\n return 0\nl_h = self.height(root.left)\nr_h = self.height(root.right)\nnodes = 0\nif l_h == r_h:\n nodes = 2 ** l_h - 1 + 1 + self.countNodes(root.right)\nelse:\n nodes = 2 ** r_h - 1 + 1 + self.countNodes(ro...
<|body_start_0|> height = 0 while root: height += 1 root = root.left return height <|end_body_0|> <|body_start_1|> if not root: return 0 l_h = self.height(root.left) r_h = self.height(root.right) nodes = 0 if l_h == r_h...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def height(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def countNodes(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> height = 0 while root: height += ...
stack_v2_sparse_classes_36k_train_000562
862
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "height", "signature": "def height(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "countNodes", "signature": "def countNodes(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def height(self, root): :type root: TreeNode :rtype: int - def countNodes(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def height(self, root): :type root: TreeNode :rtype: int - def countNodes(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def height(self, root):...
9bd2d706f014ce84356ba38fc7801da0285a91d3
<|skeleton|> class Solution: def height(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def countNodes(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def height(self, root): """:type root: TreeNode :rtype: int""" height = 0 while root: height += 1 root = root.left return height def countNodes(self, root): """:type root: TreeNode :rtype: int""" if not root: re...
the_stack_v2_python_sparse
leetcode/countNodes-222.py
pittcat/Algorithm_Practice
train
0
4bccc69ad21ca874c6040662089e9b4790183327
[ "self.bnet = bnet\nself.do_print = do_print\nself.is_quantum = is_quantum", "story_line = ''\nfor node in annotated_story.keys():\n story_line += node.name + '='\n story_line += str(annotated_story[node]) + ', '\nprint(story_line[:-2])" ]
<|body_start_0|> self.bnet = bnet self.do_print = do_print self.is_quantum = is_quantum <|end_body_0|> <|body_start_1|> story_line = '' for node in annotated_story.keys(): story_line += node.name + '=' story_line += str(annotated_story[node]) + ', ' ...
This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool
InferenceEngine
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InferenceEngine: """This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool""" def __init__(self, bnet, do_print=False, is_quantum=False): """Constructor Parameters ---------- bnet : BayesNet do_print : bool is_quantu...
stack_v2_sparse_classes_36k_train_000563
1,264
permissive
[ { "docstring": "Constructor Parameters ---------- bnet : BayesNet do_print : bool is_quantum : bool Returns -------", "name": "__init__", "signature": "def __init__(self, bnet, do_print=False, is_quantum=False)" }, { "docstring": "Prints in a pretty way an annotated story, which is a dictionary ...
2
stack_v2_sparse_classes_30k_val_001094
Implement the Python class `InferenceEngine` described below. Class description: This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool Method signatures and docstrings: - def __init__(self, bnet, do_print=False, is_quantum=False): Constructor Parame...
Implement the Python class `InferenceEngine` described below. Class description: This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool Method signatures and docstrings: - def __init__(self, bnet, do_print=False, is_quantum=False): Constructor Parame...
92e1d2a38de92422642545623341ecd9cfb7a39f
<|skeleton|> class InferenceEngine: """This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool""" def __init__(self, bnet, do_print=False, is_quantum=False): """Constructor Parameters ---------- bnet : BayesNet do_print : bool is_quantu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InferenceEngine: """This is the parent class of all inference engines. Attributes ---------- bnet : BayesNet do_print : bool is_quantum : bool""" def __init__(self, bnet, do_print=False, is_quantum=False): """Constructor Parameters ---------- bnet : BayesNet do_print : bool is_quantum : bool Retu...
the_stack_v2_python_sparse
inference/InferenceEngine.py
Statici/quantum-fog
train
2
c40b0c63acda4376adc692aefdcf5468ef603442
[ "progress_bar = ProgressBar(spinnman_constants.MAX_TAG_ID, 'Clearing tags')\nfor tag_id in range(spinnman_constants.MAX_TAG_ID):\n transceiver.clear_ip_tag(tag_id)\n progress_bar.update()\nprogress_bar.end()\nprogress_bar = None\nif tags is not None:\n progress_bar = ProgressBar(len(list(tags.ip_tags)) + l...
<|body_start_0|> progress_bar = ProgressBar(spinnman_constants.MAX_TAG_ID, 'Clearing tags') for tag_id in range(spinnman_constants.MAX_TAG_ID): transceiver.clear_ip_tag(tag_id) progress_bar.update() progress_bar.end() progress_bar = None if tags is not Non...
Loads tags onto the machine
FrontEndCommonTagsLoader
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrontEndCommonTagsLoader: """Loads tags onto the machine""" def __call__(self, transceiver, tags=None, iptags=None, reverse_iptags=None): """:param tags: the tags object which contains ip and reverse ip tags. could be none if these are being given in separate lists :param iptags: a l...
stack_v2_sparse_classes_36k_train_000564
2,725
permissive
[ { "docstring": ":param tags: the tags object which contains ip and reverse ip tags. could be none if these are being given in separate lists :param iptags: a list of iptags, given when tags is none :param reverse_iptags: a list of reverse iptags when tags is none. :param transceiver: the transceiver object :ret...
3
stack_v2_sparse_classes_30k_train_004424
Implement the Python class `FrontEndCommonTagsLoader` described below. Class description: Loads tags onto the machine Method signatures and docstrings: - def __call__(self, transceiver, tags=None, iptags=None, reverse_iptags=None): :param tags: the tags object which contains ip and reverse ip tags. could be none if t...
Implement the Python class `FrontEndCommonTagsLoader` described below. Class description: Loads tags onto the machine Method signatures and docstrings: - def __call__(self, transceiver, tags=None, iptags=None, reverse_iptags=None): :param tags: the tags object which contains ip and reverse ip tags. could be none if t...
04fa1eaf78778edea3ba3afa4c527d20c491718e
<|skeleton|> class FrontEndCommonTagsLoader: """Loads tags onto the machine""" def __call__(self, transceiver, tags=None, iptags=None, reverse_iptags=None): """:param tags: the tags object which contains ip and reverse ip tags. could be none if these are being given in separate lists :param iptags: a l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrontEndCommonTagsLoader: """Loads tags onto the machine""" def __call__(self, transceiver, tags=None, iptags=None, reverse_iptags=None): """:param tags: the tags object which contains ip and reverse ip tags. could be none if these are being given in separate lists :param iptags: a list of iptags...
the_stack_v2_python_sparse
src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spinn_front_end_common/interface/interface_functions/front_end_common_tags_loader.py
Roboy/LSM_SpiNNaker_MyoArm
train
2
f8357c6e6d0b5a278efeee7f08179a117e68be88
[ "self.big = big\nself.medium = medium\nself.small = small", "if carType == 1:\n self.big = self.big - 1\n if self.big >= 0:\n return True\n else:\n return False\nelif carType == 2:\n self.medium = self.medium - 1\n if self.medium >= 0:\n return True\n else:\n return F...
<|body_start_0|> self.big = big self.medium = medium self.small = small <|end_body_0|> <|body_start_1|> if carType == 1: self.big = self.big - 1 if self.big >= 0: return True else: return False elif carType == 2...
ParkingSystem
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" <|body_0|> def addCar(self, carType): """:type carType: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.big = big ...
stack_v2_sparse_classes_36k_train_000565
1,839
no_license
[ { "docstring": ":type big: int :type medium: int :type small: int", "name": "__init__", "signature": "def __init__(self, big, medium, small)" }, { "docstring": ":type carType: int :rtype: bool", "name": "addCar", "signature": "def addCar(self, carType)" } ]
2
stack_v2_sparse_classes_30k_train_000504
Implement the Python class `ParkingSystem` described below. Class description: Implement the ParkingSystem class. Method signatures and docstrings: - def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int - def addCar(self, carType): :type carType: int :rtype: bool
Implement the Python class `ParkingSystem` described below. Class description: Implement the ParkingSystem class. Method signatures and docstrings: - def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int - def addCar(self, carType): :type carType: int :rtype: bool <|skeleton|> cla...
6d6afba93d20665d033fe542c97e3eb50368bd3c
<|skeleton|> class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" <|body_0|> def addCar(self, carType): """:type carType: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" self.big = big self.medium = medium self.small = small def addCar(self, carType): """:type carType: int :rtype: bool""" if carType == 1: ...
the_stack_v2_python_sparse
design_parking_system.py
naomi397liu/AlgorithmPactice
train
1
ef9af024a00c829bfb773d16dea0cd6cbb8fd4ee
[ "course_keys = value\nfor course in course_keys:\n try:\n CourseKey.from_string(course)\n except InvalidKeyError:\n raise serializers.ValidationError(f'Course key not valid: {course}')\nreturn value", "if attrs.get('cohorts'):\n if attrs['action'] != 'enroll':\n raise serializers.Val...
<|body_start_0|> course_keys = value for course in course_keys: try: CourseKey.from_string(course) except InvalidKeyError: raise serializers.ValidationError(f'Course key not valid: {course}') return value <|end_body_0|> <|body_start_1|> ...
Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.
BulkEnrollmentSerializer
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" ...
stack_v2_sparse_classes_36k_train_000566
2,612
permissive
[ { "docstring": "Check that each course key in list is valid.", "name": "validate_courses", "signature": "def validate_courses(self, value)" }, { "docstring": "Check that the cohorts list is the same size as the courses list.", "name": "validate", "signature": "def validate(self, attrs)" ...
2
stack_v2_sparse_classes_30k_train_003975
Implement the Python class `BulkEnrollmentSerializer` described below. Class description: Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations. Method signatures and docstrings: - def validate_courses(self, ...
Implement the Python class `BulkEnrollmentSerializer` described below. Class description: Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations. Method signatures and docstrings: - def validate_courses(self, ...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BulkEnrollmentSerializer: """Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.""" def validate_courses(self, value): """Check that each course key in list is valid.""" course...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/bulk_enroll/serializers.py
luque/better-ways-of-thinking-about-software
train
3
39db05e5f8928b1e9f0f42edcd2e27b1fcd61565
[ "new_ml_model = Project()\nnew_ml_model.create(dto)\nif dto.users:\n ProjectAccess.list_update(new_ml_model.id, [], dto.users)\nreturn new_ml_model.id", "ml_model = Project.get(model_id)\nif ml_model:\n ml_model.delete()\nelse:\n raise NotFound('Model does not exist')", "ml_model = Project.get(model_id...
<|body_start_0|> new_ml_model = Project() new_ml_model.create(dto) if dto.users: ProjectAccess.list_update(new_ml_model.id, [], dto.users) return new_ml_model.id <|end_body_0|> <|body_start_1|> ml_model = Project.get(model_id) if ml_model: ml_mode...
ProjectService
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectService: def subscribe_ml_model(dto: ProjectDTO) -> int: """Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model""" <|body_0|> def delete_ml_model(model_id: int): """Deletes ML model and associated predi...
stack_v2_sparse_classes_36k_train_000567
2,737
permissive
[ { "docstring": "Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model", "name": "subscribe_ml_model", "signature": "def subscribe_ml_model(dto: ProjectDTO) -> int" }, { "docstring": "Deletes ML model and associated predictions :params model...
5
null
Implement the Python class `ProjectService` described below. Class description: Implement the ProjectService class. Method signatures and docstrings: - def subscribe_ml_model(dto: ProjectDTO) -> int: Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model - def de...
Implement the Python class `ProjectService` described below. Class description: Implement the ProjectService class. Method signatures and docstrings: - def subscribe_ml_model(dto: ProjectDTO) -> int: Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model - def de...
cff1b5955c6f110e64489427dfb8902d442a0e62
<|skeleton|> class ProjectService: def subscribe_ml_model(dto: ProjectDTO) -> int: """Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model""" <|body_0|> def delete_ml_model(model_id: int): """Deletes ML model and associated predi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectService: def subscribe_ml_model(dto: ProjectDTO) -> int: """Subscribes an ML Model by saving it in the database :params dto :raises DataError :returns ID of the ml model""" new_ml_model = Project() new_ml_model.create(dto) if dto.users: ProjectAccess.list_upd...
the_stack_v2_python_sparse
ml_enabler/services/project_service.py
rustyb/ml-enabler
train
0
aee5f921b197272216abd6db0f4c73ae10077b7f
[ "for j in range(len(nums)):\n for k in range(j + 1, len(nums)):\n if nums[j] + nums[k] == target:\n return (j, k)", "memo = {}\nfor i in range(len(nums)):\n if nums[i] in memo:\n return (memo[nums[i]], i)\n elif target - nums[i] not in memo:\n memo[target - nums[i]] = i" ]
<|body_start_0|> for j in range(len(nums)): for k in range(j + 1, len(nums)): if nums[j] + nums[k] == target: return (j, k) <|end_body_0|> <|body_start_1|> memo = {} for i in range(len(nums)): if nums[i] in memo: return...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSum2(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_000568
1,211
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "twoSum", "signature": "def twoSum(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "twoSum2", "signature": "def twoSum2(self, nums, target)" }...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[...
af3b19adefb31ea17fa8096eb03a77634795a807
<|skeleton|> class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSum2(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" for j in range(len(nums)): for k in range(j + 1, len(nums)): if nums[j] + nums[k] == target: return (j, k) def twoSum2(self, nums, targ...
the_stack_v2_python_sparse
ib/5.Hashing/LC001. Two Sum.py
qq279585876/algorithm
train
0
75fb30c209f4171b12406183cba2682d00fa0e56
[ "origin_country_id = self._context.get('origin_country_ept', False)\nif not origin_country_id:\n return super(AccountFiscalPosition, self)._get_fpos_by_region(country_id=country_id, state_id=state_id, zipcode=zipcode, vat_required=vat_required)\nreturn self.search_fiscal_position_based_on_origin_country(origin_c...
<|body_start_0|> origin_country_id = self._context.get('origin_country_ept', False) if not origin_country_id: return super(AccountFiscalPosition, self)._get_fpos_by_region(country_id=country_id, state_id=state_id, zipcode=zipcode, vat_required=vat_required) return self.search_fiscal_...
AccountFiscalPosition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountFiscalPosition: def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): """Inherited this method for selecting fiscal position based on warehouse (origin country). @param country_id: @param state_id: @param zipcode: @param vat_required: ...
stack_v2_sparse_classes_36k_train_000569
2,584
no_license
[ { "docstring": "Inherited this method for selecting fiscal position based on warehouse (origin country). @param country_id: @param state_id: @param zipcode: @param vat_required: @return:", "name": "_get_fpos_by_region", "signature": "def _get_fpos_by_region(self, country_id=False, state_id=False, zipcod...
2
stack_v2_sparse_classes_30k_train_000180
Implement the Python class `AccountFiscalPosition` described below. Class description: Implement the AccountFiscalPosition class. Method signatures and docstrings: - def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): Inherited this method for selecting fiscal position ...
Implement the Python class `AccountFiscalPosition` described below. Class description: Implement the AccountFiscalPosition class. Method signatures and docstrings: - def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): Inherited this method for selecting fiscal position ...
581b23342122c0568407c1c42efd4b2085719335
<|skeleton|> class AccountFiscalPosition: def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): """Inherited this method for selecting fiscal position based on warehouse (origin country). @param country_id: @param state_id: @param zipcode: @param vat_required: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountFiscalPosition: def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): """Inherited this method for selecting fiscal position based on warehouse (origin country). @param country_id: @param state_id: @param zipcode: @param vat_required: @return:""" ...
the_stack_v2_python_sparse
modules/common_connector_library/models/account_fiscal_position.py
yspcn/odoo14-import
train
0
da870b8b761d45d90f2b88d06d0fd53082368f15
[ "assert alpha >= 0\nsuper(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma)\nself.max_priority, self.tree_ptr = (1.0, 0)\nself.alpha = alpha\ntree_capacity = 1\nwhile tree_capacity < self.max_size:\n tree_capacity *= 2\nself.sum_tree = SumSegmentTree(tree_capacity)\nself.min_tree = MinSegm...
<|body_start_0|> assert alpha >= 0 super(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma) self.max_priority, self.tree_ptr = (1.0, 0) self.alpha = alpha tree_capacity = 1 while tree_capacity < self.max_size: tree_capacity *= 2 s...
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight
PrioritizedReplayBuffer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrioritizedReplayBuffer: """Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ...
stack_v2_sparse_classes_36k_train_000570
26,535
no_license
[ { "docstring": "Initialization.", "name": "__init__", "signature": "def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99)" }, { "docstring": "Store experience and priority.", "name": "store", "signature": "def store(self, obs: OdinsynthEnvS...
6
stack_v2_sparse_classes_30k_train_003501
Implement the Python class `PrioritizedReplayBuffer` described below. Class description: Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS...
Implement the Python class `PrioritizedReplayBuffer` described below. Class description: Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS...
60e0c3389724460b5b32ba35c89d8838da4d51c9
<|skeleton|> class PrioritizedReplayBuffer: """Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrioritizedReplayBuffer: """Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weigh...
the_stack_v2_python_sparse
lrec2022-odinsynth/python/rl_rainbow_implementation.py
clulab/releases
train
29
6c7ddd7f616d26e75fa33a900a13ca836a3416ad
[ "end_date = dateutil.get_today()\nstart_date = dateutil.get_previous_date(end_date, 6)\nc = RequestContext(request, {'first_nav_name': FIRST_NAV, 'app_name': 'stats', 'second_navs': export.get_stats_second_navs(request), 'second_nav_name': export.STATS_SALES_SECOND_NAV, 'third_nav_name': export.SALES_ORDER_SUMMARY_...
<|body_start_0|> end_date = dateutil.get_today() start_date = dateutil.get_previous_date(end_date, 6) c = RequestContext(request, {'first_nav_name': FIRST_NAV, 'app_name': 'stats', 'second_navs': export.get_stats_second_navs(request), 'second_nav_name': export.STATS_SALES_SECOND_NAV, 'third_nav_...
订单概况
OrderSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderSummary: """订单概况""" def get(request): """显示订单概况""" <|body_0|> def api_get(request): """获取订单概况数据""" <|body_1|> <|end_skeleton|> <|body_start_0|> end_date = dateutil.get_today() start_date = dateutil.get_previous_date(end_date, 6) ...
stack_v2_sparse_classes_36k_train_000571
19,458
no_license
[ { "docstring": "显示订单概况", "name": "get", "signature": "def get(request)" }, { "docstring": "获取订单概况数据", "name": "api_get", "signature": "def api_get(request)" } ]
2
null
Implement the Python class `OrderSummary` described below. Class description: 订单概况 Method signatures and docstrings: - def get(request): 显示订单概况 - def api_get(request): 获取订单概况数据
Implement the Python class `OrderSummary` described below. Class description: 订单概况 Method signatures and docstrings: - def get(request): 显示订单概况 - def api_get(request): 获取订单概况数据 <|skeleton|> class OrderSummary: """订单概况""" def get(request): """显示订单概况""" <|body_0|> def api_get(request): ...
8b2f7befe92841bcc35e0e60cac5958ef3f3af54
<|skeleton|> class OrderSummary: """订单概况""" def get(request): """显示订单概况""" <|body_0|> def api_get(request): """获取订单概况数据""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderSummary: """订单概况""" def get(request): """显示订单概况""" end_date = dateutil.get_today() start_date = dateutil.get_previous_date(end_date, 6) c = RequestContext(request, {'first_nav_name': FIRST_NAV, 'app_name': 'stats', 'second_navs': export.get_stats_second_navs(request),...
the_stack_v2_python_sparse
weapp/stats/sales/order_summary.py
chengdg/weizoom
train
1
ef89d1ecbeef51897ed5c1ad374848730ec3d2eb
[ "data_course = request.data\nauth_token = request.headers['Authorization'][6:]\nuser = YouYodaUser.objects.get(auth_token=auth_token)\ncourse = Courses.objects.get(id=data_course['course_id'])\ndata_course['participant_id'] = user.id\ndata_course['course_id'] = course.id\ncourse_add = CoursesSubscribers.objects.fil...
<|body_start_0|> data_course = request.data auth_token = request.headers['Authorization'][6:] user = YouYodaUser.objects.get(auth_token=auth_token) course = Courses.objects.get(id=data_course['course_id']) data_course['participant_id'] = user.id data_course['course_id'] =...
Takes data from CoursesSubscribersPostSerializator for add user to course
UserSubscribeToCourse
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSubscribeToCourse: """Takes data from CoursesSubscribersPostSerializator for add user to course""" def post(self, request): """Push user, course to db with CoursesSubscribersPostSerializator""" <|body_0|> def get(self, request): """Receives and transmits user...
stack_v2_sparse_classes_36k_train_000572
5,378
no_license
[ { "docstring": "Push user, course to db with CoursesSubscribersPostSerializator", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Receives and transmits user course data and schedule data about these courses", "name": "get", "signature": "def get(self, request)"...
4
stack_v2_sparse_classes_30k_train_009956
Implement the Python class `UserSubscribeToCourse` described below. Class description: Takes data from CoursesSubscribersPostSerializator for add user to course Method signatures and docstrings: - def post(self, request): Push user, course to db with CoursesSubscribersPostSerializator - def get(self, request): Receiv...
Implement the Python class `UserSubscribeToCourse` described below. Class description: Takes data from CoursesSubscribersPostSerializator for add user to course Method signatures and docstrings: - def post(self, request): Push user, course to db with CoursesSubscribersPostSerializator - def get(self, request): Receiv...
62b4f1cc79b4c71cc44bb741fb20af066c7023a5
<|skeleton|> class UserSubscribeToCourse: """Takes data from CoursesSubscribersPostSerializator for add user to course""" def post(self, request): """Push user, course to db with CoursesSubscribersPostSerializator""" <|body_0|> def get(self, request): """Receives and transmits user...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserSubscribeToCourse: """Takes data from CoursesSubscribersPostSerializator for add user to course""" def post(self, request): """Push user, course to db with CoursesSubscribersPostSerializator""" data_course = request.data auth_token = request.headers['Authorization'][6:] ...
the_stack_v2_python_sparse
backend/appsrc/views/user_subscribe_to_course.py
OleksandrHavrylchyk/YouYoda
train
0
ce37bfb51b8ee9a419a980b6ebf21d6be9122366
[ "vowels = 'aeiouAEIOU'\nli = list(a)\ni = 0\nj = len(li) - 1\nwhile i < j:\n if li[i] in vowels and li[j] in vowels:\n li[i], li[j] = (li[j], li[i])\n i += 1\n j -= 1\n elif li[i] in vowels and li[j] not in vowels:\n j -= 1\n else:\n i += 1\nreturn ''.join(li)", "li = '...
<|body_start_0|> vowels = 'aeiouAEIOU' li = list(a) i = 0 j = len(li) - 1 while i < j: if li[i] in vowels and li[j] in vowels: li[i], li[j] = (li[j], li[i]) i += 1 j -= 1 elif li[i] in vowels and li[j] not in...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseVowels(self, a): """:type s: str :rtype: str""" <|body_0|> def reverseVowels(self, a): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> vowels = 'aeiouAEIOU' li = list(a) i = 0 ...
stack_v2_sparse_classes_36k_train_000573
1,503
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "reverseVowels", "signature": "def reverseVowels(self, a)" }, { "docstring": ":type s: str :rtype: str", "name": "reverseVowels", "signature": "def reverseVowels(self, a)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseVowels(self, a): :type s: str :rtype: str - def reverseVowels(self, a): :type s: str :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseVowels(self, a): :type s: str :rtype: str - def reverseVowels(self, a): :type s: str :rtype: str <|skeleton|> class Solution: def reverseVowels(self, a): ...
a509b383a42f54313970168d9faa11f088f18708
<|skeleton|> class Solution: def reverseVowels(self, a): """:type s: str :rtype: str""" <|body_0|> def reverseVowels(self, a): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverseVowels(self, a): """:type s: str :rtype: str""" vowels = 'aeiouAEIOU' li = list(a) i = 0 j = len(li) - 1 while i < j: if li[i] in vowels and li[j] in vowels: li[i], li[j] = (li[j], li[i]) i += 1 ...
the_stack_v2_python_sparse
0345_Reverse_Vowels_of_a_String.py
bingli8802/leetcode
train
0
672074117f60aa2cf181251521ec8d928efb1360
[ "heap = [-t for t in target]\nheapify(heap)\ns = sum(target)\nwhile len(heap) > 0:\n t = -heap[0]\n if t == 1:\n break\n old = t - (s - t)\n s -= t - old\n if old < 1:\n return False\n heapreplace(heap, -old)\nreturn True", "s = len(target) - 1\nv = set()\nfor t in target:\n if ...
<|body_start_0|> heap = [-t for t in target] heapify(heap) s = sum(target) while len(heap) > 0: t = -heap[0] if t == 1: break old = t - (s - t) s -= t - old if old < 1: return False he...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPossible(self, target: [int]) -> bool: """To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up this process.""" <|body_0|> def isPossible0(self, target: [int]) -> bool: """O...
stack_v2_sparse_classes_36k_train_000574
1,744
permissive
[ { "docstring": "To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up this process.", "name": "isPossible", "signature": "def isPossible(self, target: [int]) -> bool" }, { "docstring": "Original solution We first check ...
2
stack_v2_sparse_classes_30k_train_000756
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPossible(self, target: [int]) -> bool: To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up th...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPossible(self, target: [int]) -> bool: To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up th...
58974b6e661101686eeab357dcf6821cf7b51064
<|skeleton|> class Solution: def isPossible(self, target: [int]) -> bool: """To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up this process.""" <|body_0|> def isPossible0(self, target: [int]) -> bool: """O...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPossible(self, target: [int]) -> bool: """To construct a list of all 1's, we need to find the max elements `m`, and replace it with `m-(sum-m)`. We can use heap to speed up this process.""" heap = [-t for t in target] heapify(heap) s = sum(target) while ...
the_stack_v2_python_sparse
practice/weekly-contest-176/construct-target-array-with-multiple-sums.py
yangtau/algorithms-practice
train
1
9f63011c1fc6009bfef6603fc54d9d310ea9d3e5
[ "super().__init__(default_factory)\nself.connection = connect(GUNGAME_DATA_PATH / 'winners.db')\nself.connection.text_factory = str\nself.cursor = self.connection.cursor()\nself.cursor.execute('CREATE TABLE IF NOT EXISTS gungame_winners(unique_id varchar(20), name varchar(31), wins varchar(10) DEFAULT 0, time_stamp...
<|body_start_0|> super().__init__(default_factory) self.connection = connect(GUNGAME_DATA_PATH / 'winners.db') self.connection.text_factory = str self.cursor = self.connection.cursor() self.cursor.execute('CREATE TABLE IF NOT EXISTS gungame_winners(unique_id varchar(20), name var...
Database to store player wins.
_WinsDatabase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _WinsDatabase: """Database to store player wins.""" def __init__(self, default_factory): """Create the dictionary and gather any stored values.""" <|body_0|> def load_database(self): """Fill the dictionary with the data from the stored database.""" <|body...
stack_v2_sparse_classes_36k_train_000575
5,149
no_license
[ { "docstring": "Create the dictionary and gather any stored values.", "name": "__init__", "signature": "def __init__(self, default_factory)" }, { "docstring": "Fill the dictionary with the data from the stored database.", "name": "load_database", "signature": "def load_database(self)" ...
4
stack_v2_sparse_classes_30k_train_001010
Implement the Python class `_WinsDatabase` described below. Class description: Database to store player wins. Method signatures and docstrings: - def __init__(self, default_factory): Create the dictionary and gather any stored values. - def load_database(self): Fill the dictionary with the data from the stored databa...
Implement the Python class `_WinsDatabase` described below. Class description: Database to store player wins. Method signatures and docstrings: - def __init__(self, default_factory): Create the dictionary and gather any stored values. - def load_database(self): Fill the dictionary with the data from the stored databa...
dd76d1f581a1a8aff18c2194834665fa66a82aab
<|skeleton|> class _WinsDatabase: """Database to store player wins.""" def __init__(self, default_factory): """Create the dictionary and gather any stored values.""" <|body_0|> def load_database(self): """Fill the dictionary with the data from the stored database.""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _WinsDatabase: """Database to store player wins.""" def __init__(self, default_factory): """Create the dictionary and gather any stored values.""" super().__init__(default_factory) self.connection = connect(GUNGAME_DATA_PATH / 'winners.db') self.connection.text_factory = s...
the_stack_v2_python_sparse
addons/source-python/plugins/gungame/core/players/database.py
Hackmastr/GunGame-SP
train
0
803ab85ac425511dcee71923e21499053c053a5d
[ "self.matrix = matrix\nself.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if i == 0:\n self.prefix_sum[i][j] = matrix[i][j]\n else:\n self.prefix_sum[i][j] = matrix[i][j] + self.p...
<|body_start_0|> self.matrix = matrix self.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if i == 0: self.prefix_sum[i][j] = matrix[i][j] el...
NumMatrix
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def update(self, row, col, val): """:type row: int :type col: int :type val: int :rtype: void""" <|body_1|> def sumRegion(self, row1, col1, row2, col2): """:typ...
stack_v2_sparse_classes_36k_train_000576
16,103
no_license
[ { "docstring": ":type matrix: List[List[int]]", "name": "__init__", "signature": "def __init__(self, matrix)" }, { "docstring": ":type row: int :type col: int :type val: int :rtype: void", "name": "update", "signature": "def update(self, row, col, val)" }, { "docstring": ":type r...
3
null
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void - def sumRegion(self, row...
Implement the Python class `NumMatrix` described below. Class description: Implement the NumMatrix class. Method signatures and docstrings: - def __init__(self, matrix): :type matrix: List[List[int]] - def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void - def sumRegion(self, row...
fa3704af37d9e04ab6fd13b7b17cc83c239946f7
<|skeleton|> class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" <|body_0|> def update(self, row, col, val): """:type row: int :type col: int :type val: int :rtype: void""" <|body_1|> def sumRegion(self, row1, col1, row2, col2): """:typ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumMatrix: def __init__(self, matrix): """:type matrix: List[List[int]]""" self.matrix = matrix self.prefix_sum = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if i == 0:...
the_stack_v2_python_sparse
lintcode/medium/817_range_sum_query_2d_mutable.py
simonfqy/SimonfqyGitHub
train
2
de852b6b8894290405d2c0c75fb2b6aec7fe09a0
[ "self.model = model\nself.learning_rate = learning_rate\nself.momentum = momentum\nself.type = 'SGD'\nself.old_gradients = [[] for _ in range(len(self.model.layers))]", "for i, l in enumerate(self.model.layers):\n if isinstance(l, TrainableModule):\n current_old_grad = [l.weights_gradient, l.bias_gradie...
<|body_start_0|> self.model = model self.learning_rate = learning_rate self.momentum = momentum self.type = 'SGD' self.old_gradients = [[] for _ in range(len(self.model.layers))] <|end_body_0|> <|body_start_1|> for i, l in enumerate(self.model.layers): if isi...
A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent.
SGDOptimizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SGDOptimizer: """A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent.""" def __init__(self, model, learning_rate, momentum=0.0): """Initialization of the SGD optimizer :param model: a sequential model :param learning_rate: paramete...
stack_v2_sparse_classes_36k_train_000577
1,730
no_license
[ { "docstring": "Initialization of the SGD optimizer :param model: a sequential model :param learning_rate: parameter to train the model :param momentum: a parameter to specify how much of the old gradient to keep", "name": "__init__", "signature": "def __init__(self, model, learning_rate, momentum=0.0)"...
2
stack_v2_sparse_classes_30k_train_014902
Implement the Python class `SGDOptimizer` described below. Class description: A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent. Method signatures and docstrings: - def __init__(self, model, learning_rate, momentum=0.0): Initialization of the SGD optimizer :param...
Implement the Python class `SGDOptimizer` described below. Class description: A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent. Method signatures and docstrings: - def __init__(self, model, learning_rate, momentum=0.0): Initialization of the SGD optimizer :param...
f716276d44d25bfb6ee4e2a76e3248b109127cc7
<|skeleton|> class SGDOptimizer: """A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent.""" def __init__(self, model, learning_rate, momentum=0.0): """Initialization of the SGD optimizer :param model: a sequential model :param learning_rate: paramete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SGDOptimizer: """A simple class to take care of the optimization process, i.e. learning, with stochastic gradient descent.""" def __init__(self, model, learning_rate, momentum=0.0): """Initialization of the SGD optimizer :param model: a sequential model :param learning_rate: parameter to train th...
the_stack_v2_python_sparse
framework/optimizers/sgd_optimizer.py
AndreCI/DL_p2
train
0
71e0d620d501f1e639aff5f2664927fe7770653a
[ "src = request.GET.get('utm_source', None)\nif src == 'Email Newsletter':\n self.record_newsletter_interaction(request, response)\nreturn response", "try:\n plus_one_month = datetime.today() + timedelta(weeks=4)\n timestamp = to_js_timestamp(plus_one_month)\n cookie = request.COOKIES['crimson.intersti...
<|body_start_0|> src = request.GET.get('utm_source', None) if src == 'Email Newsletter': self.record_newsletter_interaction(request, response) return response <|end_body_0|> <|body_start_1|> try: plus_one_month = datetime.today() + timedelta(weeks=4) ...
NewsletterSubscribeMiddleware
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewsletterSubscribeMiddleware: def process_response(self, request, response): """Hides the newlsetter interstitial if the link came from a newsletter.""" <|body_0|> def record_newsletter_interaction(request, response): """Updates the subscribe cookie so that it won't...
stack_v2_sparse_classes_36k_train_000578
1,418
no_license
[ { "docstring": "Hides the newlsetter interstitial if the link came from a newsletter.", "name": "process_response", "signature": "def process_response(self, request, response)" }, { "docstring": "Updates the subscribe cookie so that it won't be shown for another month. This function is used by t...
2
null
Implement the Python class `NewsletterSubscribeMiddleware` described below. Class description: Implement the NewsletterSubscribeMiddleware class. Method signatures and docstrings: - def process_response(self, request, response): Hides the newlsetter interstitial if the link came from a newsletter. - def record_newsle...
Implement the Python class `NewsletterSubscribeMiddleware` described below. Class description: Implement the NewsletterSubscribeMiddleware class. Method signatures and docstrings: - def process_response(self, request, response): Hides the newlsetter interstitial if the link came from a newsletter. - def record_newsle...
a9045ea79c73c7b864a391039799c2f22234fed3
<|skeleton|> class NewsletterSubscribeMiddleware: def process_response(self, request, response): """Hides the newlsetter interstitial if the link came from a newsletter.""" <|body_0|> def record_newsletter_interaction(request, response): """Updates the subscribe cookie so that it won't...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NewsletterSubscribeMiddleware: def process_response(self, request, response): """Hides the newlsetter interstitial if the link came from a newsletter.""" src = request.GET.get('utm_source', None) if src == 'Email Newsletter': self.record_newsletter_interaction(request, resp...
the_stack_v2_python_sparse
crimtech_final_project/crimsononline/newsletter/middleware.py
cindyz8735/crimtechcomp
train
0
2ef4c427f2917abd541c462115bf1861aad919c5
[ "res1 = res2 = 0\nfor n in num1:\n res1 = res1 * 10 + (ord(n) - ord('0'))\nfor n in num2:\n res2 = res2 * 10 + (ord(n) - ord('0'))\nreturn str(res1 * res2)", "n1 = len(num1)\nn2 = len(num2)\ndigits = [0] * (n1 + n2)\nfor i in range(n1 - 1, -1, -1):\n for j in range(n2 - 1, -1, -1):\n idx = i + j\n...
<|body_start_0|> res1 = res2 = 0 for n in num1: res1 = res1 * 10 + (ord(n) - ord('0')) for n in num2: res2 = res2 * 10 + (ord(n) - ord('0')) return str(res1 * res2) <|end_body_0|> <|body_start_1|> n1 = len(num1) n2 = len(num2) digits = [0]...
Strings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Strings: def multiply(self, num1: str, num2: str) -> str: """:param num1: :param num2: :return:""" <|body_0|> def multiply_(self, num1: str, num2: str) -> str: """:param num1: :param num2: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> res...
stack_v2_sparse_classes_36k_train_000579
1,197
no_license
[ { "docstring": ":param num1: :param num2: :return:", "name": "multiply", "signature": "def multiply(self, num1: str, num2: str) -> str" }, { "docstring": ":param num1: :param num2: :return:", "name": "multiply_", "signature": "def multiply_(self, num1: str, num2: str) -> str" } ]
2
null
Implement the Python class `Strings` described below. Class description: Implement the Strings class. Method signatures and docstrings: - def multiply(self, num1: str, num2: str) -> str: :param num1: :param num2: :return: - def multiply_(self, num1: str, num2: str) -> str: :param num1: :param num2: :return:
Implement the Python class `Strings` described below. Class description: Implement the Strings class. Method signatures and docstrings: - def multiply(self, num1: str, num2: str) -> str: :param num1: :param num2: :return: - def multiply_(self, num1: str, num2: str) -> str: :param num1: :param num2: :return: <|skelet...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Strings: def multiply(self, num1: str, num2: str) -> str: """:param num1: :param num2: :return:""" <|body_0|> def multiply_(self, num1: str, num2: str) -> str: """:param num1: :param num2: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Strings: def multiply(self, num1: str, num2: str) -> str: """:param num1: :param num2: :return:""" res1 = res2 = 0 for n in num1: res1 = res1 * 10 + (ord(n) - ord('0')) for n in num2: res2 = res2 * 10 + (ord(n) - ord('0')) return str(res1 * res2)...
the_stack_v2_python_sparse
revisited_2021/math_and_string/multiply_strings.py
Shiv2157k/leet_code
train
1
b62da8b5e42d227bace30884e6ea35adb059f562
[ "self.dict = {}\nself.min_val = float('inf')\nself.max_val = float('-inf')", "if number not in self.dict:\n self.dict[number] = 1\nelse:\n self.dict[number] += 1\nself.min_val = min(number, self.min_val)\nself.max_val = max(number, self.max_val)", "if self.min_val * 2 > value or self.max_val * 2 < value:\...
<|body_start_0|> self.dict = {} self.min_val = float('inf') self.max_val = float('-inf') <|end_body_0|> <|body_start_1|> if number not in self.dict: self.dict[number] = 1 else: self.dict[number] += 1 self.min_val = min(number, self.min_val) ...
TwoSum
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoSum: def __init__(self): """Initialize your data structure here.""" <|body_0|> def add(self, number): """Add the number to an internal data structure.. :type number: int :rtype: void""" <|body_1|> def find(self, value): """Find if there exists...
stack_v2_sparse_classes_36k_train_000580
5,501
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Add the number to an internal data structure.. :type number: int :rtype: void", "name": "add", "signature": "def add(self, number)" }, { "docstring": "F...
3
null
Implement the Python class `TwoSum` described below. Class description: Implement the TwoSum class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def add(self, number): Add the number to an internal data structure.. :type number: int :rtype: void - def find(self, value...
Implement the Python class `TwoSum` described below. Class description: Implement the TwoSum class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def add(self, number): Add the number to an internal data structure.. :type number: int :rtype: void - def find(self, value...
c34b55bb42dc44a9026a902f6afcc018b4154662
<|skeleton|> class TwoSum: def __init__(self): """Initialize your data structure here.""" <|body_0|> def add(self, number): """Add the number to an internal data structure.. :type number: int :rtype: void""" <|body_1|> def find(self, value): """Find if there exists...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TwoSum: def __init__(self): """Initialize your data structure here.""" self.dict = {} self.min_val = float('inf') self.max_val = float('-inf') def add(self, number): """Add the number to an internal data structure.. :type number: int :rtype: void""" if numb...
the_stack_v2_python_sparse
Algorithm/Two Sum III - Data structure design.py
superpigBB/Happy-Coding
train
0
31edbf4054ca2a69e083dad074b0e7ad01713e02
[ "self.parameter_dict = parameter_dict\nself.para_names = list(parameter_dict.keys())\nself.no_para = len(self.para_names)\nself.formula = FiniteDifferenceStep(formula)\nself.step = step\nself.store = store\nself.scenario_nominal = [parameter_dict[d] for d in self.para_names]\nself.generate_scenario()", "eps_abs =...
<|body_start_0|> self.parameter_dict = parameter_dict self.para_names = list(parameter_dict.keys()) self.no_para = len(self.para_names) self.formula = FiniteDifferenceStep(formula) self.step = step self.store = store self.scenario_nominal = [parameter_dict[d] for ...
ScenarioGenerator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScenarioGenerator: def __init__(self, parameter_dict=None, formula='central', step=0.001, store=False): """Generate scenarios. DoE library first calls this function to generate scenarios. Parameters ----------- parameter_dict: a ``dict`` of parameter, keys are names of ''string'', values...
stack_v2_sparse_classes_36k_train_000581
6,574
permissive
[ { "docstring": "Generate scenarios. DoE library first calls this function to generate scenarios. Parameters ----------- parameter_dict: a ``dict`` of parameter, keys are names of ''string'', values are their nominal value of ''float''. for e.g., {'A1': 84.79, 'A2': 371.72, 'E1': 7.78, 'E2': 15.05} formula: choo...
2
null
Implement the Python class `ScenarioGenerator` described below. Class description: Implement the ScenarioGenerator class. Method signatures and docstrings: - def __init__(self, parameter_dict=None, formula='central', step=0.001, store=False): Generate scenarios. DoE library first calls this function to generate scena...
Implement the Python class `ScenarioGenerator` described below. Class description: Implement the ScenarioGenerator class. Method signatures and docstrings: - def __init__(self, parameter_dict=None, formula='central', step=0.001, store=False): Generate scenarios. DoE library first calls this function to generate scena...
05ed25d76d244d983a3aee3ebc84545b276688a1
<|skeleton|> class ScenarioGenerator: def __init__(self, parameter_dict=None, formula='central', step=0.001, store=False): """Generate scenarios. DoE library first calls this function to generate scenarios. Parameters ----------- parameter_dict: a ``dict`` of parameter, keys are names of ''string'', values...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScenarioGenerator: def __init__(self, parameter_dict=None, formula='central', step=0.001, store=False): """Generate scenarios. DoE library first calls this function to generate scenarios. Parameters ----------- parameter_dict: a ``dict`` of parameter, keys are names of ''string'', values are their nom...
the_stack_v2_python_sparse
pyomo/contrib/doe/scenario.py
mrmundt/pyomo
train
2
258b25351b08bd4184886e76564ee8d23b1513e8
[ "self.mobile_number = mobile_number\nself.date_of_birth = date_of_birth\nself.get_social_security_number = get_social_security_number\nself.external_reference = external_reference\nself.addonservices = addonservices\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nmo...
<|body_start_0|> self.mobile_number = mobile_number self.date_of_birth = date_of_birth self.get_social_security_number = get_social_security_number self.external_reference = external_reference self.addonservices = addonservices self.additional_properties = additional_prop...
Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified get_social_security_number (bool): Should the social...
CreateBankIDMobileRequest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateBankIDMobileRequest: """Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified...
stack_v2_sparse_classes_36k_train_000582
3,537
permissive
[ { "docstring": "Constructor for the CreateBankIDMobileRequest class", "name": "__init__", "signature": "def __init__(self, mobile_number=None, date_of_birth=None, get_social_security_number=None, external_reference=None, addonservices=None, additional_properties={})" }, { "docstring": "Creates a...
2
null
Implement the Python class `CreateBankIDMobileRequest` described below. Class description: Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birt...
Implement the Python class `CreateBankIDMobileRequest` described below. Class description: Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birt...
fa3918a6c54ea0eedb9146578645b7eb1755b642
<|skeleton|> class CreateBankIDMobileRequest: """Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateBankIDMobileRequest: """Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified get_social_s...
the_stack_v2_python_sparse
idfy_rest_client/models/create_bank_id_mobile_request.py
dealflowteam/Idfy
train
0
013edbd8447129b361126f345c19579d4e313d93
[ "log.debug('Getting bee record with ID')\nengine = database.get_engine()\nbee = database.beerecord\nif id == -1:\n query = sql.select([bee.c.bee_dict_id, bee.c.bee_name, bee.c.loc_info, bee.c.time])\nelse:\n query = sql.select([bee.c.beerecord_id, bee.c.user_id, bee.c.bee_dict_id, bee.c.bee_name, bee.c.colora...
<|body_start_0|> log.debug('Getting bee record with ID') engine = database.get_engine() bee = database.beerecord if id == -1: query = sql.select([bee.c.bee_dict_id, bee.c.bee_name, bee.c.loc_info, bee.c.time]) else: query = sql.select([bee.c.beerecord_id, ...
BeeRecord
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BeeRecord: def get(self, id: int, user=None): """Get a bee record by ID""" <|body_0|> def put(self, id: int, user=None): """Update a bee record by ID""" <|body_1|> def delete(self, id: int, user): """Delete a bee record by ID""" <|body_2|...
stack_v2_sparse_classes_36k_train_000583
12,437
no_license
[ { "docstring": "Get a bee record by ID", "name": "get", "signature": "def get(self, id: int, user=None)" }, { "docstring": "Update a bee record by ID", "name": "put", "signature": "def put(self, id: int, user=None)" }, { "docstring": "Delete a bee record by ID", "name": "dele...
3
stack_v2_sparse_classes_30k_train_002576
Implement the Python class `BeeRecord` described below. Class description: Implement the BeeRecord class. Method signatures and docstrings: - def get(self, id: int, user=None): Get a bee record by ID - def put(self, id: int, user=None): Update a bee record by ID - def delete(self, id: int, user): Delete a bee record ...
Implement the Python class `BeeRecord` described below. Class description: Implement the BeeRecord class. Method signatures and docstrings: - def get(self, id: int, user=None): Get a bee record by ID - def put(self, id: int, user=None): Update a bee record by ID - def delete(self, id: int, user): Delete a bee record ...
ab45d78d207b957bb31381b0df12f4e318fb1e41
<|skeleton|> class BeeRecord: def get(self, id: int, user=None): """Get a bee record by ID""" <|body_0|> def put(self, id: int, user=None): """Update a bee record by ID""" <|body_1|> def delete(self, id: int, user): """Delete a bee record by ID""" <|body_2|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BeeRecord: def get(self, id: int, user=None): """Get a bee record by ID""" log.debug('Getting bee record with ID') engine = database.get_engine() bee = database.beerecord if id == -1: query = sql.select([bee.c.bee_dict_id, bee.c.bee_name, bee.c.loc_info, bee...
the_stack_v2_python_sparse
beecology_api/bee_data_api/endpoints/bee_record.py
C7C8/beecology-api-v7
train
0
131063fe699912e27c33fe66b721f9866fc8fea6
[ "if user_input is None:\n return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA)\nservice = await WyomingService.create(user_input[CONF_HOST], user_input[CONF_PORT])\nif service is None:\n return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA, errors={'base': 'c...
<|body_start_0|> if user_input is None: return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA) service = await WyomingService.create(user_input[CONF_HOST], user_input[CONF_PORT]) if service is None: return self.async_show_form(step_id='user', data_...
Handle a config flow for Wyoming integration.
ConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigFlow: """Handle a config flow for Wyoming integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_hassio(self, discovery_info: HassioServiceInfo) -> FlowRe...
stack_v2_sparse_classes_36k_train_000584
3,831
permissive
[ { "docstring": "Handle the initial step.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult" }, { "docstring": "Handle Supervisor add-on discovery.", "name": "async_step_hassio", "signature": "async def async_s...
3
null
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Wyoming integration. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def async_step_hassio(self, discovery_in...
Implement the Python class `ConfigFlow` described below. Class description: Handle a config flow for Wyoming integration. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def async_step_hassio(self, discovery_in...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ConfigFlow: """Handle a config flow for Wyoming integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_hassio(self, discovery_info: HassioServiceInfo) -> FlowRe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigFlow: """Handle a config flow for Wyoming integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" if user_input is None: return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_S...
the_stack_v2_python_sparse
homeassistant/components/wyoming/config_flow.py
home-assistant/core
train
35,501
571877102adc99457f378f1488928f7ed4640ae1
[ "self.stack = []\nself.p = root\nwhile self.p:\n self.stack.append(self.p)\n self.p = self.p.left", "if self.stack or self.p:\n while self.p:\n self.stack.append(self.p)\n self.p = self.p.left\n else:\n next_node = self.stack.pop()\n self.p = next_node.right\n return...
<|body_start_0|> self.stack = [] self.p = root while self.p: self.stack.append(self.p) self.p = self.p.left <|end_body_0|> <|body_start_1|> if self.stack or self.p: while self.p: self.stack.append(self.p) self.p = self....
BSTIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def next(self): """@return the next smallest number :rtype: int""" <|body_1|> def hasNext(self): """@return whether we have a next smallest number :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_000585
1,183
no_license
[ { "docstring": ":type root: TreeNode", "name": "__init__", "signature": "def __init__(self, root)" }, { "docstring": "@return the next smallest number :rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": "@return whether we have a next smallest number :rt...
3
stack_v2_sparse_classes_30k_train_012424
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def next(self): @return the next smallest number :rtype: int - def hasNext(self): @return whether we have a next smallest n...
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def next(self): @return the next smallest number :rtype: int - def hasNext(self): @return whether we have a next smallest n...
f234bd7b62cb7bc2150faa764bf05a9095e19192
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def next(self): """@return the next smallest number :rtype: int""" <|body_1|> def hasNext(self): """@return whether we have a next smallest number :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BSTIterator: def __init__(self, root): """:type root: TreeNode""" self.stack = [] self.p = root while self.p: self.stack.append(self.p) self.p = self.p.left def next(self): """@return the next smallest number :rtype: int""" if self.s...
the_stack_v2_python_sparse
alg/binary_search_tree_iterator.py
nyannko/leetcode-python
train
0
c1fdd9913757d8d8db9ee8d67874c31371b81259
[ "if s == s[::-1]:\n return 0\nfor i in range(1, len(s)):\n if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:\n return 1\ns_len = len(s)\nmem = [i for i in range(-1, s_len)]\nfor i in range(1, s_len + 1):\n for j in range(i):\n if s[j:i] == s[j:i][::-1]:\n mem[i] = min(mem[i], mem[j...
<|body_start_0|> if s == s[::-1]: return 0 for i in range(1, len(s)): if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]: return 1 s_len = len(s) mem = [i for i in range(-1, s_len)] for i in range(1, s_len + 1): for j in range(i):...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minCut(self, s): """:type s: str :rtype: int""" <|body_0|> def minCut2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if s == s[::-1]: return 0 for i in range(1, len(s)): ...
stack_v2_sparse_classes_36k_train_000586
2,167
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "minCut", "signature": "def minCut(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "minCut2", "signature": "def minCut2(self, s)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCut(self, s): :type s: str :rtype: int - def minCut2(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 minCut(self, s): :type s: str :rtype: int - def minCut2(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def minCut(self, s): """:type s: str :rt...
db2d0b05020a1fcb9f0cfaf9386f79daeaad759e
<|skeleton|> class Solution: def minCut(self, s): """:type s: str :rtype: int""" <|body_0|> def minCut2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minCut(self, s): """:type s: str :rtype: int""" if s == s[::-1]: return 0 for i in range(1, len(s)): if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]: return 1 s_len = len(s) mem = [i for i in range(-1, s_len)] ...
the_stack_v2_python_sparse
leetcode/dynamic_programming/132_min_cut.py
longgb246/MLlearn
train
0
7680e5fc945fd522179262f9a2402180856c8dac
[ "for i in range(len(array)):\n min_index = i\n for j in range(i + 1, len(array)):\n if array[j] < array[min_index]:\n min_index = j\n array[i], array[min_index] = (array[min_index], array[i])\n print(i, ': ', array)\nreturn array", "for _ in range(len(array)):\n swapped = False\n ...
<|body_start_0|> for i in range(len(array)): min_index = i for j in range(i + 1, len(array)): if array[j] < array[min_index]: min_index = j array[i], array[min_index] = (array[min_index], array[i]) print(i, ': ', array) ...
Implements two sorting algorithms: selection sort and bubble sort
Sort
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sort: """Implements two sorting algorithms: selection sort and bubble sort""" def selection_sort(array): """Sort a list of numbers using selection sort""" <|body_0|> def bubble_sort(array): """Sort a list of numbers using bubble sort""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_000587
1,699
no_license
[ { "docstring": "Sort a list of numbers using selection sort", "name": "selection_sort", "signature": "def selection_sort(array)" }, { "docstring": "Sort a list of numbers using bubble sort", "name": "bubble_sort", "signature": "def bubble_sort(array)" } ]
2
stack_v2_sparse_classes_30k_train_001933
Implement the Python class `Sort` described below. Class description: Implements two sorting algorithms: selection sort and bubble sort Method signatures and docstrings: - def selection_sort(array): Sort a list of numbers using selection sort - def bubble_sort(array): Sort a list of numbers using bubble sort
Implement the Python class `Sort` described below. Class description: Implements two sorting algorithms: selection sort and bubble sort Method signatures and docstrings: - def selection_sort(array): Sort a list of numbers using selection sort - def bubble_sort(array): Sort a list of numbers using bubble sort <|skele...
51698ba8bfc2201639e6f4d358e0fc531780d2fc
<|skeleton|> class Sort: """Implements two sorting algorithms: selection sort and bubble sort""" def selection_sort(array): """Sort a list of numbers using selection sort""" <|body_0|> def bubble_sort(array): """Sort a list of numbers using bubble sort""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sort: """Implements two sorting algorithms: selection sort and bubble sort""" def selection_sort(array): """Sort a list of numbers using selection sort""" for i in range(len(array)): min_index = i for j in range(i + 1, len(array)): if array[j] < arr...
the_stack_v2_python_sparse
Course_case/2018_11_27/sort.py
xiaohaiguicc/CS5001
train
0
5a866f7ed3243b014c36d9fffeec10b9cd2b94f3
[ "if db_field.name == 'author':\n kwargs['initial'] = request.user.id\nreturn super().formfield_for_foreignkey(db_field, request, **kwargs)", "try:\n profile = Profile.objects.get(user=request.user)\nexcept Profile.DoesNotExist:\n if request.user.is_superuser:\n return Mark.objects.all()\nif profil...
<|body_start_0|> if db_field.name == 'author': kwargs['initial'] = request.user.id return super().formfield_for_foreignkey(db_field, request, **kwargs) <|end_body_0|> <|body_start_1|> try: profile = Profile.objects.get(user=request.user) except Profile.DoesNotExi...
MarksAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_0|> def get_queryset(self, request): """Get all marks for current profile""" <|body_1|> <|end_skeleton|> <|body_start_0|> if db_field.name ...
stack_v2_sparse_classes_36k_train_000588
2,628
no_license
[ { "docstring": "Set default teacher", "name": "formfield_for_foreignkey", "signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)" }, { "docstring": "Get all marks for current profile", "name": "get_queryset", "signature": "def get_queryset(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_001949
Implement the Python class `MarksAdmin` described below. Class description: Implement the MarksAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher - def get_queryset(self, request): Get all marks for current profile
Implement the Python class `MarksAdmin` described below. Class description: Implement the MarksAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher - def get_queryset(self, request): Get all marks for current profile <|skeleton|> class ...
76c0df6f07f41f4baf7346acdbbf316b4dd13ee5
<|skeleton|> class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_0|> def get_queryset(self, request): """Get all marks for current profile""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" if db_field.name == 'author': kwargs['initial'] = request.user.id return super().formfield_for_foreignkey(db_field, request, **kwargs) def get_queryset(self, request)...
the_stack_v2_python_sparse
journal/admin.py
HallrizonX/api_chpk
train
3
6ba37f844aafe25216c328a80324aa8a695997fb
[ "if not hasattr(self, 'allEvents'):\n self.allEvents = Event.objects.filter(Q(instance_of=PublicEvent) | Q(instance_of=Series)).annotate(**self.get_annotations()).exclude(Q(status=Event.RegStatus.hidden) | Q(status=Event.RegStatus.regHidden) | Q(status=Event.RegStatus.linkOnly)).order_by(*self.get_ordering()).di...
<|body_start_0|> if not hasattr(self, 'allEvents'): self.allEvents = Event.objects.filter(Q(instance_of=PublicEvent) | Q(instance_of=Series)).annotate(**self.get_annotations()).exclude(Q(status=Event.RegStatus.hidden) | Q(status=Event.RegStatus.regHidden) | Q(status=Event.RegStatus.linkOnly)).order_...
RegisterView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegisterView: def get_allEvents(self): """Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis.""" <|body_0|> def get_context_data(self, **kwargs): """Add the event and series listing d...
stack_v2_sparse_classes_36k_train_000589
3,366
permissive
[ { "docstring": "Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis.", "name": "get_allEvents", "signature": "def get_allEvents(self)" }, { "docstring": "Add the event and series listing data. If If \"today\" is s...
2
stack_v2_sparse_classes_30k_train_001337
Implement the Python class `RegisterView` described below. Class description: Implement the RegisterView class. Method signatures and docstrings: - def get_allEvents(self): Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis. - def get...
Implement the Python class `RegisterView` described below. Class description: Implement the RegisterView class. Method signatures and docstrings: - def get_allEvents(self): Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis. - def get...
19db3e83e76ea2002ee841989410d12d1e601023
<|skeleton|> class RegisterView: def get_allEvents(self): """Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis.""" <|body_0|> def get_context_data(self, **kwargs): """Add the event and series listing d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegisterView: def get_allEvents(self): """Exclude hidden and link-only events by default, as well as private events, etc. Additional restrictions are made on a per-plugin basis.""" if not hasattr(self, 'allEvents'): self.allEvents = Event.objects.filter(Q(instance_of=PublicEvent) |...
the_stack_v2_python_sparse
danceschool/register/views.py
django-danceschool/django-danceschool
train
40
3a76492557c51661b9afccd4bf42b8e54c737698
[ "self.head = Node(0)\nself.tail = Node(0)\nself.head.next = self.tail\nself.tail.prev = self.head\nself.key2node = {}", "if key in self.key2node:\n cur_node = self.key2node[key]\n cur_node.keys.remove(key)\nelse:\n cur_node = self.head\ncur_freq = cur_node.val\nif cur_freq + 1 != cur_node.next.val:\n ...
<|body_start_0|> self.head = Node(0) self.tail = Node(0) self.head.next = self.tail self.tail.prev = self.head self.key2node = {} <|end_body_0|> <|body_start_1|> if key in self.key2node: cur_node = self.key2node[key] cur_node.keys.remove(key) ...
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_36k_train_000590
4,239
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.", "name": "inc", "signature": "def inc(self, key: str) -> None" }, { "docstrin...
5
null
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
e431ff831ddd5f26891e6ee4506a20d7972b4f02
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllOne: def __init__(self): """Initialize your data structure here.""" self.head = Node(0) self.tail = Node(0) self.head.next = self.tail self.tail.prev = self.head self.key2node = {} def inc(self, key: str) -> None: """Inserts a new key <Key> with ...
the_stack_v2_python_sparse
leetcode_python/432.All_O`one_Data_Structure.py
zihuaweng/leetcode-solutions
train
4
f17060eb4fa78843e232aa8ae5e49612935cf8ac
[ "if USER_NOT_FOUND:\n return HttpResponseNotFound(USER_NOT_FOUND_MSG)\nreturn Response([{'ruleId': 0, 'ruleUser': user, 'ruleBlockedFrom': 'string', 'ruleBlockedTo': 'string', 'ruleReason': 'string'}])", "if USER_NOT_FOUND:\n return HttpResponseNotFound(USER_NOT_FOUND_MSG)\nif len(request.data) != 2:\n r...
<|body_start_0|> if USER_NOT_FOUND: return HttpResponseNotFound(USER_NOT_FOUND_MSG) return Response([{'ruleId': 0, 'ruleUser': user, 'ruleBlockedFrom': 'string', 'ruleBlockedTo': 'string', 'ruleReason': 'string'}]) <|end_body_0|> <|body_start_1|> if USER_NOT_FOUND: retur...
[GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address and direction (from or to)
UserBlockUser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserBlockUser: """[GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address and direction (from or to)""" def ...
stack_v2_sparse_classes_36k_train_000591
5,784
permissive
[ { "docstring": ":param user: any number of word characters", "name": "get", "signature": "def get(self, request, user, **kwargs)" }, { "docstring": ":param user: any number of word characters", "name": "put", "signature": "def put(self, request, user, **kwargs)" }, { "docstring":...
3
null
Implement the Python class `UserBlockUser` described below. Class description: [GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address ...
Implement the Python class `UserBlockUser` described below. Class description: [GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address ...
73e4ac0ced6c3ac46d24ac5c3feb01a1e88bd36b
<|skeleton|> class UserBlockUser: """[GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address and direction (from or to)""" def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserBlockUser: """[GET] /userBlock/{user} Get all rules with specified ruleAddress [PUT] /userBlock/{user} Change a reason and direction for all rules with the specified e-mail address [DELETE] /userBlock/{user} Delete all rules for specified e-mail address and direction (from or to)""" def get(self, req...
the_stack_v2_python_sparse
crusoe_act/act-component/userBlock-wrapper/userBlock_wrapper_project/views.py
wumingruiye/CRUSOE
train
0
4ce8d150a417071ce7da500cb5f4777d9e9a28e6
[ "baseSQL = 'SELECT count(*) FROM wmbs_job\\n WHERE location = (SELECT ID FROM wmbs_location WHERE site_name = :location)\\n AND state IN (SELECT ID FROM wmbs_job_state js WHERE js.name IN (\\n '\ntypeSQL = 'SELECT count(*) FROM wmbs_job\\n INNER JOIN wmbs_jobgr...
<|body_start_0|> baseSQL = 'SELECT count(*) FROM wmbs_job\n WHERE location = (SELECT ID FROM wmbs_location WHERE site_name = :location)\n AND state IN (SELECT ID FROM wmbs_job_state js WHERE js.name IN (\n ' typeSQL = 'SELECT count(*) FROM wmbs_job\n ...
_GetLocation_ Retrieve all files that are associated with the given job from the database.
GetNumberOfJobsPerSite
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetNumberOfJobsPerSite: """_GetLocation_ Retrieve all files that are associated with the given job from the database.""" def buildSQL(self, states, type): """_buildSQL_ builds the sql statements; necessary for lists""" <|body_0|> def format(self, results): """_fo...
stack_v2_sparse_classes_36k_train_000592
2,859
permissive
[ { "docstring": "_buildSQL_ builds the sql statements; necessary for lists", "name": "buildSQL", "signature": "def buildSQL(self, states, type)" }, { "docstring": "_format_", "name": "format", "signature": "def format(self, results)" }, { "docstring": "_buildBinds_ Build a list of...
4
null
Implement the Python class `GetNumberOfJobsPerSite` described below. Class description: _GetLocation_ Retrieve all files that are associated with the given job from the database. Method signatures and docstrings: - def buildSQL(self, states, type): _buildSQL_ builds the sql statements; necessary for lists - def forma...
Implement the Python class `GetNumberOfJobsPerSite` described below. Class description: _GetLocation_ Retrieve all files that are associated with the given job from the database. Method signatures and docstrings: - def buildSQL(self, states, type): _buildSQL_ builds the sql statements; necessary for lists - def forma...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class GetNumberOfJobsPerSite: """_GetLocation_ Retrieve all files that are associated with the given job from the database.""" def buildSQL(self, states, type): """_buildSQL_ builds the sql statements; necessary for lists""" <|body_0|> def format(self, results): """_fo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetNumberOfJobsPerSite: """_GetLocation_ Retrieve all files that are associated with the given job from the database.""" def buildSQL(self, states, type): """_buildSQL_ builds the sql statements; necessary for lists""" baseSQL = 'SELECT count(*) FROM wmbs_job\n WHERE location...
the_stack_v2_python_sparse
src/python/WMCore/WMBS/MySQL/Jobs/GetNumberOfJobsPerSite.py
vkuznet/WMCore
train
0
644e7f637bbae867f3b761e42a0ae599dbfdcae1
[ "n = len(nums)\nif not n % 2:\n return True\ndp = [[-1 for _ in xrange(n)] for _ in xrange(n)]\nmaxSum = self.dfs(dp, 0, n - 1, nums)\nreturn 2 * maxSum >= sum(nums)", "if i > j:\n return 0\nif dp[i][j] != -1:\n return dp[i][j]\na = nums[i] + min(self.dfs(dp, i + 1, j - 1, nums), self.dfs(dp, i + 2, j, n...
<|body_start_0|> n = len(nums) if not n % 2: return True dp = [[-1 for _ in xrange(n)] for _ in xrange(n)] maxSum = self.dfs(dp, 0, n - 1, nums) return 2 * maxSum >= sum(nums) <|end_body_0|> <|body_start_1|> if i > j: return 0 if dp[i][j] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def dfs(self, dp, i, j, nums): """:dp: dp table :i: left index :j: right index""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) if n...
stack_v2_sparse_classes_36k_train_000593
802
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "PredictTheWinner", "signature": "def PredictTheWinner(self, nums)" }, { "docstring": ":dp: dp table :i: left index :j: right index", "name": "dfs", "signature": "def dfs(self, dp, i, j, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool - def dfs(self, dp, i, j, nums): :dp: dp table :i: left index :j: right index
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool - def dfs(self, dp, i, j, nums): :dp: dp table :i: left index :j: right index <|skeleton|> class Solution: ...
43bf3c594a71535a3f4ee9154cc72344b92b0608
<|skeleton|> class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def dfs(self, dp, i, j, nums): """:dp: dp table :i: left index :j: right index""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def PredictTheWinner(self, nums): """:type nums: List[int] :rtype: bool""" n = len(nums) if not n % 2: return True dp = [[-1 for _ in xrange(n)] for _ in xrange(n)] maxSum = self.dfs(dp, 0, n - 1, nums) return 2 * maxSum >= sum(nums) d...
the_stack_v2_python_sparse
python/predictthewinner.py
john15518513/leetcode
train
0
e65ec2b05344504d9f89662d5a2b0a9cbeda6b2a
[ "counters = []\nletters = set(words[0])\nfor word in words:\n counters.append(Counter(word))\n letters &= set(word)\nans = []\nfor letter in letters:\n count = float('inf')\n for counter in counters:\n count = min(count, counter.get(letter, 0))\n ans.extend([letter] * count)\nreturn ans", "m...
<|body_start_0|> counters = [] letters = set(words[0]) for word in words: counters.append(Counter(word)) letters &= set(word) ans = [] for letter in letters: count = float('inf') for counter in counters: count = min(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def commonChars(self, words: List[str]) -> List[str]: """哈希表""" <|body_0|> def commonChars2(self, words: List[str]) -> List[str]: """官方答案""" <|body_1|> <|end_skeleton|> <|body_start_0|> counters = [] letters = set(words[0]) ...
stack_v2_sparse_classes_36k_train_000594
1,827
no_license
[ { "docstring": "哈希表", "name": "commonChars", "signature": "def commonChars(self, words: List[str]) -> List[str]" }, { "docstring": "官方答案", "name": "commonChars2", "signature": "def commonChars2(self, words: List[str]) -> List[str]" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def commonChars(self, words: List[str]) -> List[str]: 哈希表 - def commonChars2(self, words: List[str]) -> List[str]: 官方答案
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def commonChars(self, words: List[str]) -> List[str]: 哈希表 - def commonChars2(self, words: List[str]) -> List[str]: 官方答案 <|skeleton|> class Solution: def commonChars(self, w...
52756b30e9d51794591aca030bc918e707f473f1
<|skeleton|> class Solution: def commonChars(self, words: List[str]) -> List[str]: """哈希表""" <|body_0|> def commonChars2(self, words: List[str]) -> List[str]: """官方答案""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def commonChars(self, words: List[str]) -> List[str]: """哈希表""" counters = [] letters = set(words[0]) for word in words: counters.append(Counter(word)) letters &= set(word) ans = [] for letter in letters: count = flo...
the_stack_v2_python_sparse
1002.查找常用字符/solution.py
QtTao/daily_leetcode
train
0
4f591ff1b4d2662d55479682e1cee2f827db8fb2
[ "flownames = ['EEin', 'Sigin', 'Watin', 'Watout']\nstates = {'eff': 1.0}\nself.delay = delay\nsuper().__init__(flownames, flows, states, timers={'timer'})\nself.failrate = 1e-05\nself.assoc_modes({'mech_break': [0.6, [0.1, 1.2, 0.1], 5000], 'short': [1.0, [1.5, 1.0, 1.0], 10000]})", "if self.delay:\n if self.W...
<|body_start_0|> flownames = ['EEin', 'Sigin', 'Watin', 'Watout'] states = {'eff': 1.0} self.delay = delay super().__init__(flownames, flows, states, timers={'timer'}) self.failrate = 1e-05 self.assoc_modes({'mech_break': [0.6, [0.1, 1.2, 0.1], 5000], 'short': [1.0, [1.5,...
Move Water is the pump itself. While one could decompose this further, one function is used for simplicity
MoveWat
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MoveWat: """Move Water is the pump itself. While one could decompose this further, one function is used for simplicity""" def __init__(self, flows, delay): """In this function, more states are initialized than flows: - states (internal variables to be given to the function) states ar...
stack_v2_sparse_classes_36k_train_000595
13,659
permissive
[ { "docstring": "In this function, more states are initialized than flows: - states (internal variables to be given to the function) states are given as {'name':initval} - timers (objects that keep track of time), given as a set of timer names We also have a parameter `delay` which we use to change a design vari...
3
null
Implement the Python class `MoveWat` described below. Class description: Move Water is the pump itself. While one could decompose this further, one function is used for simplicity Method signatures and docstrings: - def __init__(self, flows, delay): In this function, more states are initialized than flows: - states (...
Implement the Python class `MoveWat` described below. Class description: Move Water is the pump itself. While one could decompose this further, one function is used for simplicity Method signatures and docstrings: - def __init__(self, flows, delay): In this function, more states are initialized than flows: - states (...
2d87c415c036f44fe10310500788f5ab697e618d
<|skeleton|> class MoveWat: """Move Water is the pump itself. While one could decompose this further, one function is used for simplicity""" def __init__(self, flows, delay): """In this function, more states are initialized than flows: - states (internal variables to be given to the function) states ar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MoveWat: """Move Water is the pump itself. While one could decompose this further, one function is used for simplicity""" def __init__(self, flows, delay): """In this function, more states are initialized than flows: - states (internal variables to be given to the function) states are given as {'...
the_stack_v2_python_sparse
pump example/ex_pump.py
DesignEngrLab/fmdtools
train
10
c2db422cc7a9bb4ec61ea1f37c28c02e9da345ff
[ "try:\n with datastore_services.get_ndb_context():\n question_summary = question_services.get_question_summary_from_model(question_summary_model)\n question_summary.version = question_version\n question_summary.validate()\nexcept Exception as e:\n logging.exception(e)\n return result.Err((ques...
<|body_start_0|> try: with datastore_services.get_ndb_context(): question_summary = question_services.get_question_summary_from_model(question_summary_model) question_summary.version = question_version question_summary.validate() except Exception as e:...
Job that audits PopulateQuestionSummaryVersionOneOffJob.
AuditPopulateQuestionSummaryVersionOneOffJob
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuditPopulateQuestionSummaryVersionOneOffJob: """Job that audits PopulateQuestionSummaryVersionOneOffJob.""" def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummary...
stack_v2_sparse_classes_36k_train_000596
12,101
permissive
[ { "docstring": "Transform question summary model into question summary object, add a version field and return the populated summary model. Args: question_version: int. The version number in the corresponding question domain object. question_summary_model: QuestionSummaryModel. The question summary model to migr...
2
stack_v2_sparse_classes_30k_train_007850
Implement the Python class `AuditPopulateQuestionSummaryVersionOneOffJob` described below. Class description: Job that audits PopulateQuestionSummaryVersionOneOffJob. Method signatures and docstrings: - def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSumma...
Implement the Python class `AuditPopulateQuestionSummaryVersionOneOffJob` described below. Class description: Job that audits PopulateQuestionSummaryVersionOneOffJob. Method signatures and docstrings: - def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSumma...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class AuditPopulateQuestionSummaryVersionOneOffJob: """Job that audits PopulateQuestionSummaryVersionOneOffJob.""" def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummary...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuditPopulateQuestionSummaryVersionOneOffJob: """Job that audits PopulateQuestionSummaryVersionOneOffJob.""" def _update_and_validate_summary_model(question_version: int, question_summary_model: question_models.QuestionSummaryModel) -> result.Result[Tuple[str, question_models.QuestionSummaryModel], Tuple...
the_stack_v2_python_sparse
core/jobs/batch_jobs/question_migration_jobs.py
oppia/oppia
train
6,172
8dc3ee7c3a0060d45db9487c320fd1ed381d8109
[ "filenames = []\nfor attachment in self.attachments.entries:\n try:\n return filenames.append(attachment.upload.data.filename)\n except AttributeError:\n continue\nreturn filenames if len(filenames) > 0 else None", "current_app.logger.info('CONDUCTOR EMAIL UPDATE | New update on stage \"{}\" f...
<|body_start_0|> filenames = [] for attachment in self.attachments.entries: try: return filenames.append(attachment.upload.data.filename) except AttributeError: continue return filenames if len(filenames) > 0 else None <|end_body_0|> <|bod...
Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject the update should have body: The body of the message the subject should have. This ...
SendUpdateForm
[ "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SendUpdateForm: """Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject the update should have body: The body of ...
stack_v2_sparse_classes_36k_train_000597
21,451
permissive
[ { "docstring": "Return the names of all of the attached files or None", "name": "get_attachment_filenames", "signature": "def get_attachment_filenames(self)" }, { "docstring": "Send the email updates Arguments: action: A :py:class:`~purchasing.data.contract_stages.ContractStageActionItem` that n...
2
stack_v2_sparse_classes_30k_train_010232
Implement the Python class `SendUpdateForm` described below. Class description: Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject th...
Implement the Python class `SendUpdateForm` described below. Class description: Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject th...
d676ed9c137e5aaa100992a798acd60ac464a2c1
<|skeleton|> class SendUpdateForm: """Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject the update should have body: The body of ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SendUpdateForm: """Form to send an email update Attributes: send_to: Email or semicolon-delimited list of email addresses to send the update email to send_to_cc: Email or semicolon-delimited list of email addresses to cc on the update subject: The subject the update should have body: The body of the message t...
the_stack_v2_python_sparse
purchasing/conductor/forms.py
CityofPittsburgh/pittsburgh-purchasing-suite
train
2
78db134fffac10f1e3c757a6506cbf1135214a5f
[ "rawline = self.file.readline()\nwhile rawline:\n rematch = self.line_re.match(rawline)\n if not rematch:\n rawline = self.file.readline()\n continue\n while rematch:\n rep = Replica()\n self.reps.append(rep)\n rep.index = [0 for i in range(self.numexchg)]\n rep.po...
<|body_start_0|> rawline = self.file.readline() while rawline: rematch = self.line_re.match(rawline) if not rematch: rawline = self.file.readline() continue while rematch: rep = Replica() self.reps.append...
Replica exchange log file
TempRemLog
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" <|body_0|> def _parse(self): """Parses the rem.log file and loads the data arrays""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_000598
12,296
no_license
[ { "docstring": "Gets all of the replica information from the first block of repinfo", "name": "_get_replicas", "signature": "def _get_replicas(self)" }, { "docstring": "Parses the rem.log file and loads the data arrays", "name": "_parse", "signature": "def _parse(self)" } ]
2
null
Implement the Python class `TempRemLog` described below. Class description: Replica exchange log file Method signatures and docstrings: - def _get_replicas(self): Gets all of the replica information from the first block of repinfo - def _parse(self): Parses the rem.log file and loads the data arrays
Implement the Python class `TempRemLog` described below. Class description: Replica exchange log file Method signatures and docstrings: - def _get_replicas(self): Gets all of the replica information from the first block of repinfo - def _parse(self): Parses the rem.log file and loads the data arrays <|skeleton|> cla...
5cec8112637be7a19c4aac893f612aa8c354b733
<|skeleton|> class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" <|body_0|> def _parse(self): """Parses the rem.log file and loads the data arrays""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" rawline = self.file.readline() while rawline: rematch = self.line_re.match(rawline) if not rematch: ...
the_stack_v2_python_sparse
remd.py
jeff-wang/JmsScripts
train
0
0c035d19991b348c7c10d98530763afb4cba642d
[ "self.encap = encap\nself.unidir_mode = unidir_mode\nself.mtu = mtu\nself.rx_bandwidth = rx_bandwidth\nself.tx_bandwidth = tx_bandwidth\nself.snmp_index = snmp_index\nself.islayer2 = islayer2\nself.display_name = display_name\nself.mac_address = mac_address\nself.description = description\nself.iphelper = []\nself....
<|body_start_0|> self.encap = encap self.unidir_mode = unidir_mode self.mtu = mtu self.rx_bandwidth = rx_bandwidth self.tx_bandwidth = tx_bandwidth self.snmp_index = snmp_index self.islayer2 = islayer2 self.display_name = display_name self.mac_addr...
This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indicates if this a Layer-2 Interface @type islayer2: C{bool} @ivar display_name: The na...
InterfaceConfig
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InterfaceConfig: """This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indicates if this a Layer-2 Interface @type i...
stack_v2_sparse_classes_36k_train_000599
10,222
no_license
[ { "docstring": "Constructor of InterfaceConfig class.", "name": "__init__", "signature": "def __init__(self, encap, unidir_mode, mtu, rx_bandwidth, tx_bandwidth, snmp_index, islayer2, display_name, mac_address, description, ip_redirect, ip_unreachable, ip_proxy_arp, ip_unicast_reverse_path, vrf, speed=N...
2
stack_v2_sparse_classes_30k_train_013963
Implement the Python class `InterfaceConfig` described below. Class description: This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indica...
Implement the Python class `InterfaceConfig` described below. Class description: This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indica...
54bc49eaed14f7832aca45c4f52311a00282d862
<|skeleton|> class InterfaceConfig: """This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indicates if this a Layer-2 Interface @type i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InterfaceConfig: """This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indicates if this a Layer-2 Interface @type islayer2: C{bo...
the_stack_v2_python_sparse
onepk_without_pyc/build/lib.linux-x86_64-2.7/onep/interfaces/InterfaceConfig.py
neoyogi/onepk
train
0