Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>from __future__ import annotations @reentrant @attrs.define(eq=False) class LocalEventBroker(BaseEventBroker): _executor: ThreadPoolExecutor = attrs.field(init=False) _exit_stack: ExitStack = attrs.field(init=False) _subscriptions_lock: Lock = att...
def __enter__(self):
Next line prediction: <|code_start|>@attrs.define(eq=False) class LocalEventBroker(BaseEventBroker): _executor: ThreadPoolExecutor = attrs.field(init=False) _exit_stack: ExitStack = attrs.field(init=False) _subscriptions_lock: Lock = attrs.field(init=False, factory=Lock) def __enter__(self): se...
self.publish_local(event)
Given snippet: <|code_start|>from __future__ import annotations @reentrant @attrs.define(eq=False) class LocalEventBroker(BaseEventBroker): _executor: ThreadPoolExecutor = attrs.field(init=False) _exit_stack: ExitStack = attrs.field(init=False) <|code_end|> , continue by predicting the next line. Consider ...
_subscriptions_lock: Lock = attrs.field(init=False, factory=Lock)
Given the code snippet: <|code_start|>@attrs.define(eq=False) class LocalEventBroker(BaseEventBroker): _executor: ThreadPoolExecutor = attrs.field(init=False) _exit_stack: ExitStack = attrs.field(init=False) _subscriptions_lock: Lock = attrs.field(init=False, factory=Lock) def __enter__(self): ...
self.publish_local(event)
Here is a snippet: <|code_start|>from __future__ import annotations if sys.version_info >= (3, 9): else: def marshal_object(obj) -> tuple[str, Any]: return f'{obj.__class__.__module__}:{obj.__class__.__qualname__}', obj.__getstate__() def unmarshal_object(ref: str, state): cls = callable_from_ref(ref) ...
...
Predict the next line after this snippet: <|code_start|>from __future__ import annotations @reentrant @attrs.define(eq=False) class LocalAsyncEventBroker(AsyncEventBroker, BaseEventBroker): _task_group: TaskGroup = attrs.field(init=False) _exit_stack: AsyncExitStack = attrs.field(init=False) async def...
self._exit_stack = AsyncExitStack()
Using the snippet: <|code_start|>from __future__ import annotations @reentrant @attrs.define(eq=False) class LocalAsyncEventBroker(AsyncEventBroker, BaseEventBroker): _task_group: TaskGroup = attrs.field(init=False) _exit_stack: AsyncExitStack = attrs.field(init=False) async def __aenter__(self) -> Lo...
self._exit_stack = AsyncExitStack()
Given snippet: <|code_start|> self._task_group = create_task_group() await self._exit_stack.enter_async_context(self._task_group) return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb) del self._task_grou...
self._logger.exception('Error delivering %s event', event.__class__.__name__)
Given the code snippet: <|code_start|>from __future__ import annotations @reentrant @attrs.define(eq=False) class LocalAsyncEventBroker(AsyncEventBroker, BaseEventBroker): _task_group: TaskGroup = attrs.field(init=False) _exit_stack: AsyncExitStack = attrs.field(init=False) async def __aenter__(self) ...
one_shot_tokens: list[object] = []
Using the snippet: <|code_start|>class TaskUpdated(DataStoreEvent): task_id: str @attrs.define(kw_only=True, frozen=True) class TaskRemoved(DataStoreEvent): task_id: str @attrs.define(kw_only=True, frozen=True) class ScheduleAdded(DataStoreEvent): schedule_id: str next_fire_time: datetime | None = a...
schedule_id: str | None
Next line prediction: <|code_start|>class SchedulerEvent(Event): pass @attrs.define(kw_only=True, frozen=True) class SchedulerStarted(SchedulerEvent): pass @attrs.define(kw_only=True, frozen=True) class SchedulerStopped(SchedulerEvent): exception: BaseException | None = None # # Worker events # @attr...
exception: BaseException | None = None
Predict the next line after this snippet: <|code_start|>from __future__ import annotations @attrs.define(kw_only=True, frozen=True) class Event: timestamp: datetime = attrs.field(factory=partial(datetime.now, timezone.utc), converter=as_aware_datetime) # # Data store eve...
class DataStoreEvent(Event):
Predict the next line for this snippet: <|code_start|> @attrs.define(kw_only=True, eq=False) class CBORSerializer(Serializer): type_tag: int = 4664 dump_options: dict[str, Any] = attrs.field(factory=dict) load_options: dict[str, Any] = attrs.field(factory=dict) def __attrs_post_init__(self): ...
return loads(serialized, **self.load_options)
Using the snippet: <|code_start|> @attrs.define(kw_only=True, eq=False) class CBORSerializer(Serializer): type_tag: int = 4664 dump_options: dict[str, Any] = attrs.field(factory=dict) load_options: dict[str, Any] = attrs.field(factory=dict) def __attrs_post_init__(self): self.dump_options.s...
def deserialize(self, serialized: bytes):
Here is a snippet: <|code_start|> @attrs.define(kw_only=True, eq=False) class CBORSerializer(Serializer): type_tag: int = 4664 dump_options: dict[str, Any] = attrs.field(factory=dict) load_options: dict[str, Any] = attrs.field(factory=dict) def __attrs_post_init__(self): self.dump_options.se...
return loads(serialized, **self.load_options)
Predict the next line after this snippet: <|code_start|>from __future__ import annotations @attrs.define(kw_only=True, eq=False) class PickleSerializer(Serializer): <|code_end|> using the current file's imports: from pickle import dumps, loads from ..abc import Serializer import attrs and any relevant context f...
protocol: int = 4
Predict the next line for this snippet: <|code_start|>from __future__ import annotations if sys.version_info >= (3, 9): else: <|code_end|> with the help of current file imports: import sys import attrs from datetime import date, datetime, timedelta, timezone, tzinfo from typing import Any from attrs import Attr...
def as_int(value) -> int | None:
Given snippet: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sample_prediction_log: Callable[[np.ndarray]...
self.f_tree_mutation_log = f_tree_mutation_log
Continue the code snippet: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sample_prediction_log: Callable[...
self.f_model_log = f_model_log
Given the following code snippet before the placeholder: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sa...
return self.f_model_log
Given snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.data)) self.c = Dec...
self.assertNotIn(proposal.updated_node, self.tree.nodes)
Next line prediction: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.data)) self....
class TestGrowTreeMutationProposer(unittest.TestCase):
Predict the next line for this snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.da...
self.assertIn(proposal.existing_node, self.tree.nodes)
Continue the code snippet: <|code_start|> self.a = DecisionNode(Split(self.data), self.b, self.c) self.tree = Tree([self.a, self.b, self.c, self.d, self.e]) def test_proposal_isnt_mutating(self): proposal = uniformly_sample_prune_mutation(self.tree) self.assertIn(proposal.existing_no...
def test_types(self):
Predict the next line after this snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self....
class TestGrowTreeMutationProposer(unittest.TestCase):
Next line prediction: <|code_start|> def test_types(self): proposal = uniformly_sample_prune_mutation(self.tree) self.assertIsInstance(proposal.existing_node, DecisionNode) self.assertIsInstance(proposal.updated_node, LeafNode) class TestGrowTreeMutationProposer(unittest.TestCase): def...
if __name__ == '__main__':
Predict the next line for this snippet: <|code_start|> class SigmaSampler(Sampler): def step(self, model: Model, sigma: Sigma) -> float: sample_value = self.sample(model, sigma) sigma.set_value(sample_value) return sample_value @staticmethod def sample(model: Model, sigma: Sigma)...
posterior_alpha = sigma.alpha + (model.data.X.n_obsv / 2.)
Given the code snippet: <|code_start|> class SigmaSampler(Sampler): def step(self, model: Model, sigma: Sigma) -> float: sample_value = self.sample(model, sigma) sigma.set_value(sample_value) return sample_value @staticmethod def sample(model: Model, sigma: Sigma) -> float: ...
return draw
Using the snippet: <|code_start|> def run(alpha, beta, n_trees): x = np.random.normal(0, 1, size=3000) X = pd.DataFrame(x) y = np.random.normal(0, 0.1, size=3000) + 2 * x + np.sin(x) plt.scatter(x, y) <|code_end|> , determine the next line of code. You have imports: import pandas as pd import numpy a...
plt.show()
Next line prediction: <|code_start|> n_trees=50): warnings.simplefilter("error", UserWarning) x = np.linspace(0, 5, size) X = pd.DataFrame(x) y = np.random.normal(0, 0.1, size=size) + np.sin(x) model = ResidualBART( n_samples=100, n_burn=50, ...
print(rmse)
Given snippet: <|code_start|> def test_most_recent_split(self): data = make_bartpy_data(pd.DataFrame({"a": [1, 2, 3, 4]}).values, np.array([1, 2, 1, 1])) first_left_condition, first_right_condition = SplitCondition(0, 3, le), SplitCondition(0, 3, gt) second_left_condition, second_right_cond...
self.assertEqual(combined_condition.variables[0].min_value, 2)
Predict the next line for this snippet: <|code_start|> updated_split = split + first_left_condition + second_right_condition conditioned_data = updated_split.data self.assertListEqual([2, 3], list(conditioned_data.X.get_column(0))) def test_most_recent_split(self): data = make_bartpy...
]
Next line prediction: <|code_start|> class TestSplit(unittest.TestCase): def test_null_split_returns_all_values(self): data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}).values, np.array([1, 2])) split = Split(data) conditioned_data = split.data self.assertListEqual(list(data.X....
self.assertListEqual([2, 3], list(conditioned_data.X.get_column(0)))
Given the following code snippet before the placeholder: <|code_start|> Chain = Mapping[str, Union[List[Any], np.ndarray]] class ModelSampler(Sampler): def __init__(self, schedule: SampleSchedule, trace_logger_class: Type[TraceLogger]=TraceLogger): <|code_end|> , predict the n...
self.schedule = schedule
Given the following code snippet before the placeholder: <|code_start|> org='edX_course_org', course='edX_course_course', run='edX_course_run', key_version=1 ) self.edx_course_key = self.edx_course.course_key() self.edx_usage_id = 'edx_content_usage...
'edx2canvas.models.EdxCourse.objects.get',
Predict the next line for this snippet: <|code_start|> self.edx_course_key = self.edx_course.course_key() self.edx_usage_id = 'edx_content_usage_id' self.content_title = 'content item title' self.edx_url_base = 'https://edx.example.com' settings.EDX_URL_BASE = self.edx_url_base ...
[self.edx_course]
Given snippet: <|code_start|> class TestEdxCourseModel(TestCase): def setUp(self): super(TestEdxCourseModel, self).setUp() self.course = EdxCourse( title='title', org='org', course='course', run='run', ) def test_v0_course_key(self): ...
def test_v1_course_key(self):
Given the code snippet: <|code_start|> class BaseMorrisChart(BaseChart): def get_data(self): header = self.header data = super(BaseMorrisChart, self).get_data() data_only = data[1:] rows = [] for row in data_only: rows.append(dict(zip(header, row))) retu...
def get_y_keys(self):
Next line prediction: <|code_start|> class BaseMorrisChart(BaseChart): def get_data(self): header = self.header data = super(BaseMorrisChart, self).get_data() data_only = data[1:] <|code_end|> . Use current file imports: (from .base import BaseChart from ..utils import JSONEncoderForHTML ...
rows = []
Next line prediction: <|code_start|> class BaseChart(object): def __init__(self, data_source, html_id=None, width=None, height=None, options=None, encoder=GraphosEncoder, <|code_end|> . Use current file imports: (import json import sys from django.template.loader import render_...
*args, **kwargs):
Continue the code snippet: <|code_start|> class BaseChart(object): def __init__(self, data_source, html_id=None, width=None, height=None, options=None, encoder=GraphosEncoder, <|code_end|> . Use current file imports: import json import sys from django.template.loader import ren...
*args, **kwargs):
Predict the next line after this snippet: <|code_start|> class BaseGChart(BaseChart): def get_html_template(self): return "graphos/gchart/html.html" class LineChart(BaseGChart): <|code_end|> using the current file's imports: from .base import BaseChart and any relevant context from other files: # Pat...
def get_js_template(self):
Continue the code snippet: <|code_start|> class BaseYuiChart(BaseChart): def get_data(self): data = super(BaseYuiChart, self).get_data() header = self.header data_only = data[1:] rows = [] for row in data_only: rows.append(dict(zip(header, row))) return r...
def get_chart_type(self):
Predict the next line after this snippet: <|code_start|> def get_serieses(self): data_only = self.get_data()[1:] serieses = [] for i in range(0, len(self.header)): current_column = [float(el[i]) for el in data_only] serieses.append(current_column) return serie...
def get_image(self):
Predict the next line after this snippet: <|code_start|> and `False` otherwise. `CCS_aligned_alignment` and `CCS_aligned_target` give the :py:mod:`dms_tools2.minimap2.Alignment` (or `None`) and the target (or empty string). """ if isinstance(ccslist, collections.Iterable):...
df_bi.CCS_rev_aligned)
Using the snippet: <|code_start|># load modules that are not referenced and we're very # lazy in this file. As a workaround let's load all # modules when we're in windows and we are not frozen # so we should reference all modules when py2exe is # inspecting us. # if sys.platform == 'win32' and not hasattr(sys, 'frozen...
if not module in MODULES:
Given the code snippet: <|code_start|> result['privacy_can_share'] = 0 connection.execute(query, result) connection.execute("DROP TABLE results;") connection.execute("""UPDATE config SET value='2.0' WHERE name='version';""") connection.commit() #...
]
Using the snippet: <|code_start|> ('bittorrent.listen', False, 'Run in server mode'), ('bittorrent.negotiate', True, 'Enable negotiate client/server'), ('bittorrent.negotiate.port', 8080, 'Negotiate port'), ('bittorrent.my_id', '', 'Set local PeerId ("" = auto)'), ('bittorrent.numpieces', NUMPIECES, ...
if not conf['bittorrent.bytes.down']:
Given the code snippet: <|code_start|> ('bittorrent.watchdog', WATCHDOG, 'Maximum test run-time in seconds'), ) CONFIG.register_defaults_helper(PROPERTIES) def register_descriptions(): ''' Registers the description of bittorrent variables ''' CONFIG.register_descriptions_helper(PROPERTIES) def _random_byt...
conf['bittorrent.address'] = 'master.neubot.org master2.neubot.org'
Using the snippet: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode_literals, print_function, division ...
raise ValueError("The function '{}' has an invalid name: the number of characters "
Using the snippet: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode_literals, print_function, division ...
"must be higher or lower than this. Otherwise get_task(task_id) "
Given the following code snippet before the placeholder: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode...
def func(self):
Predict the next line after this snippet: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode_literals, prin...
"could potentially fail".format(func.__name__))
Predict the next line for this snippet: <|code_start|> # We're outside a task self.assertFalse(weblablib.current_task_stopping) self.weblab.join_tasks(self.current_task, timeout=0.01, stop=True) # But the counter is still zero self.assertEquals(self.counter, 0) glob...
self.assertFalse(background_thread.isAlive())
Continue the code snippet: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode_literals, print_function, div...
return -1
Predict the next line after this snippet: <|code_start|> backend = _current_backend() if session_id: if weblab_user.active: # If there was no data in the beginning # OR there was data in the beginning and now it is different, # only then modify the current session ...
weblab._on_dispose()
Given the code snippet: <|code_start|> def status_time(session_id): weblab = _current_weblab() backend = weblab._backend user = backend.get_user(session_id) if isinstance(user, ExpiredUser) and user.disposing_resources: return 2 # Try again in 2 seconds if user.is_anonymous or not isinsta...
current_user = backend.get_user(session_id)
Given snippet: <|code_start|> # Nothing is triggered in Redis. For this reason, after each request # we check that the data has changed or not. # session_id = _current_session_id() backend = _current_backend() if session_id: if weblab_user.active: # If there was no data in the...
if weblab._on_dispose:
Here is a snippet: <|code_start|> # If there was no data in the beginning # OR there was data in the beginning and now it is different, # only then modify the current session if not hasattr(g, '_initial_data') or g._initial_data != json.dumps(weblab_user.data): ...
update_weblab_user_data(response=None)
Here is a snippet: <|code_start|># Copyright 2017 onwards LabsLand Experimentia S.L. # This software is licensed under the GNU AGPL v3: # GNU Affero General Public License version 3 (see the file LICENSE) # Read in the documentation about the license from __future__ import unicode_literals, print_function, division ...
if user.exited:
Continue the code snippet: <|code_start|> def dispose_user(session_id, waiting): backend = _current_backend() user = backend.get_user(session_id) if user.is_anonymous: raise NotFoundError() if isinstance(user, CurrentUser): current_expired_user = user.to_expired_user() deleted ...
if unfinished_task:
Predict the next line for this snippet: <|code_start|> if session_id: backend = _current_backend() current_user = backend.get_user(session_id) if current_user.active: g._initial_data = json.dumps(current_user.data) def update_weblab_user_data(response): # If a developer does:...
if user.is_anonymous:
Using the snippet: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sample_prediction_log: Callable[[np.ndar...
if item == "Tree":
Next line prediction: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sample_prediction_log: Callable[[np.n...
if item == "In Sample Prediction":
Based on the snippet: <|code_start|> class TraceLogger(): def __init__(self, f_tree_mutation_log: Callable[[TreeMutation], Any]=lambda x: x is not None, f_model_log: Callable[[Model], Any]=lambda x: deep_copy_model(x), f_in_sample_prediction_log: Callable[[np.n...
self.f_tree_mutation_log = f_tree_mutation_log
Given the code snippet: <|code_start|> self.e = LeafNode(Split(self.data)) self.c = DecisionNode(Split(self.data), self.d, self.e) self.b = LeafNode(Split(self.data)) self.a = DecisionNode(Split(self.data), self.b, self.c) self.tree = Tree([self.a, self.b, self.c, self.d, self.e])...
self.assertIn(proposal.existing_node, self.tree.nodes)
Predict the next line after this snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self....
self.assertIn(proposal.existing_node, self.tree.nodes)
Here is a snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.data)) self.c =...
class TestGrowTreeMutationProposer(unittest.TestCase):
Based on the snippet: <|code_start|> self.c = DecisionNode(Split(self.data), self.d, self.e) self.b = LeafNode(Split(self.data)) self.a = DecisionNode(Split(self.data), self.b, self.c) self.tree = Tree([self.a, self.b, self.c, self.d, self.e]) def test_proposal_isnt_mutating(self): ...
self.assertNotIn(proposal.updated_node, self.tree.nodes)
Given snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.data)) self.c = Dec...
def test_proposal_isnt_mutating(self):
Predict the next line for this snippet: <|code_start|> self.c = DecisionNode(Split(self.data), self.d, self.e) self.b = LeafNode(Split(self.data)) self.a = DecisionNode(Split(self.data), self.b, self.c) self.tree = Tree([self.a, self.b, self.c, self.d, self.e]) def test_proposal_isnt...
self.assertNotIn(proposal.updated_node, self.tree.nodes)
Given snippet: <|code_start|> class TestPruneTreeMutationProposer(unittest.TestCase): def setUp(self): self.data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}), np.array([1, 2]), normalize=False) self.d = LeafNode(Split(self.data)) self.e = LeafNode(Split(self.data)) self.c = Dec...
def test_proposal_isnt_mutating(self):
Given snippet: <|code_start|> class SigmaSampler(Sampler): def step(self, model: Model, sigma: Sigma) -> float: sample_value = self.sample(model, sigma) sigma.set_value(sample_value) return sample_value @staticmethod def sample(model: Model, sigma: Sigma) -> float: poster...
posterior_beta = sigma.beta + (0.5 * (np.sum(np.square(model.residuals()))))
Given snippet: <|code_start|> class SigmaSampler(Sampler): def step(self, model: Model, sigma: Sigma) -> float: sample_value = self.sample(model, sigma) sigma.set_value(sample_value) return sample_value <|code_end|> , continue by predicting the next line. Consider current file imports: ...
@staticmethod
Here is a snippet: <|code_start|> class SigmaSampler(Sampler): def step(self, model: Model, sigma: Sigma) -> float: sample_value = self.sample(model, sigma) sigma.set_value(sample_value) return sample_value @staticmethod def sample(model: Model, sigma: Sigma) -> float: po...
draw = np.power(np.random.gamma(posterior_alpha, 1./posterior_beta), -0.5)
Using the snippet: <|code_start|> def run(alpha, beta, n_trees): x = np.random.normal(0, 1, size=3000) X = pd.DataFrame(x) y = np.random.normal(0, 0.1, size=3000) + 2 * x + np.sin(x) plt.scatter(x, y) plt.show() model = ResidualBART(n_samples=200, n_burn=50, n_trees=n_trees, alpha=alpha, beta=...
if __name__ == "__main__":
Continue the code snippet: <|code_start|> def run(size=100, alpha=0.95, beta=2.0, n_trees=50): warnings.simplefilter("error", UserWarning) x = np.linspace(0, 5, size) X = pd.DataFrame(x) y = np.random.normal(0, 0.1, size=size) + np.sin(x) model = ResidualBART( ...
X_train, X_test, y_train, y_test = train_test_split(X,
Using the snippet: <|code_start|> def test_single_condition_data(self): data = make_bartpy_data(pd.DataFrame({"a": [1, 2]}).values, np.array([1, 2])) left_condition, right_condition = SplitCondition(0, 1, le), SplitCondition(0, 1, gt) left_split, right_split = Split(data) + left_condition, Sp...
class TestCombinedCondition(unittest.TestCase):
Predict the next line after this snippet: <|code_start|> data = make_bartpy_data(pd.DataFrame({"a": [1, 2, 3, 4]}).values, np.array([1, 2, 1, 1])) first_left_condition, first_right_condition = SplitCondition(0, 3, le), SplitCondition(0, 3, gt) second_left_condition, second_right_condition = Spli...
self.assertListEqual(list(combined_condition.condition(self.X)), [False, False, True, False, True, True])
Continue the code snippet: <|code_start|> def test_most_recent_split(self): data = make_bartpy_data(pd.DataFrame({"a": [1, 2, 3, 4]}).values, np.array([1, 2, 1, 1])) first_left_condition, first_right_condition = SplitCondition(0, 3, le), SplitCondition(0, 3, gt) second_left_condition, second...
self.assertEqual(combined_condition.variables[0].max_value, 5)
Predict the next line for this snippet: <|code_start|> def test_most_recent_split(self): data = make_bartpy_data(pd.DataFrame({"a": [1, 2, 3, 4]}).values, np.array([1, 2, 1, 1])) first_left_condition, first_right_condition = SplitCondition(0, 3, le), SplitCondition(0, 3, gt) second_left_con...
self.assertEqual(combined_condition.variables[0].min_value, 2)
Continue the code snippet: <|code_start|> def __init__(self, raw, user): """Initialize comment from raw JSON dict and user""" super(Comment, self).__init__(raw, user) self.comment = raw["comment"] self.comment_id = raw["commentID"] try: self.gmt = raw["gmt"] ...
return True
Predict the next line after this snippet: <|code_start|> def __init__(self, raw, user): """Initialize comment from raw JSON dict and user""" super(Comment, self).__init__(raw, user) self.comment = raw["comment"] self.comment_id = raw["commentID"] try: self.gmt = ra...
return True
Given snippet: <|code_start|> # Session for requests SESSION = Session() REQUEST = SESSION.request def _create_installation(iid): """Send a request to create an installation (ID: iid). Return the object ID associated with it""" data = { "deviceType": "android", "appVersion": setti...
}
Predict the next line for this snippet: <|code_start|> "timeZone": tzname[0], "installationId": iid, "appIdentifier": "com.yik.yak" } return _send("create", data, iid) def _save_user(user_id, iid, object_id): """Send a request to add user_id to the installation w...
"iid": iid,
Here is a snippet: <|code_start|> "data": data, "osVersion": settings.ANDROID_VERSION, "appBuildVersion": settings.PARSE_BUILD, "appDisplayVersion": settings.YIKYAK_VERSION, "v": settings.PARSE_VERSION_LETTER + settings.PARSE_VERSION, "iid": iid, ...
try:
Predict the next line after this snippet: <|code_start|> ("long", user.location.longitude), ("userID", user.user_id), ("userLat", user.location.latitude), ("userLong", user.location.longitude)] return _send("GET", settings.YIKYAK_ENDPOINT, "getMyTops", params) ...
("token", get_token()),
Using the snippet: <|code_start|> def log_event(user, event_type): """Return raw response data from logging an app event of type event_type using user""" params = [("accuracy", user.location.accuracy), ("token", get_token()), ("userID", user.user_id), ("userLat", u...
("message", message)]
Based on the snippet: <|code_start|> if basecamp and location is None: location = user.basecamp_location params = [("accuracy", user.location.accuracy), ("bc", int(basecamp)), ("lat", location.latitude), ("long", location.longitude), ("token", get_t...
if basecamp:
Predict the next line for this snippet: <|code_start|>class Message(object): """An abstract class for a postable object on Yik Yak (Comment or Yak)""" def __init__(self, raw, user): """Initialize message from raw JSON dict and user""" self.delivery_id = raw["deliveryID"] self.liked = raw...
self.likes -= 1
Here is a snippet: <|code_start|> class Uptime: def __init__(self, manager): self.client = manager.client <|code_end|> . Write the next line using the current file imports: import os import psutil import datetime from time import time from dasbit.helper import timesince and context from other files: # P...
manager.registerCommand('uptime', 'uptime', 'uptime', None, self.getUptime)
Using the snippet: <|code_start|> # Convert headers dictionary to # twisted raw headers format. headers = kwargs.get('headers') if headers: if isinstance(headers, dict): h = Headers({}) for k, v in headers.iteritems(): if isi...
if data:
Next line prediction: <|code_start|> # make test deterministic transactions = transactions.order_by("-created") self.assertEqual(len(transactions), 1) self.assertEqual(transactions[0].title, 'this_month') def test_this_months_transactions_list(self): with moc...
self.assertEqual(transactions[1].title, 'last_month')
Here is a snippet: <|code_start|> self.assertEqual(transactions[2].title, 'this_year') def test_this_years_transactions_list(self): with mock.patch('books.services.timezone') as mock_now: mock_now.now.return_value = datetime(2015, 4, 23, tzinfo=pytz.utc) c = Client() ...
{'filter': 'all_time'},
Continue the code snippet: <|code_start|> c = Client() logged_in = c.login(username=self.user.username, password='secret') self.assertTrue(logged_in) response = c.get(reverse('transaction_list_filter'), {'filter': 'this_year'}, ...
self.assertSequenceEqual(
Here is a snippet: <|code_start|> class TransactionTests(TestCase): def setUp(self): self.user = UserFactory() def test_create_model(self): self.assertEqual(0, Transaction.objects.count()) TransactionFactory(title='first') self.assertEqual(1, Transaction.objects.count()) ...
def test_transaction_create_get(self):
Here is a snippet: <|code_start|> self.assertTrue(logged_in) self.assertEqual(0, DebtLoan.objects.count()) response = c.post(reverse('debt_loan_create'), {'with_who': 'FooBar inc.', 'title': 'forty-two', 'amount': 42...
self.assertTrue(logged_in)
Next line prediction: <|code_start|> response = c.get(reverse('debt_loan_update', args=[t.id])) self.assertEqual(200, response.status_code) def test_debt_loan_update_post(self): c = Client() logged_in = c.login(username=self.user.username, password='secret') self.assertTrue(l...
amount=1,
Predict the next line for this snippet: <|code_start|> urlpatterns = [ url(r'^transactions/$', views.transaction_list, name='transaction_list'), url(r'^create/$', views.transaction_create, name='transaction_create'), url(r'^delete/(?P<pk>\d+)/$', views.transaction_delete, name='transaction_delete'...
name='debt_loan_delete'),
Given the following code snippet before the placeholder: <|code_start|> class TransactionForm(forms.ModelForm): class Meta: model = models.Transaction <|code_end|> , predict the next line using imports from the current file: from django import forms from books import models and context including class n...
fields = ['title', 'amount', 'category']