Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> pcrbdata_offset = kdbg.get_field_offset("nt", KPCR, "PrcbData.VectorToInterruptObject") except WindowsError: pcrbdata_offset = 0 addr_nt_KiStartUnexpectedRange = kdbg.get_symbol_offset("nt!KiStartUnexpectedRange") addr_nt_KiEndUnexpectedRange = kdbg.get_symbol_of...
kdbg = LocalKernelDebugger()
Based on the snippet: <|code_start|> def minus_one_error_check(func_name, result, func, args): if result == -1: raise Kernel32Error(func_name) return args def kernel32_error_check(func_name, result, func, args): """raise Kernel32Error if result is 0""" if not result: raise Kernel32Erro...
raise NtStatusException(result & 0xffffffff)
Predict the next line after this snippet: <|code_start|> default_error_check = staticmethod(kernel32_error_check) class IphlpapiProxy(ApiProxy): APIDLL = iphlpapi default_error_check = staticmethod(iphlpapi_error_check) class NtdllProxy(ApiProxy): APIDLL = ntdll default_error_check = staticmethod...
dbgprint("Export <{e.func_name}> not found in <{e.api_name}>".format(e=e), "EXPORTNOTFOUND")
Here is a snippet: <|code_start|>"""Basic contact management functions. Contacts are linked to monitors and are used to determine where to send alerts for monitors. Contacts are basic name/email/phone sets. Contacts are only stored in the database and not in memory, they are loaded from the database each time an ale...
async def create_contact(dbcon: DBConnection, name: Optional[str], email: Optional[str],
Given the code snippet: <|code_start|>"""Basic contact management functions. Contacts are linked to monitors and are used to determine where to send alerts for monitors. Contacts are basic name/email/phone sets. Contacts are only stored in the database and not in memory, they are loaded from the database each time a...
async def _run(cur: Cursor) -> None:
Using the snippet: <|code_start|>Contacts are linked to monitors and are used to determine where to send alerts for monitors. Contacts are basic name/email/phone sets. Contacts are only stored in the database and not in memory, they are loaded from the database each time an alert is sent. """ async def create_cont...
raise errors.IrisettError('invalid contact key %s' % key)
Given the code snippet: <|code_start|> return contact_group_id async def update_contact_group(dbcon: DBConnection, contact_group_id: int, data: Dict[str, str]) -> None: """Update a contact groups information in the database. Data is a dict with name/active values that will be updated. """ async d...
async def get_all_contacts_for_active_monitor(dbcon: DBConnection, monitor_id: int) -> Iterable[object_models.Contact]:
Continue the code snippet: <|code_start|>Contacts are only stored in the database and not in memory, they are loaded from the database each time an alert is sent. """ async def create_contact(dbcon: DBConnection, name: Optional[str], email: Optional[str], phone: Optional[str], active: bool) ...
if not await contact_exists(dbcon, contact_id):
Given the code snippet: <|code_start|> left join contact_groups on contact_groups.id=monitor_group_contact_groups.contact_group_id left join contact_group_contacts on contact_group_contacts.contact_group_id=contact_groups.id left join contacts on contacts.id=contact_group_contacts.contact_id ...
if not await active_monitor_exists(dbcon, monitor_id):
Using the snippet: <|code_start|>async def delete_contact(dbcon: DBConnection, contact_id: int) -> None: """Remove a contact from the database.""" if not await contact_exists(dbcon, contact_id): raise errors.InvalidArguments('contact does not exist') q = """delete from contacts where id=%s""" aw...
if not await contact_group_exists(dbcon, contact_group_id):
Based on the snippet: <|code_start|> CLICKSEND_URL = 'https://rest.clicksend.com/v3/sms/send' async def send_sms(recipients: Iterable[str], msg: str, username: str, api_key: str, sender: str): data = { 'messages': [], } # type: Dict[str, List] for recipient in recipients: data['messages'...
log.msg('Error sending clicksend sms notification: http status %s' % (str(resp.status)),
Predict the next line after this snippet: <|code_start|> async def send_slack_notification(url: str, attachments: List[Dict]): data = { 'attachments': attachments } try: async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(data), timeout=3...
log.msg('Error sending slack notification: http status %s' % (str(resp.status)),
Given the code snippet: <|code_start|> # noinspection PyMethodMayBeStatic class NotificationManager: def __init__(self, config: Any, *, loop: asyncio.AbstractEventLoop=None) -> None: self.loop = loop or asyncio.get_event_loop() if not config: <|code_end|> , generate the next line using the imports...
log.msg('Missing config section, no alert notification will be sent', 'NOTIFICATIONS')
Given the code snippet: <|code_start|> # noinspection PyMethodMayBeStatic class NotificationManager: def __init__(self, config: Any, *, loop: asyncio.AbstractEventLoop=None) -> None: self.loop = loop or asyncio.get_event_loop() if not config: log.msg('Missing config section, no alert n...
self.email_settings = email.parse_settings(config)
Given snippet: <|code_start|> # noinspection PyMethodMayBeStatic class NotificationManager: def __init__(self, config: Any, *, loop: asyncio.AbstractEventLoop=None) -> None: self.loop = loop or asyncio.get_event_loop() if not config: log.msg('Missing config section, no alert notificati...
self.http_settings = http.parse_settings(config)
Predict the next line after this snippet: <|code_start|> # noinspection PyMethodMayBeStatic class NotificationManager: def __init__(self, config: Any, *, loop: asyncio.AbstractEventLoop=None) -> None: self.loop = loop or asyncio.get_event_loop() if not config: log.msg('Missing config s...
self.sms_settings = sms.parse_settings(config)
Given the code snippet: <|code_start|> self.slack_settings = None else: self.http_settings = http.parse_settings(config) self.email_settings = email.parse_settings(config) self.sms_settings = sms.parse_settings(config) self.slack_settings = slack.parse_...
await clicksend.send_sms(recipients, msg, self.sms_settings['username'], self.sms_settings['api-key'],
Here is a snippet: <|code_start|> # noinspection PyMethodMayBeStatic class NotificationManager: def __init__(self, config: Any, *, loop: asyncio.AbstractEventLoop=None) -> None: self.loop = loop or asyncio.get_event_loop() if not config: log.msg('Missing config section, no alert notifi...
self.slack_settings = slack.parse_settings(config)
Given the code snippet: <|code_start|> raise MonitorFailedError(std_data) text, perf = parse_plugin_output(std_data) if proc.returncode not in [STATUS_OK, STATUS_WARNING]: raise MonitorFailedError(text) return text, perf def parse_plugin_output(output: Union[str, bytes]) -> Tuple[str, List[...
log.debug('nagios.encode_monitor_output: error: %s' % str(e))
Using the snippet: <|code_start|> async def send_http_notification(url: str, in_data: Any): out_data = json.dumps(in_data) try: async with aiohttp.ClientSession() as session: async with session.post(url, data=out_data, timeout=10) as resp: if resp.status != 200: <|code_end|...
log.msg('Error sending http notification: http status %s' % (str(resp.status)),
Next line prediction: <|code_start|>"""Websocket proxy for irisett events. Setup a websocket listener that sends irisett events over the websocket as they arrive. """ class WSEventProxy: def __init__(self, request: web.Request) -> None: self.request = request self.ws = web.WebSocketResponse() ...
self.listener = event.listen(self._handle_events)
Predict the next line for this snippet: <|code_start|> If a list of filter arguments are passed in convert it to a set for increased lookup speed and reduced size. """ ret = None if filter: ret = set(filter) return ret def wants_event(self, event_name: str...
stats.set('num_listeners', 0, 'EVENT')
Continue the code snippet: <|code_start|> active_monitor_filter can be a list of active monitor ids that must match. """ stats.inc('num_listeners', 'EVENT') listener = EventListener(self, callback, event_filter=event_filter, active_monitor_filter=active_monitor_filter) self.listen...
log.msg('Failed to run event listener callback: %s' % str(e))
Using the snippet: <|code_start|>"""Webapi middleware helpers. Middleware for common actions, authentication etc. """ # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(request: ...
log.msg('Received request: %s' % request, 'WEBAPI')
Continue the code snippet: <|code_start|>"""Webapi middleware helpers. Middleware for common actions, authentication etc. """ # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(r...
stats.inc('num_calls', 'WEBAPI')
Predict the next line after this snippet: <|code_start|> # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(request: web.Request) -> web.Response: stats.inc('num_calls', 'WE...
auth_str = auth_bytes.decode('utf-8', errors='ignore')
Given the following code snippet before the placeholder: <|code_start|> return await handler(request) return middleware_handler # noinspection PyUnusedLocal async def error_handler_middleware_factory(app: web.Application, handler: Any) -> Callable: """Error handling middle. Catch errors raised in...
except IrisettError as e:
Using the snippet: <|code_start|>"""Send notification emails.""" charset.add_charset('utf-8', charset.SHORTEST, charset.QP) # type: ignore # noinspection PyPep8 # noinspection PyPep8 async def send_email(loop: asyncio.AbstractEventLoop, mail_from: str, mail_to: Union[Iterable, str], subject: s...
log.msg('Error sending smtp notification: %s' % (str(e)), 'NOTIFICATIONS')
Given the code snippet: <|code_start|>"""Monitor groups. Monitor groups are used to group monitors into.. groups. They can be used as a cosmetic feature, but also to connect multiple monitors to contacts without setting the contact(s) for each monitor. """ <|code_end|> , generate the next line using the imports in ...
async def create_monitor_group(dbcon: DBConnection, parent_id: Optional[int], name: str):
Given the code snippet: <|code_start|>"""Monitor groups. Monitor groups are used to group monitors into.. groups. They can be used as a cosmetic feature, but also to connect multiple monitors to contacts without setting the contact(s) for each monitor. """ async def create_monitor_group(dbcon: DBConnection, parent_...
async def _run(cur: Cursor) -> None:
Predict the next line for this snippet: <|code_start|>"""Monitor groups. Monitor groups are used to group monitors into.. groups. They can be used as a cosmetic feature, but also to connect multiple monitors to contacts without setting the contact(s) for each monitor. """ async def create_monitor_group(dbcon: DBCon...
raise errors.InvalidArguments('missing monitor group name')
Given the following code snippet before the placeholder: <|code_start|> if not await monitor_group_exists(dbcon, monitor_group_id): raise errors.InvalidArguments('monitor_group does not exist') q = """delete from monitor_group_contacts where monitor_group_id=%s and contact_id=%s""" q_args = (monitor_...
async def get_all_monitor_groups(dbcon: DBConnection) -> Iterable[object_models.MonitorGroup]:
Using the snippet: <|code_start|>"""Monitor groups. Monitor groups are used to group monitors into.. groups. They can be used as a cosmetic feature, but also to connect multiple monitors to contacts without setting the contact(s) for each monitor. """ async def create_monitor_group(dbcon: DBConnection, parent_id: O...
if not await monitor_group_exists(dbcon, parent_id):
Given the code snippet: <|code_start|> q = """delete from object_metadata where object_type="monitor_group" and object_id=%s""" await cur.execute(q, (monitor_group_id,)) await dbcon.transact(_run) async def add_active_monitor_to_monitor_group(dbcon: DBConnection, monitor_group_id: int, monitor_id:...
if not await contact_exists(dbcon, contact_id):
Based on the snippet: <|code_start|> if key not in ['parent_id', 'name']: raise errors.IrisettError('invalid monitor_group key %s' % key) if key == 'parent_id' and value: if monitor_group_id == int(value): raise errors.InvalidArguments('monitor ...
if not await active_monitor_exists(dbcon, monitor_id):
Predict the next line after this snippet: <|code_start|> raise errors.InvalidArguments('monitor_group does not exist') q = """delete from monitor_group_active_monitors where monitor_group_id=%s and active_monitor_id=%s""" q_args = (monitor_group_id, monitor_id) await dbcon.operation(q, q_args) asyn...
if not await contact_group_exists(dbcon, contact_group_id):
Using the snippet: <|code_start|> def parse_settings(config: Any) -> Optional[Dict[str, Any]]: provider = config.get('sms-provider') if not provider: <|code_end|> , determine the next line of code. You have imports: from typing import Dict, Any, Optional, Iterable from irisett import ( log, ) from iriset...
log.msg('No SMS provider specified, no sms notifications will be sent', 'NOTIFICATIONS')
Given the following code snippet before the placeholder: <|code_start|> def parse_settings(config: Any) -> Optional[Dict[str, Any]]: provider = config.get('sms-provider') if not provider: log.msg('No SMS provider specified, no sms notifications will be sent', 'NOTIFICATIONS') return None i...
ret = clicksend.parse_settings(config)
Given the following code snippet before the placeholder: <|code_start|>"""Object metadata management. Metadata can be applied to any object type/id pair. Metadata is managed using metadicts, ie. key/value pairs of (short) data that are attached to an object. """ <|code_end|> , predict the next line using imports fr...
async def get_metadata(dbcon: DBConnection, object_type: str, object_id: int) -> Dict[str, str]:
Predict the next line for this snippet: <|code_start|>"""Object metadata management. Metadata can be applied to any object type/id pair. Metadata is managed using metadicts, ie. key/value pairs of (short) data that are attached to an object. """ async def get_metadata(dbcon: DBConnection, object_type: str, object_i...
async def _run(cur: Cursor) -> None:
Here is a snippet: <|code_start|> q_args = (object_type, object_id, str(key), str(value)) await cur.execute(q, q_args) await dbcon.transact(_run) async def delete_metadata(dbcon: DBConnection, object_type: str, object_id: int, keys: Optional[Iterable[str]] = N...
dbcon: DBConnection, object_type: str, object_id: int) -> Iterable[object_models.ObjectMetadata]:
Continue the code snippet: <|code_start|>"""Basic logging functionality. Supports logging to stdout, syslog and file. """ # Yes yes, globals are ugly. logger = None def configure_logging(logtype: str, logfilename: Optional[str]=None, debug_logging: bool=False, rotate_length: int=1000000, ma...
raise errors.IrisettError('invalid logtype name %s' % logtype)
Next line prediction: <|code_start|>"""Webmgmt middleware helpers. Middleware for common actions, authentication etc. """ # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(reque...
log.msg('Received request: %s' % request, 'WEBMGMT')
Here is a snippet: <|code_start|>"""Webmgmt middleware helpers. Middleware for common actions, authentication etc. """ # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(request:...
stats.inc('num_calls', 'WEBMGMT')
Next line prediction: <|code_start|> # noinspection PyUnusedLocal async def logging_middleware_factory(app: web.Application, handler: Any) -> Callable: """Basic logging and accounting.""" async def middleware_handler(request: web.Request) -> web.Response: stats.inc('num_calls', 'WEBMGMT') log....
auth_str = auth_bytes.decode('utf-8', errors='ignore')
Given snippet: <|code_start|># noinspection PyUnusedLocal async def error_handler_middleware_factory(app: web.Application, handler: Any) -> Callable: """Error handling middle. Catch errors raised in web views and try to return a corresponding HTTP error code. """ async def middleware_handler(reques...
except IrisettError as e:
Given snippet: <|code_start|>"""A set of functions used to validate HTTP input data. These functions are primarily used to valid that arguments sent in http requests are what they are supposed to be. """ def require_str(value: Any, convert: bool=False, allow_none: bool=False) -> Any: """Make sure a value is a ...
raise InvalidData('value was %s(%s), expected str' % (type(value), value))
Predict the next line for this snippet: <|code_start|> file. [default: settings.yaml] --mongo-host=<hostname> Host for mongo database [default: localhost] --mongo-port=<port> Port for mongo database [default: 27017] """ args_schema = schema.Schema({ '--mongo...
eprint("Using '%s' from config file" % (key,))
Here is a snippet: <|code_start|> __all__ = ["CompressibleForcing", "IncompressibleForcing", "EadyForcing", "CompressibleEadyForcing", "ShallowWaterForcing"] class Forcing(object, metaclass=ABCMeta): """ Base class for forcing terms for Gusto. :arg state: x :class:`.State` object. :arg euler_poincar...
logger.warning('Setting euler_poincare to False because you have set linear=True')
Predict the next line after this snippet: <|code_start|> if self.extruded: L += self.gravity_term() if self.coriolis: L += self.coriolis_term() if self.euler_poincare: L += self.euler_poincare_term() if self.topography: L += self.topography_...
if logger.isEnabledFor(DEBUG):
Continue the code snippet: <|code_start|> raise ValueError('Your coordinates do not appear to match the coordinates of a DoF') if field is None or new_value is None: return point_indices @pytest.mark.parametrize("geometry", ["1D", "2D"]) def test_gaussian_elimination(geometry, mesh): cell = m...
kernel = kernels.GaussianElimination(DG1)
Here is a snippet: <|code_start|> if field is not None and new_value is not None: field.dat.data[i] = new_value break if not point_found: raise ValueError('Your coordinates do not appear to match the coordinates of a DoF') if field is None or new_value is None: ...
kernel = kernels.PhysicsRecoveryTop() if boundary == "top" else kernels.PhysicsRecoveryBottom()
Based on the snippet: <|code_start|> self.on_sphere = (mesh._base_mesh.geometric_dimension() == 3 and mesh._base_mesh.topological_dimension() == 2) except AttributeError: self.on_sphere = (mesh.geometric_dimension() == 3 and mesh.topological_dimension() == 2) # build the vertica...
logger.setLevel(output.log_level)
Using the snippet: <|code_start|> except AttributeError: self.on_sphere = (mesh.geometric_dimension() == 3 and mesh.topological_dimension() == 2) # build the vertical normal and define perp for 2d geometries dim = mesh.topological_dimension() if self.on_sphere: x...
set_log_handler(mesh.comm)
Based on the snippet: <|code_start|> """ An object that 'recovers' a low order field (e.g. in DG0) into a higher order field (e.g. in CG1). The code is essentially that of the Firedrake Projector object, using the "average" method, and could possibly be replaced by it if it comes into the master ...
self.average_kernel = kernels.Average(self.V)
Here is a snippet: <|code_start|> __all__ = ["IncompressibleSolver", "ShallowWaterSolver", "CompressibleSolver"] class TimesteppingSolver(object, metaclass=ABCMeta): """ Base class for timestepping linear solvers for Gusto. This is a dummy base class. :arg state: :class:`.State` object. :arg so...
if logger.isEnabledFor(DEBUG):
Given the code snippet: <|code_start|> __all__ = ["IncompressibleSolver", "ShallowWaterSolver", "CompressibleSolver"] class TimesteppingSolver(object, metaclass=ABCMeta): """ Base class for timestepping linear solvers for Gusto. This is a dummy base class. :arg state: :class:`.State` object. :a...
if logger.isEnabledFor(DEBUG):
Continue the code snippet: <|code_start|> num_points = len(coord_field.dat.data[:]) point_found = False for i in range(num_points): # Do the coordinates at the ith point match our desired coords? if np.allclose(coord_field.dat.data[i], coords, rtol=1e-14): point_found = True ...
kernel = kernels.AverageWeightings(vec_CG1)
Next line prediction: <|code_start|> if field is not None and new_value is not None: field.dat.data[i] = new_value break if not point_found: raise ValueError('Your coordinates do not appear to match the coordinates of a DoF') if field is None or new_value is None...
kernel = kernels.Average(vec_CG1)
Predict the next line after this snippet: <|code_start|> class Timer(Stat): def __init__(self): self.count = 0 <|code_end|> using the current file's imports: import contextlib from time import time from .meter import Meter from .stats import Stat from .histogram import Histogram and any relevant contex...
self.meter = Meter()
Predict the next line for this snippet: <|code_start|> class Timer(Stat): def __init__(self): self.count = 0 self.meter = Meter() <|code_end|> with the help of current file imports: import contextlib from time import time from .meter import Meter from .stats import Stat from .histogram import Hi...
self.histogram = Histogram()
Here is a snippet: <|code_start|> app = Flask(__name__) registry = DistributedRegistry() registry.connect() timer = registry.timer('my.timer') @app.route('/') def hello(): with timer.time(): return 'finished' if __name__ == '__main__': def _report(_registry): while True: sleep(1...
RegistryAggregator(_report).start()
Predict the next line for this snippet: <|code_start|>from __future__ import print_function def is_within(delta): class _(object): def of(self, expected_value): def _check(value): return abs(value - expected_value) < delta return arg.passes_test(_check) return...
class StatsdReportingTestCase(StatsTest):
Using the snippet: <|code_start|>from __future__ import division _INTERVAL = 5.0 class Meter(Stat): def __init__(self): self.last_tick = time() self.count = 0 <|code_end|> , determine the next line of code. You have imports: from time import time from .average import EWMA from .stats import St...
self.m1 = EWMA.one()
Continue the code snippet: <|code_start|> class CounterProxy(MetricsProxy): def __init__(self, socket, name): super(CounterProxy, self).__init__(socket) self.name = name def increment(self, n=1): <|code_end|> . Use current file imports: from .proxy import MetricsProxy from .message import Mes...
self.send(Message('counter', self.name, n))
Given the code snippet: <|code_start|> @abc.abstractmethod def timer(self, name): raise NotImplementedError() @abc.abstractmethod def gauge(self, name, producer): raise NotImplementedError() @abc.abstractmethod def counter(self, name): raise NotImplementedError() @...
return self._get_or_add_stat(name, Meter)
Based on the snippet: <|code_start|> def meter(self, name): """Creates or gets an existing meter. :param name: The name :return: The created or existing meter for the given name """ return self._get_or_add_stat(name, Meter) def timer(self, name): """Creates or ge...
return self._get_or_add_stat(name, Counter)
Here is a snippet: <|code_start|> class Registry(BaseRegistry): """Factory and storage location for all metrics stuff. Use producer methods to create metrics. Metrics are hierarchical, the names are split on '.'. """ def meter(self, name): """Creates or gets an existing meter. :param...
return self._get_or_add_stat(name, functools.partial(Gauge, producer))
Given snippet: <|code_start|> def timer(self, name): """Creates or gets an existing timer. :param name: The name :return: The created or existing timer for the given name """ return self._get_or_add_stat(name, Timer) def gauge(self, name, producer): """Creates or...
return self._get_or_add_stat(name, Histogram)
Using the snippet: <|code_start|> @abc.abstractmethod def counter(self, name): raise NotImplementedError() @abc.abstractmethod def histogram(self, name): raise NotImplementedError() class Registry(BaseRegistry): """Factory and storage location for all metrics stuff. Use produ...
return self._get_or_add_stat(name, Timer)
Given snippet: <|code_start|>from __future__ import division class MeterProxy(MetricsProxy): def __init__(self, socket, name): super(MeterProxy, self).__init__(socket) self.name = name def mark(self, n=1): <|code_end|> , continue by predicting the next line. Consider current file imports: f...
self.send(Message('meter', self.name, n))
Given the following code snippet before the placeholder: <|code_start|>from __future__ import print_function class HTTPReportingTestCase(StatsTest): def test_http_reporter_serves_stats_as_json(self): counter = self.registry.counter('some.path') counter.increment(42) sock, http_port = ...
reporter = HTTPReporter(http_port, self.registry)
Here is a snippet: <|code_start|> class TornadoConsoleReportingTestCase(testing.AsyncTestCase): @testing.gen_test def test_tornado_stream_reporting_writes_to_stream(self): <|code_end|> . Write the next line using the current file imports: from datetime import timedelta from six import StringIO from tornado im...
registry = Registry()
Using the snippet: <|code_start|> class TornadoConsoleReportingTestCase(testing.AsyncTestCase): @testing.gen_test def test_tornado_stream_reporting_writes_to_stream(self): registry = Registry() counter = registry.counter('some.tornado.path') counter.increment(66) s = StringIO()...
reporter = TornadoStreamReporter(timedelta(milliseconds=100), stream=s, registry=registry)
Predict the next line after this snippet: <|code_start|> registry = DistributedRegistry() class TimedHandler(web.RequestHandler): timer = registry.timer('my.timer') @gen.coroutine def get(self): with TimedHandler.timer.time(): self.write('finished') if __name__ == "__main__": a...
RegistryAggregator(HTTPReporter(8889)).start()
Predict the next line for this snippet: <|code_start|> registry = DistributedRegistry() class TimedHandler(web.RequestHandler): timer = registry.timer('my.timer') @gen.coroutine def get(self): with TimedHandler.timer.time(): self.write('finished') if __name__ == "__main__": app...
RegistryAggregator(HTTPReporter(8889)).start()
Predict the next line for this snippet: <|code_start|> class HistogramProxy(MetricsProxy): def __init__(self, socket, name): super(HistogramProxy, self).__init__(socket) self.name = name def update(self, value): <|code_end|> with the help of current file imports: from .proxy import MetricsPr...
self.send(Message('histogram', self.name, value))
Using the snippet: <|code_start|> class ExponentiallyDecayingReservoirTestCase(unittest.TestCase): @fudge.patch('tapes.reservoir.time', 'tapes.reservoir.random') def test_update_always_applies_weight_to_values(self, time, random): (time .expects_call().returns(1.0) .next_call().retu...
reservoir = ExponentiallyDecayingReservoir(size=3)
Here is a snippet: <|code_start|> def test_distributed_registry_logs_stuff(): sock, http_port = bind_unused_port() sock.close() <|code_end|> . Write the next line using the current file imports: from time import sleep from tornado.testing import bind_unused_port from tapes.reporting.http import HTTPReporte...
aggregator = RegistryAggregator(HTTPReporter(http_port))
Continue the code snippet: <|code_start|> def test_distributed_registry_logs_stuff(): sock, http_port = bind_unused_port() sock.close() <|code_end|> . Use current file imports: from time import sleep from tornado.testing import bind_unused_port from tapes.reporting.http import HTTPReporter from tapes.distr...
aggregator = RegistryAggregator(HTTPReporter(http_port))
Given snippet: <|code_start|> class TornadoStatsdReportingTestCase(testing.AsyncTestCase): @testing.gen_test @fudge.patch('statsd.StatsClient') def test_tornado_statsd_reporter_works(self, StatsClient): (StatsClient.expects_call().with_args('localhost', 8125, None) .returns_fa...
registry = Registry()
Predict the next line for this snippet: <|code_start|> class TornadoStatsdReportingTestCase(testing.AsyncTestCase): @testing.gen_test @fudge.patch('statsd.StatsClient') def test_tornado_statsd_reporter_works(self, StatsClient): (StatsClient.expects_call().with_args('localhost', 8125, None) ...
reporter = TornadoStatsdReporter(timedelta(milliseconds=500), registry=registry)
Given the following code snippet before the placeholder: <|code_start|> registry = DistributedRegistry() registry.connect() timer = registry.timer('my.timer') class TimedHandler(web.RequestHandler): @gen.coroutine def get(self): with timer.time(): self.write('finished') if __name__ == "_...
RegistryAggregator(HTTPReporter(8889)).start()
Predict the next line after this snippet: <|code_start|> registry = DistributedRegistry() registry.connect() timer = registry.timer('my.timer') class TimedHandler(web.RequestHandler): @gen.coroutine def get(self): with timer.time(): self.write('finished') if __name__ == "__main__": a...
RegistryAggregator(HTTPReporter(8889)).start()
Based on the snippet: <|code_start|> class Histogram(Stat): def __init__(self): self.count = 0 <|code_end|> , predict the immediate next line with the help of imports: from tapes.reservoir import ExponentiallyDecayingReservoir from .stats import Stat and context (classes, functions, sometimes code) from ...
self.reservoir = ExponentiallyDecayingReservoir()
Using the snippet: <|code_start|>from __future__ import print_function class StreamReportingTestCase(StatsTest): def test_threaded_stream_reporter_prints_stats_with_intervals(self): counter = self.registry.counter( 'some.path' ) counter.increment(42) s = StringIO() ...
reporter = ThreadedStreamReporter(timedelta(milliseconds=100), stream=s, registry=self.registry)
Given the code snippet: <|code_start|> class TimerProxy(MetricsProxy): def __init__(self, socket, name): super(TimerProxy, self).__init__(socket) self.name = name @contextlib.contextmanager def time(self): start_time = time() try: yield finally: ...
self.send(Message('timer', self.name, end_time - start_time))
Given snippet: <|code_start|>parser.add_argument('data_dir', help='dir containing the input data.') parser.add_argument('out_dir', help='dir to write results to.') args = parser.parse_args() params = load_config(args.json) topicDict = params.get('outDir').format('topicDict.dict') opinionDict = params.get('outDir').fo...
s = get_sampler(params, corpus, nTopics=nTopics, initialize=False)
Predict the next line for this snippet: <|code_start|>documents. The corpus is not divided in perspectives. Used to estimate the likelihood of party manifestos given opinions for the different perspectives (party manifestos come from the manifesto project). Before this script can be run, a cptm corpus should be crea...
params = load_config(args.json)
Here is a snippet: <|code_start|>different perspectives (party manifestos come from the manifesto project). Before this script can be run, a cptm corpus should be created. Use the manifestoproject2cptm_input.py script to create a corpus that can be used as input. Usage: python experiment_manifesto.py <experiment.json...
c_perspectives = get_corpus(params)
Next line prediction: <|code_start|> opinionDict=opinionDict, testSplit=100, file_dict=None, topicLines=params.get('topicLines'), opinionLines=params.get('opinionLines')) # Update perspective names (default name is directory name, which is currently # the same fo...
t.to_csv(thetaFileName(params), encoding='utf8')
Based on the snippet: <|code_start|> Used for the CAP vragenuurtje data. Uses frog to pos-tag and lemmatize the data. Usage: python tabular2cpt_input.py <csv of excel file> <full text field name> <dir out> """ logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logg...
p = Perspective('', pos_topic_words(), pos_opinion_words())
Next line prediction: <|code_start|> logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('in_file', help='excel or csv file containing text data') parser.add_argument('text_field', help='name of the ...
p.add(pos, remove_trailing_digits(lemma))
Next line prediction: <|code_start|> Used for the CAP vragenuurtje data. Uses frog to pos-tag and lemmatize the data. Usage: python tabular2cpt_input.py <csv of excel file> <full text field name> <dir out> """ logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logg...
p = Perspective('', pos_topic_words(), pos_opinion_words())
Next line prediction: <|code_start|> Used for the CAP vragenuurtje data. Uses frog to pos-tag and lemmatize the data. Usage: python tabular2cpt_input.py <csv of excel file> <full text field name> <dir out> """ logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logg...
p = Perspective('', pos_topic_words(), pos_opinion_words())
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('in_file', help='excel or csv file containing text data') parser.add_argum...
if pos in word_types():
Predict the next line after this snippet: <|code_start|>"""Script that converts a field in a tabular data file to cptm input files Used for the CAP vragenuurtje data. Uses frog to pos-tag and lemmatize the data. Usage: python tabular2cpt_input.py <csv of excel file> <full text field name> <dir out> """ logger = l...
frogclient = get_frogclient()
Continue the code snippet: <|code_start|><dir out> """ logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('in_file', help='excel or csv file containing text data') parser.add_argument('text_field'...
for pos, lemma in pos_and_lemmas(text, frogclient):
Using the snippet: <|code_start|> logger = logging.getLogger(__name__) logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO) logger.setLevel(logging.DEBUG) logging.getLogger('inputgeneration').setLevel(logging.DEBUG) if __name__ == '__main__': parser = argparse.ArgumentParser() parser...
p = Perspective('', pos_topic_words(), pos_opinion_words())
Given the code snippet: <|code_start|> if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('dir_in', help='directory containing the data ' '(manifesto project csv files)') parser.add_argument('dir_out', help='the name of the dir where the ' ...
p.add(pos, remove_trailing_digits(lemma))