Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> if not stochastic: # dump every remaining one if live_k > 0: for idx in xrange(live_k): sample.append(hyp_samples[idx]) sample_score.append(hyp_scores[idx]) return sample, sample_score def translate_model(queue, rqueue, pid, models, options, k, normalize): trng = RandomStreams(1234) # allocate model parameters params = [] for i in xrange(len(models)): params.append(init_params(options)) # load model parameters and set theano shared variables tparams = [] for i in xrange(len(params)): params[i] = load_params(models[i], params[i]) tparams.append(init_tparams(params[i])) # word index use_noise = theano.shared(numpy.float32(0.)) f_inits = [] f_nexts = [] for i in xrange(len(tparams)): <|code_end|> . Use current file imports: import argparse import numpy import cPickle as pkl from nmt import (build_sampler, init_params) from mixer import * from multiprocessing import Process, Queue from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams and context (classes, functions, or code) from other files: # Path: nmt.py # def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None, # n_words_src=30000, n_words=30000): # def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None): # def train( # dim_word=100, # dim_word_src=200, # enc_dim=1000, # dec_dim=1000, # the number of LSTM units # patience=-1, # early stopping patience # max_epochs=5000, # finish_after=-1, # finish after this many updates # decay_c=0., # L2 regularization penalty # alpha_c=0., # alignment regularization # clip_c=-1., # gradient clipping threshold # lrate=0.01, # learning rate # n_words_src=100000, # source vocabulary size # n_words=100000, # target vocabulary size # maxlen=100, # maximum length of the description # maxlen_trg=None, # maximum length of the description # maxlen_sample=1000, # optimizer='rmsprop', # batch_size=16, # valid_batch_size=16, # sort_size=20, # save_path=None, # save_file_name='model', # save_best_models=0, # dispFreq=100, # validFreq=100, # saveFreq=1000, # save the parameters after every saveFreq updates # sampleFreq=-1, # verboseFreq=10000, # datasets=[ # 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok', # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'], # valid_datasets=['../data/dev/newstest2011.en.tok', # '../data/dev/newstest2011.fr.tok'], # dictionaries=[ # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl', # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'], # source_word_level=0, # target_word_level=0, # use_dropout=False, # re_load=False, # re_load_old_setting=False, # uidx=None, # eidx=None, # cidx=None, # layers=None, # save_every_saveFreq=0, # save_burn_in=20000, # use_bpe=0, # init_params=None, # build_model=None, # build_sampler=None, # gen_sample=None, # **kwargs # ): . Output only the next line.
f_init, f_next = build_sampler(tparams[i], options, trng, use_noise)
Next line prediction: <|code_start|> next_state_chars[i] = numpy.array(hyp_states_char) next_state_words[i] = numpy.array(hyp_states_word) hyp_scores = numpy.array(hyp_scores) live_k = new_live_k if new_live_k < 1: break if dead_k >= k: break next_w = numpy.array([w[-1] for w in hyp_samples]) if not stochastic: # dump every remaining one if live_k > 0: for idx in xrange(live_k): sample.append(hyp_samples[idx]) sample_score.append(hyp_scores[idx]) return sample, sample_score def translate_model(queue, rqueue, pid, models, options, k, normalize): trng = RandomStreams(1234) # allocate model parameters params = [] for i in xrange(len(models)): <|code_end|> . Use current file imports: (import argparse import numpy import cPickle as pkl from nmt import (build_sampler, init_params) from mixer import * from multiprocessing import Process, Queue from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams) and context including class names, function names, or small code snippets from other files: # Path: nmt.py # def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None, # n_words_src=30000, n_words=30000): # def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None): # def train( # dim_word=100, # dim_word_src=200, # enc_dim=1000, # dec_dim=1000, # the number of LSTM units # patience=-1, # early stopping patience # max_epochs=5000, # finish_after=-1, # finish after this many updates # decay_c=0., # L2 regularization penalty # alpha_c=0., # alignment regularization # clip_c=-1., # gradient clipping threshold # lrate=0.01, # learning rate # n_words_src=100000, # source vocabulary size # n_words=100000, # target vocabulary size # maxlen=100, # maximum length of the description # maxlen_trg=None, # maximum length of the description # maxlen_sample=1000, # optimizer='rmsprop', # batch_size=16, # valid_batch_size=16, # sort_size=20, # save_path=None, # save_file_name='model', # save_best_models=0, # dispFreq=100, # validFreq=100, # saveFreq=1000, # save the parameters after every saveFreq updates # sampleFreq=-1, # verboseFreq=10000, # datasets=[ # 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok', # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'], # valid_datasets=['../data/dev/newstest2011.en.tok', # '../data/dev/newstest2011.fr.tok'], # dictionaries=[ # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl', # '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'], # source_word_level=0, # target_word_level=0, # use_dropout=False, # re_load=False, # re_load_old_setting=False, # uidx=None, # eidx=None, # cidx=None, # layers=None, # save_every_saveFreq=0, # save_burn_in=20000, # use_bpe=0, # init_params=None, # build_model=None, # build_sampler=None, # gen_sample=None, # **kwargs # ): . Output only the next line.
params.append(init_params(options))
Given the code snippet: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionHtmlFile", create=True, request=request) <|code_end|> , generate the next line using the imports in this file: from unittest import mock from aiohttp import web from aiohttp.test_utils import make_mocked_coro from sockjs.transports import htmlfile import pytest and context (functions, classes, or occasionally code) from other files: # Path: sockjs/transports/htmlfile.py # PRELUDE1 = b""" # <!doctype html> # <html><head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # </head><body><h2>Don't panic!</h2> # <script> # document.domain = document.domain; # var c = parent.""" # PRELUDE2 = b"""; # c.start(); # function p(d) {c.message(d);}; # window.onload = function() {c.stop();}; # </script>""" # class HTMLFileTransport(StreamingTransport): # async def send(self, text): # async def process(self): . Output only the next line.
return htmlfile.HTMLFileTransport(manager, session, request)
Given the following code snippet before the placeholder: <|code_start|> class XHRStreamingTransport(StreamingTransport): maxsize = 131072 # 128K bytes open_seq = b"h" * 2048 + b"\n" async def process(self): request = self.request headers = ( (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), <|code_end|> , predict the next line using imports from the current file: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context including class names, function names, and sometimes code from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Using the snippet: <|code_start|> class XHRStreamingTransport(StreamingTransport): maxsize = 131072 # 128K bytes open_seq = b"h" * 2048 + b"\n" async def process(self): request = self.request headers = ( (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) <|code_end|> , determine the next line of code. You have imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context (class names, function names, or code) available: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += session_cookie(request)
Next line prediction: <|code_start|> class XHRStreamingTransport(StreamingTransport): maxsize = 131072 # 128K bytes open_seq = b"h" * 2048 + b"\n" async def process(self): request = self.request headers = ( (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) headers += session_cookie(request) <|code_end|> . Use current file imports: (from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers) and context including class names, function names, or small code snippets from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += cors_headers(request.headers)
Given snippet: <|code_start|> class XHRStreamingTransport(StreamingTransport): maxsize = 131072 # 128K bytes open_seq = b"h" * 2048 + b"\n" async def process(self): request = self.request headers = ( (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) headers += session_cookie(request) headers += cors_headers(request.headers) if request.method == hdrs.METH_OPTIONS: headers += ((hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),) <|code_end|> , continue by predicting the next line. Consider current file imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) which might include code, classes, or functions. Output only the next line.
headers += cache_headers()
Continue the code snippet: <|code_start|> close = WSMessage(type=WSMsgType.closing, data=b"", extra="") future = Future() future.set_result(pong) future2 = Future() future2.set_result(close) ws = mock.Mock() ws.receive.side_effect = [future, future2] session = transp.session await transp.client(ws, session) assert session._tick.called async def test_sends_ping(make_transport, make_fut): transp = make_transport() future = Future() future.set_result(False) ws = mock.Mock() ws.ping.side_effect = [future] hb_future = Future() hb_future.set_result((FRAME_HEARTBEAT, b"")) session_close_future = Future() <|code_end|> . Use current file imports: from unittest import mock from asyncio import Future from sockjs.exceptions import SessionIsClosed from sockjs.protocol import FRAME_CLOSE, FRAME_HEARTBEAT from sockjs.transports.rawwebsocket import RawWebSocketTransport from aiohttp import WSMessage, WSMsgType import pytest and context (classes, functions, or code) from other files: # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/transports/rawwebsocket.py # class RawWebSocketTransport(Transport): # async def server(self, ws, session): # while True: # try: # frame, data = await session._wait(pack=False) # except SessionIsClosed: # break # # if frame == FRAME_MESSAGE: # for text in data: # await ws.send_str(text) # elif frame == FRAME_MESSAGE_BLOB: # data = data[1:] # if data.startswith("["): # data = data[1:-1] # await ws.send_str(data) # elif frame == FRAME_HEARTBEAT: # await ws.ping() # elif frame == FRAME_CLOSE: # try: # await ws.close(message="Go away!") # finally: # await session._remote_closed() # # async def client(self, ws, session): # while True: # msg = await ws.receive() # # if msg.type == web.WSMsgType.text: # if not msg.data: # continue # await self.session._remote_message(msg.data) # elif msg.type == web.WSMsgType.close: # await self.session._remote_close() # elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): # await self.session._remote_closed() # break # elif msg.type == web.WSMsgType.PONG: # self.session._tick() # # async def process(self): # # start websocket connection # ws = self.ws = web.WebSocketResponse(autoping=False) # await ws.prepare(self.request) # # try: # await self.manager.acquire(self.session) # except Exception: # should use specific exception # await ws.close(message="Go away!") # return ws # # server = ensure_future(self.server(ws, self.session)) # client = ensure_future(self.client(ws, self.session)) # try: # await asyncio.wait((server, client), return_when=asyncio.FIRST_COMPLETED) # except asyncio.CancelledError: # raise # except Exception as exc: # await self.session._remote_close(exc) # finally: # await self.manager.release(self.session) # if not server.done(): # server.cancel() # if not client.done(): # client.cancel() # # return ws . Output only the next line.
session_close_future.set_exception(SessionIsClosed)
Predict the next line after this snippet: <|code_start|> @pytest.fixture def make_transport(make_request, make_fut): def maker(method="GET", path="/", query_params={}): manager = mock.Mock() session = mock.Mock() session._remote_closed = make_fut(1) <|code_end|> using the current file's imports: from unittest import mock from asyncio import Future from sockjs.exceptions import SessionIsClosed from sockjs.protocol import FRAME_CLOSE, FRAME_HEARTBEAT from sockjs.transports.rawwebsocket import RawWebSocketTransport from aiohttp import WSMessage, WSMsgType import pytest and any relevant context from other files: # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/transports/rawwebsocket.py # class RawWebSocketTransport(Transport): # async def server(self, ws, session): # while True: # try: # frame, data = await session._wait(pack=False) # except SessionIsClosed: # break # # if frame == FRAME_MESSAGE: # for text in data: # await ws.send_str(text) # elif frame == FRAME_MESSAGE_BLOB: # data = data[1:] # if data.startswith("["): # data = data[1:-1] # await ws.send_str(data) # elif frame == FRAME_HEARTBEAT: # await ws.ping() # elif frame == FRAME_CLOSE: # try: # await ws.close(message="Go away!") # finally: # await session._remote_closed() # # async def client(self, ws, session): # while True: # msg = await ws.receive() # # if msg.type == web.WSMsgType.text: # if not msg.data: # continue # await self.session._remote_message(msg.data) # elif msg.type == web.WSMsgType.close: # await self.session._remote_close() # elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): # await self.session._remote_closed() # break # elif msg.type == web.WSMsgType.PONG: # self.session._tick() # # async def process(self): # # start websocket connection # ws = self.ws = web.WebSocketResponse(autoping=False) # await ws.prepare(self.request) # # try: # await self.manager.acquire(self.session) # except Exception: # should use specific exception # await ws.close(message="Go away!") # return ws # # server = ensure_future(self.server(ws, self.session)) # client = ensure_future(self.client(ws, self.session)) # try: # await asyncio.wait((server, client), return_when=asyncio.FIRST_COMPLETED) # except asyncio.CancelledError: # raise # except Exception as exc: # await self.session._remote_close(exc) # finally: # await self.manager.release(self.session) # if not server.done(): # server.cancel() # if not client.done(): # client.cancel() # # return ws . Output only the next line.
session._wait = make_fut((FRAME_CLOSE, ""))
Predict the next line after this snippet: <|code_start|> transp = make_transport() pong = WSMessage(type=WSMsgType.PONG, data=b"", extra="") close = WSMessage(type=WSMsgType.closing, data=b"", extra="") future = Future() future.set_result(pong) future2 = Future() future2.set_result(close) ws = mock.Mock() ws.receive.side_effect = [future, future2] session = transp.session await transp.client(ws, session) assert session._tick.called async def test_sends_ping(make_transport, make_fut): transp = make_transport() future = Future() future.set_result(False) ws = mock.Mock() ws.ping.side_effect = [future] hb_future = Future() <|code_end|> using the current file's imports: from unittest import mock from asyncio import Future from sockjs.exceptions import SessionIsClosed from sockjs.protocol import FRAME_CLOSE, FRAME_HEARTBEAT from sockjs.transports.rawwebsocket import RawWebSocketTransport from aiohttp import WSMessage, WSMsgType import pytest and any relevant context from other files: # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/transports/rawwebsocket.py # class RawWebSocketTransport(Transport): # async def server(self, ws, session): # while True: # try: # frame, data = await session._wait(pack=False) # except SessionIsClosed: # break # # if frame == FRAME_MESSAGE: # for text in data: # await ws.send_str(text) # elif frame == FRAME_MESSAGE_BLOB: # data = data[1:] # if data.startswith("["): # data = data[1:-1] # await ws.send_str(data) # elif frame == FRAME_HEARTBEAT: # await ws.ping() # elif frame == FRAME_CLOSE: # try: # await ws.close(message="Go away!") # finally: # await session._remote_closed() # # async def client(self, ws, session): # while True: # msg = await ws.receive() # # if msg.type == web.WSMsgType.text: # if not msg.data: # continue # await self.session._remote_message(msg.data) # elif msg.type == web.WSMsgType.close: # await self.session._remote_close() # elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): # await self.session._remote_closed() # break # elif msg.type == web.WSMsgType.PONG: # self.session._tick() # # async def process(self): # # start websocket connection # ws = self.ws = web.WebSocketResponse(autoping=False) # await ws.prepare(self.request) # # try: # await self.manager.acquire(self.session) # except Exception: # should use specific exception # await ws.close(message="Go away!") # return ws # # server = ensure_future(self.server(ws, self.session)) # client = ensure_future(self.client(ws, self.session)) # try: # await asyncio.wait((server, client), return_when=asyncio.FIRST_COMPLETED) # except asyncio.CancelledError: # raise # except Exception as exc: # await self.session._remote_close(exc) # finally: # await self.manager.release(self.session) # if not server.done(): # server.cancel() # if not client.done(): # client.cancel() # # return ws . Output only the next line.
hb_future.set_result((FRAME_HEARTBEAT, b""))
Next line prediction: <|code_start|> @pytest.fixture def make_transport(make_request, make_fut): def maker(method="GET", path="/", query_params={}): manager = mock.Mock() session = mock.Mock() session._remote_closed = make_fut(1) session._wait = make_fut((FRAME_CLOSE, "")) request = make_request(method, path, query_params=query_params) request.app.freeze() <|code_end|> . Use current file imports: (from unittest import mock from asyncio import Future from sockjs.exceptions import SessionIsClosed from sockjs.protocol import FRAME_CLOSE, FRAME_HEARTBEAT from sockjs.transports.rawwebsocket import RawWebSocketTransport from aiohttp import WSMessage, WSMsgType import pytest) and context including class names, function names, or small code snippets from other files: # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/transports/rawwebsocket.py # class RawWebSocketTransport(Transport): # async def server(self, ws, session): # while True: # try: # frame, data = await session._wait(pack=False) # except SessionIsClosed: # break # # if frame == FRAME_MESSAGE: # for text in data: # await ws.send_str(text) # elif frame == FRAME_MESSAGE_BLOB: # data = data[1:] # if data.startswith("["): # data = data[1:-1] # await ws.send_str(data) # elif frame == FRAME_HEARTBEAT: # await ws.ping() # elif frame == FRAME_CLOSE: # try: # await ws.close(message="Go away!") # finally: # await session._remote_closed() # # async def client(self, ws, session): # while True: # msg = await ws.receive() # # if msg.type == web.WSMsgType.text: # if not msg.data: # continue # await self.session._remote_message(msg.data) # elif msg.type == web.WSMsgType.close: # await self.session._remote_close() # elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): # await self.session._remote_closed() # break # elif msg.type == web.WSMsgType.PONG: # self.session._tick() # # async def process(self): # # start websocket connection # ws = self.ws = web.WebSocketResponse(autoping=False) # await ws.prepare(self.request) # # try: # await self.manager.acquire(self.session) # except Exception: # should use specific exception # await ws.close(message="Go away!") # return ws # # server = ensure_future(self.server(ws, self.session)) # client = ensure_future(self.client(ws, self.session)) # try: # await asyncio.wait((server, client), return_when=asyncio.FIRST_COMPLETED) # except asyncio.CancelledError: # raise # except Exception as exc: # await self.session._remote_close(exc) # finally: # await self.manager.release(self.session) # if not server.done(): # server.cancel() # if not client.done(): # client.cancel() # # return ws . Output only the next line.
return RawWebSocketTransport(manager, session, request)
Predict the next line for this snippet: <|code_start|> class XHRTransport(StreamingTransport): """Long polling derivative transports, used for XHRPolling and JSONPolling.""" maxsize = 0 async def process(self): request = self.request if request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), ) headers += session_cookie(request) headers += cors_headers(request.headers) headers += cache_headers() return web.Response(status=204, headers=headers) headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), <|code_end|> with the help of current file imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) , which may contain function names, class names, or code. Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Predict the next line after this snippet: <|code_start|> class XHRTransport(StreamingTransport): """Long polling derivative transports, used for XHRPolling and JSONPolling.""" maxsize = 0 async def process(self): request = self.request if request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), ) <|code_end|> using the current file's imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and any relevant context from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += session_cookie(request)
Here is a snippet: <|code_start|> class XHRTransport(StreamingTransport): """Long polling derivative transports, used for XHRPolling and JSONPolling.""" maxsize = 0 async def process(self): request = self.request if request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), ) headers += session_cookie(request) <|code_end|> . Write the next line using the current file imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) , which may include functions, classes, or code. Output only the next line.
headers += cors_headers(request.headers)
Given snippet: <|code_start|> class XHRTransport(StreamingTransport): """Long polling derivative transports, used for XHRPolling and JSONPolling.""" maxsize = 0 async def process(self): request = self.request if request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), ) headers += session_cookie(request) headers += cors_headers(request.headers) <|code_end|> , continue by predicting the next line. Consider current file imports: from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) which might include code, classes, or functions. Output only the next line.
headers += cache_headers()
Given snippet: <|code_start|>"""raw websocket transport.""" class RawWebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait(pack=False) <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import FRAME_CLOSE, FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT and context: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" which might include code, classes, or functions. Output only the next line.
except SessionIsClosed:
Continue the code snippet: <|code_start|>"""raw websocket transport.""" class RawWebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait(pack=False) except SessionIsClosed: break if frame == FRAME_MESSAGE: for text in data: await ws.send_str(text) elif frame == FRAME_MESSAGE_BLOB: data = data[1:] if data.startswith("["): data = data[1:-1] await ws.send_str(data) elif frame == FRAME_HEARTBEAT: await ws.ping() <|code_end|> . Use current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import FRAME_CLOSE, FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT and context (classes, functions, or code) from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" . Output only the next line.
elif frame == FRAME_CLOSE:
Given snippet: <|code_start|>"""raw websocket transport.""" class RawWebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait(pack=False) except SessionIsClosed: break <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import FRAME_CLOSE, FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT and context: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" which might include code, classes, or functions. Output only the next line.
if frame == FRAME_MESSAGE:
Continue the code snippet: <|code_start|>"""raw websocket transport.""" class RawWebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait(pack=False) except SessionIsClosed: break if frame == FRAME_MESSAGE: for text in data: await ws.send_str(text) <|code_end|> . Use current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import FRAME_CLOSE, FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT and context (classes, functions, or code) from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" . Output only the next line.
elif frame == FRAME_MESSAGE_BLOB:
Given snippet: <|code_start|>"""raw websocket transport.""" class RawWebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait(pack=False) except SessionIsClosed: break if frame == FRAME_MESSAGE: for text in data: await ws.send_str(text) elif frame == FRAME_MESSAGE_BLOB: data = data[1:] if data.startswith("["): data = data[1:-1] await ws.send_str(data) <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import FRAME_CLOSE, FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT and context: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" which might include code, classes, or functions. Output only the next line.
elif frame == FRAME_HEARTBEAT:
Here is a snippet: <|code_start|>""" iframe-htmlfile transport """ PRELUDE1 = b""" <!doctype html> <html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head><body><h2>Don't panic!</h2> <script> document.domain = document.domain; var c = parent.""" PRELUDE2 = b"""; c.start(); function p(d) {c.message(d);}; window.onload = function() {c.stop();}; </script>""" class HTMLFileTransport(StreamingTransport): maxsize = 131072 # 128K bytes check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") async def send(self, text): <|code_end|> . Write the next line using the current file imports: import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers and context from other files: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors , which may include functions, classes, or code. Output only the next line.
blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING)
Given snippet: <|code_start|>""" iframe-htmlfile transport """ PRELUDE1 = b""" <!doctype html> <html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head><body><h2>Don't panic!</h2> <script> document.domain = document.domain; var c = parent.""" PRELUDE2 = b"""; c.start(); function p(d) {c.message(d);}; window.onload = function() {c.stop();}; </script>""" class HTMLFileTransport(StreamingTransport): maxsize = 131072 # 128K bytes check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") async def send(self, text): <|code_end|> , continue by predicting the next line. Consider current file imports: import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers and context: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors which might include code, classes, or functions. Output only the next line.
blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING)
Next line prediction: <|code_start|>""" iframe-htmlfile transport """ PRELUDE1 = b""" <!doctype html> <html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head><body><h2>Don't panic!</h2> <script> document.domain = document.domain; var c = parent.""" PRELUDE2 = b"""; c.start(); function p(d) {c.message(d);}; window.onload = function() {c.stop();}; </script>""" <|code_end|> . Use current file imports: (import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors . Output only the next line.
class HTMLFileTransport(StreamingTransport):
Here is a snippet: <|code_start|> check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") async def send(self, text): blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def process(self): request = self.request try: callback = request.query.get("c", None) except Exception: callback = request.GET.get("c", None) if callback is None: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), <|code_end|> . Write the next line using the current file imports: import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers and context from other files: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors , which may include functions, classes, or code. Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Using the snippet: <|code_start|> blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def process(self): request = self.request try: callback = request.query.get("c", None) except Exception: callback = request.GET.get("c", None) if callback is None: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), (hdrs.CONNECTION, "close"), ) <|code_end|> , determine the next line of code. You have imports: import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers and context (class names, function names, or code) available: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors . Output only the next line.
headers += session_cookie(request)
Given snippet: <|code_start|> await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def process(self): request = self.request try: callback = request.query.get("c", None) except Exception: callback = request.GET.get("c", None) if callback is None: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), (hdrs.CONNECTION, "close"), ) headers += session_cookie(request) <|code_end|> , continue by predicting the next line. Consider current file imports: import re from aiohttp import web, hdrs from ..protocol import dumps, ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers and context: # Path: sockjs/protocol.py # def dumps(data): # return json.dumps(data, **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors which might include code, classes, or functions. Output only the next line.
headers += cors_headers(request.headers)
Next line prediction: <|code_start|> async def test_streaming_send(make_transport): trans = make_transport() resp = trans.response = mock.Mock() resp.write = make_mocked_coro(None) stop = await trans.send("text data") assert not stop assert trans.size == len(b"text data\n") resp.write.assert_called_with(b"text data\n") trans.maxsize = 1 stop = await trans.send("text data") assert stop async def test_handle_session_interrupted(make_transport, make_fut): trans = make_transport() trans.session.interrupted = True trans.send = make_fut(1) trans.response = web.StreamResponse() await trans.handle_session() trans.send.assert_called_with('c[1002,"Connection interrupted"]') async def test_handle_session_closing(make_transport, make_fut): trans = make_transport() trans.send = make_fut(1) trans.session.interrupted = False <|code_end|> . Use current file imports: (from unittest import mock from aiohttp import web from aiohttp.test_utils import make_mocked_coro from sockjs import protocol from sockjs.transports import base import pytest) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # class StreamingTransport(Transport): # def __init__(self, manager, session, request): # def __init__(self, manager, session, request): # async def send(self, text): # async def handle_session(self): . Output only the next line.
trans.session.state = protocol.STATE_CLOSING
Given the code snippet: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionStreaming", create=True, request=request) <|code_end|> , generate the next line using the imports in this file: from unittest import mock from aiohttp import web from aiohttp.test_utils import make_mocked_coro from sockjs import protocol from sockjs.transports import base import pytest and context (functions, classes, or occasionally code) from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # class StreamingTransport(Transport): # def __init__(self, manager, session, request): # def __init__(self, manager, session, request): # async def send(self, text): # async def handle_session(self): . Output only the next line.
return base.StreamingTransport(manager, session, request)
Predict the next line for this snippet: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionXhrStreaming", create=True, request=request) <|code_end|> with the help of current file imports: from aiohttp import web from sockjs.transports import xhrstreaming import pytest and context from other files: # Path: sockjs/transports/xhrstreaming.py # class XHRStreamingTransport(StreamingTransport): # async def process(self): , which may contain function names, class names, or code. Output only the next line.
return xhrstreaming.XHRStreamingTransport(manager, session, request)
Continue the code snippet: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionEventSource", create=True, request=request) <|code_end|> . Use current file imports: from unittest import mock from aiohttp import web from aiohttp.test_utils import make_mocked_coro from sockjs.transports import EventsourceTransport import pytest and context (classes, functions, or code) from other files: # Path: sockjs/transports/eventsource.py # class EventsourceTransport(StreamingTransport): # async def send(self, text): # blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # headers = ( # (hdrs.CONTENT_TYPE, "text/event-stream"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # headers += session_cookie(self.request) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write(b"\r\n") # # # handle session # await self.handle_session() # # return resp . Output only the next line.
return EventsourceTransport(manager, session, request)
Predict the next line for this snippet: <|code_start|> async def echoSession(msg, session): if msg.type == sockjs.MSG_MESSAGE: session.send(msg.data) async def closeSessionHander(msg, session): if msg.type == sockjs.MSG_OPEN: session.close() async def broadcastSession(msg, session): if msg.type == sockjs.MSG_OPEN: session.manager.broadcast(msg.data) if __name__ == '__main__': """ Sockjs tests server """ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') HTMLFileTransport.maxsize = 4096 <|code_end|> with the help of current file imports: import asyncio import logging import sockjs from aiohttp import web from sockjs.transports.eventsource import EventsourceTransport from sockjs.transports.htmlfile import HTMLFileTransport from sockjs.transports.xhrstreaming import XHRStreamingTransport and context from other files: # Path: sockjs/transports/eventsource.py # class EventsourceTransport(StreamingTransport): # async def send(self, text): # blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # headers = ( # (hdrs.CONTENT_TYPE, "text/event-stream"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # headers += session_cookie(self.request) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write(b"\r\n") # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/htmlfile.py # class HTMLFileTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") # # async def send(self, text): # blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # request = self.request # # try: # callback = request.query.get("c", None) # except Exception: # callback = request.GET.get("c", None) # # if callback is None: # await self.session._remote_closed() # return web.HTTPInternalServerError(text='"callback" parameter required') # # elif not self.check_callback.match(callback): # await self.session._remote_closed() # return web.HTTPInternalServerError(text='invalid "callback" parameter') # # headers = ( # (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # (hdrs.CONNECTION, "close"), # ) # headers += session_cookie(request) # headers += cors_headers(request.headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write( # b"".join((PRELUDE1, callback.encode("utf-8"), PRELUDE2, b" " * 1024)) # ) # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/xhrstreaming.py # class XHRStreamingTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # open_seq = b"h" * 2048 + b"\n" # # async def process(self): # request = self.request # headers = ( # (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), # (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # # headers += session_cookie(request) # headers += cors_headers(request.headers) # # if request.method == hdrs.METH_OPTIONS: # headers += ((hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),) # headers += cache_headers() # return web.Response(status=204, headers=headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # resp.force_close() # await resp.prepare(request) # await resp.write(self.open_seq) # # # event loop # await self.handle_session() # # return resp , which may contain function names, class names, or code. Output only the next line.
EventsourceTransport.maxsize = 4096
Predict the next line after this snippet: <|code_start|> async def echoSession(msg, session): if msg.type == sockjs.MSG_MESSAGE: session.send(msg.data) async def closeSessionHander(msg, session): if msg.type == sockjs.MSG_OPEN: session.close() async def broadcastSession(msg, session): if msg.type == sockjs.MSG_OPEN: session.manager.broadcast(msg.data) if __name__ == '__main__': """ Sockjs tests server """ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') <|code_end|> using the current file's imports: import asyncio import logging import sockjs from aiohttp import web from sockjs.transports.eventsource import EventsourceTransport from sockjs.transports.htmlfile import HTMLFileTransport from sockjs.transports.xhrstreaming import XHRStreamingTransport and any relevant context from other files: # Path: sockjs/transports/eventsource.py # class EventsourceTransport(StreamingTransport): # async def send(self, text): # blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # headers = ( # (hdrs.CONTENT_TYPE, "text/event-stream"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # headers += session_cookie(self.request) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write(b"\r\n") # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/htmlfile.py # class HTMLFileTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") # # async def send(self, text): # blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # request = self.request # # try: # callback = request.query.get("c", None) # except Exception: # callback = request.GET.get("c", None) # # if callback is None: # await self.session._remote_closed() # return web.HTTPInternalServerError(text='"callback" parameter required') # # elif not self.check_callback.match(callback): # await self.session._remote_closed() # return web.HTTPInternalServerError(text='invalid "callback" parameter') # # headers = ( # (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # (hdrs.CONNECTION, "close"), # ) # headers += session_cookie(request) # headers += cors_headers(request.headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write( # b"".join((PRELUDE1, callback.encode("utf-8"), PRELUDE2, b" " * 1024)) # ) # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/xhrstreaming.py # class XHRStreamingTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # open_seq = b"h" * 2048 + b"\n" # # async def process(self): # request = self.request # headers = ( # (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), # (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # # headers += session_cookie(request) # headers += cors_headers(request.headers) # # if request.method == hdrs.METH_OPTIONS: # headers += ((hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),) # headers += cache_headers() # return web.Response(status=204, headers=headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # resp.force_close() # await resp.prepare(request) # await resp.write(self.open_seq) # # # event loop # await self.handle_session() # # return resp . Output only the next line.
HTMLFileTransport.maxsize = 4096
Here is a snippet: <|code_start|> async def echoSession(msg, session): if msg.type == sockjs.MSG_MESSAGE: session.send(msg.data) async def closeSessionHander(msg, session): if msg.type == sockjs.MSG_OPEN: session.close() async def broadcastSession(msg, session): if msg.type == sockjs.MSG_OPEN: session.manager.broadcast(msg.data) if __name__ == '__main__': """ Sockjs tests server """ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') HTMLFileTransport.maxsize = 4096 EventsourceTransport.maxsize = 4096 <|code_end|> . Write the next line using the current file imports: import asyncio import logging import sockjs from aiohttp import web from sockjs.transports.eventsource import EventsourceTransport from sockjs.transports.htmlfile import HTMLFileTransport from sockjs.transports.xhrstreaming import XHRStreamingTransport and context from other files: # Path: sockjs/transports/eventsource.py # class EventsourceTransport(StreamingTransport): # async def send(self, text): # blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # headers = ( # (hdrs.CONTENT_TYPE, "text/event-stream"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # headers += session_cookie(self.request) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write(b"\r\n") # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/htmlfile.py # class HTMLFileTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") # # async def send(self, text): # blob = ("<script>\np(%s);\n</script>\r\n" % dumps(text)).encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def process(self): # request = self.request # # try: # callback = request.query.get("c", None) # except Exception: # callback = request.GET.get("c", None) # # if callback is None: # await self.session._remote_closed() # return web.HTTPInternalServerError(text='"callback" parameter required') # # elif not self.check_callback.match(callback): # await self.session._remote_closed() # return web.HTTPInternalServerError(text='invalid "callback" parameter') # # headers = ( # (hdrs.CONTENT_TYPE, "text/html; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # (hdrs.CONNECTION, "close"), # ) # headers += session_cookie(request) # headers += cors_headers(request.headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # await resp.prepare(self.request) # await resp.write( # b"".join((PRELUDE1, callback.encode("utf-8"), PRELUDE2, b" " * 1024)) # ) # # # handle session # await self.handle_session() # # return resp # # Path: sockjs/transports/xhrstreaming.py # class XHRStreamingTransport(StreamingTransport): # # maxsize = 131072 # 128K bytes # open_seq = b"h" * 2048 + b"\n" # # async def process(self): # request = self.request # headers = ( # (hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")), # (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), # (hdrs.CACHE_CONTROL, CACHE_CONTROL), # ) # # headers += session_cookie(request) # headers += cors_headers(request.headers) # # if request.method == hdrs.METH_OPTIONS: # headers += ((hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),) # headers += cache_headers() # return web.Response(status=204, headers=headers) # # # open sequence (sockjs protocol) # resp = self.response = web.StreamResponse(headers=headers) # resp.force_close() # await resp.prepare(request) # await resp.write(self.open_seq) # # # event loop # await self.handle_session() # # return resp , which may include functions, classes, or code. Output only the next line.
XHRStreamingTransport.maxsize = 4096
Predict the next line after this snippet: <|code_start|> class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) headers += session_cookie(request) headers += cors_headers(request.headers) headers += cache_headers() return web.Response(status=204, headers=headers) data = await request.read() if not data: return web.HTTPInternalServerError(text="Payload expected.") try: <|code_end|> using the current file's imports: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and any relevant context from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
messages = loads(data.decode(ENCODING))
Given the following code snippet before the placeholder: <|code_start|> class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) headers += session_cookie(request) headers += cors_headers(request.headers) headers += cache_headers() return web.Response(status=204, headers=headers) data = await request.read() if not data: return web.HTTPInternalServerError(text="Payload expected.") try: <|code_end|> , predict the next line using imports from the current file: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
messages = loads(data.decode(ENCODING))
Given the code snippet: <|code_start|>class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) headers += session_cookie(request) headers += cors_headers(request.headers) headers += cache_headers() return web.Response(status=204, headers=headers) data = await request.read() if not data: return web.HTTPInternalServerError(text="Payload expected.") try: messages = loads(data.decode(ENCODING)) except Exception: return web.HTTPInternalServerError(text="Broken JSON encoding.") await self.session._remote_messages(messages) headers = ( (hdrs.CONTENT_TYPE, "text/plain; charset=UTF-8"), <|code_end|> , generate the next line using the imports in this file: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context (functions, classes, or occasionally code) from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Continue the code snippet: <|code_start|> class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) <|code_end|> . Use current file imports: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context (classes, functions, or code) from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += session_cookie(request)
Based on the snippet: <|code_start|> class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) headers += session_cookie(request) <|code_end|> , predict the immediate next line with the help of imports: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context (classes, functions, sometimes code) from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += cors_headers(request.headers)
Using the snippet: <|code_start|> class XHRSendTransport(Transport): async def process(self): request = self.request if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS): return web.HTTPForbidden(text="Method is not allowed") if self.request.method == hdrs.METH_OPTIONS: headers = ( (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"), (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), ) headers += session_cookie(request) headers += cors_headers(request.headers) <|code_end|> , determine the next line of code. You have imports: from aiohttp import web, hdrs from ..protocol import loads, ENCODING from .base import Transport from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers and context (class names, function names, or code) available: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): # # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # def cache_headers(): # d = datetime.now() + td365 # return ( # (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds), # (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds), # (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")), # ) . Output only the next line.
headers += cache_headers()
Given the code snippet: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionXhr", create=True, request=request) <|code_end|> , generate the next line using the imports in this file: from aiohttp import web from sockjs.transports import xhr import pytest and context (functions, classes, or occasionally code) from other files: # Path: sockjs/transports/xhr.py # class XHRTransport(StreamingTransport): # async def process(self): . Output only the next line.
return xhr.XHRTransport(manager, session, request)
Next line prediction: <|code_start|> @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionXhrSend", create=True, request=request) <|code_end|> . Use current file imports: (from aiohttp import web from sockjs.transports import xhrsend import pytest) and context including class names, function names, or small code snippets from other files: # Path: sockjs/transports/xhrsend.py # class XHRSendTransport(Transport): # async def process(self): . Output only the next line.
return xhrsend.XHRSendTransport(manager, session, request)
Based on the snippet: <|code_start|> log = logging.getLogger("sockjs") class Session(object): """SockJS session object ``state``: Session state ``manager``: Session manager that hold this session ``acquired``: Acquired state, indicates that transport is using session ``timeout``: Session timeout """ manager = None acquired = False <|code_end|> , predict the immediate next line with the help of imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context (classes, functions, sometimes code) from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
state = STATE_NEW
Using the snippet: <|code_start|> ``timeout``: Session timeout """ manager = None acquired = False state = STATE_NEW interrupted = False exception = None def __init__( self, id, handler, request, *, timeout=timedelta(seconds=10), debug=False ): self.id = id self.handler = handler self.request = request self.expired = False self.timeout = timeout self.expires = datetime.now() + timeout self._hits = 0 self._heartbeats = 0 self._heartbeat_transport = False self._debug = debug self._waiter = None self._queue = collections.deque() def __str__(self): result = ["id=%r" % (self.id,)] <|code_end|> , determine the next line of code. You have imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context (class names, function names, or code) available: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
if self.state == STATE_OPEN:
Given the following code snippet before the placeholder: <|code_start|> if self._hits: result.append("hits=%s" % self._hits) if self._heartbeats: result.append("heartbeats=%s" % self._heartbeats) return " ".join(result) def _tick(self, timeout=None): if timeout is None: self.expires = datetime.now() + self.timeout else: self.expires = datetime.now() + timeout async def _acquire(self, manager, heartbeat=True): self.acquired = True self.manager = manager self._heartbeat_transport = heartbeat self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN self._feed(FRAME_OPEN, FRAME_OPEN) try: await self.handler(OpenMessage, self) except asyncio.CancelledError: raise except Exception as exc: <|code_end|> , predict the next line using imports from the current file: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
self.state = STATE_CLOSING
Predict the next line after this snippet: <|code_start|> """ manager = None acquired = False state = STATE_NEW interrupted = False exception = None def __init__( self, id, handler, request, *, timeout=timedelta(seconds=10), debug=False ): self.id = id self.handler = handler self.request = request self.expired = False self.timeout = timeout self.expires = datetime.now() + timeout self._hits = 0 self._heartbeats = 0 self._heartbeat_transport = False self._debug = debug self._waiter = None self._queue = collections.deque() def __str__(self): result = ["id=%r" % (self.id,)] if self.state == STATE_OPEN: result.append("connected") <|code_end|> using the current file's imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and any relevant context from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
elif self.state == STATE_CLOSED:
Next line prediction: <|code_start|> if self.acquired: result.append("acquired") if len(self._queue): result.append("queue[%s]" % len(self._queue)) if self._hits: result.append("hits=%s" % self._hits) if self._heartbeats: result.append("heartbeats=%s" % self._heartbeats) return " ".join(result) def _tick(self, timeout=None): if timeout is None: self.expires = datetime.now() + self.timeout else: self.expires = datetime.now() + timeout async def _acquire(self, manager, heartbeat=True): self.acquired = True self.manager = manager self._heartbeat_transport = heartbeat self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN <|code_end|> . Use current file imports: (import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
self._feed(FRAME_OPEN, FRAME_OPEN)
Given snippet: <|code_start|> result.append("heartbeats=%s" % self._heartbeats) return " ".join(result) def _tick(self, timeout=None): if timeout is None: self.expires = datetime.now() + self.timeout else: self.expires = datetime.now() + timeout async def _acquire(self, manager, heartbeat=True): self.acquired = True self.manager = manager self._heartbeat_transport = heartbeat self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN self._feed(FRAME_OPEN, FRAME_OPEN) try: await self.handler(OpenMessage, self) except asyncio.CancelledError: raise except Exception as exc: self.state = STATE_CLOSING self.exception = exc self.interrupted = True <|code_end|> , continue by predicting the next line. Consider current file imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): which might include code, classes, or functions. Output only the next line.
self._feed(FRAME_CLOSE, (3000, "Internal error"))
Given snippet: <|code_start|> self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN self._feed(FRAME_OPEN, FRAME_OPEN) try: await self.handler(OpenMessage, self) except asyncio.CancelledError: raise except Exception as exc: self.state = STATE_CLOSING self.exception = exc self.interrupted = True self._feed(FRAME_CLOSE, (3000, "Internal error")) log.exception("Exception in open session handling.") def _release(self): self.acquired = False self.manager = None self._heartbeat_transport = False def _heartbeat(self): self._heartbeats += 1 if self._heartbeat: self._feed(FRAME_HEARTBEAT, FRAME_HEARTBEAT) def _feed(self, frame, data): # pack messages <|code_end|> , continue by predicting the next line. Consider current file imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): which might include code, classes, or functions. Output only the next line.
if frame == FRAME_MESSAGE:
Given the following code snippet before the placeholder: <|code_start|> log.debug("incoming message: %s, %s", self.id, msg[:200]) try: await self.handler(SockjsMessage(MSG_MESSAGE, msg), self) except Exception: log.exception("Exception in message handler.") def expire(self): """Manually expire a session.""" self.expired = True def send(self, msg): """send message to client.""" assert isinstance(msg, str), "String is required" if self._debug: log.info("outgoing message: %s, %s", self.id, str(msg)[:200]) if self.state != STATE_OPEN: return self._feed(FRAME_MESSAGE, msg) def send_frame(self, frm): """send message frame to client.""" if self._debug: log.info("outgoing message: %s, %s", self.id, frm[:200]) if self.state != STATE_OPEN: return <|code_end|> , predict the next line using imports from the current file: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
self._feed(FRAME_MESSAGE_BLOB, frm)
Given snippet: <|code_start|> self.acquired = True self.manager = manager self._heartbeat_transport = heartbeat self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN self._feed(FRAME_OPEN, FRAME_OPEN) try: await self.handler(OpenMessage, self) except asyncio.CancelledError: raise except Exception as exc: self.state = STATE_CLOSING self.exception = exc self.interrupted = True self._feed(FRAME_CLOSE, (3000, "Internal error")) log.exception("Exception in open session handling.") def _release(self): self.acquired = False self.manager = None self._heartbeat_transport = False def _heartbeat(self): self._heartbeats += 1 if self._heartbeat: <|code_end|> , continue by predicting the next line. Consider current file imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): which might include code, classes, or functions. Output only the next line.
self._feed(FRAME_HEARTBEAT, FRAME_HEARTBEAT)
Given snippet: <|code_start|> session.registry = self.app self[session.id] = session self.sessions.append(session) return session def get(self, id, create=False, request=None, default=_marker): session = super(SessionManager, self).get(id, None) if session is None: if create: session = self._add( self.factory( id, self.handler, request, timeout=self.timeout, debug=self.debug, ) ) else: if default is not _marker: return default raise KeyError(id) return session async def acquire(self, s): sid = s.id if sid in self.acquired: <|code_end|> , continue by predicting the next line. Consider current file imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): which might include code, classes, or functions. Output only the next line.
raise SessionIsAcquired("Another connection still open")
Here is a snippet: <|code_start|> else: self._queue.append((frame, [data])) else: self._queue.append((frame, data)) # notify waiter waiter = self._waiter if waiter is not None: self._waiter = None if not waiter.cancelled(): waiter.set_result(True) async def _wait(self, pack=True): if not self._queue and self.state != STATE_CLOSED: assert not self._waiter loop = asyncio.get_event_loop() self._waiter = loop.create_future() await self._waiter if self._queue: frame, payload = self._queue.popleft() self._tick() if pack: if frame == FRAME_CLOSE: return FRAME_CLOSE, close_frame(*payload) elif frame == FRAME_MESSAGE: return FRAME_MESSAGE, messages_frame(payload) return frame, payload else: <|code_end|> . Write the next line using the current file imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): , which may include functions, classes, or code. Output only the next line.
raise SessionIsClosed()
Given the following code snippet before the placeholder: <|code_start|> if not self._queue and self.state != STATE_CLOSED: assert not self._waiter loop = asyncio.get_event_loop() self._waiter = loop.create_future() await self._waiter if self._queue: frame, payload = self._queue.popleft() self._tick() if pack: if frame == FRAME_CLOSE: return FRAME_CLOSE, close_frame(*payload) elif frame == FRAME_MESSAGE: return FRAME_MESSAGE, messages_frame(payload) return frame, payload else: raise SessionIsClosed() async def _remote_close(self, exc=None): """close session from remote.""" if self.state in (STATE_CLOSING, STATE_CLOSED): return log.info("close session: %s", self.id) self.state = STATE_CLOSING if exc is not None: self.exception = exc self.interrupted = True try: <|code_end|> , predict the next line using imports from the current file: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.handler(SockjsMessage(MSG_CLOSE, exc), self)
Next line prediction: <|code_start|> self.interrupted = True try: await self.handler(SockjsMessage(MSG_CLOSE, exc), self) except Exception: log.exception("Exception in close handler.") async def _remote_closed(self): if self.state == STATE_CLOSED: return log.info("session closed: %s", self.id) self.state = STATE_CLOSED self.expire() try: await self.handler(ClosedMessage, self) except Exception: log.exception("Exception in closed handler.") # notify waiter waiter = self._waiter if waiter is not None: self._waiter = None if not waiter.cancelled(): waiter.set_result(True) async def _remote_message(self, msg): log.debug("incoming message: %s, %s", self.id, msg[:200]) self._tick() try: <|code_end|> . Use current file imports: (import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.handler(SockjsMessage(MSG_MESSAGE, msg), self)
Using the snippet: <|code_start|> def _feed(self, frame, data): # pack messages if frame == FRAME_MESSAGE: if self._queue and self._queue[-1][0] == FRAME_MESSAGE: self._queue[-1][1].append(data) else: self._queue.append((frame, [data])) else: self._queue.append((frame, data)) # notify waiter waiter = self._waiter if waiter is not None: self._waiter = None if not waiter.cancelled(): waiter.set_result(True) async def _wait(self, pack=True): if not self._queue and self.state != STATE_CLOSED: assert not self._waiter loop = asyncio.get_event_loop() self._waiter = loop.create_future() await self._waiter if self._queue: frame, payload = self._queue.popleft() self._tick() if pack: if frame == FRAME_CLOSE: <|code_end|> , determine the next line of code. You have imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context (class names, function names, or code) available: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
return FRAME_CLOSE, close_frame(*payload)
Next line prediction: <|code_start|> raise KeyError("Unknown session") await s._acquire(self) self.acquired[sid] = True return s def is_acquired(self, session): return session.id in self.acquired async def release(self, s): if s.id in self.acquired: s._release() del self.acquired[s.id] def active_sessions(self): for session in list(self.values()): if not session.expired: yield session async def clear(self): """Manually expire all sessions in the pool.""" for session in list(self.values()): if session.state != STATE_CLOSED: await session._remote_closed() self.sessions.clear() super(SessionManager, self).clear() def broadcast(self, message): <|code_end|> . Use current file imports: (import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
blob = message_frame(message)
Next line prediction: <|code_start|> # pack messages if frame == FRAME_MESSAGE: if self._queue and self._queue[-1][0] == FRAME_MESSAGE: self._queue[-1][1].append(data) else: self._queue.append((frame, [data])) else: self._queue.append((frame, data)) # notify waiter waiter = self._waiter if waiter is not None: self._waiter = None if not waiter.cancelled(): waiter.set_result(True) async def _wait(self, pack=True): if not self._queue and self.state != STATE_CLOSED: assert not self._waiter loop = asyncio.get_event_loop() self._waiter = loop.create_future() await self._waiter if self._queue: frame, payload = self._queue.popleft() self._tick() if pack: if frame == FRAME_CLOSE: return FRAME_CLOSE, close_frame(*payload) elif frame == FRAME_MESSAGE: <|code_end|> . Use current file imports: (import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
return FRAME_MESSAGE, messages_frame(payload)
Based on the snippet: <|code_start|> if not self._queue and self.state != STATE_CLOSED: assert not self._waiter loop = asyncio.get_event_loop() self._waiter = loop.create_future() await self._waiter if self._queue: frame, payload = self._queue.popleft() self._tick() if pack: if frame == FRAME_CLOSE: return FRAME_CLOSE, close_frame(*payload) elif frame == FRAME_MESSAGE: return FRAME_MESSAGE, messages_frame(payload) return frame, payload else: raise SessionIsClosed() async def _remote_close(self, exc=None): """close session from remote.""" if self.state in (STATE_CLOSING, STATE_CLOSED): return log.info("close session: %s", self.id) self.state = STATE_CLOSING if exc is not None: self.exception = exc self.interrupted = True try: <|code_end|> , predict the immediate next line with the help of imports: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context (classes, functions, sometimes code) from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.handler(SockjsMessage(MSG_CLOSE, exc), self)
Next line prediction: <|code_start|> result.append("acquired") if len(self._queue): result.append("queue[%s]" % len(self._queue)) if self._hits: result.append("hits=%s" % self._hits) if self._heartbeats: result.append("heartbeats=%s" % self._heartbeats) return " ".join(result) def _tick(self, timeout=None): if timeout is None: self.expires = datetime.now() + self.timeout else: self.expires = datetime.now() + timeout async def _acquire(self, manager, heartbeat=True): self.acquired = True self.manager = manager self._heartbeat_transport = heartbeat self._tick() self._hits += 1 if self.state == STATE_NEW: log.debug("open session: %s", self.id) self.state = STATE_OPEN self._feed(FRAME_OPEN, FRAME_OPEN) try: <|code_end|> . Use current file imports: (import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage) and context including class names, function names, or small code snippets from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.handler(OpenMessage, self)
Given the following code snippet before the placeholder: <|code_start|> elif frame == FRAME_MESSAGE: return FRAME_MESSAGE, messages_frame(payload) return frame, payload else: raise SessionIsClosed() async def _remote_close(self, exc=None): """close session from remote.""" if self.state in (STATE_CLOSING, STATE_CLOSED): return log.info("close session: %s", self.id) self.state = STATE_CLOSING if exc is not None: self.exception = exc self.interrupted = True try: await self.handler(SockjsMessage(MSG_CLOSE, exc), self) except Exception: log.exception("Exception in close handler.") async def _remote_closed(self): if self.state == STATE_CLOSED: return log.info("session closed: %s", self.id) self.state = STATE_CLOSED self.expire() try: <|code_end|> , predict the next line using imports from the current file: import warnings import asyncio import collections import logging from datetime import datetime, timedelta from asyncio import ensure_future from .protocol import STATE_NEW, STATE_OPEN, STATE_CLOSING, STATE_CLOSED from .protocol import FRAME_OPEN, FRAME_CLOSE from .protocol import FRAME_MESSAGE, FRAME_MESSAGE_BLOB, FRAME_HEARTBEAT from .exceptions import SessionIsAcquired, SessionIsClosed from .protocol import MSG_CLOSE, MSG_MESSAGE from .protocol import close_frame, message_frame, messages_frame from .protocol import SockjsMessage, OpenMessage, ClosedMessage and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # STATE_NEW = 0 # # STATE_OPEN = 1 # # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # Path: sockjs/protocol.py # FRAME_OPEN = "o" # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # FRAME_MESSAGE = "a" # # FRAME_MESSAGE_BLOB = "a1" # # FRAME_HEARTBEAT = "h" # # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # MSG_CLOSE = 3 # # MSG_MESSAGE = 2 # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # def message_frame(message): # return FRAME_MESSAGE + json.dumps([message], **kwargs) # # def messages_frame(messages): # return FRAME_MESSAGE + json.dumps(messages, **kwargs) # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.handler(ClosedMessage, self)
Given the following code snippet before the placeholder: <|code_start|> async def test_info(make_route, make_request): route = make_route() request = make_request("GET", "/sm/") response = await route.info(request) <|code_end|> , predict the next line using imports from the current file: import asyncio from aiohttp import web from multidict import CIMultiDict from sockjs import protocol and context including class names, function names, and sometimes code from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
info = protocol.loads(response.body.decode("utf-8"))
Predict the next line after this snippet: <|code_start|>"""websocket transport""" class WebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait() <|code_end|> using the current file's imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import STATE_CLOSED, FRAME_CLOSE from ..protocol import loads, close_frame and any relevant context from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
except SessionIsClosed:
Given snippet: <|code_start|> continue try: text = loads(data) except Exception as exc: await session._remote_close(exc) await session._remote_closed() await ws.close(message=b"broken json") break if data.startswith("["): await session._remote_messages(text) else: await session._remote_message(text) elif msg.type == web.WSMsgType.close: await session._remote_close() elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): await session._remote_closed() break async def process(self): # start websocket connection ws = self.ws = web.WebSocketResponse() await ws.prepare(self.request) # session was interrupted if self.session.interrupted: await self.ws.send_str(close_frame(1002, "Connection interrupted")) <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import STATE_CLOSED, FRAME_CLOSE from ..protocol import loads, close_frame and context: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): which might include code, classes, or functions. Output only the next line.
elif self.session.state == STATE_CLOSED:
Continue the code snippet: <|code_start|>"""websocket transport""" class WebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait() except SessionIsClosed: break try: await ws.send_str(data) except OSError: pass # ignore 'cannot write to closed transport' <|code_end|> . Use current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import STATE_CLOSED, FRAME_CLOSE from ..protocol import loads, close_frame and context (classes, functions, or code) from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
if frame == FRAME_CLOSE:
Here is a snippet: <|code_start|> class WebSocketTransport(Transport): async def server(self, ws, session): while True: try: frame, data = await session._wait() except SessionIsClosed: break try: await ws.send_str(data) except OSError: pass # ignore 'cannot write to closed transport' if frame == FRAME_CLOSE: try: await ws.close() finally: await session._remote_closed() async def client(self, ws, session): while True: msg = await ws.receive() if msg.type == web.WSMsgType.text: data = msg.data if not data: continue try: <|code_end|> . Write the next line using the current file imports: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import STATE_CLOSED, FRAME_CLOSE from ..protocol import loads, close_frame and context from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): , which may include functions, classes, or code. Output only the next line.
text = loads(data)
Given the following code snippet before the placeholder: <|code_start|> data = msg.data if not data: continue try: text = loads(data) except Exception as exc: await session._remote_close(exc) await session._remote_closed() await ws.close(message=b"broken json") break if data.startswith("["): await session._remote_messages(text) else: await session._remote_message(text) elif msg.type == web.WSMsgType.close: await session._remote_close() elif msg.type in (web.WSMsgType.closed, web.WSMsgType.closing): await session._remote_closed() break async def process(self): # start websocket connection ws = self.ws = web.WebSocketResponse() await ws.prepare(self.request) # session was interrupted if self.session.interrupted: <|code_end|> , predict the next line using imports from the current file: import asyncio from aiohttp import web from asyncio import ensure_future from .base import Transport from ..exceptions import SessionIsClosed from ..protocol import STATE_CLOSED, FRAME_CLOSE from ..protocol import loads, close_frame and context including class names, function names, and sometimes code from other files: # Path: sockjs/transports/base.py # class Transport: # def __init__(self, manager, session, request): # self.manager = manager # self.session = session # self.request = request # # Path: sockjs/exceptions.py # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.ws.send_str(close_frame(1002, "Connection interrupted"))
Using the snippet: <|code_start|> check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") callback = "" async def send(self, text): data = "/**/%s(%s);\r\n" % (self.callback, dumps(text)) await self.response.write(data.encode(ENCODING)) return True async def process(self): session = self.session request = self.request meth = request.method if request.method == hdrs.METH_GET: try: callback = self.callback = request.query.get("c") except Exception: callback = self.callback = request.GET.get("c") if not callback: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), <|code_end|> , determine the next line of code. You have imports: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and context (class names, function names, or code) available: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Using the snippet: <|code_start|> callback = "" async def send(self, text): data = "/**/%s(%s);\r\n" % (self.callback, dumps(text)) await self.response.write(data.encode(ENCODING)) return True async def process(self): session = self.session request = self.request meth = request.method if request.method == hdrs.METH_GET: try: callback = self.callback = request.query.get("c") except Exception: callback = self.callback = request.GET.get("c") if not callback: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) <|code_end|> , determine the next line of code. You have imports: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and context (class names, function names, or code) available: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
headers += session_cookie(request)
Given the code snippet: <|code_start|> async def send(self, text): data = "/**/%s(%s);\r\n" % (self.callback, dumps(text)) await self.response.write(data.encode(ENCODING)) return True async def process(self): session = self.session request = self.request meth = request.method if request.method == hdrs.METH_GET: try: callback = self.callback = request.query.get("c") except Exception: callback = self.callback = request.GET.get("c") if not callback: await self.session._remote_closed() return web.HTTPInternalServerError(text='"callback" parameter required') elif not self.check_callback.match(callback): await self.session._remote_closed() return web.HTTPInternalServerError(text='invalid "callback" parameter') headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) headers += session_cookie(request) <|code_end|> , generate the next line using the imports in this file: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and context (functions, classes, or occasionally code) from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
headers += cors_headers(request.headers)
Predict the next line after this snippet: <|code_start|>"""jsonp transport""" class JSONPolling(StreamingTransport): check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") callback = "" async def send(self, text): <|code_end|> using the current file's imports: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and any relevant context from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
data = "/**/%s(%s);\r\n" % (self.callback, dumps(text))
Here is a snippet: <|code_start|> headers = ( (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) headers += session_cookie(request) headers += cors_headers(request.headers) resp = self.response = web.StreamResponse(headers=headers) await resp.prepare(request) await self.handle_session() return resp elif request.method == hdrs.METH_POST: data = await request.read() ctype = request.content_type.lower() if ctype == "application/x-www-form-urlencoded": if not data.startswith(b"d="): return web.HTTPInternalServerError(text="Payload expected.") data = unquote_plus(data[2:].decode(ENCODING)) else: data = data.decode(ENCODING) if not data: return web.HTTPInternalServerError(text="Payload expected.") try: <|code_end|> . Write the next line using the current file imports: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and context from other files: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): , which may include functions, classes, or code. Output only the next line.
messages = loads(data)
Using the snippet: <|code_start|>"""jsonp transport""" class JSONPolling(StreamingTransport): check_callback = re.compile(r"^[a-zA-Z0-9_\.]+$") callback = "" async def send(self, text): data = "/**/%s(%s);\r\n" % (self.callback, dumps(text)) <|code_end|> , determine the next line of code. You have imports: import re from urllib.parse import unquote_plus from aiohttp import web, hdrs from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie, cors_headers from ..protocol import dumps, loads, ENCODING and context (class names, function names, or code) available: # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) # # def cors_headers(headers, nocreds=False): # origin = headers.get(hdrs.ORIGIN, "*") # cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),) # # ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS) # if ac_headers: # cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),) # # if origin != "*": # return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),) # else: # return cors # # Path: sockjs/protocol.py # ENCODING = "utf-8" # STATE_NEW = 0 # STATE_OPEN = 1 # STATE_CLOSING = 2 # STATE_CLOSED = 3 # FRAME_OPEN = "o" # FRAME_CLOSE = "c" # FRAME_MESSAGE = "a" # FRAME_MESSAGE_BLOB = "a1" # FRAME_HEARTBEAT = "h" # IFRAME_HTML = """<!DOCTYPE html> # <html> # <head> # <meta http-equiv="X-UA-Compatible" content="IE=edge" /> # <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> # <script src="%s"></script> # <script> # document.domain = document.domain; # SockJS.bootstrap_iframe(); # </script> # </head> # <body> # <h2>Don't panic!</h2> # <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p> # </body> # </html> # """.strip() # IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest() # ENCODING = "utf-8" # MSG_OPEN = 1 # MSG_MESSAGE = 2 # MSG_CLOSE = 3 # MSG_CLOSED = 4 # def dthandler(obj): # def dumps(data): # def close_frame(code, reason): # def message_frame(message): # def messages_frame(messages): # def tp(self): # class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])): . Output only the next line.
await self.response.write(data.encode(ENCODING))
Predict the next line for this snippet: <|code_start|> @pytest.fixture def make_transport(make_request, make_manager, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = make_handler(None) manager = make_manager(handler) request = make_request(method, path, query_params=query_params) session = manager.get("TestSessionJsonP", create=True, request=request) request.app.freeze() <|code_end|> with the help of current file imports: from unittest import mock from aiohttp import web from aiohttp.test_utils import make_mocked_coro from sockjs.transports import jsonp import pytest and context from other files: # Path: sockjs/transports/jsonp.py # class JSONPolling(StreamingTransport): # async def send(self, text): # async def process(self): , which may contain function names, class names, or code. Output only the next line.
return jsonp.JSONPolling(manager, session, request)
Predict the next line for this snippet: <|code_start|>""" iframe-eventsource transport """ class EventsourceTransport(StreamingTransport): async def send(self, text): blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def process(self): headers = ( (hdrs.CONTENT_TYPE, "text/event-stream"), <|code_end|> with the help of current file imports: from aiohttp import web, hdrs from sockjs.protocol import ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie and context from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) , which may contain function names, class names, or code. Output only the next line.
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
Predict the next line for this snippet: <|code_start|>""" iframe-eventsource transport """ class EventsourceTransport(StreamingTransport): async def send(self, text): blob = "".join(("data: ", text, "\r\n\r\n")).encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def process(self): headers = ( (hdrs.CONTENT_TYPE, "text/event-stream"), (hdrs.CACHE_CONTROL, CACHE_CONTROL), ) <|code_end|> with the help of current file imports: from aiohttp import web, hdrs from sockjs.protocol import ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie and context from other files: # Path: sockjs/protocol.py # ENCODING = "utf-8" # # Path: sockjs/transports/base.py # class StreamingTransport(Transport): # # timeout = None # maxsize = 131072 # 128K bytes # # def __init__(self, manager, session, request): # super().__init__(manager, session, request) # # self.size = 0 # self.response = None # # async def send(self, text): # blob = (text + "\n").encode(ENCODING) # await self.response.write(blob) # # self.size += len(blob) # if self.size > self.maxsize: # return True # else: # return False # # async def handle_session(self): # assert self.response is not None, "Response is not specified." # # # session was interrupted # if self.session.interrupted: # await self.send(close_frame(1002, "Connection interrupted")) # # # session is closing or closed # elif self.session.state in (STATE_CLOSING, STATE_CLOSED): # await self.session._remote_closed() # await self.send(close_frame(3000, "Go away!")) # # else: # # acquire session # try: # await self.manager.acquire(self.session) # except SessionIsAcquired: # await self.send(close_frame(2010, "Another connection still open")) # else: # try: # while True: # if self.timeout: # try: # frame, text = await asyncio.wait_for( # self.session._wait(), timeout=self.timeout # ) # except asyncio.futures.TimeoutError: # frame, text = FRAME_MESSAGE, "a[]" # else: # frame, text = await self.session._wait() # # if frame == FRAME_CLOSE: # await self.session._remote_closed() # await self.send(text) # return # else: # stop = await self.send(text) # if stop: # break # except asyncio.CancelledError: # await self.session._remote_close(exc=aiohttp.ClientConnectionError) # await self.session._remote_closed() # raise # except SessionIsClosed: # pass # finally: # await self.manager.release(self.session) # # Path: sockjs/transports/utils.py # CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0" # # def session_cookie(request): # cookie = request.cookies.get("JSESSIONID", "dummy") # cookies = http.cookies.SimpleCookie() # cookies["JSESSIONID"] = cookie # cookies["JSESSIONID"]["path"] = "/" # return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),) , which may contain function names, class names, or code. Output only the next line.
headers += session_cookie(self.request)
Based on the snippet: <|code_start|> self.size = 0 self.response = None async def send(self, text): blob = (text + "\n").encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def handle_session(self): assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: await self.send(close_frame(1002, "Connection interrupted")) # session is closing or closed elif self.session.state in (STATE_CLOSING, STATE_CLOSED): await self.session._remote_closed() await self.send(close_frame(3000, "Go away!")) else: # acquire session try: await self.manager.acquire(self.session) <|code_end|> , predict the immediate next line with the help of imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (classes, functions, sometimes code) from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
except SessionIsAcquired:
Using the snippet: <|code_start|> # acquire session try: await self.manager.acquire(self.session) except SessionIsAcquired: await self.send(close_frame(2010, "Another connection still open")) else: try: while True: if self.timeout: try: frame, text = await asyncio.wait_for( self.session._wait(), timeout=self.timeout ) except asyncio.futures.TimeoutError: frame, text = FRAME_MESSAGE, "a[]" else: frame, text = await self.session._wait() if frame == FRAME_CLOSE: await self.session._remote_closed() await self.send(text) return else: stop = await self.send(text) if stop: break except asyncio.CancelledError: await self.session._remote_close(exc=aiohttp.ClientConnectionError) await self.session._remote_closed() raise <|code_end|> , determine the next line of code. You have imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (class names, function names, or code) available: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
except SessionIsClosed:
Given the code snippet: <|code_start|> self.session = session self.request = request class StreamingTransport(Transport): timeout = None maxsize = 131072 # 128K bytes def __init__(self, manager, session, request): super().__init__(manager, session, request) self.size = 0 self.response = None async def send(self, text): blob = (text + "\n").encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def handle_session(self): assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: <|code_end|> , generate the next line using the imports in this file: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (functions, classes, or occasionally code) from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
await self.send(close_frame(1002, "Connection interrupted"))
Continue the code snippet: <|code_start|> class Transport: def __init__(self, manager, session, request): self.manager = manager self.session = session self.request = request class StreamingTransport(Transport): timeout = None maxsize = 131072 # 128K bytes def __init__(self, manager, session, request): super().__init__(manager, session, request) self.size = 0 self.response = None async def send(self, text): <|code_end|> . Use current file imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (classes, functions, or code) from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
blob = (text + "\n").encode(ENCODING)
Here is a snippet: <|code_start|> class StreamingTransport(Transport): timeout = None maxsize = 131072 # 128K bytes def __init__(self, manager, session, request): super().__init__(manager, session, request) self.size = 0 self.response = None async def send(self, text): blob = (text + "\n").encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def handle_session(self): assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: await self.send(close_frame(1002, "Connection interrupted")) # session is closing or closed <|code_end|> . Write the next line using the current file imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" , which may include functions, classes, or code. Output only the next line.
elif self.session.state in (STATE_CLOSING, STATE_CLOSED):
Based on the snippet: <|code_start|> class StreamingTransport(Transport): timeout = None maxsize = 131072 # 128K bytes def __init__(self, manager, session, request): super().__init__(manager, session, request) self.size = 0 self.response = None async def send(self, text): blob = (text + "\n").encode(ENCODING) await self.response.write(blob) self.size += len(blob) if self.size > self.maxsize: return True else: return False async def handle_session(self): assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: await self.send(close_frame(1002, "Connection interrupted")) # session is closing or closed <|code_end|> , predict the immediate next line with the help of imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (classes, functions, sometimes code) from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
elif self.session.state in (STATE_CLOSING, STATE_CLOSED):
Given the code snippet: <|code_start|> assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: await self.send(close_frame(1002, "Connection interrupted")) # session is closing or closed elif self.session.state in (STATE_CLOSING, STATE_CLOSED): await self.session._remote_closed() await self.send(close_frame(3000, "Go away!")) else: # acquire session try: await self.manager.acquire(self.session) except SessionIsAcquired: await self.send(close_frame(2010, "Another connection still open")) else: try: while True: if self.timeout: try: frame, text = await asyncio.wait_for( self.session._wait(), timeout=self.timeout ) except asyncio.futures.TimeoutError: frame, text = FRAME_MESSAGE, "a[]" else: frame, text = await self.session._wait() <|code_end|> , generate the next line using the imports in this file: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context (functions, classes, or occasionally code) from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" . Output only the next line.
if frame == FRAME_CLOSE:
Predict the next line for this snippet: <|code_start|> else: return False async def handle_session(self): assert self.response is not None, "Response is not specified." # session was interrupted if self.session.interrupted: await self.send(close_frame(1002, "Connection interrupted")) # session is closing or closed elif self.session.state in (STATE_CLOSING, STATE_CLOSED): await self.session._remote_closed() await self.send(close_frame(3000, "Go away!")) else: # acquire session try: await self.manager.acquire(self.session) except SessionIsAcquired: await self.send(close_frame(2010, "Another connection still open")) else: try: while True: if self.timeout: try: frame, text = await asyncio.wait_for( self.session._wait(), timeout=self.timeout ) except asyncio.futures.TimeoutError: <|code_end|> with the help of current file imports: import aiohttp import asyncio from ..exceptions import SessionIsAcquired, SessionIsClosed from ..protocol import close_frame, ENCODING from ..protocol import STATE_CLOSING, STATE_CLOSED, FRAME_CLOSE, FRAME_MESSAGE and context from other files: # Path: sockjs/exceptions.py # class SessionIsAcquired(SockjsException): # """Session is acquired.""" # # class SessionIsClosed(SockjsException): # """Session is closed.""" # # Path: sockjs/protocol.py # def close_frame(code, reason): # return FRAME_CLOSE + json.dumps([code, reason], **kwargs) # # ENCODING = "utf-8" # # Path: sockjs/protocol.py # STATE_CLOSING = 2 # # STATE_CLOSED = 3 # # FRAME_CLOSE = "c" # # FRAME_MESSAGE = "a" , which may contain function names, class names, or code. Output only the next line.
frame, text = FRAME_MESSAGE, "a[]"
Given the following code snippet before the placeholder: <|code_start|>#!/usr/local/bin/python3 __author__ = 'apaeffgen' # -*- coding: utf-8 -*- # This file is part of Panconvert. # # Panconvert is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class OpenURIDialog(QtWidgets.QDialog): global uri def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) <|code_end|> , predict the next line using imports from the current file: from source.gui.panconvert_diag_openuri import Ui_DialogOpenURI from source.language.messages import * from source.main_gui import * from os.path import isfile import builtins import codecs and context including class names, function names, and sometimes code from other files: # Path: source/gui/panconvert_diag_openuri.py # class Ui_DialogOpenURI(object): # def setupUi(self, DialogOpenURI): # DialogOpenURI.setObjectName("DialogOpenURI") # DialogOpenURI.resize(386, 90) # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(DialogOpenURI.sizePolicy().hasHeightForWidth()) # DialogOpenURI.setSizePolicy(sizePolicy) # DialogOpenURI.setMinimumSize(QtCore.QSize(386, 90)) # DialogOpenURI.setMaximumSize(QtCore.QSize(386, 90)) # self.URI = QtWidgets.QPlainTextEdit(DialogOpenURI) # self.URI.setGeometry(QtCore.QRect(10, 10, 371, 41)) # self.URI.setObjectName("URI") # self.layoutWidget = QtWidgets.QWidget(DialogOpenURI) # self.layoutWidget.setGeometry(QtCore.QRect(7, 60, 371, 32)) # self.layoutWidget.setObjectName("layoutWidget") # self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget) # self.horizontalLayout.setContentsMargins(0, 0, 0, 0) # self.horizontalLayout.setObjectName("horizontalLayout") # self.CheckBoxStayOnTop = QtWidgets.QCheckBox(self.layoutWidget) # self.CheckBoxStayOnTop.setEnabled(False) # self.CheckBoxStayOnTop.setObjectName("CheckBoxStayOnTop") # self.horizontalLayout.addWidget(self.CheckBoxStayOnTop) # self.ButtonCancel = QtWidgets.QPushButton(self.layoutWidget) # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(self.ButtonCancel.sizePolicy().hasHeightForWidth()) # self.ButtonCancel.setSizePolicy(sizePolicy) # self.ButtonCancel.setMinimumSize(QtCore.QSize(114, 32)) # self.ButtonCancel.setMaximumSize(QtCore.QSize(114, 32)) # self.ButtonCancel.setBaseSize(QtCore.QSize(114, 32)) # self.ButtonCancel.setObjectName("ButtonCancel") # self.horizontalLayout.addWidget(self.ButtonCancel) # self.ButtonOpenURI = QtWidgets.QPushButton(self.layoutWidget) # self.ButtonOpenURI.setObjectName("ButtonOpenURI") # self.horizontalLayout.addWidget(self.ButtonOpenURI) # # self.retranslateUi(DialogOpenURI) # QtCore.QMetaObject.connectSlotsByName(DialogOpenURI) # # def retranslateUi(self, DialogOpenURI): # _translate = QtCore.QCoreApplication.translate # DialogOpenURI.setWindowTitle(_translate("DialogOpenURI", "Open URI")) # self.CheckBoxStayOnTop.setText(_translate("DialogOpenURI", "Stay on Top")) # self.ButtonCancel.setText(_translate("DialogOpenURI", "Cancel")) # self.ButtonOpenURI.setText(_translate("DialogOpenURI", "Open URI")) . Output only the next line.
self.ui = Ui_DialogOpenURI()
Based on the snippet: <|code_start|> # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class ToFormatDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_To_Format_Dialog() self.ui.setupUi(self) #self.ui.ButtonInfo.clicked.connect(self.info) self.ui.ButtonCancel.clicked.connect(self.closeEvent) #self.ui.ButtonMoreInfo.clicked.connect(self.moreinfo) #Initialize Settings settings = QSettings('Pandoc', 'PanConvert') path_pandoc = settings.value('path_pandoc','') self.resize(settings.value("ToFormat_size", QSize(270, 225))) self.move(settings.value("ToFormat_pos", QPoint(50, 50))) if os.path.isfile(path_pandoc): <|code_end|> , predict the immediate next line with the help of imports: from source.helpers.interface_pandoc import get_pandoc_formats from source.gui.panconvert_diag_toformat import Ui_To_Format_Dialog from source.language.messages import * and context (classes, functions, sometimes code) from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_formats(): # """ # Dynamic preprocessor for Pandoc formats. # Return 2 lists. "from_formats" and "to_formats". # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 118: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(False) # txt = ' '.join(help_text[1:help_text.index('Options:')]) # # # aux = txt.split('Output formats: ') # in_ = aux[0].split('Input formats: ')[1].split(',') # out = aux[1].split(',') # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # # p = subprocess.Popen( # [path_pandoc, '--list-input-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # inputformats = p.communicate()[0].decode().splitlines(False) # # # p = subprocess.Popen( # [path_pandoc, '--list-output-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # outputformats = p.communicate()[0].decode().splitlines(False) # # in_ = inputformats # out = outputformats # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # Path: source/gui/panconvert_diag_toformat.py # class Ui_To_Format_Dialog(object): # def setupUi(self, To_Format_Dialog): # To_Format_Dialog.setObjectName("To_Format_Dialog") # To_Format_Dialog.setWindowModality(QtCore.Qt.NonModal) # To_Format_Dialog.setEnabled(True) # To_Format_Dialog.resize(334, 402) # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) # sizePolicy.setHorizontalStretch(1) # sizePolicy.setVerticalStretch(1) # sizePolicy.setHeightForWidth(To_Format_Dialog.sizePolicy().hasHeightForWidth()) # To_Format_Dialog.setSizePolicy(sizePolicy) # To_Format_Dialog.setMinimumSize(QtCore.QSize(224, 234)) # To_Format_Dialog.setSizeGripEnabled(False) # To_Format_Dialog.setModal(False) # self.gridLayout = QtWidgets.QGridLayout(To_Format_Dialog) # self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.ButtonCancel = QtWidgets.QPushButton(To_Format_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.verticalLayout.addWidget(self.ButtonCancel) # self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(To_Format_Dialog) # self.textBrowser.setMinimumSize(QtCore.QSize(200, 100)) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(To_Format_Dialog) # QtCore.QMetaObject.connectSlotsByName(To_Format_Dialog) # # def retranslateUi(self, To_Format_Dialog): # _translate = QtCore.QCoreApplication.translate # To_Format_Dialog.setWindowTitle(_translate("To_Format_Dialog", "Pandoc To Formats")) # self.ButtonCancel.setText(_translate("To_Format_Dialog", "Cancel")) . Output only the next line.
formats = get_pandoc_formats()
Predict the next line after this snippet: <|code_start|>#!/usr/local/bin/python3 __author__ = 'apaeffgen' # -*- coding: utf-8 -*- # This file is part of Panconvert. # # Panconvert is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class ToFormatDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) <|code_end|> using the current file's imports: from source.helpers.interface_pandoc import get_pandoc_formats from source.gui.panconvert_diag_toformat import Ui_To_Format_Dialog from source.language.messages import * and any relevant context from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_formats(): # """ # Dynamic preprocessor for Pandoc formats. # Return 2 lists. "from_formats" and "to_formats". # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 118: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(False) # txt = ' '.join(help_text[1:help_text.index('Options:')]) # # # aux = txt.split('Output formats: ') # in_ = aux[0].split('Input formats: ')[1].split(',') # out = aux[1].split(',') # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # # p = subprocess.Popen( # [path_pandoc, '--list-input-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # inputformats = p.communicate()[0].decode().splitlines(False) # # # p = subprocess.Popen( # [path_pandoc, '--list-output-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # outputformats = p.communicate()[0].decode().splitlines(False) # # in_ = inputformats # out = outputformats # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # Path: source/gui/panconvert_diag_toformat.py # class Ui_To_Format_Dialog(object): # def setupUi(self, To_Format_Dialog): # To_Format_Dialog.setObjectName("To_Format_Dialog") # To_Format_Dialog.setWindowModality(QtCore.Qt.NonModal) # To_Format_Dialog.setEnabled(True) # To_Format_Dialog.resize(334, 402) # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) # sizePolicy.setHorizontalStretch(1) # sizePolicy.setVerticalStretch(1) # sizePolicy.setHeightForWidth(To_Format_Dialog.sizePolicy().hasHeightForWidth()) # To_Format_Dialog.setSizePolicy(sizePolicy) # To_Format_Dialog.setMinimumSize(QtCore.QSize(224, 234)) # To_Format_Dialog.setSizeGripEnabled(False) # To_Format_Dialog.setModal(False) # self.gridLayout = QtWidgets.QGridLayout(To_Format_Dialog) # self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.ButtonCancel = QtWidgets.QPushButton(To_Format_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.verticalLayout.addWidget(self.ButtonCancel) # self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(To_Format_Dialog) # self.textBrowser.setMinimumSize(QtCore.QSize(200, 100)) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(To_Format_Dialog) # QtCore.QMetaObject.connectSlotsByName(To_Format_Dialog) # # def retranslateUi(self, To_Format_Dialog): # _translate = QtCore.QCoreApplication.translate # To_Format_Dialog.setWindowTitle(_translate("To_Format_Dialog", "Pandoc To Formats")) # self.ButtonCancel.setText(_translate("To_Format_Dialog", "Cancel")) . Output only the next line.
self.ui = Ui_To_Format_Dialog()
Based on the snippet: <|code_start|>#!/usr/local/bin/python3 __author__ = 'apaeffgen' # -*- coding: utf-8 -*- # This file is part of Panconvert. # # Panconvert is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. #from source.converter.interface_pandoc import get_pandoc_options class HelpDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) <|code_end|> , predict the immediate next line with the help of imports: from PyQt5 import QtWidgets from PyQt5 import QtCore from PyQt5.QtCore import QSettings from PyQt5.QtCore import QPoint, QSize from source.gui.panconvert_diag_help import Ui_Information_Dialog and context (classes, functions, sometimes code) from other files: # Path: source/gui/panconvert_diag_help.py # class Ui_Information_Dialog(object): # def setupUi(self, Information_Dialog): # Information_Dialog.setObjectName("Information_Dialog") # Information_Dialog.resize(492, 575) # self.gridLayout = QtWidgets.QGridLayout(Information_Dialog) # self.gridLayout.setObjectName("gridLayout") # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # self.ButtonCancel = QtWidgets.QPushButton(Information_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.horizontalLayout.addWidget(self.ButtonCancel) # self.ButtonHelpPanconvert = QtWidgets.QPushButton(Information_Dialog) # self.ButtonHelpPanconvert.setObjectName("ButtonHelpPanconvert") # self.horizontalLayout.addWidget(self.ButtonHelpPanconvert) # self.ButtonHelpPandoc = QtWidgets.QPushButton(Information_Dialog) # self.ButtonHelpPandoc.setObjectName("ButtonHelpPandoc") # self.horizontalLayout.addWidget(self.ButtonHelpPandoc) # self.ButtonBackward = QtWidgets.QPushButton(Information_Dialog) # self.ButtonBackward.setObjectName("ButtonBackward") # self.horizontalLayout.addWidget(self.ButtonBackward) # self.ButtonForward = QtWidgets.QPushButton(Information_Dialog) # self.ButtonForward.setObjectName("ButtonForward") # self.horizontalLayout.addWidget(self.ButtonForward) # self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(Information_Dialog) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(Information_Dialog) # QtCore.QMetaObject.connectSlotsByName(Information_Dialog) # # def retranslateUi(self, Information_Dialog): # _translate = QtCore.QCoreApplication.translate # Information_Dialog.setWindowTitle(_translate("Information_Dialog", "Help")) # self.ButtonCancel.setText(_translate("Information_Dialog", "Cancel")) # self.ButtonHelpPanconvert.setText(_translate("Information_Dialog", "Panconvert-Help")) # self.ButtonHelpPandoc.setText(_translate("Information_Dialog", "Pandoc-Help")) # self.ButtonBackward.setText(_translate("Information_Dialog", "<")) # self.ButtonForward.setText(_translate("Information_Dialog", ">")) . Output only the next line.
self.ui = Ui_Information_Dialog()
Here is a snippet: <|code_start|> # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class InfoDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Information_Dialog() self.ui.setupUi(self) self.ui.ButtonInfo.clicked.connect(self.info) self.ui.ButtonCancel.clicked.connect(self.closeEvent) self.ui.ButtonMoreInfo.clicked.connect(self.moreinfo) #Initialize Settings settings = QSettings('Pandoc', 'PanConvert') path_pandoc = settings.value('path_pandoc','') self.resize(settings.value("Option_size", QSize(270, 225))) self.move(settings.value("Option_pos", QPoint(50, 50))) if not os.path.isfile(path_pandoc): path_pandoc = get_path_pandoc() path_pandoc = settings.value('path_pandoc') if os.path.isfile(path_pandoc): <|code_end|> . Write the next line using the current file imports: from source.helpers.interface_pandoc import get_pandoc_options, get_path_pandoc from source.gui.panconvert_diag_info import Ui_Information_Dialog from source.language.messages import * and context from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_options(): # """ # Get the Options of the Pandoc help section # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 1.18: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # # # aux = help_text[15:89] # # return aux # # # else: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # aux = help_text # # return aux # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_info.py # class Ui_Information_Dialog(object): # def setupUi(self, Information_Dialog): # Information_Dialog.setObjectName("Information_Dialog") # Information_Dialog.resize(707, 575) # self.gridLayout_2 = QtWidgets.QGridLayout(Information_Dialog) # self.gridLayout_2.setObjectName("gridLayout_2") # self.gridLayout = QtWidgets.QGridLayout() # self.gridLayout.setObjectName("gridLayout") # self.ButtonCancel = QtWidgets.QPushButton(Information_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.gridLayout.addWidget(self.ButtonCancel, 0, 0, 1, 1) # self.ButtonInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonInfo.setObjectName("ButtonInfo") # self.gridLayout.addWidget(self.ButtonInfo, 0, 2, 1, 1) # self.ButtonMoreInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonMoreInfo.setObjectName("ButtonMoreInfo") # self.gridLayout.addWidget(self.ButtonMoreInfo, 0, 1, 1, 1) # self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(Information_Dialog) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout_2.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(Information_Dialog) # QtCore.QMetaObject.connectSlotsByName(Information_Dialog) # # def retranslateUi(self, Information_Dialog): # _translate = QtCore.QCoreApplication.translate # Information_Dialog.setWindowTitle(_translate("Information_Dialog", "Information")) # self.ButtonCancel.setText(_translate("Information_Dialog", "Cancel")) # self.ButtonInfo.setText(_translate("Information_Dialog", "Pandoc-Options")) # self.ButtonMoreInfo.setText(_translate("Information_Dialog", "More Information")) , which may include functions, classes, or code. Output only the next line.
options = get_pandoc_options()
Predict the next line for this snippet: <|code_start|> # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class InfoDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Information_Dialog() self.ui.setupUi(self) self.ui.ButtonInfo.clicked.connect(self.info) self.ui.ButtonCancel.clicked.connect(self.closeEvent) self.ui.ButtonMoreInfo.clicked.connect(self.moreinfo) #Initialize Settings settings = QSettings('Pandoc', 'PanConvert') path_pandoc = settings.value('path_pandoc','') self.resize(settings.value("Option_size", QSize(270, 225))) self.move(settings.value("Option_pos", QPoint(50, 50))) if not os.path.isfile(path_pandoc): <|code_end|> with the help of current file imports: from source.helpers.interface_pandoc import get_pandoc_options, get_path_pandoc from source.gui.panconvert_diag_info import Ui_Information_Dialog from source.language.messages import * and context from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_options(): # """ # Get the Options of the Pandoc help section # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 1.18: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # # # aux = help_text[15:89] # # return aux # # # else: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # aux = help_text # # return aux # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_info.py # class Ui_Information_Dialog(object): # def setupUi(self, Information_Dialog): # Information_Dialog.setObjectName("Information_Dialog") # Information_Dialog.resize(707, 575) # self.gridLayout_2 = QtWidgets.QGridLayout(Information_Dialog) # self.gridLayout_2.setObjectName("gridLayout_2") # self.gridLayout = QtWidgets.QGridLayout() # self.gridLayout.setObjectName("gridLayout") # self.ButtonCancel = QtWidgets.QPushButton(Information_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.gridLayout.addWidget(self.ButtonCancel, 0, 0, 1, 1) # self.ButtonInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonInfo.setObjectName("ButtonInfo") # self.gridLayout.addWidget(self.ButtonInfo, 0, 2, 1, 1) # self.ButtonMoreInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonMoreInfo.setObjectName("ButtonMoreInfo") # self.gridLayout.addWidget(self.ButtonMoreInfo, 0, 1, 1, 1) # self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(Information_Dialog) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout_2.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(Information_Dialog) # QtCore.QMetaObject.connectSlotsByName(Information_Dialog) # # def retranslateUi(self, Information_Dialog): # _translate = QtCore.QCoreApplication.translate # Information_Dialog.setWindowTitle(_translate("Information_Dialog", "Information")) # self.ButtonCancel.setText(_translate("Information_Dialog", "Cancel")) # self.ButtonInfo.setText(_translate("Information_Dialog", "Pandoc-Options")) # self.ButtonMoreInfo.setText(_translate("Information_Dialog", "More Information")) , which may contain function names, class names, or code. Output only the next line.
path_pandoc = get_path_pandoc()
Here is a snippet: <|code_start|>#!/usr/local/bin/python3 __author__ = 'apaeffgen' # -*- coding: utf-8 -*- # This file is part of Panconvert. # # Panconvert is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class InfoDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) <|code_end|> . Write the next line using the current file imports: from source.helpers.interface_pandoc import get_pandoc_options, get_path_pandoc from source.gui.panconvert_diag_info import Ui_Information_Dialog from source.language.messages import * and context from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_options(): # """ # Get the Options of the Pandoc help section # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 1.18: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # # # aux = help_text[15:89] # # return aux # # # else: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(True) # aux = help_text # # return aux # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_info.py # class Ui_Information_Dialog(object): # def setupUi(self, Information_Dialog): # Information_Dialog.setObjectName("Information_Dialog") # Information_Dialog.resize(707, 575) # self.gridLayout_2 = QtWidgets.QGridLayout(Information_Dialog) # self.gridLayout_2.setObjectName("gridLayout_2") # self.gridLayout = QtWidgets.QGridLayout() # self.gridLayout.setObjectName("gridLayout") # self.ButtonCancel = QtWidgets.QPushButton(Information_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.gridLayout.addWidget(self.ButtonCancel, 0, 0, 1, 1) # self.ButtonInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonInfo.setObjectName("ButtonInfo") # self.gridLayout.addWidget(self.ButtonInfo, 0, 2, 1, 1) # self.ButtonMoreInfo = QtWidgets.QPushButton(Information_Dialog) # self.ButtonMoreInfo.setObjectName("ButtonMoreInfo") # self.gridLayout.addWidget(self.ButtonMoreInfo, 0, 1, 1, 1) # self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(Information_Dialog) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout_2.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(Information_Dialog) # QtCore.QMetaObject.connectSlotsByName(Information_Dialog) # # def retranslateUi(self, Information_Dialog): # _translate = QtCore.QCoreApplication.translate # Information_Dialog.setWindowTitle(_translate("Information_Dialog", "Information")) # self.ButtonCancel.setText(_translate("Information_Dialog", "Cancel")) # self.ButtonInfo.setText(_translate("Information_Dialog", "Pandoc-Options")) # self.ButtonMoreInfo.setText(_translate("Information_Dialog", "More Information")) , which may include functions, classes, or code. Output only the next line.
self.ui = Ui_Information_Dialog()
Here is a snippet: <|code_start|> # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class FromFormatDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_From_Format_Dialog() self.ui.setupUi(self) #self.ui.ButtonInfo.clicked.connect(self.info) self.ui.ButtonCancel.clicked.connect(self.closeEvent) #self.ui.ButtonMoreInfo.clicked.connect(self.moreinfo) #Initialize Settings settings = QSettings('Pandoc', 'PanConvert') path_pandoc = settings.value('path_pandoc','') self.resize(settings.value("FromFormat_size", QSize(270, 225))) self.move(settings.value("FromFormat_pos", QPoint(50, 50))) if not os.path.isfile(path_pandoc): path_pandoc = get_path_pandoc() path_pandoc = settings.value('path_pandoc') if os.path.isfile(path_pandoc): <|code_end|> . Write the next line using the current file imports: from source.helpers.interface_pandoc import get_pandoc_formats, get_path_pandoc from source.gui.panconvert_diag_fromformat import Ui_From_Format_Dialog from source.language.messages import * and context from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_formats(): # """ # Dynamic preprocessor for Pandoc formats. # Return 2 lists. "from_formats" and "to_formats". # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 118: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(False) # txt = ' '.join(help_text[1:help_text.index('Options:')]) # # # aux = txt.split('Output formats: ') # in_ = aux[0].split('Input formats: ')[1].split(',') # out = aux[1].split(',') # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # # p = subprocess.Popen( # [path_pandoc, '--list-input-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # inputformats = p.communicate()[0].decode().splitlines(False) # # # p = subprocess.Popen( # [path_pandoc, '--list-output-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # outputformats = p.communicate()[0].decode().splitlines(False) # # in_ = inputformats # out = outputformats # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_fromformat.py # class Ui_From_Format_Dialog(object): # def setupUi(self, From_Format_Dialog): # From_Format_Dialog.setObjectName("From_Format_Dialog") # From_Format_Dialog.resize(224, 234) # self.gridLayout = QtWidgets.QGridLayout(From_Format_Dialog) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.ButtonCancel = QtWidgets.QPushButton(From_Format_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.verticalLayout.addWidget(self.ButtonCancel) # self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(From_Format_Dialog) # self.textBrowser.setMinimumSize(QtCore.QSize(200, 100)) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(From_Format_Dialog) # QtCore.QMetaObject.connectSlotsByName(From_Format_Dialog) # # def retranslateUi(self, From_Format_Dialog): # _translate = QtCore.QCoreApplication.translate # From_Format_Dialog.setWindowTitle(_translate("From_Format_Dialog", "Pandoc From Formats")) # self.ButtonCancel.setText(_translate("From_Format_Dialog", "Cancel")) , which may include functions, classes, or code. Output only the next line.
formats = get_pandoc_formats()
Using the snippet: <|code_start|> # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class FromFormatDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_From_Format_Dialog() self.ui.setupUi(self) #self.ui.ButtonInfo.clicked.connect(self.info) self.ui.ButtonCancel.clicked.connect(self.closeEvent) #self.ui.ButtonMoreInfo.clicked.connect(self.moreinfo) #Initialize Settings settings = QSettings('Pandoc', 'PanConvert') path_pandoc = settings.value('path_pandoc','') self.resize(settings.value("FromFormat_size", QSize(270, 225))) self.move(settings.value("FromFormat_pos", QPoint(50, 50))) if not os.path.isfile(path_pandoc): <|code_end|> , determine the next line of code. You have imports: from source.helpers.interface_pandoc import get_pandoc_formats, get_path_pandoc from source.gui.panconvert_diag_fromformat import Ui_From_Format_Dialog from source.language.messages import * and context (class names, function names, or code) available: # Path: source/helpers/interface_pandoc.py # def get_pandoc_formats(): # """ # Dynamic preprocessor for Pandoc formats. # Return 2 lists. "from_formats" and "to_formats". # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 118: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(False) # txt = ' '.join(help_text[1:help_text.index('Options:')]) # # # aux = txt.split('Output formats: ') # in_ = aux[0].split('Input formats: ')[1].split(',') # out = aux[1].split(',') # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # # p = subprocess.Popen( # [path_pandoc, '--list-input-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # inputformats = p.communicate()[0].decode().splitlines(False) # # # p = subprocess.Popen( # [path_pandoc, '--list-output-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # outputformats = p.communicate()[0].decode().splitlines(False) # # in_ = inputformats # out = outputformats # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_fromformat.py # class Ui_From_Format_Dialog(object): # def setupUi(self, From_Format_Dialog): # From_Format_Dialog.setObjectName("From_Format_Dialog") # From_Format_Dialog.resize(224, 234) # self.gridLayout = QtWidgets.QGridLayout(From_Format_Dialog) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.ButtonCancel = QtWidgets.QPushButton(From_Format_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.verticalLayout.addWidget(self.ButtonCancel) # self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(From_Format_Dialog) # self.textBrowser.setMinimumSize(QtCore.QSize(200, 100)) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(From_Format_Dialog) # QtCore.QMetaObject.connectSlotsByName(From_Format_Dialog) # # def retranslateUi(self, From_Format_Dialog): # _translate = QtCore.QCoreApplication.translate # From_Format_Dialog.setWindowTitle(_translate("From_Format_Dialog", "Pandoc From Formats")) # self.ButtonCancel.setText(_translate("From_Format_Dialog", "Cancel")) . Output only the next line.
path_pandoc = get_path_pandoc()
Continue the code snippet: <|code_start|>#!/usr/local/bin/python3 __author__ = 'apaeffgen' # -*- coding: utf-8 -*- # This file is part of Panconvert. # # Panconvert is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Panconvert is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Panconvert. If not, see <http://www.gnu.org/licenses/>. class FromFormatDialog(QtWidgets.QDialog): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) <|code_end|> . Use current file imports: from source.helpers.interface_pandoc import get_pandoc_formats, get_path_pandoc from source.gui.panconvert_diag_fromformat import Ui_From_Format_Dialog from source.language.messages import * and context (classes, functions, or code) from other files: # Path: source/helpers/interface_pandoc.py # def get_pandoc_formats(): # """ # Dynamic preprocessor for Pandoc formats. # Return 2 lists. "from_formats" and "to_formats". # """ # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc = settings.value('path_pandoc','') # # if os.path.isfile(path_pandoc): # # version = get_pandoc_version() # # if version < 118: # # p = subprocess.Popen( # [path_pandoc, '-h'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # help_text = p.communicate()[0].decode().splitlines(False) # txt = ' '.join(help_text[1:help_text.index('Options:')]) # # # aux = txt.split('Output formats: ') # in_ = aux[0].split('Input formats: ')[1].split(',') # out = aux[1].split(',') # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # # p = subprocess.Popen( # [path_pandoc, '--list-input-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # inputformats = p.communicate()[0].decode().splitlines(False) # # # p = subprocess.Popen( # [path_pandoc, '--list-output-formats'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE) # outputformats = p.communicate()[0].decode().splitlines(False) # # in_ = inputformats # out = outputformats # # return [f.strip() for f in in_], [f.strip() for f in out] # # # else: # path_pandoc = get_path_pandoc() # path_pandoc = settings.value('path_pandoc','') # if not os.path.isfile(path_pandoc): # message = error_converter_path() # return message # # def get_path_pandoc(): # # settings = QSettings('Pandoc', 'PanConvert') # path_pandoc_tmp = settings.value('path_pandoc','') # path_pandoc = str(path_pandoc_tmp) # # if not os.path.isfile(path_pandoc): # # if platform.system() == 'Darwin' or os.name == 'posix': # path_pandoc = which("pandoc") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # else: # path_pandoc = where("pandoc.exe") # settings.setValue('path_pandoc', path_pandoc) # settings.sync() # # Path: source/gui/panconvert_diag_fromformat.py # class Ui_From_Format_Dialog(object): # def setupUi(self, From_Format_Dialog): # From_Format_Dialog.setObjectName("From_Format_Dialog") # From_Format_Dialog.resize(224, 234) # self.gridLayout = QtWidgets.QGridLayout(From_Format_Dialog) # self.gridLayout.setObjectName("gridLayout") # self.verticalLayout = QtWidgets.QVBoxLayout() # self.verticalLayout.setObjectName("verticalLayout") # self.ButtonCancel = QtWidgets.QPushButton(From_Format_Dialog) # self.ButtonCancel.setObjectName("ButtonCancel") # self.verticalLayout.addWidget(self.ButtonCancel) # self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) # self.textBrowser = QtWebEngineWidgets.QWebEngineView(From_Format_Dialog) # self.textBrowser.setMinimumSize(QtCore.QSize(200, 100)) # self.textBrowser.setObjectName("textBrowser") # self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1) # # self.retranslateUi(From_Format_Dialog) # QtCore.QMetaObject.connectSlotsByName(From_Format_Dialog) # # def retranslateUi(self, From_Format_Dialog): # _translate = QtCore.QCoreApplication.translate # From_Format_Dialog.setWindowTitle(_translate("From_Format_Dialog", "Pandoc From Formats")) # self.ButtonCancel.setText(_translate("From_Format_Dialog", "Cancel")) . Output only the next line.
self.ui = Ui_From_Format_Dialog()
Based on the snippet: <|code_start|># Copyright 2014 OpenCore LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class HadoopClientInitializer(object): """ Create a new initializer Param user The user login for the git repo """ def __init__(self, system): self.system = system self.template_dir = None self.template_repo = None self.hive_client = HiveClientInitializer(system) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import sh from string import Template from ferry.install import FERRY_HOME from ferry.config.hadoop.hiveconfig import * and context (classes, functions, sometimes code) from other files: # Path: ferry/install.py # FERRY_HOME=_get_ferry_home() . Output only the next line.
self.hive_client.template_dir = FERRY_HOME + '/data/templates/hive-metastore/'
Based on the snippet: <|code_start|> class AWSLauncher(object): """ Launches new instances/networks on an AWS cluster and initializes the instances to run Ferry processes. """ def __init__(self, controller): self.name = "AWS launcher" self.docker_registry = None self.docker_user = None self.controller = controller self.subnets = [] self.stacks = {} self.num_network_hosts = 1024 self.num_subnet_hosts = 256 self.vpc_cidr = None self.nat_images = { "us-east-1" : "ami-4c9e4b24", "us-west-1" : "ami-2b2b296e", "us-west-2" : "ami-8b6912bb", "eu-west-1" : "ami-3760b040", "sa-east-1" : "ami-8b72db96", "ap-northeast-1" : "ami-55c29e54", "ap-southeast-1" : "ami-b082dae2", "ap-southeast-2" : "ami-996402a3" } self._init_app_db() self._init_aws_stack() <|code_end|> , predict the immediate next line with the help of imports: import boto import boto.cloudformation import boto.ec2 import boto.vpc import copy import ferry.install import json import logging import math import os import sys import time import yaml from boto.ec2.address import * from boto.ec2.networkinterface import * from boto.exception import BotoServerError, EC2ResponseError from boto.ec2.blockdevicemapping import BlockDeviceType, EBSBlockDeviceType, BlockDeviceMapping from ferry.config.system.aws import System from pymongo import MongoClient and context (classes, functions, sometimes code) from other files: # Path: ferry/config/system/aws.py # class System(object): # def __init__(self): # self.instance_type = "t2.small" # # def get_total_memory(self): # """ # Get total memory of current system. # """ # if self.instance_type in AWS_INSTANCE_INFO: # return AWS_INSTANCE_INFO[self.instance_type]["mem"] * 1024 # else: # logging.warning("AWS system could not find " + self.instance_type) # return 1024 # # def get_free_memory(self): # """ # Get free memory of current system. # """ # if self.instance_type in AWS_INSTANCE_INFO: # return AWS_INSTANCE_INFO[self.instance_type]["mem"] * 1024 # else: # return 1024 # # def get_num_cores(self): # """ # Get total number of cores. # """ # if self.instance_type in AWS_INSTANCE_INFO: # return AWS_INSTANCE_INFO[self.instance_type]["cores"] # else: # return 1 . Output only the next line.
self.system = System()
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class HadoopInitializer(object): def __init__(self, system): """ Create a new initializer Param user The user login for the git repo """ self.system = system self.template_dir = None self.template_repo = None self.container_data_dir = HadoopConfig.data_directory self.container_log_dir = HadoopConfig.log_directory self.hive_client = HiveClientInitializer(system) self.hive_ms = MetaStoreInitializer(system) <|code_end|> , generate the next line using the imports in this file: import logging import os import sys import time import sh from string import Template from ferry.install import FERRY_HOME from ferry.config.hadoop.hiveconfig import * from ferry.config.hadoop.metastore import * and context (functions, classes, or occasionally code) from other files: # Path: ferry/install.py # FERRY_HOME=_get_ferry_home() . Output only the next line.
self.hive_client.template_dir = FERRY_HOME + '/data/templates/hive-metastore/'
Based on the snippet: <|code_start|> """ if not server: # The server is not supplied, so just execute # the command locally. proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) if read_output: out = proc.stdout.read() err = proc.stderr.read() else: # Do not store results in hosts file or warn about # changing ssh keys. Also use the key given to us by the fabric. flags = " -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null " flags += " -i " + self.key # If the user is given explicitly use that. Otherwise use the # default user (which is probably root). if user: ip = user + '@' + server else: ip = self.docker_user + '@' + server flags += " -t -t " + ip # Wrap the command around an ssh command. ssh = 'ssh ' + flags + ' \'%s\'' % cmd logging.warning(ssh) # All the possible errors that might happen when # we try to connect via ssh. if read_output: <|code_end|> , predict the immediate next line with the help of imports: from ferry.fabric.com import robust_com from subprocess import Popen, PIPE import json import logging import os import re import sys and context (classes, functions, sometimes code) from other files: # Path: ferry/fabric/com.py # def robust_com(cmd): # # All the possible errors that might happen when # # we try to connect via ssh. # route_closed = re.compile('.*No route to host.*', re.DOTALL) # conn_closed = re.compile('.*Connection closed.*', re.DOTALL) # refused_closed = re.compile('.*Connection refused.*', re.DOTALL) # timed_out = re.compile('.*timed out*', re.DOTALL) # permission = re.compile('.*Permission denied.*', re.DOTALL) # # num_tries = 0 # while(True): # proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) # output = proc.stdout.read() # err = proc.stderr.read() # if route_closed.match(err) or conn_closed.match(err) or refused_closed.match(err) or timed_out.match(err) or permission.match(err): # if num_tries < MAX_COM_RETRIES: # logging.warning("com error, trying again...") # num_tries += 1 # time.sleep(10 * num_tries) # else: # logging.error("could not communicate") # return None, None, False # else: # logging.warning("com msg: " + err) # break # # return output, err, True . Output only the next line.
out, err, success = robust_com(ssh)
Based on the snippet: <|code_start|># Copyright 2014 OpenCore LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class CassandraInitializer(object): """ Create a new initializer Param user The user login for the git repo """ def __init__(self, system): self.template_dir = None self.template_repo = None self.titan = TitanInitializer(system) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import sh from string import Template from ferry.install import FERRY_HOME from ferry.config.titan.titanconfig import * and context (classes, functions, sometimes code) from other files: # Path: ferry/install.py # FERRY_HOME=_get_ferry_home() . Output only the next line.
self.titan.template_dir = FERRY_HOME + '/data/templates/titan'
Here is a snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class ConfigFactory(object): def __init__(self, system): self.system = system self.gluster = GlusterInitializer(self.system) self.hadoop = HadoopInitializer(self.system) self.yarn = HadoopInitializer(self.system) self.hive = MetaStoreInitializer(self.system) self.spark = SparkInitializer(self.system) self.cassandra = CassandraInitializer(self.system) self.titan = TitanInitializer(self.system) self.mpi = OpenMPIInitializer(self.system) self.mongo = MongoInitializer(self.system) self.mongo_client = MongoClientInitializer(self.system) self.cassandra_client = CassandraClientInitializer(self.system) self.mpi_client = OpenMPIClientInitializer(self.system) self.hadoop_client = HadoopClientInitializer(self.system) self.spark_client = SparkClientInitializer(self.system) # Get the Ferry home to find the templates. <|code_end|> . Write the next line using the current file imports: import os import logging from pymongo import MongoClient from ferry.install import FERRY_HOME, DEFAULT_TEMPLATE_DIR from ferry.docker.docker import DockerInstance from ferry.config.gluster.glusterconfig import * from ferry.config.hadoop.hadoopconfig import * from ferry.config.hadoop.hadoopclientconfig import * from ferry.config.hadoop.metastore import * from ferry.config.spark.sparkconfig import * from ferry.config.spark.sparkclientconfig import * from ferry.config.openmpi.mpiconfig import * from ferry.config.openmpi.mpiclientconfig import * from ferry.config.titan.titanconfig import * from ferry.config.cassandra.cassandraconfig import * from ferry.config.cassandra.cassandraclientconfig import * from ferry.config.mongo.mongoconfig import * from ferry.config.mongo.mongoclientconfig import * and context from other files: # Path: ferry/install.py # FERRY_HOME=_get_ferry_home() # # DEFAULT_TEMPLATE_DIR=FERRY_HOME + '/data/templates' # # Path: ferry/docker/docker.py # class DockerInstance(object): # """ Docker instance """ # # def __init__(self, json_data=None): # if not json_data: # self.container = '' # self.vm = 'local' # self.service_type = None # self.host_name = None # self.manage_ip = None # self.external_ip = None # self.internal_ip = None # self.ports = {} # self.image = '' # self.keydir = None # self.keyname = None # self.privatekey = None # self.volumes = None # self.default_user = None # self.name = None # self.args = None # self.tunnel = False # else: # self.container = json_data['container'] # self.vm = json_data['vm'] # self.service_type = json_data['type'] # self.host_name = json_data['hostname'] # self.manage_ip = json_data['manage_ip'] # self.external_ip = json_data['external_ip'] # self.internal_ip = json_data['internal_ip'] # self.ports = json_data['ports'] # self.image = json_data['image'] # self.default_user = json_data['user'] # self.name = json_data['name'] # self.args = json_data['args'] # self.keydir = json_data['keydir'] # self.keyname =json_data['keyname'] # self.privatekey = json_data['privatekey'] # self.volumes = json_data['volumes'] # self.tunnel = json_data['tunnel'] # # """ # Return in JSON format. # """ # def json(self): # json_reply = { '_type' : 'docker', # 'manage_ip' : self.manage_ip, # 'external_ip' : self.external_ip, # 'internal_ip' : self.internal_ip, # 'ports' : self.ports, # 'hostname' : self.host_name, # 'container' : self.container, # 'vm' : self.vm, # 'image' : self.image, # 'type': self.service_type, # 'keydir' : self.keydir, # 'keyname' : self.keyname, # 'privatekey' : self.privatekey, # 'volumes' : self.volumes, # 'user' : self.default_user, # 'name' : self.name, # 'args' : self.args, # 'tunnel' : self.tunnel } # return json_reply , which may include functions, classes, or code. Output only the next line.
template_dir = DEFAULT_TEMPLATE_DIR
Predict the next line for this snippet: <|code_start|>logging.root.setLevel(logging.INFO) # Connect to the database conn = helper_functions.load_graph_database(N) # Load the list of invariants to compute options = load_options() invariant_names = options["invariant_function_names"] # Check the inputs to see if they are valid queries for func_name, val in cargs["invariant_query"]: if func_name not in invariant_names: err = "{} not a known invariant".format(func_name) raise KeyError(err) try: int(val) except Exception as ex: err = "{}={} is {}".format(func_name, val, ex) raise ValueError(err) cmd_search = ''' SELECT adj FROM invariant_integer AS A JOIN graph AS B ON A.graph_id = B.graph_id''' constraints = ["{}={}".format(*items) for items in cargs["invariant_query"]] if constraints: cmd_search += ' WHERE ' + ' AND '.join(constraints) cmd_search += " LIMIT {limit} ".format(**cargs) # Add limit at some point <|code_end|> with the help of current file imports: import logging import argparse import graph_tool as gt import numpy as np from src.helper_functions import grab_vector, load_options, load_graph_database from src.invariants import convert_to_numpy and context from other files: # Path: src/helper_functions.py # def grab_vector(connection, cmd, *args): # return [x[0] for x in connection.execute(cmd, *args).fetchall()] # # def load_options(f_option_file="options_simple_connected.json"): # # Load the file into a string # try: # with open(f_option_file) as FIN: # raw_text = FIN.read() # except: # msg = "Couldn't find option file {}".format(f_option_file) # raise IOError(msg) # # # Parse the text as json # try: # return json.loads(raw_text) # except Exception as Ex: # msg = "Couldn't parse JSON file {}, {}".format(f_option_file, Ex) # raise IOError(msg) # # def load_graph_database(N, check_exist=True, special=False, timeout=5): # ''' Given an input value of N, return a connection to the # cooresponding database ''' # # # Build the needed directories # mkdir_p("database") # mkdir_p("database/special") # # if not special: # f_database = generate_database_name(N) # else: # f_database = generate_special_database_name(N) # # # Check if database exists, if so exit! # if check_exist and not os.path.exists(f_database): # err = "Database %s does not exist." % f_database # logging.critical(err) # exit() # # return sqlite3.connect(f_database, check_same_thread=False, # timeout=timeout) # # Path: src/invariants.py # def convert_to_numpy(adj, N, **kwargs): # possible_edges = int ((N * (N + 1)) / 2) # # edge_map = np.binary_repr(adj, possible_edges) # edge_int = [int(x) for x in edge_map] # # idx = np.triu_indices(N) # A = np.zeros((N, N), dtype=np.int) # # A[idx] = edge_int # # # Works for loopless graphs only # A += A.T # return A , which may contain function names, class names, or code. Output only the next line.
ADJ = grab_vector(conn, cmd_search)