Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|> _inputArray = True
_returns = kwparams['_returns']
if isinstance(_returns,xmltypes.Array):
_output = _returns
_outputArray = True
elif isinstance(_returns,list) or issubclass(_returns,xmltypes.PrimitiveType) or issubclass(_returns,complextypes.ComplexType):
_output = _returns
else:
_output = _returns
def operation(*args,**kwargs):
return f(*args,**kwargs)
operation.__name__ = f.__name__
operation._is_operation = True
operation._args = _args
operation._input = _input
operation._output = _output
operation._operation = f.__name__
operation._inputArray = _inputArray
operation._outputArray = _outputArray
return operation
return method
def soapfault(faultstring):
""" Method for generate a soap fault
soapfault() return a SoapMessage() object with a message
for Soap Envelope
"""
<|code_end|>
. Use current file imports:
(import tornado.httpserver
import tornado.web
import xml.dom.minidom
import inspect
from tornado.options import options
from webui.server.tornadows import soap
from webui.server.tornadows import xmltypes
from webui.server.tornadows import complextypes
from webui.server.tornadows import wsdl)
and context including class names, function names, or small code snippets from other files:
# Path: webui/server/tornadows/soap.py
# class SoapMessage:
# def __init__(self):
# def getSoap(self):
# def getHeader(self):
# def getBody(self):
# def setHeader(self, header):
# def setBody(self,body):
# def removeHeader(self):
# def removeBody(self):
#
# Path: webui/server/tornadows/xmltypes.py
# def createElementXML(name,type,prefix='xsd'):
# def createArrayXML(name,type,prefix='xsd',maxoccurs=None):
# def __init__(self,type,maxOccurs=None):
# def createArray(self,name):
# def createType(self,name):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# class Array:
# class PrimitiveType:
# class Integer(PrimitiveType):
# class Decimal(PrimitiveType):
# class Double(PrimitiveType):
# class Float(PrimitiveType):
# class Duration(PrimitiveType):
# class Date(PrimitiveType):
# class Time(PrimitiveType):
# class DateTime(PrimitiveType):
# class String(PrimitiveType):
# class Boolean(PrimitiveType):
#
# Path: webui/server/tornadows/complextypes.py
# class Property:
# class IntegerProperty(Property):
# class DecimalProperty(Property):
# class DoubleProperty(Property):
# class FloatProperty(Property):
# class DurationProperty(Property):
# class DateProperty(Property):
# class TimeProperty(Property):
# class DateTimeProperty(Property):
# class StringProperty(Property):
# class BooleanProperty(Property):
# class ArrayProperty(list):
# class ComplexType(object):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]):
# def toXSD(self,namespace='xsd',nameelement=None):
# def __init__(self):
# def toXML(self,name=None,method=''):
# def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]):
# def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]):
# def getName(cls):
# def _createAttributeType(self,element):
# def xml2object(xml,xsd,complex,method=''):
# def cls2dict(complex):
# def xsd2dict(xsd,namespace='xsd'):
# def xml2list(xmldoc,name,types,method=''):
# def generateOBJ(d,namecls,types):
# def createProperty(typ,value):
# def genattr(elems):
# def findElementFromDict(dictionary,key):
# def convert(typeelement,value):
# def createPythonType2XMLType(pyType):
#
# Path: webui/server/tornadows/wsdl.py
# class Wsdl:
# def __init__(self,nameservice=None,targetNamespace=None,methods=None,location=None):
# def createWsdl(self):
# def _createTypes(self, name, elements):
# def _createComplexTypes(self, name, arguments, elements):
. Output only the next line. | fault = soap.SoapMessage() |
Using the snippet: <|code_start|>
""" Global variable. If you want use your own wsdl file """
wsdl_path = None
def webservice(*params,**kwparams):
""" Decorator method for web services operators """
def method(f):
_input = None
_output = None
_inputArray = False
_outputArray = False
_args = None
if len(kwparams):
_params = kwparams['_params']
if inspect.isclass(_params) and issubclass(_params,complextypes.ComplexType):
_args = inspect.getargspec(f).args[1:]
_input = _params
elif isinstance(_params,list):
_args = inspect.getargspec(f).args[1:]
_input = {}
i = 0
for arg in _args:
_input[arg] = _params[i]
i+=1
else:
_args = inspect.getargspec(f).args[1:]
_input = {}
for arg in _args:
_input[arg] = _params
<|code_end|>
, determine the next line of code. You have imports:
import tornado.httpserver
import tornado.web
import xml.dom.minidom
import inspect
from tornado.options import options
from webui.server.tornadows import soap
from webui.server.tornadows import xmltypes
from webui.server.tornadows import complextypes
from webui.server.tornadows import wsdl
and context (class names, function names, or code) available:
# Path: webui/server/tornadows/soap.py
# class SoapMessage:
# def __init__(self):
# def getSoap(self):
# def getHeader(self):
# def getBody(self):
# def setHeader(self, header):
# def setBody(self,body):
# def removeHeader(self):
# def removeBody(self):
#
# Path: webui/server/tornadows/xmltypes.py
# def createElementXML(name,type,prefix='xsd'):
# def createArrayXML(name,type,prefix='xsd',maxoccurs=None):
# def __init__(self,type,maxOccurs=None):
# def createArray(self,name):
# def createType(self,name):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# class Array:
# class PrimitiveType:
# class Integer(PrimitiveType):
# class Decimal(PrimitiveType):
# class Double(PrimitiveType):
# class Float(PrimitiveType):
# class Duration(PrimitiveType):
# class Date(PrimitiveType):
# class Time(PrimitiveType):
# class DateTime(PrimitiveType):
# class String(PrimitiveType):
# class Boolean(PrimitiveType):
#
# Path: webui/server/tornadows/complextypes.py
# class Property:
# class IntegerProperty(Property):
# class DecimalProperty(Property):
# class DoubleProperty(Property):
# class FloatProperty(Property):
# class DurationProperty(Property):
# class DateProperty(Property):
# class TimeProperty(Property):
# class DateTimeProperty(Property):
# class StringProperty(Property):
# class BooleanProperty(Property):
# class ArrayProperty(list):
# class ComplexType(object):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]):
# def toXSD(self,namespace='xsd',nameelement=None):
# def __init__(self):
# def toXML(self,name=None,method=''):
# def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]):
# def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]):
# def getName(cls):
# def _createAttributeType(self,element):
# def xml2object(xml,xsd,complex,method=''):
# def cls2dict(complex):
# def xsd2dict(xsd,namespace='xsd'):
# def xml2list(xmldoc,name,types,method=''):
# def generateOBJ(d,namecls,types):
# def createProperty(typ,value):
# def genattr(elems):
# def findElementFromDict(dictionary,key):
# def convert(typeelement,value):
# def createPythonType2XMLType(pyType):
#
# Path: webui/server/tornadows/wsdl.py
# class Wsdl:
# def __init__(self,nameservice=None,targetNamespace=None,methods=None,location=None):
# def createWsdl(self):
# def _createTypes(self, name, elements):
# def _createComplexTypes(self, name, arguments, elements):
. Output only the next line. | if isinstance(_params,xmltypes.Array): |
Here is a snippet: <|code_start|># Copyright 2011 Rodrigo Ancavil del Pino
#
# 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.
""" Implementation of soaphandler for webservices API 0.9.4.2 (Beta) """
""" Global variable. If you want use your own wsdl file """
wsdl_path = None
def webservice(*params,**kwparams):
""" Decorator method for web services operators """
def method(f):
_input = None
_output = None
_inputArray = False
_outputArray = False
_args = None
if len(kwparams):
_params = kwparams['_params']
<|code_end|>
. Write the next line using the current file imports:
import tornado.httpserver
import tornado.web
import xml.dom.minidom
import inspect
from tornado.options import options
from webui.server.tornadows import soap
from webui.server.tornadows import xmltypes
from webui.server.tornadows import complextypes
from webui.server.tornadows import wsdl
and context from other files:
# Path: webui/server/tornadows/soap.py
# class SoapMessage:
# def __init__(self):
# def getSoap(self):
# def getHeader(self):
# def getBody(self):
# def setHeader(self, header):
# def setBody(self,body):
# def removeHeader(self):
# def removeBody(self):
#
# Path: webui/server/tornadows/xmltypes.py
# def createElementXML(name,type,prefix='xsd'):
# def createArrayXML(name,type,prefix='xsd',maxoccurs=None):
# def __init__(self,type,maxOccurs=None):
# def createArray(self,name):
# def createType(self,name):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# def createElement(name,prefix='xsd'):
# def getType(self):
# def genType(self,v):
# class Array:
# class PrimitiveType:
# class Integer(PrimitiveType):
# class Decimal(PrimitiveType):
# class Double(PrimitiveType):
# class Float(PrimitiveType):
# class Duration(PrimitiveType):
# class Date(PrimitiveType):
# class Time(PrimitiveType):
# class DateTime(PrimitiveType):
# class String(PrimitiveType):
# class Boolean(PrimitiveType):
#
# Path: webui/server/tornadows/complextypes.py
# class Property:
# class IntegerProperty(Property):
# class DecimalProperty(Property):
# class DoubleProperty(Property):
# class FloatProperty(Property):
# class DurationProperty(Property):
# class DateProperty(Property):
# class TimeProperty(Property):
# class DateTimeProperty(Property):
# class StringProperty(Property):
# class BooleanProperty(Property):
# class ArrayProperty(list):
# class ComplexType(object):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]):
# def toXSD(self,namespace='xsd',nameelement=None):
# def __init__(self):
# def toXML(self,name=None,method=''):
# def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]):
# def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]):
# def getName(cls):
# def _createAttributeType(self,element):
# def xml2object(xml,xsd,complex,method=''):
# def cls2dict(complex):
# def xsd2dict(xsd,namespace='xsd'):
# def xml2list(xmldoc,name,types,method=''):
# def generateOBJ(d,namecls,types):
# def createProperty(typ,value):
# def genattr(elems):
# def findElementFromDict(dictionary,key):
# def convert(typeelement,value):
# def createPythonType2XMLType(pyType):
#
# Path: webui/server/tornadows/wsdl.py
# class Wsdl:
# def __init__(self,nameservice=None,targetNamespace=None,methods=None,location=None):
# def createWsdl(self):
# def _createTypes(self, name, elements):
# def _createComplexTypes(self, name, arguments, elements):
, which may include functions, classes, or code. Output only the next line. | if inspect.isclass(_params) and issubclass(_params,complextypes.ComplexType): |
Next line prediction: <|code_start|># Copyright 2017 Bo Shao. All Rights Reserved.
#
# 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.
# ==============================================================================
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def test_demo():
print("# Creating TF session ...")
<|code_end|>
. Use current file imports:
(import os
import re
import tensorflow as tf
import time
from settings import PROJECT_ROOT
from chatbot.botpredictor import BotPredictor)
and context including class names, function names, or small code snippets from other files:
# Path: settings.py
# PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
#
# Path: chatbot/botpredictor.py
# class BotPredictor(object):
# def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file):
# """
# Args:
# session: The TensorFlow session.
# corpus_dir: Name of the folder storing corpus files and vocab information.
# knbase_dir: Name of the folder storing data files for the knowledge base.
# result_dir: The folder containing the trained result files.
# result_file: The file name of the trained model.
# """
# self.session = session
#
# # Prepare data and hyper parameters
# print("# Prepare dataset placeholder and hyper parameters ...")
# tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False)
#
# self.knowledge_base = KnowledgeBase()
# self.knowledge_base.load_knbase(knbase_dir)
#
# self.session_data = SessionData()
#
# self.hparams = tokenized_data.hparams
# self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string)
# src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder)
# self.infer_batch = tokenized_data.get_inference_batch(src_dataset)
#
# # Create model
# print("# Creating inference model ...")
# self.model = ModelCreator(training=False, tokenized_data=tokenized_data,
# batch_input=self.infer_batch)
# # Restore model weights
# print("# Restoring model weights ...")
# self.model.saver.restore(session, os.path.join(result_dir, result_file))
#
# self.session.run(tf.tables_initializer())
#
# def predict(self, session_id, question):
# chat_session = self.session_data.get_session(session_id)
# chat_session.before_prediction() # Reset before each prediction
#
# if question.strip() == '':
# answer = "Don't you want to say something to me?"
# chat_session.after_prediction(question, answer)
# return answer
#
# pat_matched, new_sentence, para_list = check_patterns_and_replace(question)
#
# for pre_time in range(2):
# tokens = nltk.word_tokenize(new_sentence.lower())
# tmp_sentence = [' '.join(tokens[:]).strip()]
#
# self.session.run(self.infer_batch.initializer,
# feed_dict={self.src_placeholder: tmp_sentence})
#
# outputs, _ = self.model.infer(self.session)
#
# if self.hparams.beam_width > 0:
# outputs = outputs[0]
#
# eos_token = self.hparams.eos_token.encode("utf-8")
# outputs = outputs.tolist()[0]
#
# if eos_token in outputs:
# outputs = outputs[:outputs.index(eos_token)]
#
# if pat_matched and pre_time == 0:
# out_sentence, if_func_val = self._get_final_output(outputs, chat_session,
# para_list=para_list)
# if if_func_val:
# chat_session.after_prediction(question, out_sentence)
# return out_sentence
# else:
# new_sentence = question
# else:
# out_sentence, _ = self._get_final_output(outputs, chat_session)
# chat_session.after_prediction(question, out_sentence)
# return out_sentence
#
# def _get_final_output(self, sentence, chat_session, para_list=None):
# sentence = b' '.join(sentence).decode('utf-8')
# if sentence == '':
# return "I don't know what to say.", False
#
# if_func_val = False
# last_word = None
# word_list = []
# for word in sentence.split(' '):
# word = word.strip()
# if not word:
# continue
#
# if word.startswith('_func_val_'):
# if_func_val = True
# word = call_function(word[10:], knowledge_base=self.knowledge_base,
# chat_session=chat_session, para_list=para_list)
# if word is None or word == '':
# continue
# else:
# if word in self.knowledge_base.upper_words:
# word = self.knowledge_base.upper_words[word]
#
# if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper():
# word = word.capitalize()
#
# if not word.startswith('\'') and word != 'n\'t' \
# and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \
# and last_word not in ['(', '[', '{', '``', '$']:
# word = ' ' + word
#
# word_list.append(word)
# last_word = word
#
# return ''.join(word_list).strip(), if_func_val
. Output only the next line. | corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus') |
Next line prediction: <|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.
# ==============================================================================
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def test_demo():
print("# Creating TF session ...")
corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus')
knbs_dir = os.path.join(PROJECT_ROOT, 'Data', 'KnowledgeBase')
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
test_dir = os.path.join(PROJECT_ROOT, 'Data', 'Test')
in_file = os.path.join(test_dir, 'samples.txt')
out_file = os.path.join(test_dir, 'responses.txt')
with tf.Session() as sess:
<|code_end|>
. Use current file imports:
(import os
import re
import tensorflow as tf
import time
from settings import PROJECT_ROOT
from chatbot.botpredictor import BotPredictor)
and context including class names, function names, or small code snippets from other files:
# Path: settings.py
# PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
#
# Path: chatbot/botpredictor.py
# class BotPredictor(object):
# def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file):
# """
# Args:
# session: The TensorFlow session.
# corpus_dir: Name of the folder storing corpus files and vocab information.
# knbase_dir: Name of the folder storing data files for the knowledge base.
# result_dir: The folder containing the trained result files.
# result_file: The file name of the trained model.
# """
# self.session = session
#
# # Prepare data and hyper parameters
# print("# Prepare dataset placeholder and hyper parameters ...")
# tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False)
#
# self.knowledge_base = KnowledgeBase()
# self.knowledge_base.load_knbase(knbase_dir)
#
# self.session_data = SessionData()
#
# self.hparams = tokenized_data.hparams
# self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string)
# src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder)
# self.infer_batch = tokenized_data.get_inference_batch(src_dataset)
#
# # Create model
# print("# Creating inference model ...")
# self.model = ModelCreator(training=False, tokenized_data=tokenized_data,
# batch_input=self.infer_batch)
# # Restore model weights
# print("# Restoring model weights ...")
# self.model.saver.restore(session, os.path.join(result_dir, result_file))
#
# self.session.run(tf.tables_initializer())
#
# def predict(self, session_id, question):
# chat_session = self.session_data.get_session(session_id)
# chat_session.before_prediction() # Reset before each prediction
#
# if question.strip() == '':
# answer = "Don't you want to say something to me?"
# chat_session.after_prediction(question, answer)
# return answer
#
# pat_matched, new_sentence, para_list = check_patterns_and_replace(question)
#
# for pre_time in range(2):
# tokens = nltk.word_tokenize(new_sentence.lower())
# tmp_sentence = [' '.join(tokens[:]).strip()]
#
# self.session.run(self.infer_batch.initializer,
# feed_dict={self.src_placeholder: tmp_sentence})
#
# outputs, _ = self.model.infer(self.session)
#
# if self.hparams.beam_width > 0:
# outputs = outputs[0]
#
# eos_token = self.hparams.eos_token.encode("utf-8")
# outputs = outputs.tolist()[0]
#
# if eos_token in outputs:
# outputs = outputs[:outputs.index(eos_token)]
#
# if pat_matched and pre_time == 0:
# out_sentence, if_func_val = self._get_final_output(outputs, chat_session,
# para_list=para_list)
# if if_func_val:
# chat_session.after_prediction(question, out_sentence)
# return out_sentence
# else:
# new_sentence = question
# else:
# out_sentence, _ = self._get_final_output(outputs, chat_session)
# chat_session.after_prediction(question, out_sentence)
# return out_sentence
#
# def _get_final_output(self, sentence, chat_session, para_list=None):
# sentence = b' '.join(sentence).decode('utf-8')
# if sentence == '':
# return "I don't know what to say.", False
#
# if_func_val = False
# last_word = None
# word_list = []
# for word in sentence.split(' '):
# word = word.strip()
# if not word:
# continue
#
# if word.startswith('_func_val_'):
# if_func_val = True
# word = call_function(word[10:], knowledge_base=self.knowledge_base,
# chat_session=chat_session, para_list=para_list)
# if word is None or word == '':
# continue
# else:
# if word in self.knowledge_base.upper_words:
# word = self.knowledge_base.upper_words[word]
#
# if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper():
# word = word.capitalize()
#
# if not word.startswith('\'') and word != 'n\'t' \
# and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \
# and last_word not in ['(', '[', '{', '``', '$']:
# word = ' ' + word
#
# word_list.append(word)
# last_word = word
#
# return ''.join(word_list).strip(), if_func_val
. Output only the next line. | predictor = BotPredictor(sess, corpus_dir=corp_dir, knbase_dir=knbs_dir, |
Given the code snippet: <|code_start|>
def init_login_manager(db):
"""Init security extensions (login manager and principal)
:param db: Database which stores user accounts and roles
:type db: ``flask_sqlalchemy.SQLAlchemy``
:return: Login manager and principal extensions
:rtype: (``flask_login.LoginManager``, ``flask_principal.Principal``
"""
login_manager = flask_login.LoginManager()
principals = flask_principal.Principal()
login_manager.anonymous_user = Anonymous
@login_manager.unauthorized_handler
def unauthorized():
flask.abort(403)
@login_manager.user_loader
def load_user(user_id):
<|code_end|>
, generate the next line using the imports in this file:
import flask
import flask_login
import flask_principal
from .models import UserAccount, Anonymous, Role
and context (functions, classes, or occasionally code) from other files:
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Anonymous(flask_login.AnonymousUserMixin, UserMixin):
# """Anonymous (not logged) user representation"""
#
# rolename = 'anonymous'
# _roles = []
#
# @property
# def roles(self):
# return type(self)._roles
#
# @classmethod
# def set_role(cls, role):
# cls._roles = [role]
#
# @property
# def is_active(self):
# """Check whether is user active
#
# :return: False, anonymous is not active
# :rtype: bool
# """
# return False
#
# def has_role(self, role):
# """Check whether has the role
#
# :param role: Role to be checked
# :type role: ``repocribro.models.RoleMixin``
# :return: False, anonymous has no roles
# :rtype: bool
# """
# return role == self.rolename
#
# @property
# def rolenames(self):
# """Get names of all roles of that user
#
# :return: Empty list, anonymous has no roles
# :rtype: list of str
# """
# return [self.rolename]
#
# def owns_repo(self, repo):
# """Check if user owns the repository
#
# :param repo: Repository which shoudl be tested
# :type repo: ``repocribro.models.Repository``
# :return: False, anonymous can not own repository
# :rtype: bool
# """
# return False
#
# def sees_repo(self, repo, has_secret=False):
# """Check if user is allowed to see the repo
#
# Anonymous can see only public repos
#
# :param repo: Repository which user want to see
# :type repo: ``repocribro.models.Repository``
# :param has_secret: If current user knows the secret URL
# :type has_secret: bool
# :return: If user can see repo
# :rtype: bool
# """
# visible = repo.is_public or (has_secret and repo.is_hidden)
# return visible
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | return db.session.query(UserAccount).get(int(user_id)) |
Based on the snippet: <|code_start|>
def init_login_manager(db):
"""Init security extensions (login manager and principal)
:param db: Database which stores user accounts and roles
:type db: ``flask_sqlalchemy.SQLAlchemy``
:return: Login manager and principal extensions
:rtype: (``flask_login.LoginManager``, ``flask_principal.Principal``
"""
login_manager = flask_login.LoginManager()
principals = flask_principal.Principal()
<|code_end|>
, predict the immediate next line with the help of imports:
import flask
import flask_login
import flask_principal
from .models import UserAccount, Anonymous, Role
and context (classes, functions, sometimes code) from other files:
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Anonymous(flask_login.AnonymousUserMixin, UserMixin):
# """Anonymous (not logged) user representation"""
#
# rolename = 'anonymous'
# _roles = []
#
# @property
# def roles(self):
# return type(self)._roles
#
# @classmethod
# def set_role(cls, role):
# cls._roles = [role]
#
# @property
# def is_active(self):
# """Check whether is user active
#
# :return: False, anonymous is not active
# :rtype: bool
# """
# return False
#
# def has_role(self, role):
# """Check whether has the role
#
# :param role: Role to be checked
# :type role: ``repocribro.models.RoleMixin``
# :return: False, anonymous has no roles
# :rtype: bool
# """
# return role == self.rolename
#
# @property
# def rolenames(self):
# """Get names of all roles of that user
#
# :return: Empty list, anonymous has no roles
# :rtype: list of str
# """
# return [self.rolename]
#
# def owns_repo(self, repo):
# """Check if user owns the repository
#
# :param repo: Repository which shoudl be tested
# :type repo: ``repocribro.models.Repository``
# :return: False, anonymous can not own repository
# :rtype: bool
# """
# return False
#
# def sees_repo(self, repo, has_secret=False):
# """Check if user is allowed to see the repo
#
# Anonymous can see only public repos
#
# :param repo: Repository which user want to see
# :type repo: ``repocribro.models.Repository``
# :param has_secret: If current user knows the secret URL
# :type has_secret: bool
# :return: If user can see repo
# :rtype: bool
# """
# visible = repo.is_public or (has_secret and repo.is_hidden)
# return visible
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | login_manager.anonymous_user = Anonymous |
Given snippet: <|code_start|>def logout():
"""Logout the current user from the app"""
flask_login.logout_user()
clear_session('identity.name', 'identity.auth_type')
flask_principal.identity_changed.send(
flask.current_app._get_current_object(),
identity=flask_principal.AnonymousIdentity()
)
def clear_session(*args):
"""Simple helper for clearing variables from session
:param args: names of session variables to remove
"""
for key in args:
flask.session.pop(key, None)
def reload_anonymous_role(app, db):
"""Reload special role for anonymous users
:param app: Current flask application
:type app: ``repocribro.repocribro.Repocribro``
:param db: Database connection
:type db: ``flask_sqlalchemy.SQLAlchemy``
"""
with app.app_context():
anonymous_role = None
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import flask
import flask_login
import flask_principal
from .models import UserAccount, Anonymous, Role
and context:
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Anonymous(flask_login.AnonymousUserMixin, UserMixin):
# """Anonymous (not logged) user representation"""
#
# rolename = 'anonymous'
# _roles = []
#
# @property
# def roles(self):
# return type(self)._roles
#
# @classmethod
# def set_role(cls, role):
# cls._roles = [role]
#
# @property
# def is_active(self):
# """Check whether is user active
#
# :return: False, anonymous is not active
# :rtype: bool
# """
# return False
#
# def has_role(self, role):
# """Check whether has the role
#
# :param role: Role to be checked
# :type role: ``repocribro.models.RoleMixin``
# :return: False, anonymous has no roles
# :rtype: bool
# """
# return role == self.rolename
#
# @property
# def rolenames(self):
# """Get names of all roles of that user
#
# :return: Empty list, anonymous has no roles
# :rtype: list of str
# """
# return [self.rolename]
#
# def owns_repo(self, repo):
# """Check if user owns the repository
#
# :param repo: Repository which shoudl be tested
# :type repo: ``repocribro.models.Repository``
# :return: False, anonymous can not own repository
# :rtype: bool
# """
# return False
#
# def sees_repo(self, repo, has_secret=False):
# """Check if user is allowed to see the repo
#
# Anonymous can see only public repos
#
# :param repo: Repository which user want to see
# :type repo: ``repocribro.models.Repository``
# :param has_secret: If current user knows the secret URL
# :type has_secret: bool
# :return: If user can see repo
# :rtype: bool
# """
# visible = repo.is_public or (has_secret and repo.is_hidden)
# return visible
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
which might include code, classes, or functions. Output only the next line. | anonymous_role = db.session.query(Role).filter_by( |
Continue the code snippet: <|code_start|> permissions = self.app.container.get('permissions')
for role_name, role in self.provide_roles().items():
permissions.register_role(role_name)
create_default_role(self.app, self.db, role)
reload_anonymous_role(self.app, self.db)
for action_name in self.provide_actions():
permissions.register_action(action_name)
def init_template_vars(self):
if not hasattr(self.app.config, 'dropdown_menu_items'):
self.app.config.dropdown_menu_items = {}
for route, title in self.provide_dropdown_menu_items().items():
self.app.config.dropdown_menu_items[route] = title
def introduce(self):
"""Hook operation for getting short introduction of extension (mostly
for debug/log purpose)
:return: Name of the extension
:rtype: str
"""
return getattr(self, 'NAME', 'unknown')
def view_admin_extensions(self):
"""Hook operation for getting view model of the extension in order
to show it in the administration of app
:return: Extensions view for this extension
:rtype: ``repocribro.extending.helpers.ExtensionView``
"""
<|code_end|>
. Use current file imports:
from .helpers import ExtensionView
from ..security import create_default_role, reload_anonymous_role
and context (classes, functions, or code) from other files:
# Path: repocribro/extending/helpers/views.py
# class ExtensionView:
# """View object for extensions"""
# def __init__(self, name, category, author,
# admin_url=None, home_url=None, gh_url=None):
# self.name = name
# self.category = category
# self.author = author
# self.admin_url = admin_url
# self.home_url = home_url
# self.gh_url = gh_url
#
# @staticmethod
# def from_class(cls):
# """Make view from Extension class"""
# return ExtensionView(
# getattr(cls, 'NAME', 'uknown'),
# getattr(cls, 'CATEGORY', ''),
# getattr(cls, 'AUTHOR', ''),
# getattr(cls, 'ADMIN_URL', None),
# getattr(cls, 'HOME_URL', None),
# getattr(cls, 'GH_URL', None),
# )
. Output only the next line. | return ExtensionView.from_class(self.__class__) |
Given the following code snippet before the placeholder: <|code_start|> """
return [self.rolename]
def owns_repo(self, repo):
"""Check if user owns the repository
:param repo: Repository which shoudl be tested
:type repo: ``repocribro.models.Repository``
:return: False, anonymous can not own repository
:rtype: bool
"""
return False
def sees_repo(self, repo, has_secret=False):
"""Check if user is allowed to see the repo
Anonymous can see only public repos
:param repo: Repository which user want to see
:type repo: ``repocribro.models.Repository``
:param has_secret: If current user knows the secret URL
:type has_secret: bool
:return: If user can see repo
:rtype: bool
"""
visible = repo.is_public or (has_secret and repo.is_hidden)
return visible
#: Many-to-many relationship between user accounts and roles
<|code_end|>
, predict the next line using imports from the current file:
import flask_sqlalchemy
import sqlalchemy
import flask_login
import datetime
import fnmatch
import re
import uuid
import hashlib
from .database import db
and context including class names, function names, and sometimes code from other files:
# Path: repocribro/database.py
. Output only the next line. | roles_users = db.Table( |
Predict the next line for this snippet: <|code_start|> """Repocribro is Flask web application
:ivar container: Service container for the app
:type container: ``repocribro.repocribro.DI_Container``
"""
def __init__(self):
"""Setup Flask app and prepare service container"""
super().__init__(PROG_NAME)
self.container = DI_Container()
def ext_call(self, what_to_call):
"""Call hook on all extensions
:param what_to_call: name of hook to call
:type what_to_call: str
:return: result of the call
"""
ext_master = self.container.get('ext_master')
return ext_master.call(what_to_call)
def create_app(cfg_files=['DEFAULT']):
"""Factory for making the web Flask application
:param cfg_files: Single or more config file(s)
:return: Constructed web application
:rtype: ``repocribro.repocribro.Repocribro``
"""
app = Repocribro()
<|code_end|>
with the help of current file imports:
import flask
import jinja2
import os
from .extending import ExtensionsMaster
from .config import create_config, check_config
from .database import db
from .security import permissions
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
and context from other files:
# Path: repocribro/extending/extension_master.py
# class ExtensionsMaster:
# """Collector & master of Extensions
#
# Extension master finds and holds all the **repocribro** extensions
# and is used for calling operations on them and collecting the results.
# """
#
# #: String used for looking up the extensions
# ENTRYPOINT_GROUP = 'repocribro.ext'
# #: Error message mask for extension load error
# LOAD_ERROR_MSG = 'Extension "{}" ({}) is not making an Extension ' \
# '(sub)class instance. It will be ignored!'
#
# @classmethod
# def _collect_extensions(cls, name=None):
# """Method for selecting extensions within ``ENTRYPOINT_GROUP``
#
# :param name: Can be used to select single entrypoint/extension
# :type name: str
# :return: Generator of selected entry points
# :rtype: ``pkg_resources.WorkingSet.iter_entry_points``
# """
# return pkg_resources.iter_entry_points(
# group=cls.ENTRYPOINT_GROUP, name=name
# )
#
# def __init__(self, *args, **kwargs):
# """Collects all the extensions to be mantained by this object
#
# :param args: positional args to be passed to extensions
# :param kwargs: keywords args to be passed to extensions
#
# .. todo:: There might be some problem with ordering of extensions
# """
# entry_points = self._collect_extensions()
# self.exts = []
# for ep in entry_points:
# ext_maker = ep.load()
# e = ext_maker(master=self, *args, **kwargs)
# if not isinstance(e, Extension):
# print(self.LOAD_ERROR_MSG.format(
# ep.name, ep.module_name, file=sys.stderr
# ))
# else:
# self.exts.append(e)
# self.exts.sort(key=lambda e: e.PRIORITY)
#
# def call(self, hook_name, default=None, *args, **kwargs):
# """Call the hook on all extensions registered
#
# :param hook_name: Name of hook to be called
# :type hook_name: str
# :param default: Default return value if hook operation not found
# :param args: Positional args to be passed to the hook operation
# :param kwargs: Keywords args to be passed to the hook operation
# :return: Result of the operation on the requested hook
# """
# return [ext.call(hook_name, default, *args, **kwargs)
# for ext in self.exts]
#
# Path: repocribro/config.py
# def create_config(cfg_files, env_prefix='REPOCRIBRO'):
# """Factory for making Repocribro config object
#
# :param cfg_files: Single or more config file(s)
# :return: Constructed config object
# :rtype: ``repocribro.config.Config``
# """
# config = Config()
# config.read(cfg_files)
# config.mark_mandatory('flask', 'secret_key')
# config.mark_mandatory('flask', 'SQLALCHEMY_DATABASE_URI')
# config.default['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'true'
# config.read_envs(env_prefix)
# return config
#
# def check_config(config, exit_code=1):
# """Procedure for checking mandatory config
#
# If there are some missing mandatory configurations this
# procedure prints info on stderr and exits program with
# specified exit code.
#
# :param config: Configuration object
# :type config: ``repocribro.config.Config``
# :param exit_code: Exit code on fail
# :type exit_code: int
# :raises: SystemExit
# """
# import sys
# config_errors = config.check()
# if len(config_errors) == 0:
# return
# print('Missing configuration:', file=sys.stderr)
# for err in config_errors:
# print('-> ' + err, file=sys.stderr)
# sys.exit(exit_code)
, which may contain function names, class names, or code. Output only the next line. | ext_master = ExtensionsMaster(app=app, db=db) |
Predict the next line for this snippet: <|code_start|> """Setup Flask app and prepare service container"""
super().__init__(PROG_NAME)
self.container = DI_Container()
def ext_call(self, what_to_call):
"""Call hook on all extensions
:param what_to_call: name of hook to call
:type what_to_call: str
:return: result of the call
"""
ext_master = self.container.get('ext_master')
return ext_master.call(what_to_call)
def create_app(cfg_files=['DEFAULT']):
"""Factory for making the web Flask application
:param cfg_files: Single or more config file(s)
:return: Constructed web application
:rtype: ``repocribro.repocribro.Repocribro``
"""
app = Repocribro()
ext_master = ExtensionsMaster(app=app, db=db)
app.container.set_singleton('ext_master', ext_master)
if cfg_files == ['DEFAULT']:
cfg_files = os.environ.get('REPOCRIBRO_CONFIG_FILE',
DEFAULT_CONFIG_FILES)
<|code_end|>
with the help of current file imports:
import flask
import jinja2
import os
from .extending import ExtensionsMaster
from .config import create_config, check_config
from .database import db
from .security import permissions
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
and context from other files:
# Path: repocribro/extending/extension_master.py
# class ExtensionsMaster:
# """Collector & master of Extensions
#
# Extension master finds and holds all the **repocribro** extensions
# and is used for calling operations on them and collecting the results.
# """
#
# #: String used for looking up the extensions
# ENTRYPOINT_GROUP = 'repocribro.ext'
# #: Error message mask for extension load error
# LOAD_ERROR_MSG = 'Extension "{}" ({}) is not making an Extension ' \
# '(sub)class instance. It will be ignored!'
#
# @classmethod
# def _collect_extensions(cls, name=None):
# """Method for selecting extensions within ``ENTRYPOINT_GROUP``
#
# :param name: Can be used to select single entrypoint/extension
# :type name: str
# :return: Generator of selected entry points
# :rtype: ``pkg_resources.WorkingSet.iter_entry_points``
# """
# return pkg_resources.iter_entry_points(
# group=cls.ENTRYPOINT_GROUP, name=name
# )
#
# def __init__(self, *args, **kwargs):
# """Collects all the extensions to be mantained by this object
#
# :param args: positional args to be passed to extensions
# :param kwargs: keywords args to be passed to extensions
#
# .. todo:: There might be some problem with ordering of extensions
# """
# entry_points = self._collect_extensions()
# self.exts = []
# for ep in entry_points:
# ext_maker = ep.load()
# e = ext_maker(master=self, *args, **kwargs)
# if not isinstance(e, Extension):
# print(self.LOAD_ERROR_MSG.format(
# ep.name, ep.module_name, file=sys.stderr
# ))
# else:
# self.exts.append(e)
# self.exts.sort(key=lambda e: e.PRIORITY)
#
# def call(self, hook_name, default=None, *args, **kwargs):
# """Call the hook on all extensions registered
#
# :param hook_name: Name of hook to be called
# :type hook_name: str
# :param default: Default return value if hook operation not found
# :param args: Positional args to be passed to the hook operation
# :param kwargs: Keywords args to be passed to the hook operation
# :return: Result of the operation on the requested hook
# """
# return [ext.call(hook_name, default, *args, **kwargs)
# for ext in self.exts]
#
# Path: repocribro/config.py
# def create_config(cfg_files, env_prefix='REPOCRIBRO'):
# """Factory for making Repocribro config object
#
# :param cfg_files: Single or more config file(s)
# :return: Constructed config object
# :rtype: ``repocribro.config.Config``
# """
# config = Config()
# config.read(cfg_files)
# config.mark_mandatory('flask', 'secret_key')
# config.mark_mandatory('flask', 'SQLALCHEMY_DATABASE_URI')
# config.default['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'true'
# config.read_envs(env_prefix)
# return config
#
# def check_config(config, exit_code=1):
# """Procedure for checking mandatory config
#
# If there are some missing mandatory configurations this
# procedure prints info on stderr and exits program with
# specified exit code.
#
# :param config: Configuration object
# :type config: ``repocribro.config.Config``
# :param exit_code: Exit code on fail
# :type exit_code: int
# :raises: SystemExit
# """
# import sys
# config_errors = config.check()
# if len(config_errors) == 0:
# return
# print('Missing configuration:', file=sys.stderr)
# for err in config_errors:
# print('-> ' + err, file=sys.stderr)
# sys.exit(exit_code)
, which may contain function names, class names, or code. Output only the next line. | config = create_config(cfg_files) |
Given the code snippet: <|code_start|> """Call hook on all extensions
:param what_to_call: name of hook to call
:type what_to_call: str
:return: result of the call
"""
ext_master = self.container.get('ext_master')
return ext_master.call(what_to_call)
def create_app(cfg_files=['DEFAULT']):
"""Factory for making the web Flask application
:param cfg_files: Single or more config file(s)
:return: Constructed web application
:rtype: ``repocribro.repocribro.Repocribro``
"""
app = Repocribro()
ext_master = ExtensionsMaster(app=app, db=db)
app.container.set_singleton('ext_master', ext_master)
if cfg_files == ['DEFAULT']:
cfg_files = os.environ.get('REPOCRIBRO_CONFIG_FILE',
DEFAULT_CONFIG_FILES)
config = create_config(cfg_files)
config.set('flask', 'release', RELEASE)
app.container.set_singleton('config', config)
ext_master.call('setup_config')
config.update_flask_cfg(app)
<|code_end|>
, generate the next line using the imports in this file:
import flask
import jinja2
import os
from .extending import ExtensionsMaster
from .config import create_config, check_config
from .database import db
from .security import permissions
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
and context (functions, classes, or occasionally code) from other files:
# Path: repocribro/extending/extension_master.py
# class ExtensionsMaster:
# """Collector & master of Extensions
#
# Extension master finds and holds all the **repocribro** extensions
# and is used for calling operations on them and collecting the results.
# """
#
# #: String used for looking up the extensions
# ENTRYPOINT_GROUP = 'repocribro.ext'
# #: Error message mask for extension load error
# LOAD_ERROR_MSG = 'Extension "{}" ({}) is not making an Extension ' \
# '(sub)class instance. It will be ignored!'
#
# @classmethod
# def _collect_extensions(cls, name=None):
# """Method for selecting extensions within ``ENTRYPOINT_GROUP``
#
# :param name: Can be used to select single entrypoint/extension
# :type name: str
# :return: Generator of selected entry points
# :rtype: ``pkg_resources.WorkingSet.iter_entry_points``
# """
# return pkg_resources.iter_entry_points(
# group=cls.ENTRYPOINT_GROUP, name=name
# )
#
# def __init__(self, *args, **kwargs):
# """Collects all the extensions to be mantained by this object
#
# :param args: positional args to be passed to extensions
# :param kwargs: keywords args to be passed to extensions
#
# .. todo:: There might be some problem with ordering of extensions
# """
# entry_points = self._collect_extensions()
# self.exts = []
# for ep in entry_points:
# ext_maker = ep.load()
# e = ext_maker(master=self, *args, **kwargs)
# if not isinstance(e, Extension):
# print(self.LOAD_ERROR_MSG.format(
# ep.name, ep.module_name, file=sys.stderr
# ))
# else:
# self.exts.append(e)
# self.exts.sort(key=lambda e: e.PRIORITY)
#
# def call(self, hook_name, default=None, *args, **kwargs):
# """Call the hook on all extensions registered
#
# :param hook_name: Name of hook to be called
# :type hook_name: str
# :param default: Default return value if hook operation not found
# :param args: Positional args to be passed to the hook operation
# :param kwargs: Keywords args to be passed to the hook operation
# :return: Result of the operation on the requested hook
# """
# return [ext.call(hook_name, default, *args, **kwargs)
# for ext in self.exts]
#
# Path: repocribro/config.py
# def create_config(cfg_files, env_prefix='REPOCRIBRO'):
# """Factory for making Repocribro config object
#
# :param cfg_files: Single or more config file(s)
# :return: Constructed config object
# :rtype: ``repocribro.config.Config``
# """
# config = Config()
# config.read(cfg_files)
# config.mark_mandatory('flask', 'secret_key')
# config.mark_mandatory('flask', 'SQLALCHEMY_DATABASE_URI')
# config.default['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'true'
# config.read_envs(env_prefix)
# return config
#
# def check_config(config, exit_code=1):
# """Procedure for checking mandatory config
#
# If there are some missing mandatory configurations this
# procedure prints info on stderr and exits program with
# specified exit code.
#
# :param config: Configuration object
# :type config: ``repocribro.config.Config``
# :param exit_code: Exit code on fail
# :type exit_code: int
# :raises: SystemExit
# """
# import sys
# config_errors = config.check()
# if len(config_errors) == 0:
# return
# print('Missing configuration:', file=sys.stderr)
# for err in config_errors:
# print('-> ' + err, file=sys.stderr)
# sys.exit(exit_code)
. Output only the next line. | check_config(config) |
Next line prediction: <|code_start|>
def test_login_logout(app, empty_db_session):
with app.test_request_context('/'):
account = UserAccount()
account.id = 666
empty_db_session.add(account)
empty_db_session.commit()
<|code_end|>
. Use current file imports:
(import flask_login
import pytest
from werkzeug.exceptions import Forbidden
from repocribro.security import login, logout, permissions
from repocribro.models import UserAccount, Role)
and context including class names, function names, or small code snippets from other files:
# Path: repocribro/security.py
# def init_login_manager(db):
# def unauthorized():
# def load_user(user_id):
# def identity_loader():
# def __init__(self, name):
# def __getattr__(self, key):
# def __init__(self):
# def register_role(self, role_name):
# def register_action(self, priv_name):
# def all_roles(self):
# def all_actions(self):
# def login(user_account):
# def logout():
# def clear_session(*args):
# def reload_anonymous_role(app, db):
# def get_default_user_role(app, db):
# def create_default_role(app, db, role):
# def on_identity_loaded(sender, identity):
# class PermissionsContainer:
# class Permissions:
#
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | login(account) |
Predict the next line after this snippet: <|code_start|>
def test_login_logout(app, empty_db_session):
with app.test_request_context('/'):
account = UserAccount()
account.id = 666
empty_db_session.add(account)
empty_db_session.commit()
login(account)
assert flask_login.current_user.id == 666
<|code_end|>
using the current file's imports:
import flask_login
import pytest
from werkzeug.exceptions import Forbidden
from repocribro.security import login, logout, permissions
from repocribro.models import UserAccount, Role
and any relevant context from other files:
# Path: repocribro/security.py
# def init_login_manager(db):
# def unauthorized():
# def load_user(user_id):
# def identity_loader():
# def __init__(self, name):
# def __getattr__(self, key):
# def __init__(self):
# def register_role(self, role_name):
# def register_action(self, priv_name):
# def all_roles(self):
# def all_actions(self):
# def login(user_account):
# def logout():
# def clear_session(*args):
# def reload_anonymous_role(app, db):
# def get_default_user_role(app, db):
# def create_default_role(app, db, role):
# def on_identity_loaded(sender, identity):
# class PermissionsContainer:
# class Permissions:
#
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | logout() |
Next line prediction: <|code_start|>
def test_login_logout(app, empty_db_session):
with app.test_request_context('/'):
account = UserAccount()
account.id = 666
empty_db_session.add(account)
empty_db_session.commit()
login(account)
assert flask_login.current_user.id == 666
logout()
assert flask_login.current_user.is_anonymous
def test_permission_admin(app, empty_db_session):
with app.test_request_context('/'):
<|code_end|>
. Use current file imports:
(import flask_login
import pytest
from werkzeug.exceptions import Forbidden
from repocribro.security import login, logout, permissions
from repocribro.models import UserAccount, Role)
and context including class names, function names, or small code snippets from other files:
# Path: repocribro/security.py
# def init_login_manager(db):
# def unauthorized():
# def load_user(user_id):
# def identity_loader():
# def __init__(self, name):
# def __getattr__(self, key):
# def __init__(self):
# def register_role(self, role_name):
# def register_action(self, priv_name):
# def all_roles(self):
# def all_actions(self):
# def login(user_account):
# def logout():
# def clear_session(*args):
# def reload_anonymous_role(app, db):
# def get_default_user_role(app, db):
# def create_default_role(app, db, role):
# def on_identity_loaded(sender, identity):
# class PermissionsContainer:
# class Permissions:
#
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | @permissions.roles.admin.require(403) |
Predict the next line after this snippet: <|code_start|>
def test_login_logout(app, empty_db_session):
with app.test_request_context('/'):
account = UserAccount()
account.id = 666
empty_db_session.add(account)
empty_db_session.commit()
login(account)
assert flask_login.current_user.id == 666
logout()
assert flask_login.current_user.is_anonymous
def test_permission_admin(app, empty_db_session):
with app.test_request_context('/'):
@permissions.roles.admin.require(403)
def test():
return 200
with pytest.raises(Forbidden):
assert test() == 200
<|code_end|>
using the current file's imports:
import flask_login
import pytest
from werkzeug.exceptions import Forbidden
from repocribro.security import login, logout, permissions
from repocribro.models import UserAccount, Role
and any relevant context from other files:
# Path: repocribro/security.py
# def init_login_manager(db):
# def unauthorized():
# def load_user(user_id):
# def identity_loader():
# def __init__(self, name):
# def __getattr__(self, key):
# def __init__(self):
# def register_role(self, role_name):
# def register_action(self, priv_name):
# def all_roles(self):
# def all_actions(self):
# def login(user_account):
# def logout():
# def clear_session(*args):
# def reload_anonymous_role(app, db):
# def get_default_user_role(app, db):
# def create_default_role(app, db, role):
# def on_identity_loaded(sender, identity):
# class PermissionsContainer:
# class Permissions:
#
# Path: repocribro/models.py
# class UserAccount(db.Model, UserMixin, SearchableMixin):
# """UserAccount in the repocribro app"""
# __tablename__ = 'UserAccount'
#
# default_rolename = 'user'
#
# #: Unique identifier of the user account
# id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
# #: Timestamp where account was created
# created_at = sqlalchemy.Column(
# sqlalchemy.DateTime, default=datetime.datetime.now()
# )
# #: Flag if the account is active or banned
# active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
# #: Relation to the GitHub user connected to account
# github_user = sqlalchemy.orm.relationship(
# 'User', back_populates='user_account',
# uselist=False, cascade='all, delete-orphan'
# )
# #: Roles assigned to the user account
# roles = sqlalchemy.orm.relationship(
# 'Role', back_populates='user_accounts',
# secondary=roles_users,
# )
#
# @property
# def login(self):
# """Get login name for user account from related GH user
#
# :return: Login name
# :rtype: str
# """
# if self.github_user is None:
# return '<unknown>'
# return self.github_user.login
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<UserAccount (#{})>'.format(self.id)
#
# class Role(db.Model, RoleMixin):
# """User account role in the application"""
# __tablename__ = 'Role'
#
# #: Unique identifier of the role
# id = sqlalchemy.Column(sqlalchemy.Integer(), primary_key=True)
# #: Unique name of the role
# name = sqlalchemy.Column(sqlalchemy.String(80), unique=True)
# #: Description (purpose, notes, ...) of the role
# description = sqlalchemy.Column(sqlalchemy.UnicodeText)
# #: Serialized list of privileges
# privileges = sqlalchemy.Column(sqlalchemy.Text)
# #: User accounts assigned to the role
# user_accounts = sqlalchemy.orm.relationship(
# 'UserAccount', back_populates='roles', secondary=roles_users
# )
#
# def __init__(self, name, privileges, description):
# self.name = name
# self.privileges = privileges
# self.description = description
#
# def __repr__(self):
# """Standard string representation of DB object
#
# :return: Unique string representation
# :rtype: str
# """
# return '<Role {} (#{})>'.format(
# self.name, self.id
# )
. Output only the next line. | role_admin = Role('testadmin', '*', '') |
Predict the next line for this snippet: <|code_start|>"""Start a tcp gateway."""
def common_tcp_options(func):
"""Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
<|code_end|>
with the help of current file imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
, which may contain function names, class names, or code. Output only the next line. | @common_gateway_options |
Given the code snippet: <|code_start|>"""Start a tcp gateway."""
def common_tcp_options(func):
"""Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def tcp_gateway(**kwargs):
"""Start a tcp gateway."""
<|code_end|>
, generate the next line using the imports in this file:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | gateway = TCPGateway(event_callback=handle_msg, **kwargs) |
Continue the code snippet: <|code_start|> """Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def tcp_gateway(**kwargs):
"""Start a tcp gateway."""
gateway = TCPGateway(event_callback=handle_msg, **kwargs)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def async_tcp_gateway(**kwargs):
"""Start an async tcp gateway."""
gateway = AsyncTCPGateway(event_callback=handle_msg, **kwargs)
<|code_end|>
. Use current file imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context (classes, functions, or code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_async_gateway(gateway) |
Based on the snippet: <|code_start|>"""Start a tcp gateway."""
def common_tcp_options(func):
"""Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def tcp_gateway(**kwargs):
"""Start a tcp gateway."""
gateway = TCPGateway(event_callback=handle_msg, **kwargs)
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context (classes, functions, sometimes code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_gateway(gateway) |
Given snippet: <|code_start|>def common_tcp_options(func):
"""Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def tcp_gateway(**kwargs):
"""Start a tcp gateway."""
gateway = TCPGateway(event_callback=handle_msg, **kwargs)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def async_tcp_gateway(**kwargs):
"""Start an async tcp gateway."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
which might include code, classes, or functions. Output only the next line. | gateway = AsyncTCPGateway(event_callback=handle_msg, **kwargs) |
Given the code snippet: <|code_start|>"""Start a tcp gateway."""
def common_tcp_options(func):
"""Supply common tcp gateway options."""
func = click.option(
"-p",
"--port",
default=5003,
show_default=True,
type=int,
help="TCP port of the connection.",
)(func)
func = click.option(
"-H", "--host", required=True, help="TCP address of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_tcp_options
@common_gateway_options
def tcp_gateway(**kwargs):
"""Start a tcp gateway."""
<|code_end|>
, generate the next line using the imports in this file:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_tcp.py
# class AsyncTCPGateway(BaseAsyncGateway, BaseTCPGateway):
# """MySensors async TCP gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up TCP gateway."""
# self.cancel_check_conn = None
# protocol = AsyncTCPMySensorsProtocol
# transport = AsyncTransport(
# self, async_connect, loop=loop, protocol=protocol, **kwargs
# )
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# def check_connection(self):
# """Check if connection is alive every reconnect_timeout seconds."""
# try:
# super().check_connection()
# except OSError as exc:
# _LOGGER.error(exc)
# self.tasks.transport.protocol.transport.close()
# self.tasks.transport.protocol.conn_lost_callback()
# return
# task = self.tasks.loop.call_later(
# self.tasks.transport.reconnect_timeout + 0.1, self.check_connection
# )
# self.cancel_check_conn = task.cancel
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# mac = await self.tasks.loop.run_in_executor(None, self._get_gateway_id)
# return mac
#
# class TCPGateway(BaseSyncGateway, BaseTCPGateway):
# """MySensors TCP gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up TCP gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | gateway = TCPGateway(event_callback=handle_msg, **kwargs) |
Given the code snippet: <|code_start|> I_SKETCH_VERSION = 12
# Used by OTA firmware updates. Request for node to reboot.
I_REBOOT = 13
# Send by gateway to controller when startup is complete
I_GATEWAY_READY = 14
class Stream(BaseConst):
"""MySensors stream sub-types."""
# Request new FW, payload contains current FW details
ST_FIRMWARE_CONFIG_REQUEST = 0
# New FW details to initiate OTA FW update
ST_FIRMWARE_CONFIG_RESPONSE = 1
ST_FIRMWARE_REQUEST = 2 # Request FW block
ST_FIRMWARE_RESPONSE = 3 # Response FW block
ST_SOUND = 4 # Sound
ST_IMAGE = 5 # Image
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
VALID_PRESENTATION = {member: str for member in list(Presentation)}
VALID_PRESENTATION.update(
<|code_end|>
, generate the next line using the imports in this file:
from enum import IntEnum
from mysensors.validation import is_version, percent_int
from .handler import HANDLERS
import voluptuous as vol
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
#
# Path: mysensors/handler.py
# HANDLERS = Registry()
. Output only the next line. | {Presentation.S_ARDUINO_NODE: is_version, Presentation.S_ARDUINO_RELAY: is_version} |
Given snippet: <|code_start|> SetReq.V_VAR3,
SetReq.V_VAR4,
SetReq.V_VAR5,
],
Presentation.S_DUST: [SetReq.V_DUST_LEVEL],
Presentation.S_SCENE_CONTROLLER: [SetReq.V_SCENE_ON, SetReq.V_SCENE_OFF],
}
LOGICAL_ZERO = "0"
LOGICAL_ONE = "1"
OFF = "Off"
HEAT_ON = "HeatOn"
COOL_ON = "CoolOn"
AUTO_CHANGE_OVER = "AutoChangeOver"
STABLE = "stable"
SUNNY = "sunny"
CLOUDY = "cloudy"
UNSTABLE = "unstable"
THUNDERSTORM = "thunderstorm"
UNKNOWN = "unknown"
FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
VALID_SETREQ = {
SetReq.V_TEMP: str,
SetReq.V_HUM: str,
SetReq.V_LIGHT: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_DIMMER: vol.All(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from enum import IntEnum
from mysensors.validation import is_version, percent_int
from .handler import HANDLERS
import voluptuous as vol
and context:
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
#
# Path: mysensors/handler.py
# HANDLERS = Registry()
which might include code, classes, or functions. Output only the next line. | percent_int, |
Based on the snippet: <|code_start|> help="Turn on retain on published messages at broker.",
)(func)
func = click.option(
"--out-prefix",
default="mygateway1-in",
show_default=True,
help="Topic prefix for outgoing messages.",
)(func)
func = click.option(
"--in-prefix",
default="mygateway1-out",
show_default=True,
help="Topic prefix for incoming messages.",
)(func)
func = click.option(
"-p",
"--port",
default=1883,
show_default=True,
type=int,
help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context (classes, functions, sometimes code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | @common_gateway_options |
Given snippet: <|code_start|> show_default=True,
help="Topic prefix for outgoing messages.",
)(func)
func = click.option(
"--in-prefix",
default="mygateway1-out",
show_default=True,
help="Topic prefix for incoming messages.",
)(func)
func = click.option(
"-p",
"--port",
default=1883,
show_default=True,
type=int,
help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
gateway = MQTTGateway(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
which might include code, classes, or functions. Output only the next line. | mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs |
Based on the snippet: <|code_start|> help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
gateway = MQTTGateway(
mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs
)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def async_mqtt_gateway(broker, port, **kwargs):
"""Start an async mqtt gateway."""
loop = asyncio.get_event_loop()
mqttc = loop.run_until_complete(async_start_mqtt_client(loop, broker, port))
gateway = AsyncMQTTGateway(
mqttc.publish, mqttc.subscribe, event_callback=handle_msg, loop=loop, **kwargs
)
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context (classes, functions, sometimes code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_async_gateway(gateway, mqttc.stop()) |
Continue the code snippet: <|code_start|> )(func)
func = click.option(
"--in-prefix",
default="mygateway1-out",
show_default=True,
help="Topic prefix for incoming messages.",
)(func)
func = click.option(
"-p",
"--port",
default=1883,
show_default=True,
type=int,
help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
gateway = MQTTGateway(
mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs
)
<|code_end|>
. Use current file imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context (classes, functions, or code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_gateway(gateway) |
Predict the next line for this snippet: <|code_start|> default=1883,
show_default=True,
type=int,
help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
gateway = MQTTGateway(
mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs
)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def async_mqtt_gateway(broker, port, **kwargs):
"""Start an async mqtt gateway."""
loop = asyncio.get_event_loop()
mqttc = loop.run_until_complete(async_start_mqtt_client(loop, broker, port))
<|code_end|>
with the help of current file imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
, which may contain function names, class names, or code. Output only the next line. | gateway = AsyncMQTTGateway( |
Given snippet: <|code_start|> default="mygateway1-in",
show_default=True,
help="Topic prefix for outgoing messages.",
)(func)
func = click.option(
"--in-prefix",
default="mygateway1-out",
show_default=True,
help="Topic prefix for incoming messages.",
)(func)
func = click.option(
"-p",
"--port",
default=1883,
show_default=True,
type=int,
help="MQTT port of the connection.",
)(func)
func = click.option("-b", "--broker", required=True, help="MQTT broker address.")(
func
)
return func
@click.command(options_metavar="<options>")
@common_mqtt_options
@common_gateway_options
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import logging
import socket
import sys
import click
import paho.mqtt.client as mqtt
import paho.mqtt.client as mqtt
from contextlib import contextmanager
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_mqtt import AsyncMQTTGateway, MQTTGateway
and context:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_mqtt.py
# class AsyncMQTTGateway(BaseAsyncGateway, BaseMQTTGateway):
# """MySensors async MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# loop=None,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTAsyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
#
# class MQTTGateway(BaseSyncGateway, BaseMQTTGateway):
# """MySensors MQTT client gateway."""
#
# # pylint: disable=too-many-arguments
#
# def __init__(
# self,
# pub_callback,
# sub_callback,
# in_prefix="",
# out_prefix="",
# retain=True,
# **kwargs,
# ):
# """Set up MQTT gateway."""
# transport = MQTTSyncTransport(
# self,
# pub_callback,
# sub_callback,
# in_prefix=in_prefix,
# out_prefix=out_prefix,
# retain=retain,
# )
# super().__init__(transport, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
which might include code, classes, or functions. Output only the next line. | gateway = MQTTGateway( |
Based on the snippet: <|code_start|> int(self.ack),
int(self.sub_type),
self.payload,
]
]
)
+ "\n"
)
except ValueError:
_LOGGER.error("Error encoding message to gateway")
return None
def validate(self, protocol_version):
"""Validate message."""
if self.gateway is not None:
_LOGGER.warning("Can not validate message if Message.gateway is set")
return None
const = get_const(protocol_version)
valid_node_ids = vol.All(
vol.Coerce(int),
vol.Range(
min=0,
max=BROADCAST_ID,
msg=f"Not valid node_id: {self.node_id}",
),
)
valid_child_ids = vol.All(
vol.Coerce(int),
vol.Range(
min=0,
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import voluptuous as vol
from .const import SYSTEM_CHILD_ID, get_const
and context (classes, functions, sometimes code) from other files:
# Path: mysensors/const.py
# SYSTEM_CHILD_ID = 255
#
# def get_const(protocol_version):
# """Return the const module for the protocol_version."""
# path = next(
# (
# CONST_VERSIONS[const_version]
# for const_version in sorted(CONST_VERSIONS, reverse=True)
# if parse_ver(protocol_version) >= parse_ver(const_version)
# ),
# "mysensors.const_14",
# )
# if path in LOADED_CONST:
# return LOADED_CONST[path]
# const = import_module(path)
# LOADED_CONST[path] = const # Cache the module
# return const
. Output only the next line. | max=SYSTEM_CHILD_ID, |
Given snippet: <|code_start|> raise
def encode(self, delimiter=";"):
"""Encode a command string from message."""
try:
return (
delimiter.join(
[
str(f)
for f in [
int(self.node_id),
int(self.child_id),
int(self.type),
int(self.ack),
int(self.sub_type),
self.payload,
]
]
)
+ "\n"
)
except ValueError:
_LOGGER.error("Error encoding message to gateway")
return None
def validate(self, protocol_version):
"""Validate message."""
if self.gateway is not None:
_LOGGER.warning("Can not validate message if Message.gateway is set")
return None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import voluptuous as vol
from .const import SYSTEM_CHILD_ID, get_const
and context:
# Path: mysensors/const.py
# SYSTEM_CHILD_ID = 255
#
# def get_const(protocol_version):
# """Return the const module for the protocol_version."""
# path = next(
# (
# CONST_VERSIONS[const_version]
# for const_version in sorted(CONST_VERSIONS, reverse=True)
# if parse_ver(protocol_version) >= parse_ver(const_version)
# ),
# "mysensors.const_14",
# )
# if path in LOADED_CONST:
# return LOADED_CONST[path]
# const = import_module(path)
# LOADED_CONST[path] = const # Cache the module
# return const
which might include code, classes, or functions. Output only the next line. | const = get_const(protocol_version) |
Using the snippet: <|code_start|> SetReq.V_PRESSURE: str,
SetReq.V_FORECAST: vol.Any(
str,
vol.In(
FORECASTS,
msg=f"forecast must be one of: {', '.join(FORECASTS)}",
),
),
SetReq.V_RAIN: str,
SetReq.V_RAINRATE: str,
SetReq.V_WIND: str,
SetReq.V_GUST: str,
SetReq.V_DIRECTION: str,
SetReq.V_UV: str,
SetReq.V_WEIGHT: str,
SetReq.V_DISTANCE: str,
SetReq.V_IMPEDANCE: str,
SetReq.V_ARMED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_TRIPPED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_WATT: str,
SetReq.V_KWH: str,
SetReq.V_SCENE_ON: str,
SetReq.V_SCENE_OFF: str,
SetReq.V_HVAC_FLOW_STATE: vol.In(
<|code_end|>
, determine the next line of code. You have imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (class names, function names, or code) available:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | [OFF, HEAT_ON, COOL_ON, AUTO_CHANGE_OVER], |
Given the code snippet: <|code_start|> SetReq.V_PRESSURE: str,
SetReq.V_FORECAST: vol.Any(
str,
vol.In(
FORECASTS,
msg=f"forecast must be one of: {', '.join(FORECASTS)}",
),
),
SetReq.V_RAIN: str,
SetReq.V_RAINRATE: str,
SetReq.V_WIND: str,
SetReq.V_GUST: str,
SetReq.V_DIRECTION: str,
SetReq.V_UV: str,
SetReq.V_WEIGHT: str,
SetReq.V_DISTANCE: str,
SetReq.V_IMPEDANCE: str,
SetReq.V_ARMED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_TRIPPED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_WATT: str,
SetReq.V_KWH: str,
SetReq.V_SCENE_ON: str,
SetReq.V_SCENE_OFF: str,
SetReq.V_HVAC_FLOW_STATE: vol.In(
<|code_end|>
, generate the next line using the imports in this file:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | [OFF, HEAT_ON, COOL_ON, AUTO_CHANGE_OVER], |
Given the following code snippet before the placeholder: <|code_start|>
def validate_v_rgbw(value):
"""Validate a V_RGBW value."""
if len(value) != 8:
raise vol.Invalid(f"{value} is not eight characters long")
return validate_hex(value)
AUTO = "Auto"
MAX = "Max"
MIN = "Min"
NORMAL = "Normal"
# Define this again for version 1.5 to avoid conflicts with version 1.4.
VALID_SETREQ = {
SetReq.V_TEMP: str,
SetReq.V_HUM: str,
SetReq.V_STATUS: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_PERCENTAGE: vol.All(
percent_int,
vol.Coerce(str),
msg=f"value must be integer between {0} and {100}",
),
SetReq.V_PRESSURE: str,
SetReq.V_FORECAST: vol.Any(
str,
vol.In(
<|code_end|>
, predict the next line using imports from the current file:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context including class names, function names, and sometimes code from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | FORECASTS, |
Predict the next line after this snippet: <|code_start|> SetReq.V_PRESSURE: str,
SetReq.V_FORECAST: vol.Any(
str,
vol.In(
FORECASTS,
msg=f"forecast must be one of: {', '.join(FORECASTS)}",
),
),
SetReq.V_RAIN: str,
SetReq.V_RAINRATE: str,
SetReq.V_WIND: str,
SetReq.V_GUST: str,
SetReq.V_DIRECTION: str,
SetReq.V_UV: str,
SetReq.V_WEIGHT: str,
SetReq.V_DISTANCE: str,
SetReq.V_IMPEDANCE: str,
SetReq.V_ARMED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_TRIPPED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_WATT: str,
SetReq.V_KWH: str,
SetReq.V_SCENE_ON: str,
SetReq.V_SCENE_OFF: str,
SetReq.V_HVAC_FLOW_STATE: vol.In(
<|code_end|>
using the current file's imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and any relevant context from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | [OFF, HEAT_ON, COOL_ON, AUTO_CHANGE_OVER], |
Given snippet: <|code_start|> binascii.unhexlify(value)
except Exception as exc:
raise vol.Invalid(f"{value} is not of hex format") from exc
return value
def validate_v_rgb(value):
"""Validate a V_RGB value."""
if len(value) != 6:
raise vol.Invalid(f"{value} is not six characters long")
return validate_hex(value)
def validate_v_rgbw(value):
"""Validate a V_RGBW value."""
if len(value) != 8:
raise vol.Invalid(f"{value} is not eight characters long")
return validate_hex(value)
AUTO = "Auto"
MAX = "Max"
MIN = "Min"
NORMAL = "Normal"
# Define this again for version 1.5 to avoid conflicts with version 1.4.
VALID_SETREQ = {
SetReq.V_TEMP: str,
SetReq.V_HUM: str,
SetReq.V_STATUS: vol.In(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
which might include code, classes, or functions. Output only the next line. | [LOGICAL_ZERO, LOGICAL_ONE], |
Continue the code snippet: <|code_start|> binascii.unhexlify(value)
except Exception as exc:
raise vol.Invalid(f"{value} is not of hex format") from exc
return value
def validate_v_rgb(value):
"""Validate a V_RGB value."""
if len(value) != 6:
raise vol.Invalid(f"{value} is not six characters long")
return validate_hex(value)
def validate_v_rgbw(value):
"""Validate a V_RGBW value."""
if len(value) != 8:
raise vol.Invalid(f"{value} is not eight characters long")
return validate_hex(value)
AUTO = "Auto"
MAX = "Max"
MIN = "Min"
NORMAL = "Normal"
# Define this again for version 1.5 to avoid conflicts with version 1.4.
VALID_SETREQ = {
SetReq.V_TEMP: str,
SetReq.V_HUM: str,
SetReq.V_STATUS: vol.In(
<|code_end|>
. Use current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (classes, functions, or code) from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | [LOGICAL_ZERO, LOGICAL_ONE], |
Here is a snippet: <|code_start|> SetReq.V_PRESSURE: str,
SetReq.V_FORECAST: vol.Any(
str,
vol.In(
FORECASTS,
msg=f"forecast must be one of: {', '.join(FORECASTS)}",
),
),
SetReq.V_RAIN: str,
SetReq.V_RAINRATE: str,
SetReq.V_WIND: str,
SetReq.V_GUST: str,
SetReq.V_DIRECTION: str,
SetReq.V_UV: str,
SetReq.V_WEIGHT: str,
SetReq.V_DISTANCE: str,
SetReq.V_IMPEDANCE: str,
SetReq.V_ARMED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_TRIPPED: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_WATT: str,
SetReq.V_KWH: str,
SetReq.V_SCENE_ON: str,
SetReq.V_SCENE_OFF: str,
SetReq.V_HVAC_FLOW_STATE: vol.In(
<|code_end|>
. Write the next line using the current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
, which may include functions, classes, or code. Output only the next line. | [OFF, HEAT_ON, COOL_ON, AUTO_CHANGE_OVER], |
Given the code snippet: <|code_start|> SetReq.V_IR_SEND: str,
SetReq.V_IR_RECEIVE: str,
SetReq.V_FLOW: str,
SetReq.V_VOLUME: str,
SetReq.V_LOCK_STATUS: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_LEVEL: str,
SetReq.V_VOLTAGE: str,
SetReq.V_CURRENT: str,
SetReq.V_RGB: vol.All(str, validate_v_rgb),
SetReq.V_RGBW: vol.All(str, validate_v_rgbw),
SetReq.V_ID: str,
SetReq.V_UNIT_PREFIX: str,
SetReq.V_HVAC_SETPOINT_COOL: vol.All(
vol.Coerce(float),
vol.Range(min=0.0, max=100.0),
vol.Coerce(str),
msg=f"value must be between {0.0} and {100.0}",
),
SetReq.V_HVAC_SETPOINT_HEAT: vol.All(
vol.Coerce(float),
vol.Range(min=0.0, max=100.0),
vol.Coerce(str),
msg=f"value must be between {0.0} and {100.0}",
),
SetReq.V_HVAC_FLOW_MODE: str,
}
<|code_end|>
, generate the next line using the imports in this file:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | VALID_INTERNAL = dict(VALID_INTERNAL) |
Here is a snippet: <|code_start|> SetReq.V_UNIT_PREFIX: str,
SetReq.V_HVAC_SETPOINT_COOL: vol.All(
vol.Coerce(float),
vol.Range(min=0.0, max=100.0),
vol.Coerce(str),
msg=f"value must be between {0.0} and {100.0}",
),
SetReq.V_HVAC_SETPOINT_HEAT: vol.All(
vol.Coerce(float),
vol.Range(min=0.0, max=100.0),
vol.Coerce(str),
msg=f"value must be between {0.0} and {100.0}",
),
SetReq.V_HVAC_FLOW_MODE: str,
}
VALID_INTERNAL = dict(VALID_INTERNAL)
VALID_INTERNAL.update(
{
Internal.I_REQUEST_SIGNING: str,
Internal.I_GET_NONCE: str,
Internal.I_GET_NONCE_RESPONSE: str,
}
)
VALID_PAYLOADS = {
MessageType.presentation: VALID_PRESENTATION,
MessageType.set: VALID_SETREQ,
MessageType.req: {member: "" for member in list(SetReq)},
MessageType.internal: VALID_INTERNAL,
<|code_end|>
. Write the next line using the current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
, which may include functions, classes, or code. Output only the next line. | MessageType.stream: VALID_STREAM, |
Here is a snippet: <|code_start|> I_CONFIG = 6
# When a sensor starts up, it broadcast a search request to all neighbor
# nodes. They reply with a I_FIND_PARENT_RESPONSE.
I_FIND_PARENT = 7
# Reply message type to I_FIND_PARENT request.
I_FIND_PARENT_RESPONSE = 8
# Sent by the gateway to the Controller to trace-log a message
I_LOG_MESSAGE = 9
# A message that can be used to transfer child sensors
# (from EEPROM routing table) of a repeating node.
I_CHILDREN = 10
# Optional sketch name that can be used to identify sensor in the
# Controller GUI
I_SKETCH_NAME = 11
# Optional sketch version that can be reported to keep track of the version
# of sensor in the Controller GUI.
I_SKETCH_VERSION = 12
# Used by OTA firmware updates. Request for node to reboot.
I_REBOOT = 13
# Send by gateway to controller when startup is complete
I_GATEWAY_READY = 14
# Used between sensors when initialting signing.
I_REQUEST_SIGNING = 15
# Used between sensors when requesting nonce.
I_GET_NONCE = 16
# Used between sensors for nonce response.
I_GET_NONCE_RESPONSE = 17
VALID_MESSAGE_TYPES = {
<|code_end|>
. Write the next line using the current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
, which may include functions, classes, or code. Output only the next line. | MessageType.presentation: list(Presentation), |
Continue the code snippet: <|code_start|> # Reply message type to I_FIND_PARENT request.
I_FIND_PARENT_RESPONSE = 8
# Sent by the gateway to the Controller to trace-log a message
I_LOG_MESSAGE = 9
# A message that can be used to transfer child sensors
# (from EEPROM routing table) of a repeating node.
I_CHILDREN = 10
# Optional sketch name that can be used to identify sensor in the
# Controller GUI
I_SKETCH_NAME = 11
# Optional sketch version that can be reported to keep track of the version
# of sensor in the Controller GUI.
I_SKETCH_VERSION = 12
# Used by OTA firmware updates. Request for node to reboot.
I_REBOOT = 13
# Send by gateway to controller when startup is complete
I_GATEWAY_READY = 14
# Used between sensors when initialting signing.
I_REQUEST_SIGNING = 15
# Used between sensors when requesting nonce.
I_GET_NONCE = 16
# Used between sensors for nonce response.
I_GET_NONCE_RESPONSE = 17
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
<|code_end|>
. Use current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (classes, functions, or code) from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | MessageType.stream: list(Stream), |
Predict the next line for this snippet: <|code_start|> I_CHILDREN = 10
# Optional sketch name that can be used to identify sensor in the
# Controller GUI
I_SKETCH_NAME = 11
# Optional sketch version that can be reported to keep track of the version
# of sensor in the Controller GUI.
I_SKETCH_VERSION = 12
# Used by OTA firmware updates. Request for node to reboot.
I_REBOOT = 13
# Send by gateway to controller when startup is complete
I_GATEWAY_READY = 14
# Used between sensors when initialting signing.
I_REQUEST_SIGNING = 15
# Used between sensors when requesting nonce.
I_GET_NONCE = 16
# Used between sensors for nonce response.
I_GET_NONCE_RESPONSE = 17
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
VALID_PRESENTATION = {member: str for member in list(Presentation)}
VALID_PRESENTATION.update(
{
<|code_end|>
with the help of current file imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context from other files:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
, which may contain function names, class names, or code. Output only the next line. | Presentation.S_ARDUINO_NODE: is_version, |
Using the snippet: <|code_start|>
def validate_v_rgb(value):
"""Validate a V_RGB value."""
if len(value) != 6:
raise vol.Invalid(f"{value} is not six characters long")
return validate_hex(value)
def validate_v_rgbw(value):
"""Validate a V_RGBW value."""
if len(value) != 8:
raise vol.Invalid(f"{value} is not eight characters long")
return validate_hex(value)
AUTO = "Auto"
MAX = "Max"
MIN = "Min"
NORMAL = "Normal"
# Define this again for version 1.5 to avoid conflicts with version 1.4.
VALID_SETREQ = {
SetReq.V_TEMP: str,
SetReq.V_HUM: str,
SetReq.V_STATUS: vol.In(
[LOGICAL_ZERO, LOGICAL_ONE],
msg=f"value must be either {LOGICAL_ZERO} or {LOGICAL_ONE}",
),
SetReq.V_PERCENTAGE: vol.All(
<|code_end|>
, determine the next line of code. You have imports:
import binascii
import voluptuous as vol
from mysensors.const_14 import ( # noqa: F401
AUTO_CHANGE_OVER,
COOL_ON,
FORECASTS,
HEAT_ON,
LOGICAL_ONE,
LOGICAL_ZERO,
MAX_NODE_ID,
OFF,
VALID_INTERNAL,
VALID_STREAM,
BaseConst,
MessageType,
Stream,
get_handler_registry,
)
from mysensors.validation import is_version, percent_int
and context (class names, function names, or code) available:
# Path: mysensors/const_14.py
# AUTO_CHANGE_OVER = "AutoChangeOver"
#
# COOL_ON = "CoolOn"
#
# FORECASTS = (STABLE, SUNNY, CLOUDY, UNSTABLE, THUNDERSTORM, UNKNOWN)
#
# HEAT_ON = "HeatOn"
#
# LOGICAL_ONE = "1"
#
# LOGICAL_ZERO = "0"
#
# MAX_NODE_ID = 254
#
# OFF = "Off"
#
# VALID_INTERNAL = {
# Internal.I_BATTERY_LEVEL: vol.All(
# percent_int,
# vol.Coerce(str),
# msg=f"value must be integer between {0} and {100}",
# ),
# Internal.I_TIME: vol.Any("", vol.All(vol.Coerce(int), vol.Coerce(str))),
# Internal.I_VERSION: str,
# Internal.I_ID_REQUEST: "",
# Internal.I_ID_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=1, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_INCLUSION_MODE: vol.In([LOGICAL_ZERO, LOGICAL_ONE]),
# Internal.I_CONFIG: vol.Any(
# vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID)),
# CONF_METRIC,
# CONF_IMPERIAL,
# ),
# Internal.I_FIND_PARENT: "",
# Internal.I_FIND_PARENT_RESPONSE: vol.All(
# vol.Coerce(int), vol.Range(min=0, max=MAX_NODE_ID), vol.Coerce(str)
# ),
# Internal.I_LOG_MESSAGE: str,
# Internal.I_CHILDREN: str,
# Internal.I_SKETCH_NAME: str,
# Internal.I_SKETCH_VERSION: str,
# Internal.I_REBOOT: "",
# Internal.I_GATEWAY_READY: str,
# }
#
# VALID_STREAM = {
# Stream.ST_FIRMWARE_CONFIG_REQUEST: str,
# Stream.ST_FIRMWARE_CONFIG_RESPONSE: str,
# Stream.ST_FIRMWARE_REQUEST: str,
# Stream.ST_FIRMWARE_RESPONSE: str,
# Stream.ST_SOUND: str,
# Stream.ST_IMAGE: str,
# }
#
# class BaseConst(IntEnum):
# """MySensors message types."""
#
# def get_handler(self, handler_registry):
# """Return correct message handler."""
# return handler_registry.get(self.name)
#
# def set_handler(self, handler_registry, function):
# """Set message handler for name."""
# handler_registry[self.name] = function
#
# class MessageType(BaseConst):
# """MySensors message types."""
#
# # pylint: disable=invalid-name
# presentation = 0 # sent by a node when presenting attached sensors
# set = 1 # sent from/to sensor when value should be updated
# req = 2 # requests a variable value
# internal = 3 # internal message
# stream = 4 # OTA firmware updates
#
# class Stream(BaseConst):
# """MySensors stream sub-types."""
#
# # Request new FW, payload contains current FW details
# ST_FIRMWARE_CONFIG_REQUEST = 0
# # New FW details to initiate OTA FW update
# ST_FIRMWARE_CONFIG_RESPONSE = 1
# ST_FIRMWARE_REQUEST = 2 # Request FW block
# ST_FIRMWARE_RESPONSE = 3 # Response FW block
# ST_SOUND = 4 # Sound
# ST_IMAGE = 5 # Image
#
# def get_handler_registry():
# """Return handler registry for this version."""
# return HANDLERS
#
# Path: mysensors/validation.py
# _LOGGER = logging.getLogger(__name__)
# def is_version(value):
# def safe_is_version(value):
# def is_battery_level(value):
# def is_heartbeat(value):
. Output only the next line. | percent_int, |
Continue the code snippet: <|code_start|>"""Show how to implement pymysensors async."""
logging.basicConfig(level=logging.DEBUG)
def event(message):
"""Handle mysensors updates."""
print("sensor_update " + str(message.node_id))
LOOP = asyncio.get_event_loop()
LOOP.set_debug(True)
try:
# To create a serial gateway.
<|code_end|>
. Use current file imports:
import asyncio
import logging
from mysensors import mysensors
and context (classes, functions, or code) from other files:
# Path: mysensors/mysensors.py
. Output only the next line. | GATEWAY = mysensors.AsyncSerialGateway( |
Using the snippet: <|code_start|> I_HEARTBEAT = 18 # alias from version 2.0
I_PRESENTATION = 19
I_DISCOVER_REQUEST = 20
I_DISCOVER = 20 # alias from version 2.0
I_DISCOVER_RESPONSE = 21
I_HEARTBEAT_RESPONSE = 22
# Node is locked (reason in string-payload).
I_LOCKED = 23
I_PING = 24 # Ping sent to node, payload incremental hop counter
# In return to ping, sent back to sender, payload incremental hop counter
I_PONG = 25
I_REGISTRATION_REQUEST = 26 # Register request to GW
I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
<|code_end|>
, determine the next line of code. You have imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context (class names, function names, or code) available:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | VALID_INTERNAL = dict(VALID_INTERNAL) |
Predict the next line after this snippet: <|code_start|> I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
VALID_INTERNAL = dict(VALID_INTERNAL)
VALID_INTERNAL.update(
{
Internal.I_SIGNAL_REPORT_REQUEST: str,
Internal.I_SIGNAL_REPORT_REVERSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_SIGNAL_REPORT_RESPONSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_PRE_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_POST_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
}
)
VALID_PAYLOADS = {
<|code_end|>
using the current file's imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and any relevant context from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | MessageType.presentation: VALID_PRESENTATION, |
Here is a snippet: <|code_start|> I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
VALID_INTERNAL = dict(VALID_INTERNAL)
VALID_INTERNAL.update(
{
Internal.I_SIGNAL_REPORT_REQUEST: str,
Internal.I_SIGNAL_REPORT_REVERSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_SIGNAL_REPORT_RESPONSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_PRE_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_POST_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
}
)
VALID_PAYLOADS = {
MessageType.presentation: VALID_PRESENTATION,
<|code_end|>
. Write the next line using the current file imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
, which may include functions, classes, or code. Output only the next line. | MessageType.set: VALID_SETREQ, |
Predict the next line after this snippet: <|code_start|> I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
MessageType.stream: list(Stream),
}
VALID_INTERNAL = dict(VALID_INTERNAL)
VALID_INTERNAL.update(
{
Internal.I_SIGNAL_REPORT_REQUEST: str,
Internal.I_SIGNAL_REPORT_REVERSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_SIGNAL_REPORT_RESPONSE: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_PRE_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
Internal.I_POST_SLEEP_NOTIFICATION: vol.All(vol.Coerce(int), vol.Coerce(str)),
}
)
VALID_PAYLOADS = {
MessageType.presentation: VALID_PRESENTATION,
MessageType.set: VALID_SETREQ,
MessageType.req: {member: "" for member in list(SetReq)},
MessageType.internal: VALID_INTERNAL,
<|code_end|>
using the current file's imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and any relevant context from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | MessageType.stream: VALID_STREAM, |
Given the code snippet: <|code_start|> I_REQUEST_SIGNING = 15 # alias from version 1.5
# Request for a nonce.
I_NONCE_REQUEST = 16
I_GET_NONCE = 16 # alias from version 1.5
# Payload is nonce data.
I_NONCE_RESPONSE = 17
I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
I_HEARTBEAT_REQUEST = 18
I_HEARTBEAT = 18 # alias from version 2.0
I_PRESENTATION = 19
I_DISCOVER_REQUEST = 20
I_DISCOVER = 20 # alias from version 2.0
I_DISCOVER_RESPONSE = 21
I_HEARTBEAT_RESPONSE = 22
# Node is locked (reason in string-payload).
I_LOCKED = 23
I_PING = 24 # Ping sent to node, payload incremental hop counter
# In return to ping, sent back to sender, payload incremental hop counter
I_PONG = 25
I_REGISTRATION_REQUEST = 26 # Register request to GW
I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
<|code_end|>
, generate the next line using the imports in this file:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | MessageType.presentation: list(Presentation), |
Given the following code snippet before the placeholder: <|code_start|> I_REQUEST_SIGNING = 15 # alias from version 1.5
# Request for a nonce.
I_NONCE_REQUEST = 16
I_GET_NONCE = 16 # alias from version 1.5
# Payload is nonce data.
I_NONCE_RESPONSE = 17
I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
I_HEARTBEAT_REQUEST = 18
I_HEARTBEAT = 18 # alias from version 2.0
I_PRESENTATION = 19
I_DISCOVER_REQUEST = 20
I_DISCOVER = 20 # alias from version 2.0
I_DISCOVER_RESPONSE = 21
I_HEARTBEAT_RESPONSE = 22
# Node is locked (reason in string-payload).
I_LOCKED = 23
I_PING = 24 # Ping sent to node, payload incremental hop counter
# In return to ping, sent back to sender, payload incremental hop counter
I_PONG = 25
I_REGISTRATION_REQUEST = 26 # Register request to GW
I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
<|code_end|>
, predict the next line using imports from the current file:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context including class names, function names, and sometimes code from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | MessageType.presentation: list(Presentation), |
Continue the code snippet: <|code_start|> # Request for a nonce.
I_NONCE_REQUEST = 16
I_GET_NONCE = 16 # alias from version 1.5
# Payload is nonce data.
I_NONCE_RESPONSE = 17
I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
I_HEARTBEAT_REQUEST = 18
I_HEARTBEAT = 18 # alias from version 2.0
I_PRESENTATION = 19
I_DISCOVER_REQUEST = 20
I_DISCOVER = 20 # alias from version 2.0
I_DISCOVER_RESPONSE = 21
I_HEARTBEAT_RESPONSE = 22
# Node is locked (reason in string-payload).
I_LOCKED = 23
I_PING = 24 # Ping sent to node, payload incremental hop counter
# In return to ping, sent back to sender, payload incremental hop counter
I_PONG = 25
I_REGISTRATION_REQUEST = 26 # Register request to GW
I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
<|code_end|>
. Use current file imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context (classes, functions, or code) from other files:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
. Output only the next line. | MessageType.set: list(SetReq), |
Given snippet: <|code_start|> # Payload is nonce data.
I_NONCE_RESPONSE = 17
I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
I_HEARTBEAT_REQUEST = 18
I_HEARTBEAT = 18 # alias from version 2.0
I_PRESENTATION = 19
I_DISCOVER_REQUEST = 20
I_DISCOVER = 20 # alias from version 2.0
I_DISCOVER_RESPONSE = 21
I_HEARTBEAT_RESPONSE = 22
# Node is locked (reason in string-payload).
I_LOCKED = 23
I_PING = 24 # Ping sent to node, payload incremental hop counter
# In return to ping, sent back to sender, payload incremental hop counter
I_PONG = 25
I_REGISTRATION_REQUEST = 26 # Register request to GW
I_REGISTRATION_RESPONSE = 27 # Register response from GW
I_DEBUG = 28 # Debug message
I_SIGNAL_REPORT_REQUEST = 29 # Device signal strength request
I_SIGNAL_REPORT_REVERSE = 30 # Internal
I_SIGNAL_REPORT_RESPONSE = 31 # Device signal strength response (RSSI)
I_PRE_SLEEP_NOTIFICATION = 32 # Message sent before node is going to sleep
I_POST_SLEEP_NOTIFICATION = 33 # Message sent after node woke up
VALID_MESSAGE_TYPES = {
MessageType.presentation: list(Presentation),
MessageType.set: list(SetReq),
MessageType.req: list(SetReq),
MessageType.internal: list(Internal),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import voluptuous as vol
from mysensors.const_21 import ( # noqa: F401
MAX_NODE_ID,
VALID_INTERNAL,
VALID_PRESENTATION,
VALID_SETREQ,
VALID_STREAM,
VALID_TYPES,
BaseConst,
MessageType,
Presentation,
SetReq,
Stream,
)
from .handler import HANDLERS_22
and context:
# Path: mysensors/const_21.py
# class Internal(BaseConst):
# I_BATTERY_LEVEL = 0
# I_TIME = 1
# I_VERSION = 2
# I_ID_REQUEST = 3
# I_ID_RESPONSE = 4
# I_INCLUSION_MODE = 5
# I_CONFIG = 6
# I_FIND_PARENT_REQUEST = 7
# I_FIND_PARENT = 7 # alias from version 2.0
# I_FIND_PARENT_RESPONSE = 8
# I_LOG_MESSAGE = 9
# I_CHILDREN = 10
# I_SKETCH_NAME = 11
# I_SKETCH_VERSION = 12
# I_REBOOT = 13
# I_GATEWAY_READY = 14
# I_SIGNING_PRESENTATION = 15
# I_REQUEST_SIGNING = 15 # alias from version 1.5
# I_NONCE_REQUEST = 16
# I_GET_NONCE = 16 # alias from version 1.5
# I_NONCE_RESPONSE = 17
# I_GET_NONCE_RESPONSE = 17 # alias from version 1.5
# I_HEARTBEAT_REQUEST = 18
# I_HEARTBEAT = 18 # alias from version 2.0
# I_PRESENTATION = 19
# I_DISCOVER_REQUEST = 20
# I_DISCOVER = 20 # alias from version 2.0
# I_DISCOVER_RESPONSE = 21
# I_HEARTBEAT_RESPONSE = 22
# I_LOCKED = 23
# I_PING = 24 # Ping sent to node, payload incremental hop counter
# I_PONG = 25
# I_REGISTRATION_REQUEST = 26 # Register request to GW
# I_REGISTRATION_RESPONSE = 27 # Register response from GW
# I_DEBUG = 28 # Debug message
# VALID_MESSAGE_TYPES = {
# MessageType.presentation: list(Presentation),
# MessageType.set: list(SetReq),
# MessageType.req: list(SetReq),
# MessageType.internal: list(Internal),
# MessageType.stream: list(Stream),
# }
# VALID_INTERNAL = dict(VALID_INTERNAL)
# VALID_PAYLOADS = {
# MessageType.presentation: VALID_PRESENTATION,
# MessageType.set: VALID_SETREQ,
# MessageType.req: {member: "" for member in list(SetReq)},
# MessageType.internal: VALID_INTERNAL,
# MessageType.stream: VALID_STREAM,
# }
#
# Path: mysensors/handler.py
# HANDLERS_22 = Registry()
which might include code, classes, or functions. Output only the next line. | MessageType.stream: list(Stream), |
Next line prediction: <|code_start|> sensor.init_smart_sleep_mode()
while sensor.queue:
job = sensor.queue.popleft()
msg.gateway.tasks.add_job(str, job)
for child in sensor.children.values():
new_child_state = sensor.new_state.get(child.id)
if not new_child_state:
continue
for value_type, _ in child.values.items():
new_value = new_child_state.values.get(value_type)
if new_value is None:
continue
msg_to_send = msg.gateway.create_message_to_set_sensor_value(
sensor, child.id, value_type, new_value
)
if msg_to_send is None:
continue
msg.gateway.tasks.add_job(msg_to_send.encode)
@HANDLERS.register("presentation")
def handle_presentation(msg):
"""Process a presentation message."""
<|code_end|>
. Use current file imports:
(import calendar
import logging
import time
from .const import SYSTEM_CHILD_ID
from .util import Registry)
and context including class names, function names, or small code snippets from other files:
# Path: mysensors/const.py
# SYSTEM_CHILD_ID = 255
#
# Path: mysensors/util.py
# class Registry(dict):
# """Registry of items."""
#
# def register(self, name):
# """Return decorator to register item with a specific name."""
#
# def decorator(func):
# """Register decorated function."""
# self[name] = func
# return func
#
# return decorator
. Output only the next line. | if msg.child_id == SYSTEM_CHILD_ID: |
Next line prediction: <|code_start|>"""Start a serial gateway."""
def common_serial_options(func):
"""Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
<|code_end|>
. Use current file imports:
(import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway)
and context including class names, function names, or small code snippets from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | @common_gateway_options |
Given the code snippet: <|code_start|>"""Start a serial gateway."""
def common_serial_options(func):
"""Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def serial_gateway(**kwargs):
"""Start a serial gateway."""
<|code_end|>
, generate the next line using the imports in this file:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway
and context (functions, classes, or occasionally code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | gateway = SerialGateway(event_callback=handle_msg, **kwargs) |
Continue the code snippet: <|code_start|> """Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def serial_gateway(**kwargs):
"""Start a serial gateway."""
gateway = SerialGateway(event_callback=handle_msg, **kwargs)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def async_serial_gateway(**kwargs):
"""Start an async serial gateway."""
gateway = AsyncSerialGateway(event_callback=handle_msg, **kwargs)
<|code_end|>
. Use current file imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway
and context (classes, functions, or code) from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_async_gateway(gateway) |
Using the snippet: <|code_start|>"""Start a serial gateway."""
def common_serial_options(func):
"""Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def serial_gateway(**kwargs):
"""Start a serial gateway."""
gateway = SerialGateway(event_callback=handle_msg, **kwargs)
<|code_end|>
, determine the next line of code. You have imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway
and context (class names, function names, or code) available:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | run_gateway(gateway) |
Predict the next line after this snippet: <|code_start|>def common_serial_options(func):
"""Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def serial_gateway(**kwargs):
"""Start a serial gateway."""
gateway = SerialGateway(event_callback=handle_msg, **kwargs)
run_gateway(gateway)
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def async_serial_gateway(**kwargs):
"""Start an async serial gateway."""
<|code_end|>
using the current file's imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway
and any relevant context from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
. Output only the next line. | gateway = AsyncSerialGateway(event_callback=handle_msg, **kwargs) |
Predict the next line for this snippet: <|code_start|>"""Start a serial gateway."""
def common_serial_options(func):
"""Supply common serial gateway options."""
func = click.option(
"-b",
"--baud",
default=115200,
show_default=True,
type=int,
help="Baud rate of the serial connection.",
)(func)
func = click.option(
"-p", "--port", required=True, help="Serial port of the gateway."
)(func)
return func
@click.command(options_metavar="<options>")
@common_serial_options
@common_gateway_options
def serial_gateway(**kwargs):
"""Start a serial gateway."""
<|code_end|>
with the help of current file imports:
import click
from mysensors.cli.helper import (
common_gateway_options,
handle_msg,
run_async_gateway,
run_gateway,
)
from mysensors.gateway_serial import AsyncSerialGateway, SerialGateway
and context from other files:
# Path: mysensors/cli/helper.py
# def common_gateway_options(func):
# """Supply common gateway options."""
# func = click.option(
# "-v",
# "--protocol_version",
# help="Protocol version of the gateway.",
# default="2.2",
# show_default=True,
# )(func)
# func = click.option(
# "-s", "--persistence", help="Turn on persistence.", is_flag=True
# )(func)
# return func
#
# def handle_msg(msg):
# """Handle mysensors updates."""
# _LOGGER.info("Received message: %s", msg.encode().strip())
#
# def run_async_gateway(gateway, stop_task=None):
# """Run an async gateway."""
# try:
# gateway.tasks.loop.run_until_complete(gateway.start_persistence())
# gateway.tasks.loop.run_until_complete(gateway.start())
# gateway.tasks.loop.run_forever()
# except KeyboardInterrupt:
# gateway.tasks.loop.run_until_complete(gateway.stop())
# if stop_task:
# gateway.tasks.loop.run_until_complete(stop_task)
# gateway.tasks.loop.close()
#
# def run_gateway(gateway):
# """Run a sync gateway."""
# gateway.start_persistence()
# gateway.start()
# try:
# while True:
# time.sleep(0.5)
# except KeyboardInterrupt:
# gateway.stop()
#
# Path: mysensors/gateway_serial.py
# class AsyncSerialGateway(BaseAsyncGateway, BaseSerialGateway):
# """MySensors async serial gateway."""
#
# def __init__(self, *args, loop=None, **kwargs):
# """Set up serial gateway."""
# transport = AsyncTransport(self, async_connect, loop=loop, **kwargs)
# super().__init__(transport, *args, loop=loop, **kwargs)
#
# async def get_gateway_id(self):
# """Return a unique id for the gateway."""
# serial_number = await self.tasks.loop.run_in_executor(
# None, self._get_gateway_id
# )
# return serial_number
#
# class SerialGateway(BaseSyncGateway, BaseSerialGateway):
# """MySensors serial gateway."""
#
# def __init__(self, *args, **kwargs):
# """Set up serial gateway."""
# transport = SyncTransport(self, sync_connect, **kwargs)
# super().__init__(transport, *args, **kwargs)
#
# def get_gateway_id(self):
# """Return a unique id for the gateway."""
# return self._get_gateway_id()
, which may contain function names, class names, or code. Output only the next line. | gateway = SerialGateway(event_callback=handle_msg, **kwargs) |
Based on the snippet: <|code_start|> return
def _message_callback(mqttc, userdata, msg):
"""Run callback for received message."""
callback(msg.topic, msg.payload.decode("utf-8"), msg.qos)
self._mqttc.subscribe(topic, qos)
self._mqttc.message_callback_add(topic, _message_callback)
self.topics[topic] = callback
def start(self):
"""Run the MQTT client."""
print("Start MQTT client")
self._mqttc.loop_start()
def stop(self):
"""Stop the MQTT client."""
print("Stop MQTT client")
self._mqttc.disconnect()
self._mqttc.loop_stop()
def event(message):
"""Run callback for mysensors updates."""
print("sensor_update " + str(message.node_id))
MQTTC = MQTT("localhost", 1883, 60)
MQTTC.start()
<|code_end|>
, predict the immediate next line with the help of imports:
import paho.mqtt.client as mqtt
from mysensors import mysensors
and context (classes, functions, sometimes code) from other files:
# Path: mysensors/mysensors.py
. Output only the next line. | GATEWAY = mysensors.MQTTGateway( |
Predict the next line after this snippet: <|code_start|>"""Example for using pymysensors."""
logging.basicConfig(level=logging.DEBUG)
def event(message):
"""Handle mysensors updates."""
print("sensor_update " + str(message.node_id))
# To create a serial gateway.
<|code_end|>
using the current file's imports:
import logging
from mysensors import mysensors
and any relevant context from other files:
# Path: mysensors/mysensors.py
. Output only the next line. | GATEWAY = mysensors.SerialGateway( |
Given the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestGuesser(unittest.TestCase):
def testGuesser(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pydsl.grammar import RegularExpression
from pydsl.guess import Guesser
and context (functions, classes, or occasionally code) from other files:
# Path: pydsl/grammar/definition.py
# class RegularExpression(Grammar):
# def __init__(self, regexp, flags = 0):
# Grammar.__init__(self, None)
# import re
# retype = type(re.compile('hello, world'))
# if isinstance(regexp, retype):
# self.regexp = regexp
# self.regexpstr = regexp.pattern
# self.flags = regexp.flags
# elif isinstance(regexp, str):
# self.regexpstr = regexp
# self.flags = flags
# self.regexp = re.compile(regexp, flags)
# else:
# raise TypeError
#
# def __hash__(self):
# return hash(self.regexpstr)
#
# def __eq__(self, other):
# try:
# return self.regexpstr == other.regexpstr and self.flags == other.flags
# except AttributeError:
# return False
#
# def __str__(self):
# return self.regexpstr
#
# @property
# def first(self):
# i = 0
# while True:
# if self.regexpstr[i] == "^":
# i+=1
# continue
# if self.regexpstr[i] == "[":
# from .PEG import Choice
# return Choice([String(x) for x in self.regexpstr[i+1:self.regexpstr.find("]")]])
# return String(self.regexpstr[i])
#
# def __getattr__(self, attr):
# return getattr(self.regexp, attr)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# Path: pydsl/guess.py
# class Guesser(object):
# """Returns every grammar and alphabet definition that matches the input"""
# def __init__(self, grammarlist):
# self.grammarlist = grammarlist
#
# def __call__(self, data):
# return [x for x in self.grammarlist if check(x,data)]
. Output only the next line. | cstring = RegularExpression('.*') |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestGuesser(unittest.TestCase):
def testGuesser(self):
cstring = RegularExpression('.*')
g1234 = RegularExpression('1234')
memorylist = [cstring, g1234 ]
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pydsl.grammar import RegularExpression
from pydsl.guess import Guesser
and context from other files:
# Path: pydsl/grammar/definition.py
# class RegularExpression(Grammar):
# def __init__(self, regexp, flags = 0):
# Grammar.__init__(self, None)
# import re
# retype = type(re.compile('hello, world'))
# if isinstance(regexp, retype):
# self.regexp = regexp
# self.regexpstr = regexp.pattern
# self.flags = regexp.flags
# elif isinstance(regexp, str):
# self.regexpstr = regexp
# self.flags = flags
# self.regexp = re.compile(regexp, flags)
# else:
# raise TypeError
#
# def __hash__(self):
# return hash(self.regexpstr)
#
# def __eq__(self, other):
# try:
# return self.regexpstr == other.regexpstr and self.flags == other.flags
# except AttributeError:
# return False
#
# def __str__(self):
# return self.regexpstr
#
# @property
# def first(self):
# i = 0
# while True:
# if self.regexpstr[i] == "^":
# i+=1
# continue
# if self.regexpstr[i] == "[":
# from .PEG import Choice
# return Choice([String(x) for x in self.regexpstr[i+1:self.regexpstr.find("]")]])
# return String(self.regexpstr[i])
#
# def __getattr__(self, attr):
# return getattr(self.regexp, attr)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# Path: pydsl/guess.py
# class Guesser(object):
# """Returns every grammar and alphabet definition that matches the input"""
# def __init__(self, grammarlist):
# self.grammarlist = grammarlist
#
# def __call__(self, data):
# return [x for x in self.grammarlist if check(x,data)]
, which may include functions, classes, or code. Output only the next line. | guesser = Guesser(memorylist) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (C) 2008-2013 Nestor Arocha
"""Test BNF file loading"""
class TestFileLoader(unittest.TestCase):
"""Loading a bnf instance from a .bnf file"""
def testFileLoader(self):
repository = {'integer':RegularExpression("^[0123456789]*$"),
'DayOfMonth':load_python_file('pydsl/contrib/grammar/DayOfMonth.py')}
<|code_end|>
using the current file's imports:
import unittest
from pydsl.file.BNF import load_bnf_file
from pydsl.file.python import load_python_file
from pydsl.grammar.definition import RegularExpression
and any relevant context from other files:
# Path: pydsl/file/BNF.py
# def load_bnf_file(filepath, repository = None):
# """Converts a bnf file into a BNFGrammar instance"""
# linelist = []
# with open(filepath,'r') as mlfile:
# for line in mlfile:
# linelist.append(line)
# return strlist_to_production_set(linelist, repository)
#
# Path: pydsl/file/python.py
# def load_python_file(moduleobject):
# """ Try to create an indexable instance from a module"""
# if isinstance(moduleobject, str):
# moduleobject = load_module(moduleobject)
# if not hasattr(moduleobject, "iclass"):
# raise KeyError("Element" + str(moduleobject))
# iclass = getattr(moduleobject, "iclass")
# mylist = getattr(moduleobject, "__all__", None) or list(filter(lambda x:x[:1] != "_", (dir(moduleobject))))
# mylist.remove('iclass')
# resultdic = {}
# for x in mylist:
# resultdic[x] = getattr(moduleobject, x)
# if iclass == "SymbolGrammar":
# from pydsl.grammar.BNF import BNFGrammar
# return BNFGrammar(**resultdic)
# elif iclass == "PLY":
# from pydsl.grammar.definition import PLYGrammar
# return PLYGrammar(moduleobject)
# elif iclass in ["PythonGrammar"]:
# from pydsl.grammar.definition import PythonGrammar
# return PythonGrammar(resultdic)
# elif iclass == "PythonTranslator":
# return resultdic
# elif iclass == "parsley":
# from pydsl.grammar.parsley import ParsleyGrammar
# return ParsleyGrammar(**resultdic)
# elif iclass == "pyparsing":
# return resultdic['root_symbol']
# else:
# raise ValueError(str(moduleobject))
#
# Path: pydsl/grammar/definition.py
# class RegularExpression(Grammar):
# def __init__(self, regexp, flags = 0):
# Grammar.__init__(self, None)
# import re
# retype = type(re.compile('hello, world'))
# if isinstance(regexp, retype):
# self.regexp = regexp
# self.regexpstr = regexp.pattern
# self.flags = regexp.flags
# elif isinstance(regexp, str):
# self.regexpstr = regexp
# self.flags = flags
# self.regexp = re.compile(regexp, flags)
# else:
# raise TypeError
#
# def __hash__(self):
# return hash(self.regexpstr)
#
# def __eq__(self, other):
# try:
# return self.regexpstr == other.regexpstr and self.flags == other.flags
# except AttributeError:
# return False
#
# def __str__(self):
# return self.regexpstr
#
# @property
# def first(self):
# i = 0
# while True:
# if self.regexpstr[i] == "^":
# i+=1
# continue
# if self.regexpstr[i] == "[":
# from .PEG import Choice
# return Choice([String(x) for x in self.regexpstr[i+1:self.regexpstr.find("]")]])
# return String(self.regexpstr[i])
#
# def __getattr__(self, attr):
# return getattr(self.regexp, attr)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
. Output only the next line. | self.assertTrue(load_bnf_file("pydsl/contrib/grammar/Date.bnf", repository)) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (C) 2008-2013 Nestor Arocha
"""Test BNF file loading"""
class TestFileLoader(unittest.TestCase):
"""Loading a bnf instance from a .bnf file"""
def testFileLoader(self):
repository = {'integer':RegularExpression("^[0123456789]*$"),
<|code_end|>
using the current file's imports:
import unittest
from pydsl.file.BNF import load_bnf_file
from pydsl.file.python import load_python_file
from pydsl.grammar.definition import RegularExpression
and any relevant context from other files:
# Path: pydsl/file/BNF.py
# def load_bnf_file(filepath, repository = None):
# """Converts a bnf file into a BNFGrammar instance"""
# linelist = []
# with open(filepath,'r') as mlfile:
# for line in mlfile:
# linelist.append(line)
# return strlist_to_production_set(linelist, repository)
#
# Path: pydsl/file/python.py
# def load_python_file(moduleobject):
# """ Try to create an indexable instance from a module"""
# if isinstance(moduleobject, str):
# moduleobject = load_module(moduleobject)
# if not hasattr(moduleobject, "iclass"):
# raise KeyError("Element" + str(moduleobject))
# iclass = getattr(moduleobject, "iclass")
# mylist = getattr(moduleobject, "__all__", None) or list(filter(lambda x:x[:1] != "_", (dir(moduleobject))))
# mylist.remove('iclass')
# resultdic = {}
# for x in mylist:
# resultdic[x] = getattr(moduleobject, x)
# if iclass == "SymbolGrammar":
# from pydsl.grammar.BNF import BNFGrammar
# return BNFGrammar(**resultdic)
# elif iclass == "PLY":
# from pydsl.grammar.definition import PLYGrammar
# return PLYGrammar(moduleobject)
# elif iclass in ["PythonGrammar"]:
# from pydsl.grammar.definition import PythonGrammar
# return PythonGrammar(resultdic)
# elif iclass == "PythonTranslator":
# return resultdic
# elif iclass == "parsley":
# from pydsl.grammar.parsley import ParsleyGrammar
# return ParsleyGrammar(**resultdic)
# elif iclass == "pyparsing":
# return resultdic['root_symbol']
# else:
# raise ValueError(str(moduleobject))
#
# Path: pydsl/grammar/definition.py
# class RegularExpression(Grammar):
# def __init__(self, regexp, flags = 0):
# Grammar.__init__(self, None)
# import re
# retype = type(re.compile('hello, world'))
# if isinstance(regexp, retype):
# self.regexp = regexp
# self.regexpstr = regexp.pattern
# self.flags = regexp.flags
# elif isinstance(regexp, str):
# self.regexpstr = regexp
# self.flags = flags
# self.regexp = re.compile(regexp, flags)
# else:
# raise TypeError
#
# def __hash__(self):
# return hash(self.regexpstr)
#
# def __eq__(self, other):
# try:
# return self.regexpstr == other.regexpstr and self.flags == other.flags
# except AttributeError:
# return False
#
# def __str__(self):
# return self.regexpstr
#
# @property
# def first(self):
# i = 0
# while True:
# if self.regexpstr[i] == "^":
# i+=1
# continue
# if self.regexpstr[i] == "[":
# from .PEG import Choice
# return Choice([String(x) for x in self.regexpstr[i+1:self.regexpstr.find("]")]])
# return String(self.regexpstr[i])
#
# def __getattr__(self, attr):
# return getattr(self.regexp, attr)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
. Output only the next line. | 'DayOfMonth':load_python_file('pydsl/contrib/grammar/DayOfMonth.py')} |
Using the snippet: <|code_start|># Needed because Python's regular expression matcher
# uses "first match" not "longest match" rules.
# For example, "C|Cl" matches only the "C" in "Cl"
# The "-" in "-len(symbol)" is a trick to reverse the sort order.
#
# - then by the full symbol, to make it easier for people
# (This is more complicated than needed; it's to show how
# this approach can scale to all 100+ known and named elements)
atom_names = sorted(
mw_table.keys(),
key = lambda symbol: (symbol[0], -len(symbol), symbol))
# Creates a pattern like: Cl|C|H|O|S
atom_pattern = "|".join(atom_names)
# Use a relatively new PLY feature to set the __doc__
# string based on a Python variable.
@TOKEN(atom_pattern)
def t_ATOM(t):
t.value = mw_table[t.value]
return t
def t_DIGITS(t):
r"\d+"
t.value = int(t.value)
return t
def t_error(t):
<|code_end|>
, determine the next line of code. You have imports:
from ply.lex import TOKEN
from pydsl.exceptions import ParseError
and context (class names, function names, or code) available:
# Path: pydsl/exceptions.py
# class ParseError(Exception):
#
# def __init__(self, msg, offset):
# self.msg = msg
# self.offset = offset
#
# def __repr__(self):
# return "ParseError(%r, %r)" % (self.msg, self.offset)
#
# def __str__(self):
# return "%s at position %s" % (self.msg, self.offset + 1)
. Output only the next line. | raise ParseError("unknown character", t.lexpos) |
Using the snippet: <|code_start|> def __eq__(self, anotherset):
"""Tests on itemlist equality"""
if not isinstance(anotherset, LR0ItemSet):
raise TypeError
if len(self.itemlist) != len(anotherset.itemlist):
return False
for element in self.itemlist:
if element not in anotherset.itemlist:
return False
return True
def append_item(self, item):
"""Append new item to set"""
if not isinstance(item, LR0Item):
raise TypeError
self.itemlist.append(item)
def append_transition(self, symbol, targetset):
"""Appends a transition"""
if symbol in self.transitions:
return
self.transitions[symbol] = targetset
def has_transition(self, symbol):
return symbol in self.transitions
def get_transition(self, symbol):
"""gets a transition"""
return self.transitions[symbol]
<|code_end|>
, determine the next line of code. You have imports:
import logging
import copy
from pydsl.parser.parser import BottomUpParser
from pydsl.grammar.symbol import NonTerminalSymbol, TerminalSymbol, EndSymbol, Symbol
from pydsl.grammar.BNF import Production
from pydsl.grammar.definition import Grammar
from collections import Iterable, defaultdict
from pydsl.check import check
and context (class names, function names, or code) available:
# Path: pydsl/parser/parser.py
# class BottomUpParser(Parser):
# """ leaf to root parser"""
# def __init__(self, bnfgrammar):
# self._lexer = lexer_factory(bnfgrammar.alphabet, ascii_encoding)
# super().__init__(bnfgrammar)
#
# Path: pydsl/grammar/symbol.py
# class NonTerminalSymbol(str, Symbol):
# def __init__(self, name):
# Symbol.__init__(self)
#
# def __str__(self):
# return "<NonTS: " + self + ">"
#
# def __hash__(self):
# return str.__hash__(self)
#
# def __eq__(self, other):
# if not isinstance(other, NonTerminalSymbol):
# return False
# return str.__eq__(self,other)
#
# class TerminalSymbol(Symbol):
#
# def __init__(self, gd):
# if not isinstance(gd, Grammar):
# raise TypeError("Expected Grammar, got %s" % (gd,))
# Symbol.__init__(self)
# if not gd:
# raise Exception
# self.gd = gd
#
# def __hash__(self):
# return hash(self.gd)
#
# def check(self, data):# ->bool:
# """Checks if input is recognized as this symbol"""
# return check(self.gd, data)
#
# def first(self):
# return self.gd.first
#
# def __eq__(self, other):
# """StringTerminalSymbol are equals if definition and names are equal"""
# try:
# return self.gd == other.gd
# except AttributeError:
# return False
#
# def __str__(self):
# return "<TS: " + str(self.gd) + ">"
#
# class EndSymbol(Symbol):
# _instance = None
# def __new__(cls):
# if cls._instance is None:
# cls._instance = super(EndSymbol, cls).__new__(cls)
# return cls._instance
#
# def __hash__(self):
# assert(EndSymbol._instance is not None)
# return hash(id(self._instance))
#
# def __eq__(self, other):
# result = isinstance(other, EndSymbol) or EndSymbol == other
# return result
#
# def __bool__(self):
# return False
#
# def __str__(self):
# return "$"
#
# class Symbol(object):
# pass
#
# Path: pydsl/grammar/BNF.py
# class Production(object):
#
# def __init__(self, leftside, rightside):
# # Left side must have at least one non terminal symbol
# for element in rightside:
# if not isinstance(element, Symbol):
# raise TypeError
# self.leftside = tuple(leftside)
# self.rightside = tuple(rightside)
#
# def __str__(self):
# leftstr = " ".join([x for x in self.leftside])
# rightstr = " ".join([str(x) for x in self.rightside])
# return leftstr + "::=" + rightstr
#
# def __eq__(self, other):
# try:
# if len(self.leftside) != len(other.leftside):
# return False
# if len(self.rightside) != len(other.rightside):
# return False
# if not list_eq(self.leftside, other.leftside):
# return False
# if not list_eq(self.rightside, other.rightside):
# return False
# except AttributeError:
# return False
# return True
#
# def __hash__(self):
# return hash(self.leftside) & hash(self.rightside)
#
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
. Output only the next line. | class LR0Parser(BottomUpParser): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""SLR0 implementation"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import copy
from pydsl.parser.parser import BottomUpParser
from pydsl.grammar.symbol import NonTerminalSymbol, TerminalSymbol, EndSymbol, Symbol
from pydsl.grammar.BNF import Production
from pydsl.grammar.definition import Grammar
from collections import Iterable, defaultdict
from pydsl.check import check
and context including class names, function names, and sometimes code from other files:
# Path: pydsl/parser/parser.py
# class BottomUpParser(Parser):
# """ leaf to root parser"""
# def __init__(self, bnfgrammar):
# self._lexer = lexer_factory(bnfgrammar.alphabet, ascii_encoding)
# super().__init__(bnfgrammar)
#
# Path: pydsl/grammar/symbol.py
# class NonTerminalSymbol(str, Symbol):
# def __init__(self, name):
# Symbol.__init__(self)
#
# def __str__(self):
# return "<NonTS: " + self + ">"
#
# def __hash__(self):
# return str.__hash__(self)
#
# def __eq__(self, other):
# if not isinstance(other, NonTerminalSymbol):
# return False
# return str.__eq__(self,other)
#
# class TerminalSymbol(Symbol):
#
# def __init__(self, gd):
# if not isinstance(gd, Grammar):
# raise TypeError("Expected Grammar, got %s" % (gd,))
# Symbol.__init__(self)
# if not gd:
# raise Exception
# self.gd = gd
#
# def __hash__(self):
# return hash(self.gd)
#
# def check(self, data):# ->bool:
# """Checks if input is recognized as this symbol"""
# return check(self.gd, data)
#
# def first(self):
# return self.gd.first
#
# def __eq__(self, other):
# """StringTerminalSymbol are equals if definition and names are equal"""
# try:
# return self.gd == other.gd
# except AttributeError:
# return False
#
# def __str__(self):
# return "<TS: " + str(self.gd) + ">"
#
# class EndSymbol(Symbol):
# _instance = None
# def __new__(cls):
# if cls._instance is None:
# cls._instance = super(EndSymbol, cls).__new__(cls)
# return cls._instance
#
# def __hash__(self):
# assert(EndSymbol._instance is not None)
# return hash(id(self._instance))
#
# def __eq__(self, other):
# result = isinstance(other, EndSymbol) or EndSymbol == other
# return result
#
# def __bool__(self):
# return False
#
# def __str__(self):
# return "$"
#
# class Symbol(object):
# pass
#
# Path: pydsl/grammar/BNF.py
# class Production(object):
#
# def __init__(self, leftside, rightside):
# # Left side must have at least one non terminal symbol
# for element in rightside:
# if not isinstance(element, Symbol):
# raise TypeError
# self.leftside = tuple(leftside)
# self.rightside = tuple(rightside)
#
# def __str__(self):
# leftstr = " ".join([x for x in self.leftside])
# rightstr = " ".join([str(x) for x in self.rightside])
# return leftstr + "::=" + rightstr
#
# def __eq__(self, other):
# try:
# if len(self.leftside) != len(other.leftside):
# return False
# if len(self.rightside) != len(other.rightside):
# return False
# if not list_eq(self.leftside, other.leftside):
# return False
# if not list_eq(self.rightside, other.rightside):
# return False
# except AttributeError:
# return False
# return True
#
# def __hash__(self):
# return hash(self.leftside) & hash(self.rightside)
#
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
. Output only the next line. | Extended_S = NonTerminalSymbol("EI") |
Given the code snippet: <|code_start|> #returns a set of itemsets
while changed:
changed = False
for itemset in result[:]:
for symbol in symbollist:
if itemset.has_transition(symbol): #FIXME a symbol in a LR0item list?
continue
newitemset = item_set_goto(itemset, symbol, productionset)
if newitemset in result and itemset.has_transition(symbol) and itemset.get_transition(symbol) != newitemset:
changed = True
itemset.append_transition(symbol, newitemset)
elif newitemset in result and not itemset.has_transition(symbol):
changed = True
itemset.append_transition(symbol, newitemset)
elif newitemset and newitemset not in result: #avoid adding a duplicated entry
changed = True
result.append(newitemset)
itemset.append_transition(symbol, newitemset)
return result
def _slr_build_parser_table(productionset):
"""SLR method to build parser table"""
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(statesset):
LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset))
for symbol in productionset.getSymbols() + [EndSymbol()]:
numberoptions = 0
for lritem in itemset.itemlist:
#if cursor is before a terminal, and there is a transition to another itemset with the following terminal, append shift rule
<|code_end|>
, generate the next line using the imports in this file:
import logging
import copy
from pydsl.parser.parser import BottomUpParser
from pydsl.grammar.symbol import NonTerminalSymbol, TerminalSymbol, EndSymbol, Symbol
from pydsl.grammar.BNF import Production
from pydsl.grammar.definition import Grammar
from collections import Iterable, defaultdict
from pydsl.check import check
and context (functions, classes, or occasionally code) from other files:
# Path: pydsl/parser/parser.py
# class BottomUpParser(Parser):
# """ leaf to root parser"""
# def __init__(self, bnfgrammar):
# self._lexer = lexer_factory(bnfgrammar.alphabet, ascii_encoding)
# super().__init__(bnfgrammar)
#
# Path: pydsl/grammar/symbol.py
# class NonTerminalSymbol(str, Symbol):
# def __init__(self, name):
# Symbol.__init__(self)
#
# def __str__(self):
# return "<NonTS: " + self + ">"
#
# def __hash__(self):
# return str.__hash__(self)
#
# def __eq__(self, other):
# if not isinstance(other, NonTerminalSymbol):
# return False
# return str.__eq__(self,other)
#
# class TerminalSymbol(Symbol):
#
# def __init__(self, gd):
# if not isinstance(gd, Grammar):
# raise TypeError("Expected Grammar, got %s" % (gd,))
# Symbol.__init__(self)
# if not gd:
# raise Exception
# self.gd = gd
#
# def __hash__(self):
# return hash(self.gd)
#
# def check(self, data):# ->bool:
# """Checks if input is recognized as this symbol"""
# return check(self.gd, data)
#
# def first(self):
# return self.gd.first
#
# def __eq__(self, other):
# """StringTerminalSymbol are equals if definition and names are equal"""
# try:
# return self.gd == other.gd
# except AttributeError:
# return False
#
# def __str__(self):
# return "<TS: " + str(self.gd) + ">"
#
# class EndSymbol(Symbol):
# _instance = None
# def __new__(cls):
# if cls._instance is None:
# cls._instance = super(EndSymbol, cls).__new__(cls)
# return cls._instance
#
# def __hash__(self):
# assert(EndSymbol._instance is not None)
# return hash(id(self._instance))
#
# def __eq__(self, other):
# result = isinstance(other, EndSymbol) or EndSymbol == other
# return result
#
# def __bool__(self):
# return False
#
# def __str__(self):
# return "$"
#
# class Symbol(object):
# pass
#
# Path: pydsl/grammar/BNF.py
# class Production(object):
#
# def __init__(self, leftside, rightside):
# # Left side must have at least one non terminal symbol
# for element in rightside:
# if not isinstance(element, Symbol):
# raise TypeError
# self.leftside = tuple(leftside)
# self.rightside = tuple(rightside)
#
# def __str__(self):
# leftstr = " ".join([x for x in self.leftside])
# rightstr = " ".join([str(x) for x in self.rightside])
# return leftstr + "::=" + rightstr
#
# def __eq__(self, other):
# try:
# if len(self.leftside) != len(other.leftside):
# return False
# if len(self.rightside) != len(other.rightside):
# return False
# if not list_eq(self.leftside, other.leftside):
# return False
# if not list_eq(self.rightside, other.rightside):
# return False
# except AttributeError:
# return False
# return True
#
# def __hash__(self):
# return hash(self.leftside) & hash(self.rightside)
#
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
. Output only the next line. | if isinstance(symbol, TerminalSymbol) and lritem.next_symbol() == symbol and itemset.has_transition(symbol): |
Next line prediction: <|code_start|> # xxx <cursor><nonterminalSymbol> xxx append every rule from self._productionruleset that begins with that NonTerminalSymbol
if not isinstance(itemset, LR0ItemSet):
raise TypeError
resultset = copy.copy(itemset)
changed = True
while changed:
changed = False
for currentitem in resultset.itemlist:
nextsymbol = currentitem.next_symbol()
if nextsymbol is None:
break
for rule in productionset.productions:
newitem = LR0Item(rule)
if rule.leftside[0] == nextsymbol and newitem not in resultset.itemlist:
resultset.append_item(newitem)
changed = True
return resultset
def item_set_goto(itemset, inputsymbol, productionset):
"""returns an itemset
locate inside itemset every element with inputsymbol following cursor
for every located item, append its itemclosure"""
resultset = LR0ItemSet()
for item in itemset.itemlist:
if item.next_symbol() == inputsymbol:
newitem = LR0Item(item.rule, item.position + 1)
resultset.append_item(newitem)
return _build_item_closure(resultset, productionset)
def build_states_sets(productionset):
<|code_end|>
. Use current file imports:
(import logging
import copy
from pydsl.parser.parser import BottomUpParser
from pydsl.grammar.symbol import NonTerminalSymbol, TerminalSymbol, EndSymbol, Symbol
from pydsl.grammar.BNF import Production
from pydsl.grammar.definition import Grammar
from collections import Iterable, defaultdict
from pydsl.check import check)
and context including class names, function names, or small code snippets from other files:
# Path: pydsl/parser/parser.py
# class BottomUpParser(Parser):
# """ leaf to root parser"""
# def __init__(self, bnfgrammar):
# self._lexer = lexer_factory(bnfgrammar.alphabet, ascii_encoding)
# super().__init__(bnfgrammar)
#
# Path: pydsl/grammar/symbol.py
# class NonTerminalSymbol(str, Symbol):
# def __init__(self, name):
# Symbol.__init__(self)
#
# def __str__(self):
# return "<NonTS: " + self + ">"
#
# def __hash__(self):
# return str.__hash__(self)
#
# def __eq__(self, other):
# if not isinstance(other, NonTerminalSymbol):
# return False
# return str.__eq__(self,other)
#
# class TerminalSymbol(Symbol):
#
# def __init__(self, gd):
# if not isinstance(gd, Grammar):
# raise TypeError("Expected Grammar, got %s" % (gd,))
# Symbol.__init__(self)
# if not gd:
# raise Exception
# self.gd = gd
#
# def __hash__(self):
# return hash(self.gd)
#
# def check(self, data):# ->bool:
# """Checks if input is recognized as this symbol"""
# return check(self.gd, data)
#
# def first(self):
# return self.gd.first
#
# def __eq__(self, other):
# """StringTerminalSymbol are equals if definition and names are equal"""
# try:
# return self.gd == other.gd
# except AttributeError:
# return False
#
# def __str__(self):
# return "<TS: " + str(self.gd) + ">"
#
# class EndSymbol(Symbol):
# _instance = None
# def __new__(cls):
# if cls._instance is None:
# cls._instance = super(EndSymbol, cls).__new__(cls)
# return cls._instance
#
# def __hash__(self):
# assert(EndSymbol._instance is not None)
# return hash(id(self._instance))
#
# def __eq__(self, other):
# result = isinstance(other, EndSymbol) or EndSymbol == other
# return result
#
# def __bool__(self):
# return False
#
# def __str__(self):
# return "$"
#
# class Symbol(object):
# pass
#
# Path: pydsl/grammar/BNF.py
# class Production(object):
#
# def __init__(self, leftside, rightside):
# # Left side must have at least one non terminal symbol
# for element in rightside:
# if not isinstance(element, Symbol):
# raise TypeError
# self.leftside = tuple(leftside)
# self.rightside = tuple(rightside)
#
# def __str__(self):
# leftstr = " ".join([x for x in self.leftside])
# rightstr = " ".join([str(x) for x in self.rightside])
# return leftstr + "::=" + rightstr
#
# def __eq__(self, other):
# try:
# if len(self.leftside) != len(other.leftside):
# return False
# if len(self.rightside) != len(other.rightside):
# return False
# if not list_eq(self.leftside, other.leftside):
# return False
# if not list_eq(self.rightside, other.rightside):
# return False
# except AttributeError:
# return False
# return True
#
# def __hash__(self):
# return hash(self.leftside) & hash(self.rightside)
#
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
. Output only the next line. | symbollist = productionset.getSymbols() + [EndSymbol()] |
Given snippet: <|code_start|> if not isinstance(itemset, LR0ItemSet):
raise TypeError
resultset = copy.copy(itemset)
changed = True
while changed:
changed = False
for currentitem in resultset.itemlist:
nextsymbol = currentitem.next_symbol()
if nextsymbol is None:
break
for rule in productionset.productions:
newitem = LR0Item(rule)
if rule.leftside[0] == nextsymbol and newitem not in resultset.itemlist:
resultset.append_item(newitem)
changed = True
return resultset
def item_set_goto(itemset, inputsymbol, productionset):
"""returns an itemset
locate inside itemset every element with inputsymbol following cursor
for every located item, append its itemclosure"""
resultset = LR0ItemSet()
for item in itemset.itemlist:
if item.next_symbol() == inputsymbol:
newitem = LR0Item(item.rule, item.position + 1)
resultset.append_item(newitem)
return _build_item_closure(resultset, productionset)
def build_states_sets(productionset):
symbollist = productionset.getSymbols() + [EndSymbol()]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import copy
from pydsl.parser.parser import BottomUpParser
from pydsl.grammar.symbol import NonTerminalSymbol, TerminalSymbol, EndSymbol, Symbol
from pydsl.grammar.BNF import Production
from pydsl.grammar.definition import Grammar
from collections import Iterable, defaultdict
from pydsl.check import check
and context:
# Path: pydsl/parser/parser.py
# class BottomUpParser(Parser):
# """ leaf to root parser"""
# def __init__(self, bnfgrammar):
# self._lexer = lexer_factory(bnfgrammar.alphabet, ascii_encoding)
# super().__init__(bnfgrammar)
#
# Path: pydsl/grammar/symbol.py
# class NonTerminalSymbol(str, Symbol):
# def __init__(self, name):
# Symbol.__init__(self)
#
# def __str__(self):
# return "<NonTS: " + self + ">"
#
# def __hash__(self):
# return str.__hash__(self)
#
# def __eq__(self, other):
# if not isinstance(other, NonTerminalSymbol):
# return False
# return str.__eq__(self,other)
#
# class TerminalSymbol(Symbol):
#
# def __init__(self, gd):
# if not isinstance(gd, Grammar):
# raise TypeError("Expected Grammar, got %s" % (gd,))
# Symbol.__init__(self)
# if not gd:
# raise Exception
# self.gd = gd
#
# def __hash__(self):
# return hash(self.gd)
#
# def check(self, data):# ->bool:
# """Checks if input is recognized as this symbol"""
# return check(self.gd, data)
#
# def first(self):
# return self.gd.first
#
# def __eq__(self, other):
# """StringTerminalSymbol are equals if definition and names are equal"""
# try:
# return self.gd == other.gd
# except AttributeError:
# return False
#
# def __str__(self):
# return "<TS: " + str(self.gd) + ">"
#
# class EndSymbol(Symbol):
# _instance = None
# def __new__(cls):
# if cls._instance is None:
# cls._instance = super(EndSymbol, cls).__new__(cls)
# return cls._instance
#
# def __hash__(self):
# assert(EndSymbol._instance is not None)
# return hash(id(self._instance))
#
# def __eq__(self, other):
# result = isinstance(other, EndSymbol) or EndSymbol == other
# return result
#
# def __bool__(self):
# return False
#
# def __str__(self):
# return "$"
#
# class Symbol(object):
# pass
#
# Path: pydsl/grammar/BNF.py
# class Production(object):
#
# def __init__(self, leftside, rightside):
# # Left side must have at least one non terminal symbol
# for element in rightside:
# if not isinstance(element, Symbol):
# raise TypeError
# self.leftside = tuple(leftside)
# self.rightside = tuple(rightside)
#
# def __str__(self):
# leftstr = " ".join([x for x in self.leftside])
# rightstr = " ".join([str(x) for x in self.rightside])
# return leftstr + "::=" + rightstr
#
# def __eq__(self, other):
# try:
# if len(self.leftside) != len(other.leftside):
# return False
# if len(self.rightside) != len(other.rightside):
# return False
# if not list_eq(self.leftside, other.leftside):
# return False
# if not list_eq(self.rightside, other.rightside):
# return False
# except AttributeError:
# return False
# return True
#
# def __hash__(self):
# return hash(self.leftside) & hash(self.rightside)
#
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
which might include code, classes, or functions. Output only the next line. | mainproductionrule = Production([Extended_S] , [productionset.initialsymbol, EndSymbol()]) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of pydsl.
#
# pydsl 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.
#
# pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Ptolom"
__copyright__ = "Copyright 2014, Ptolom"
__email__ = "ptolom@hexifact.co.uk"
def load_parsley_grammar_file(filepath, root_rule="expr", repository=None):
with open(filepath,'r') as file:
<|code_end|>
using the current file's imports:
from pydsl.grammar.parsley import ParsleyGrammar
and any relevant context from other files:
# Path: pydsl/grammar/parsley.py
# class ParsleyGrammar(Grammar):
# def __init__(self, rules, root_rule="expr", repository=None):
# import parsley
# Grammar.__init__(self)
# repo=dict(repository or {})
# for key in repo:
# if isinstance(repo[key], Grammar):
# repo[key] = checker_factory(repo[key])
# self.grammar=parsley.makeGrammar(rules, repo)
# self.root_rule=root_rule
. Output only the next line. | return ParsleyGrammar(file.read(), root_rule, repository) |
Next line prediction: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2017, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
def lcs(list1, list2):
differences = difflib.SequenceMatcher(None, list1, list2)
return [x for x in differences.get_matching_blocks()]
def diff_factory(definition):
<|code_end|>
. Use current file imports:
(import logging
import difflib
from pydsl.grammar.PEG import Choice)
and context including class names, function names, or small code snippets from other files:
# Path: pydsl/grammar/PEG.py
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
. Output only the next line. | if isinstance(definition, Choice): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
<|code_end|>
using the current file's imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and any relevant context from other files:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | mygrammar = OneOrMore(String("a")) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
mygrammar = OneOrMore(String("a"))
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context from other files:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | self.assertTrue(isinstance(mygrammar, Grammar)) |
Using the snippet: <|code_start|>#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
mygrammar = OneOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "aa"))
self.assertTrue(check(mygrammar, "aaaa"))
self.assertFalse(check(mygrammar, ""))
self.assertFalse(check(mygrammar, "b"))
def testZeroOrMore(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context (class names, function names, or code) available:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | mygrammar = ZeroOrMore(String("a")) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
which might include code, classes, or functions. Output only the next line. | mygrammar = OneOrMore(String("a")) |
Continue the code snippet: <|code_start|>
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
mygrammar = OneOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "aa"))
self.assertTrue(check(mygrammar, "aaaa"))
self.assertFalse(check(mygrammar, ""))
self.assertFalse(check(mygrammar, "b"))
def testZeroOrMore(self):
mygrammar = ZeroOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "aa"))
self.assertTrue(check(mygrammar, "aaaa"))
self.assertTrue(check(mygrammar, ""))
self.assertFalse(check(mygrammar, "b"))
def testChoice(self):
mygrammar = Choice((String("a"), String("b")))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "b"))
self.assertFalse(check(mygrammar, "c"))
def testNot(self):
<|code_end|>
. Use current file imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context (classes, functions, or code) from other files:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | mygrammar = Not(String("a")) |
Using the snippet: <|code_start|> mygrammar = OneOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "aa"))
self.assertTrue(check(mygrammar, "aaaa"))
self.assertFalse(check(mygrammar, ""))
self.assertFalse(check(mygrammar, "b"))
def testZeroOrMore(self):
mygrammar = ZeroOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "aa"))
self.assertTrue(check(mygrammar, "aaaa"))
self.assertTrue(check(mygrammar, ""))
self.assertFalse(check(mygrammar, "b"))
def testChoice(self):
mygrammar = Choice((String("a"), String("b")))
self.assertTrue(check(mygrammar, "a"))
self.assertTrue(check(mygrammar, "b"))
self.assertFalse(check(mygrammar, "c"))
def testNot(self):
mygrammar = Not(String("a"))
self.assertTrue(isinstance(mygrammar, Not))
def testSequence(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context (class names, function names, or code) available:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | mygrammar = Sequence((String("a"), String("b"))) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
mygrammar = OneOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
<|code_end|>
. Use current file imports:
(import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check)
and context including class names, function names, or small code snippets from other files:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | self.assertEqual(mygrammar.first(), Choice([String("a")])) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""Tests PEG grammars"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestPEG(unittest.TestCase):
def testOneOrMore(self):
mygrammar = OneOrMore(String("a"))
self.assertTrue(isinstance(mygrammar, Grammar))
self.assertEqual(mygrammar.first(), Choice([String("a")]))
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pydsl.grammar.definition import String, Grammar
from pydsl.grammar.PEG import ZeroOrMore, OneOrMore, Not, Sequence, Choice
from pydsl.check import check
and context from other files:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/grammar/PEG.py
# class ZeroOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class OneOrMore(Grammar):
# def __init__(self, element):
# Grammar.__init__(self)
# self.element = element
#
# def first(self):
# return Choice([self.element])
#
# class Not(object):
# def __init__(self, element):
# self.element = element
#
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
#
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | self.assertTrue(check(mygrammar, "a")) |
Given the following code snippet before the placeholder: <|code_start|>
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
class LL1RecursiveDescentParser(TopDownParser):
def get_trees(self, data, showerrors = False): # -> list:
""" returns a list of trees with valid guesses """
if showerrors:
raise NotImplementedError("This parser doesn't implement errors")
self.data = data
self.index = 0
try:
return [self.__aux_parser(self._productionset.initialsymbol)]
except (IndexError, ParseError):
return []
def __aux_parser(self, symbol):
if isinstance(symbol, TerminalSymbol):
LOG.debug("matching symbol %s, data:%s, index:%s" % (symbol,self.data,self.index ))
result= self.match(symbol)
LOG.debug("symbol matched %s" % result)
return result
productions = self._productionset.getProductionsBySide(symbol)
valid_firsts = []
for production in productions:
first_of_production = self._productionset.first_lookup(production.rightside[0])
<|code_end|>
, predict the next line using imports from the current file:
from pydsl.check import check
from pydsl.parser.parser import TopDownParser
from pydsl.tree import ParseTree
from pydsl.exceptions import ParseError
from pydsl.grammar.symbol import TerminalSymbol
import logging
and context including class names, function names, and sometimes code from other files:
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
#
# Path: pydsl/parser/parser.py
# class TopDownParser(Parser):
# """Top down parser like descent parser"""
# def _reduce_terminal(self, symbol, data, showerrors = False):
# from pydsl.check import check
# from pydsl.tree import ParseTree
# result = check(symbol.gd, [data])
# if result:
# return [ParseTree(0,1, symbol , data)]
# if showerrors and not result:
# return [ParseTree(0,1, symbol , data, valid = False)]
# return []
#
# Path: pydsl/tree.py
# class ParseTree(object):
#
# """Stores the position of the original tree"""
#
# def __init__(self, left, right, symbol, content, childlist=None, valid=True):
# self.symbol = symbol
# if not isinstance(left, int) and left is not None:
# raise TypeError
# if not isinstance(right, int) and right is not None:
# raise TypeError
# self.childlist = childlist or []
# self.left = left
# self.right = right
# self.content = content
# self.valid = valid
#
# def __eq__(self, other):
# try:
# return self.left == other.left and self.right == other.right and self.valid == other.valid and self.content == other.content
# except AttributeError:
# return False
#
# def __bool__(self):
# """checks if it is a null result"""
# return self.valid
#
# def __nonzero__(self):
# return self.__bool__()
#
# def shift(self, amount):
# """ shifts position """
# if self.left is not None:
# self.left += amount
# if self.left is not None:
# self.right += amount
#
# def __len__(self):
# if self.right is None and self.left is None:
# return 0
# return self.right - self.left
#
# def append(self, dpr):
# """appends dpr to childlist"""
# self.childlist.append(dpr)
#
# Path: pydsl/exceptions.py
# class ParseError(Exception):
#
# def __init__(self, msg, offset):
# self.msg = msg
# self.offset = offset
#
# def __repr__(self):
# return "ParseError(%r, %r)" % (self.msg, self.offset)
#
# def __str__(self):
# return "%s at position %s" % (self.msg, self.offset + 1)
. Output only the next line. | if check(first_of_production, [self.current]): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""LL family parsers"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
<|code_end|>
, predict the next line using imports from the current file:
from pydsl.check import check
from pydsl.parser.parser import TopDownParser
from pydsl.tree import ParseTree
from pydsl.exceptions import ParseError
from pydsl.grammar.symbol import TerminalSymbol
import logging
and context including class names, function names, and sometimes code from other files:
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
#
# Path: pydsl/parser/parser.py
# class TopDownParser(Parser):
# """Top down parser like descent parser"""
# def _reduce_terminal(self, symbol, data, showerrors = False):
# from pydsl.check import check
# from pydsl.tree import ParseTree
# result = check(symbol.gd, [data])
# if result:
# return [ParseTree(0,1, symbol , data)]
# if showerrors and not result:
# return [ParseTree(0,1, symbol , data, valid = False)]
# return []
#
# Path: pydsl/tree.py
# class ParseTree(object):
#
# """Stores the position of the original tree"""
#
# def __init__(self, left, right, symbol, content, childlist=None, valid=True):
# self.symbol = symbol
# if not isinstance(left, int) and left is not None:
# raise TypeError
# if not isinstance(right, int) and right is not None:
# raise TypeError
# self.childlist = childlist or []
# self.left = left
# self.right = right
# self.content = content
# self.valid = valid
#
# def __eq__(self, other):
# try:
# return self.left == other.left and self.right == other.right and self.valid == other.valid and self.content == other.content
# except AttributeError:
# return False
#
# def __bool__(self):
# """checks if it is a null result"""
# return self.valid
#
# def __nonzero__(self):
# return self.__bool__()
#
# def shift(self, amount):
# """ shifts position """
# if self.left is not None:
# self.left += amount
# if self.left is not None:
# self.right += amount
#
# def __len__(self):
# if self.right is None and self.left is None:
# return 0
# return self.right - self.left
#
# def append(self, dpr):
# """appends dpr to childlist"""
# self.childlist.append(dpr)
#
# Path: pydsl/exceptions.py
# class ParseError(Exception):
#
# def __init__(self, msg, offset):
# self.msg = msg
# self.offset = offset
#
# def __repr__(self):
# return "ParseError(%r, %r)" % (self.msg, self.offset)
#
# def __str__(self):
# return "%s at position %s" % (self.msg, self.offset + 1)
. Output only the next line. | class LL1RecursiveDescentParser(TopDownParser): |
Continue the code snippet: <|code_start|>class LL1RecursiveDescentParser(TopDownParser):
def get_trees(self, data, showerrors = False): # -> list:
""" returns a list of trees with valid guesses """
if showerrors:
raise NotImplementedError("This parser doesn't implement errors")
self.data = data
self.index = 0
try:
return [self.__aux_parser(self._productionset.initialsymbol)]
except (IndexError, ParseError):
return []
def __aux_parser(self, symbol):
if isinstance(symbol, TerminalSymbol):
LOG.debug("matching symbol %s, data:%s, index:%s" % (symbol,self.data,self.index ))
result= self.match(symbol)
LOG.debug("symbol matched %s" % result)
return result
productions = self._productionset.getProductionsBySide(symbol)
valid_firsts = []
for production in productions:
first_of_production = self._productionset.first_lookup(production.rightside[0])
if check(first_of_production, [self.current]):
valid_firsts.append(production)
if len(valid_firsts) != 1:
raise ParseError("Expected only one valid production, found %s" % len(valid_firsts), 0)
childlist = [self.__aux_parser(x) for x in valid_firsts[0].rightside]
left = childlist[0].left
right = childlist[-1].right
content = [x.content for x in childlist]
<|code_end|>
. Use current file imports:
from pydsl.check import check
from pydsl.parser.parser import TopDownParser
from pydsl.tree import ParseTree
from pydsl.exceptions import ParseError
from pydsl.grammar.symbol import TerminalSymbol
import logging
and context (classes, functions, or code) from other files:
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
#
# Path: pydsl/parser/parser.py
# class TopDownParser(Parser):
# """Top down parser like descent parser"""
# def _reduce_terminal(self, symbol, data, showerrors = False):
# from pydsl.check import check
# from pydsl.tree import ParseTree
# result = check(symbol.gd, [data])
# if result:
# return [ParseTree(0,1, symbol , data)]
# if showerrors and not result:
# return [ParseTree(0,1, symbol , data, valid = False)]
# return []
#
# Path: pydsl/tree.py
# class ParseTree(object):
#
# """Stores the position of the original tree"""
#
# def __init__(self, left, right, symbol, content, childlist=None, valid=True):
# self.symbol = symbol
# if not isinstance(left, int) and left is not None:
# raise TypeError
# if not isinstance(right, int) and right is not None:
# raise TypeError
# self.childlist = childlist or []
# self.left = left
# self.right = right
# self.content = content
# self.valid = valid
#
# def __eq__(self, other):
# try:
# return self.left == other.left and self.right == other.right and self.valid == other.valid and self.content == other.content
# except AttributeError:
# return False
#
# def __bool__(self):
# """checks if it is a null result"""
# return self.valid
#
# def __nonzero__(self):
# return self.__bool__()
#
# def shift(self, amount):
# """ shifts position """
# if self.left is not None:
# self.left += amount
# if self.left is not None:
# self.right += amount
#
# def __len__(self):
# if self.right is None and self.left is None:
# return 0
# return self.right - self.left
#
# def append(self, dpr):
# """appends dpr to childlist"""
# self.childlist.append(dpr)
#
# Path: pydsl/exceptions.py
# class ParseError(Exception):
#
# def __init__(self, msg, offset):
# self.msg = msg
# self.offset = offset
#
# def __repr__(self):
# return "ParseError(%r, %r)" % (self.msg, self.offset)
#
# def __str__(self):
# return "%s at position %s" % (self.msg, self.offset + 1)
. Output only the next line. | return ParseTree(left, right, symbol, content, childlist=childlist) |
Predict the next line for this snippet: <|code_start|>#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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
"""LL family parsers"""
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
class LL1RecursiveDescentParser(TopDownParser):
def get_trees(self, data, showerrors = False): # -> list:
""" returns a list of trees with valid guesses """
if showerrors:
raise NotImplementedError("This parser doesn't implement errors")
self.data = data
self.index = 0
try:
return [self.__aux_parser(self._productionset.initialsymbol)]
<|code_end|>
with the help of current file imports:
from pydsl.check import check
from pydsl.parser.parser import TopDownParser
from pydsl.tree import ParseTree
from pydsl.exceptions import ParseError
from pydsl.grammar.symbol import TerminalSymbol
import logging
and context from other files:
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
#
# Path: pydsl/parser/parser.py
# class TopDownParser(Parser):
# """Top down parser like descent parser"""
# def _reduce_terminal(self, symbol, data, showerrors = False):
# from pydsl.check import check
# from pydsl.tree import ParseTree
# result = check(symbol.gd, [data])
# if result:
# return [ParseTree(0,1, symbol , data)]
# if showerrors and not result:
# return [ParseTree(0,1, symbol , data, valid = False)]
# return []
#
# Path: pydsl/tree.py
# class ParseTree(object):
#
# """Stores the position of the original tree"""
#
# def __init__(self, left, right, symbol, content, childlist=None, valid=True):
# self.symbol = symbol
# if not isinstance(left, int) and left is not None:
# raise TypeError
# if not isinstance(right, int) and right is not None:
# raise TypeError
# self.childlist = childlist or []
# self.left = left
# self.right = right
# self.content = content
# self.valid = valid
#
# def __eq__(self, other):
# try:
# return self.left == other.left and self.right == other.right and self.valid == other.valid and self.content == other.content
# except AttributeError:
# return False
#
# def __bool__(self):
# """checks if it is a null result"""
# return self.valid
#
# def __nonzero__(self):
# return self.__bool__()
#
# def shift(self, amount):
# """ shifts position """
# if self.left is not None:
# self.left += amount
# if self.left is not None:
# self.right += amount
#
# def __len__(self):
# if self.right is None and self.left is None:
# return 0
# return self.right - self.left
#
# def append(self, dpr):
# """appends dpr to childlist"""
# self.childlist.append(dpr)
#
# Path: pydsl/exceptions.py
# class ParseError(Exception):
#
# def __init__(self, msg, offset):
# self.msg = msg
# self.offset = offset
#
# def __repr__(self):
# return "ParseError(%r, %r)" % (self.msg, self.offset)
#
# def __str__(self):
# return "%s at position %s" % (self.msg, self.offset + 1)
, which may contain function names, class names, or code. Output only the next line. | except (IndexError, ParseError): |
Using the snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2017, Nestor Arocha"
__email__ = "nesaro@gmail.com"
<|code_end|>
, determine the next line of code. You have imports:
from pydsl.grammar import String
from pydsl.grammar.PEG import Choice
and context (class names, function names, or code) available:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# Path: pydsl/grammar/PEG.py
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
. Output only the next line. | ascii_encoding = Choice([String(chr(x)) for x in range(128)], calculate_base_alphabet=False) |
Given snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2017, Nestor Arocha"
__email__ = "nesaro@gmail.com"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pydsl.grammar import String
from pydsl.grammar.PEG import Choice
and context:
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
#
# Path: pydsl/grammar/PEG.py
# class Choice(set, Grammar):
# """Uses a list of grammar definitions with common base alphabets"""
# def __init__(self, grammarlist, calculate_base_alphabet = True):
# set.__init__(self, grammarlist)
# if calculate_base_alphabet:
# base_alphabet = set()
# for x in self:
# base_alphabet = base_alphabet.union(x.alphabet)
# else:
# base_alphabet = None
# Grammar.__init__(self, base_alphabet)
#
# def __str__(self):
# return str([str(x) for x in self])
#
# def __add__(self, other):
# return Choice([x for x in self] + [x for x in other])
#
# def __hash__(self):
# return hash(tuple(x for x in self))
which might include code, classes, or functions. Output only the next line. | ascii_encoding = Choice([String(chr(x)) for x in range(128)], calculate_base_alphabet=False) |
Continue the code snippet: <|code_start|># along with pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2015, Nestor Arocha"
__email__ = "nesaro@gmail.com"
LOG = logging.getLogger(__name__)
class Symbol(object):
pass
class NonTerminalSymbol(str, Symbol):
def __init__(self, name):
Symbol.__init__(self)
def __str__(self):
return "<NonTS: " + self + ">"
def __hash__(self):
return str.__hash__(self)
def __eq__(self, other):
if not isinstance(other, NonTerminalSymbol):
return False
return str.__eq__(self,other)
class TerminalSymbol(Symbol):
def __init__(self, gd):
<|code_end|>
. Use current file imports:
import logging
from pydsl.grammar.definition import Grammar
from pydsl.check import check
and context (classes, functions, or code) from other files:
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | if not isinstance(gd, Grammar): |
Continue the code snippet: <|code_start|>
class NonTerminalSymbol(str, Symbol):
def __init__(self, name):
Symbol.__init__(self)
def __str__(self):
return "<NonTS: " + self + ">"
def __hash__(self):
return str.__hash__(self)
def __eq__(self, other):
if not isinstance(other, NonTerminalSymbol):
return False
return str.__eq__(self,other)
class TerminalSymbol(Symbol):
def __init__(self, gd):
if not isinstance(gd, Grammar):
raise TypeError("Expected Grammar, got %s" % (gd,))
Symbol.__init__(self)
if not gd:
raise Exception
self.gd = gd
def __hash__(self):
return hash(self.gd)
<|code_end|>
. Use current file imports:
import logging
from pydsl.grammar.definition import Grammar
from pydsl.check import check
and context (classes, functions, or code) from other files:
# Path: pydsl/grammar/definition.py
# class Grammar(object):
#
# def __init__(self, base_alphabet = None):
# self.__base_alphabet = base_alphabet
#
# def enum(self):
# """Generates every possible accepted string"""
# raise NotImplementedError
#
# @property
# def first(self):
# """Alphabet that matches every possible first element.
# the returned value is a subset of the base_alphabet"""
# return self.alphabet
#
# @property
# def minsize(self):# -> int:
# """Returns the minimum size in alphabet tokens"""
# return 0
#
# @property
# def maxsize(self):
# """Returns the max size in alphabet tokens"""
# return None
#
# @property
# def alphabet(self):
# if not self.__base_alphabet:
# raise AttributeError
# return self.__base_alphabet
#
# Path: pydsl/check.py
# def check(definition, data, *args, **kwargs):
# """Checks if the input follows the definition"""
# checker = checker_factory(definition)
# return checker(data, *args, **kwargs)
. Output only the next line. | def check(self, data):# ->bool: |
Given snippet: <|code_start|>__all__ = ['repository', 'iclass', 'root_rule', 'rules']
rules = """digit = anything:x ?(x in '0123456789')
number = <digit+>:ds -> int(ds)
expr = number:left ( '+' number:right -> left + right
| -> left)"""
root_rule="expr"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pydsl.grammar.PEG import Sequence
and context:
# Path: pydsl/grammar/PEG.py
# class Sequence(Grammar, list):
# def __init__(self, *args, **kwargs):
# base_alphabet = kwargs.pop('base_alphabet', None)
# Grammar.__init__(self, base_alphabet)
# list.__init__(self, *args, **kwargs)
# for x in self:
# if not isinstance(x, Grammar):
# raise TypeError(x)
#
# def __hash__(self):
# return hash(tuple(self))
#
# @classmethod
# def from_string(cls, string):
# from .definition import String
# return cls([String(x) for x in string])
which might include code, classes, or functions. Output only the next line. | repository={'string':Sequence.from_string('fas')} |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2020, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestStringEqual(unittest.TestCase):
"""BNF Checker"""
def testBasic(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from pydsl.equal import equal_factory, equal
from pydsl.grammar.definition import String
and context including class names, function names, and sometimes code from other files:
# Path: pydsl/equal.py
# def equal_factory(definition):
# from pydsl.grammar.definition import String
# if isinstance(definition, String):
# return lambda x,y: x==y
#
# def equal(definition, first_element, second_element) -> bool:
# """Compares if the two elements are equal according to the grammar definition"""
# if not check(definition, first_element):
# raise ValueError
# if not check(definition, second_element):
# raise ValueError
# equal_checker = equal_factory(definition)
# return equal_checker(first_element, second_element)
#
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
. Output only the next line. | self.assertTrue(equal(String('a'), 'a', 'a')) |
Given snippet: <|code_start|>#!/usr/bin/env python
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2020, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestStringEqual(unittest.TestCase):
"""BNF Checker"""
def testBasic(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from pydsl.equal import equal_factory, equal
from pydsl.grammar.definition import String
and context:
# Path: pydsl/equal.py
# def equal_factory(definition):
# from pydsl.grammar.definition import String
# if isinstance(definition, String):
# return lambda x,y: x==y
#
# def equal(definition, first_element, second_element) -> bool:
# """Compares if the two elements are equal according to the grammar definition"""
# if not check(definition, first_element):
# raise ValueError
# if not check(definition, second_element):
# raise ValueError
# equal_checker = equal_factory(definition)
# return equal_checker(first_element, second_element)
#
# Path: pydsl/grammar/definition.py
# class String(Grammar, str):
# def __init__(self, string):
# if isinstance(string, list):
# raise TypeError('Attempted to initialize a String with a list %s' % (string, ) )
# Grammar.__init__(self, None)
#
# @property
# def first(self):
# return String(self[0])
#
# def enum(self):
# yield self
#
# @property
# def maxsize(self):
# return len(self)
#
# @property
# def minsize(self):
# return len(self)
#
# @property
# def alphabet(self):
# from pydsl.encoding import ascii_encoding
# return ascii_encoding
which might include code, classes, or functions. Output only the next line. | self.assertTrue(equal(String('a'), 'a', 'a')) |
Next line prediction: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of pydsl.
#
# pydsl 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.
#
# pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Ptolom"
__copyright__ = "Copyright 2014, Ptolom"
__email__ = "ptolom@hexifact.co.uk"
class TestParsley(unittest.TestCase):
def testDate(self):
repository = {'DayOfMonth':load_python_file('pydsl/contrib/grammar/DayOfMonth.py')} #DayOfMonth loaded as checker
G=load_parsley_grammar_file("pydsl/contrib/grammar/Date.parsley", "expr", repository)
C=checker_factory(G)
<|code_end|>
. Use current file imports:
(import unittest
import parsley
import sys
from pydsl.translator import translator_factory
from pydsl.check import checker_factory
from pydsl.file.python import load_python_file
from pydsl.file.parsley import load_parsley_grammar_file)
and context including class names, function names, or small code snippets from other files:
# Path: pydsl/translator.py
# def translator_factory(function):
# from pydsl.grammar.definition import PLYGrammar
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(function, PLYGrammar):
# return PLYTranslator(function)
# if isinstance(function, ParsleyGrammar):
# return ParsleyTranslator(function)
# if isinstance(function, dict):
# return PythonTranslator(**function)
# from pyparsing import OneOrMore
# if isinstance(function, OneOrMore):
# return PyParsingTranslator(function)
# if isinstance(function, PythonTranslator):
# return function
# raise ValueError(function)
#
# Path: pydsl/check.py
# def checker_factory(grammar):
# from pydsl.grammar.BNF import BNFGrammar
# from pydsl.grammar.PEG import Sequence, Choice, OneOrMore, ZeroOrMore
# from pydsl.grammar.definition import PLYGrammar, RegularExpression, String, PythonGrammar, JsonSchema
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(grammar, str) and not isinstance(grammar, String):
# raise TypeError(grammar)
# if isinstance(grammar, BNFGrammar):
# return BNFChecker(grammar)
# elif isinstance(grammar, JsonSchema):
# return JsonSchemaChecker(grammar)
# elif isinstance(grammar, RegularExpression):
# return RegularExpressionChecker(grammar)
# elif isinstance(grammar, PythonGrammar) or isinstance(grammar, dict) and "matchFun" in grammar:
# return PythonChecker(grammar)
# elif isinstance(grammar, PLYGrammar):
# return PLYChecker(grammar)
# elif isinstance(grammar, Choice):
# return ChoiceChecker(grammar)
# elif isinstance(grammar, ParsleyGrammar):
# return ParsleyChecker(grammar)
# elif isinstance(grammar, String):
# return StringChecker(grammar)
# elif isinstance(grammar, Sequence):
# return SequenceChecker(grammar)
# elif isinstance(grammar, OneOrMore):
# return OneOrMoreChecker(grammar)
# elif isinstance(grammar, ZeroOrMore):
# return ZeroOrMoreChecker(grammar)
# elif isinstance(grammar, Iterable):
# return ChoiceChecker(grammar)
# else:
# raise ValueError(grammar)
#
# Path: pydsl/file/python.py
# def load_python_file(moduleobject):
# """ Try to create an indexable instance from a module"""
# if isinstance(moduleobject, str):
# moduleobject = load_module(moduleobject)
# if not hasattr(moduleobject, "iclass"):
# raise KeyError("Element" + str(moduleobject))
# iclass = getattr(moduleobject, "iclass")
# mylist = getattr(moduleobject, "__all__", None) or list(filter(lambda x:x[:1] != "_", (dir(moduleobject))))
# mylist.remove('iclass')
# resultdic = {}
# for x in mylist:
# resultdic[x] = getattr(moduleobject, x)
# if iclass == "SymbolGrammar":
# from pydsl.grammar.BNF import BNFGrammar
# return BNFGrammar(**resultdic)
# elif iclass == "PLY":
# from pydsl.grammar.definition import PLYGrammar
# return PLYGrammar(moduleobject)
# elif iclass in ["PythonGrammar"]:
# from pydsl.grammar.definition import PythonGrammar
# return PythonGrammar(resultdic)
# elif iclass == "PythonTranslator":
# return resultdic
# elif iclass == "parsley":
# from pydsl.grammar.parsley import ParsleyGrammar
# return ParsleyGrammar(**resultdic)
# elif iclass == "pyparsing":
# return resultdic['root_symbol']
# else:
# raise ValueError(str(moduleobject))
. Output only the next line. | T=translator_factory(G) |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of pydsl.
#
# pydsl 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.
#
# pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Ptolom"
__copyright__ = "Copyright 2014, Ptolom"
__email__ = "ptolom@hexifact.co.uk"
class TestParsley(unittest.TestCase):
def testDate(self):
repository = {'DayOfMonth':load_python_file('pydsl/contrib/grammar/DayOfMonth.py')} #DayOfMonth loaded as checker
G=load_parsley_grammar_file("pydsl/contrib/grammar/Date.parsley", "expr", repository)
<|code_end|>
. Write the next line using the current file imports:
import unittest
import parsley
import sys
from pydsl.translator import translator_factory
from pydsl.check import checker_factory
from pydsl.file.python import load_python_file
from pydsl.file.parsley import load_parsley_grammar_file
and context from other files:
# Path: pydsl/translator.py
# def translator_factory(function):
# from pydsl.grammar.definition import PLYGrammar
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(function, PLYGrammar):
# return PLYTranslator(function)
# if isinstance(function, ParsleyGrammar):
# return ParsleyTranslator(function)
# if isinstance(function, dict):
# return PythonTranslator(**function)
# from pyparsing import OneOrMore
# if isinstance(function, OneOrMore):
# return PyParsingTranslator(function)
# if isinstance(function, PythonTranslator):
# return function
# raise ValueError(function)
#
# Path: pydsl/check.py
# def checker_factory(grammar):
# from pydsl.grammar.BNF import BNFGrammar
# from pydsl.grammar.PEG import Sequence, Choice, OneOrMore, ZeroOrMore
# from pydsl.grammar.definition import PLYGrammar, RegularExpression, String, PythonGrammar, JsonSchema
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(grammar, str) and not isinstance(grammar, String):
# raise TypeError(grammar)
# if isinstance(grammar, BNFGrammar):
# return BNFChecker(grammar)
# elif isinstance(grammar, JsonSchema):
# return JsonSchemaChecker(grammar)
# elif isinstance(grammar, RegularExpression):
# return RegularExpressionChecker(grammar)
# elif isinstance(grammar, PythonGrammar) or isinstance(grammar, dict) and "matchFun" in grammar:
# return PythonChecker(grammar)
# elif isinstance(grammar, PLYGrammar):
# return PLYChecker(grammar)
# elif isinstance(grammar, Choice):
# return ChoiceChecker(grammar)
# elif isinstance(grammar, ParsleyGrammar):
# return ParsleyChecker(grammar)
# elif isinstance(grammar, String):
# return StringChecker(grammar)
# elif isinstance(grammar, Sequence):
# return SequenceChecker(grammar)
# elif isinstance(grammar, OneOrMore):
# return OneOrMoreChecker(grammar)
# elif isinstance(grammar, ZeroOrMore):
# return ZeroOrMoreChecker(grammar)
# elif isinstance(grammar, Iterable):
# return ChoiceChecker(grammar)
# else:
# raise ValueError(grammar)
#
# Path: pydsl/file/python.py
# def load_python_file(moduleobject):
# """ Try to create an indexable instance from a module"""
# if isinstance(moduleobject, str):
# moduleobject = load_module(moduleobject)
# if not hasattr(moduleobject, "iclass"):
# raise KeyError("Element" + str(moduleobject))
# iclass = getattr(moduleobject, "iclass")
# mylist = getattr(moduleobject, "__all__", None) or list(filter(lambda x:x[:1] != "_", (dir(moduleobject))))
# mylist.remove('iclass')
# resultdic = {}
# for x in mylist:
# resultdic[x] = getattr(moduleobject, x)
# if iclass == "SymbolGrammar":
# from pydsl.grammar.BNF import BNFGrammar
# return BNFGrammar(**resultdic)
# elif iclass == "PLY":
# from pydsl.grammar.definition import PLYGrammar
# return PLYGrammar(moduleobject)
# elif iclass in ["PythonGrammar"]:
# from pydsl.grammar.definition import PythonGrammar
# return PythonGrammar(resultdic)
# elif iclass == "PythonTranslator":
# return resultdic
# elif iclass == "parsley":
# from pydsl.grammar.parsley import ParsleyGrammar
# return ParsleyGrammar(**resultdic)
# elif iclass == "pyparsing":
# return resultdic['root_symbol']
# else:
# raise ValueError(str(moduleobject))
, which may include functions, classes, or code. Output only the next line. | C=checker_factory(G) |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of pydsl.
#
# pydsl 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.
#
# pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Ptolom"
__copyright__ = "Copyright 2014, Ptolom"
__email__ = "ptolom@hexifact.co.uk"
class TestParsley(unittest.TestCase):
def testDate(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import parsley
import sys
from pydsl.translator import translator_factory
from pydsl.check import checker_factory
from pydsl.file.python import load_python_file
from pydsl.file.parsley import load_parsley_grammar_file
and context from other files:
# Path: pydsl/translator.py
# def translator_factory(function):
# from pydsl.grammar.definition import PLYGrammar
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(function, PLYGrammar):
# return PLYTranslator(function)
# if isinstance(function, ParsleyGrammar):
# return ParsleyTranslator(function)
# if isinstance(function, dict):
# return PythonTranslator(**function)
# from pyparsing import OneOrMore
# if isinstance(function, OneOrMore):
# return PyParsingTranslator(function)
# if isinstance(function, PythonTranslator):
# return function
# raise ValueError(function)
#
# Path: pydsl/check.py
# def checker_factory(grammar):
# from pydsl.grammar.BNF import BNFGrammar
# from pydsl.grammar.PEG import Sequence, Choice, OneOrMore, ZeroOrMore
# from pydsl.grammar.definition import PLYGrammar, RegularExpression, String, PythonGrammar, JsonSchema
# from pydsl.grammar.parsley import ParsleyGrammar
# if isinstance(grammar, str) and not isinstance(grammar, String):
# raise TypeError(grammar)
# if isinstance(grammar, BNFGrammar):
# return BNFChecker(grammar)
# elif isinstance(grammar, JsonSchema):
# return JsonSchemaChecker(grammar)
# elif isinstance(grammar, RegularExpression):
# return RegularExpressionChecker(grammar)
# elif isinstance(grammar, PythonGrammar) or isinstance(grammar, dict) and "matchFun" in grammar:
# return PythonChecker(grammar)
# elif isinstance(grammar, PLYGrammar):
# return PLYChecker(grammar)
# elif isinstance(grammar, Choice):
# return ChoiceChecker(grammar)
# elif isinstance(grammar, ParsleyGrammar):
# return ParsleyChecker(grammar)
# elif isinstance(grammar, String):
# return StringChecker(grammar)
# elif isinstance(grammar, Sequence):
# return SequenceChecker(grammar)
# elif isinstance(grammar, OneOrMore):
# return OneOrMoreChecker(grammar)
# elif isinstance(grammar, ZeroOrMore):
# return ZeroOrMoreChecker(grammar)
# elif isinstance(grammar, Iterable):
# return ChoiceChecker(grammar)
# else:
# raise ValueError(grammar)
#
# Path: pydsl/file/python.py
# def load_python_file(moduleobject):
# """ Try to create an indexable instance from a module"""
# if isinstance(moduleobject, str):
# moduleobject = load_module(moduleobject)
# if not hasattr(moduleobject, "iclass"):
# raise KeyError("Element" + str(moduleobject))
# iclass = getattr(moduleobject, "iclass")
# mylist = getattr(moduleobject, "__all__", None) or list(filter(lambda x:x[:1] != "_", (dir(moduleobject))))
# mylist.remove('iclass')
# resultdic = {}
# for x in mylist:
# resultdic[x] = getattr(moduleobject, x)
# if iclass == "SymbolGrammar":
# from pydsl.grammar.BNF import BNFGrammar
# return BNFGrammar(**resultdic)
# elif iclass == "PLY":
# from pydsl.grammar.definition import PLYGrammar
# return PLYGrammar(moduleobject)
# elif iclass in ["PythonGrammar"]:
# from pydsl.grammar.definition import PythonGrammar
# return PythonGrammar(resultdic)
# elif iclass == "PythonTranslator":
# return resultdic
# elif iclass == "parsley":
# from pydsl.grammar.parsley import ParsleyGrammar
# return ParsleyGrammar(**resultdic)
# elif iclass == "pyparsing":
# return resultdic['root_symbol']
# else:
# raise ValueError(str(moduleobject))
, which may include functions, classes, or code. Output only the next line. | repository = {'DayOfMonth':load_python_file('pydsl/contrib/grammar/DayOfMonth.py')} #DayOfMonth loaded as checker |
Next line prediction: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestCase(unittest.TestCase):
def test_main_case(self):
input_data = "1+2"
<|code_end|>
. Use current file imports:
(import unittest
from pydsl.encoding import ascii_encoding
from pydsl.lex import lexer_factory
from pydsl.parser.LL import LL1RecursiveDescentParser
from pydsl.file.BNF import strlist_to_production_set
from pydsl.parser.backtracing import BacktracingErrorRecursiveDescentParser
from pydsl.grammar.symbol import NonTerminalSymbol
from pydsl.file.BNF import strlist_to_production_set
from pydsl.grammar import RegularExpression
from pydsl.grammar.symbol import NonTerminalSymbol
from pydsl.grammar.PEG import Choice
from pydsl.grammar.definition import String, RegularExpression
from pydsl.encoding import ascii_encoding
from pydsl.lex import lex)
and context including class names, function names, or small code snippets from other files:
# Path: pydsl/encoding.py
#
# Path: pydsl/lex.py
# def lexer_factory(alphabet, base, force_lexer = None):
# if force_lexer is None:
# if alphabet == ascii_encoding:
# force_lexer = "lexer"
# elif isinstance(alphabet, Choice) and alphabet.alphabet == base:
# force_lexer = "brute_force"
# else:
# force_lexer = "general"
#
# if force_lexer == "lexer":
# return ChoiceLexer(alphabet)
# elif force_lexer == "brute_force":
# return ChoiceBruteForceLexer(alphabet)
# elif force_lexer == "general":
# return GeneralLexer(alphabet, base)
# else:
# raise ValueError
#
# Path: pydsl/parser/LL.py
# class LL1RecursiveDescentParser(TopDownParser):
# def get_trees(self, data, showerrors = False): # -> list:
# """ returns a list of trees with valid guesses """
# if showerrors:
# raise NotImplementedError("This parser doesn't implement errors")
# self.data = data
# self.index = 0
# try:
# return [self.__aux_parser(self._productionset.initialsymbol)]
# except (IndexError, ParseError):
# return []
#
# def __aux_parser(self, symbol):
# from pydsl.grammar.symbol import TerminalSymbol
# if isinstance(symbol, TerminalSymbol):
# LOG.debug("matching symbol %s, data:%s, index:%s" % (symbol,self.data,self.index ))
# result= self.match(symbol)
# LOG.debug("symbol matched %s" % result)
# return result
# productions = self._productionset.getProductionsBySide(symbol)
# valid_firsts = []
# for production in productions:
# first_of_production = self._productionset.first_lookup(production.rightside[0])
# if check(first_of_production, [self.current]):
# valid_firsts.append(production)
# if len(valid_firsts) != 1:
# raise ParseError("Expected only one valid production, found %s" % len(valid_firsts), 0)
# childlist = [self.__aux_parser(x) for x in valid_firsts[0].rightside]
# left = childlist[0].left
# right = childlist[-1].right
# content = [x.content for x in childlist]
# return ParseTree(left, right, symbol, content, childlist=childlist)
#
#
# def consume(self):
# self.index +=1
# if self.index > len(self.data):
# raise IndexError("Attempted to consume index %s of data %s" % (self.index, self.data))
#
# @property
# def current(self):
# return self.data[self.index]
#
# def match(self, symbol):
# if symbol.check([self.current]):
# current = self.current
# self.consume()
# return ParseTree(self.index-1, self.index, symbol, current)
# raise Exception("Not matched")
. Output only the next line. | ascii_lexer = lexer_factory(ascii_encoding, None) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#This file is part of pydsl.
#
#pydsl 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.
#
#pydsl 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 pydsl. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Nestor Arocha"
__copyright__ = "Copyright 2008-2014, Nestor Arocha"
__email__ = "nesaro@gmail.com"
class TestCase(unittest.TestCase):
def test_main_case(self):
input_data = "1+2"
<|code_end|>
using the current file's imports:
import unittest
from pydsl.encoding import ascii_encoding
from pydsl.lex import lexer_factory
from pydsl.parser.LL import LL1RecursiveDescentParser
from pydsl.file.BNF import strlist_to_production_set
from pydsl.parser.backtracing import BacktracingErrorRecursiveDescentParser
from pydsl.grammar.symbol import NonTerminalSymbol
from pydsl.file.BNF import strlist_to_production_set
from pydsl.grammar import RegularExpression
from pydsl.grammar.symbol import NonTerminalSymbol
from pydsl.grammar.PEG import Choice
from pydsl.grammar.definition import String, RegularExpression
from pydsl.encoding import ascii_encoding
from pydsl.lex import lex
and any relevant context from other files:
# Path: pydsl/encoding.py
#
# Path: pydsl/lex.py
# def lexer_factory(alphabet, base, force_lexer = None):
# if force_lexer is None:
# if alphabet == ascii_encoding:
# force_lexer = "lexer"
# elif isinstance(alphabet, Choice) and alphabet.alphabet == base:
# force_lexer = "brute_force"
# else:
# force_lexer = "general"
#
# if force_lexer == "lexer":
# return ChoiceLexer(alphabet)
# elif force_lexer == "brute_force":
# return ChoiceBruteForceLexer(alphabet)
# elif force_lexer == "general":
# return GeneralLexer(alphabet, base)
# else:
# raise ValueError
#
# Path: pydsl/parser/LL.py
# class LL1RecursiveDescentParser(TopDownParser):
# def get_trees(self, data, showerrors = False): # -> list:
# """ returns a list of trees with valid guesses """
# if showerrors:
# raise NotImplementedError("This parser doesn't implement errors")
# self.data = data
# self.index = 0
# try:
# return [self.__aux_parser(self._productionset.initialsymbol)]
# except (IndexError, ParseError):
# return []
#
# def __aux_parser(self, symbol):
# from pydsl.grammar.symbol import TerminalSymbol
# if isinstance(symbol, TerminalSymbol):
# LOG.debug("matching symbol %s, data:%s, index:%s" % (symbol,self.data,self.index ))
# result= self.match(symbol)
# LOG.debug("symbol matched %s" % result)
# return result
# productions = self._productionset.getProductionsBySide(symbol)
# valid_firsts = []
# for production in productions:
# first_of_production = self._productionset.first_lookup(production.rightside[0])
# if check(first_of_production, [self.current]):
# valid_firsts.append(production)
# if len(valid_firsts) != 1:
# raise ParseError("Expected only one valid production, found %s" % len(valid_firsts), 0)
# childlist = [self.__aux_parser(x) for x in valid_firsts[0].rightside]
# left = childlist[0].left
# right = childlist[-1].right
# content = [x.content for x in childlist]
# return ParseTree(left, right, symbol, content, childlist=childlist)
#
#
# def consume(self):
# self.index +=1
# if self.index > len(self.data):
# raise IndexError("Attempted to consume index %s of data %s" % (self.index, self.data))
#
# @property
# def current(self):
# return self.data[self.index]
#
# def match(self, symbol):
# if symbol.check([self.current]):
# current = self.current
# self.consume()
# return ParseTree(self.index-1, self.index, symbol, current)
# raise Exception("Not matched")
. Output only the next line. | ascii_lexer = lexer_factory(ascii_encoding, None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.