Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> DEFAULT_NUM_RANDOM_NUMS = 200 #TODO should create a config to set this DEFAULT_BITS = 32 #TODO should create a config to set this # we want to use the same random numbers across all documents we check, that is why I'm using # a thread safe, singleton to generate my random numbers RANDOM_NUMBERS = RNG.instance(DEFAULT_NUM_RANDOM_NUMS, DEFAULT_BITS) <|code_end|> , predict the next line using imports from the current file: from operator import xor from lsh.utils.similarity import compute_positive_hash from lsh.utils.random_number_generator import RNG import heapq and context including class names, function names, and sometimes code from other files: # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/utils/random_number_generator.py # class RNG(object): # """ # Implements a thread safe, random number generator. It generates a list of n random numbers. By default # all numbers are 32bit randomly generated numbers. Users can specify the number of random numbers to be # generated. # # This class is designed such that all threads will have access the same random numbers. This implementation # is specific to the needs of our minhash algorithm. In order to implement n number hash functions we use n # number random generated numbers and XOR those numbers against hashed values. All documents we process need to # use the same random numbers. In order for our LSH implementation to be scalable each thread / instance should # have it's own set of generated numbers and this class enables us to do this. # # """ # # __lock = threading.Lock() # __instance = None # __random_numbers = None # # @classmethod # def instance(cls, n=1, bits=32): # if not cls.__instance and not cls.__random_numbers: # with cls.__lock: # if not cls.__instance and not cls.__random_numbers: # cls.__instance = RNG() # cls.__random_numbers = generate_random_numbers(n, bits) # return cls.__random_numbers . Output only the next line.
def run(shingles_list):
Using the snippet: <|code_start|> DEFAULT_NUM_RANDOM_NUMS = 200 #TODO should create a config to set this DEFAULT_BITS = 32 #TODO should create a config to set this # we want to use the same random numbers across all documents we check, that is why I'm using # a thread safe, singleton to generate my random numbers RANDOM_NUMBERS = RNG.instance(DEFAULT_NUM_RANDOM_NUMS, DEFAULT_BITS) <|code_end|> , determine the next line of code. You have imports: from operator import xor from lsh.utils.similarity import compute_positive_hash from lsh.utils.random_number_generator import RNG import heapq and context (class names, function names, or code) available: # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/utils/random_number_generator.py # class RNG(object): # """ # Implements a thread safe, random number generator. It generates a list of n random numbers. By default # all numbers are 32bit randomly generated numbers. Users can specify the number of random numbers to be # generated. # # This class is designed such that all threads will have access the same random numbers. This implementation # is specific to the needs of our minhash algorithm. In order to implement n number hash functions we use n # number random generated numbers and XOR those numbers against hashed values. All documents we process need to # use the same random numbers. In order for our LSH implementation to be scalable each thread / instance should # have it's own set of generated numbers and this class enables us to do this. # # """ # # __lock = threading.Lock() # __instance = None # __random_numbers = None # # @classmethod # def instance(cls, n=1, bits=32): # if not cls.__instance and not cls.__random_numbers: # with cls.__lock: # if not cls.__instance and not cls.__random_numbers: # cls.__instance = RNG() # cls.__random_numbers = generate_random_numbers(n, bits) # return cls.__random_numbers . Output only the next line.
def run(shingles_list):
Based on the snippet: <|code_start|> DEFAULT_NUM_TWEETS = 600 TWEET_BATCH_SIZE = 40 def get_tweets(duik, old_duik): this_app = AppOpenLSH.get_or_insert('KeyOpenLSH') auth = tweepy.OAuthHandler(this_app.twitter_consumer_key, this_app.twitter_consumer_secret) <|code_end|> , predict the immediate next line with the help of imports: import session, time, datetime, logging, hashlib, json import tweepy import settings, twitter_settings from collections import defaultdict from inspect import currentframe, getframeinfo from tweepy import StreamListener from tweepy.api import API from google.appengine.api import users from google.appengine.ext import ndb from utils.deferred import deferred from models import * from lsh_matrix import * and context (classes, functions, sometimes code) from other files: # Path: utils/deferred.py # class deferred(object): # @staticmethod # def defer(*args, **kwargs): # args1 = args[1:] # args[0](*args1, **kwargs) . Output only the next line.
auth.set_access_token(this_app.twitter_access_token_key, this_app.twitter_access_token_secret)
Next line prediction: <|code_start|> class BlobDataset(Dataset): filename = ndb.StringProperty() blob_key = ndb.BlobKeyProperty() @classmethod def create(cls, blob_key, **kwargs): blob_key = blob_key filename = kwargs.get('filename') rows = kwargs.get('rows', 5) bands = kwargs.get('bands', 40) buckets_per_band = kwargs.get('buckets_per_band', 100) shingle_type = kwargs.get('shingle_type', 'c4') minhash_modulo = kwargs.get('minhash_modulo', 5000) max_hashes = calculate_max_hashes(rows, bands) dataset = cls.get(blob_key) if not dataset: dataset = BlobDataset( filename = filename, blob_key = blob_key, random_seeds = get_random_bits(max_hashes), rows = rows, bands = bands, buckets_per_band = buckets_per_band, shingle_type = shingle_type, <|code_end|> . Use current file imports: (from google.appengine.ext import ndb from repositories.gae.dataset import Dataset from repositories.gae.dataset import calculate_max_hashes, get_random_bits) and context including class names, function names, or small code snippets from other files: # Path: repositories/gae/dataset.py # class Dataset(ndb.Model): # dataset_key = ndb.KeyProperty() # random_seeds = ndb.IntegerProperty(repeated = True) # buckets = ndb.IntegerProperty(repeated = True) # # # The following parameters can be tuned via the Datastore Admin Interface # rows = ndb.IntegerProperty() # bands = ndb.IntegerProperty() # buckets_per_band = ndb.IntegerProperty() # shingle_type = ndb.StringProperty(choices=('w', 'c4')) # minhash_modulo = ndb.IntegerProperty() # # @classmethod # def create(cls, dataset_key, **kwargs): # # rows = kwargs.get('rows', 5) # bands = kwargs.get('bands', 40) # buckets_per_band = kwargs.get('buckets_per_band', 100) # shingle_type = kwargs.get('shingle_type', 'c4') # minhash_modulo = kwargs.get('minhash_modulo', 5000) # dataset_key = dataset_key # # max_hashes = calculate_max_hashes(rows, bands) # dataset = cls.get(dataset_key) # # if not dataset: # dataset = Dataset( # dataset_key = dataset_key, # random_seeds = get_random_bits(max_hashes), # rows = rows, # bands = bands, # buckets_per_band = buckets_per_band, # shingle_type = shingle_type, # minhash_modulo = minhash_modulo, # ) # # return dataset.put() # # @classmethod # def get(cls, key): # return Dataset.query(cls.dataset_key == key).get() # # Path: repositories/gae/dataset.py # def calculate_max_hashes(rows, bands): # return rows * bands # # def get_random_bits(max_hashes): # return [random.getrandbits(get_max_bits()) for _ in xrange(max_hashes)] . Output only the next line.
minhash_modulo = minhash_modulo)
Next line prediction: <|code_start|> class BlobDataset(Dataset): filename = ndb.StringProperty() blob_key = ndb.BlobKeyProperty() @classmethod def create(cls, blob_key, **kwargs): blob_key = blob_key filename = kwargs.get('filename') rows = kwargs.get('rows', 5) bands = kwargs.get('bands', 40) <|code_end|> . Use current file imports: (from google.appengine.ext import ndb from repositories.gae.dataset import Dataset from repositories.gae.dataset import calculate_max_hashes, get_random_bits) and context including class names, function names, or small code snippets from other files: # Path: repositories/gae/dataset.py # class Dataset(ndb.Model): # dataset_key = ndb.KeyProperty() # random_seeds = ndb.IntegerProperty(repeated = True) # buckets = ndb.IntegerProperty(repeated = True) # # # The following parameters can be tuned via the Datastore Admin Interface # rows = ndb.IntegerProperty() # bands = ndb.IntegerProperty() # buckets_per_band = ndb.IntegerProperty() # shingle_type = ndb.StringProperty(choices=('w', 'c4')) # minhash_modulo = ndb.IntegerProperty() # # @classmethod # def create(cls, dataset_key, **kwargs): # # rows = kwargs.get('rows', 5) # bands = kwargs.get('bands', 40) # buckets_per_band = kwargs.get('buckets_per_band', 100) # shingle_type = kwargs.get('shingle_type', 'c4') # minhash_modulo = kwargs.get('minhash_modulo', 5000) # dataset_key = dataset_key # # max_hashes = calculate_max_hashes(rows, bands) # dataset = cls.get(dataset_key) # # if not dataset: # dataset = Dataset( # dataset_key = dataset_key, # random_seeds = get_random_bits(max_hashes), # rows = rows, # bands = bands, # buckets_per_band = buckets_per_band, # shingle_type = shingle_type, # minhash_modulo = minhash_modulo, # ) # # return dataset.put() # # @classmethod # def get(cls, key): # return Dataset.query(cls.dataset_key == key).get() # # Path: repositories/gae/dataset.py # def calculate_max_hashes(rows, bands): # return rows * bands # # def get_random_bits(max_hashes): # return [random.getrandbits(get_max_bits()) for _ in xrange(max_hashes)] . Output only the next line.
buckets_per_band = kwargs.get('buckets_per_band', 100)
Given the code snippet: <|code_start|> class BlobDataset(Dataset): filename = ndb.StringProperty() blob_key = ndb.BlobKeyProperty() @classmethod def create(cls, blob_key, **kwargs): blob_key = blob_key filename = kwargs.get('filename') rows = kwargs.get('rows', 5) bands = kwargs.get('bands', 40) buckets_per_band = kwargs.get('buckets_per_band', 100) <|code_end|> , generate the next line using the imports in this file: from google.appengine.ext import ndb from repositories.gae.dataset import Dataset from repositories.gae.dataset import calculate_max_hashes, get_random_bits and context (functions, classes, or occasionally code) from other files: # Path: repositories/gae/dataset.py # class Dataset(ndb.Model): # dataset_key = ndb.KeyProperty() # random_seeds = ndb.IntegerProperty(repeated = True) # buckets = ndb.IntegerProperty(repeated = True) # # # The following parameters can be tuned via the Datastore Admin Interface # rows = ndb.IntegerProperty() # bands = ndb.IntegerProperty() # buckets_per_band = ndb.IntegerProperty() # shingle_type = ndb.StringProperty(choices=('w', 'c4')) # minhash_modulo = ndb.IntegerProperty() # # @classmethod # def create(cls, dataset_key, **kwargs): # # rows = kwargs.get('rows', 5) # bands = kwargs.get('bands', 40) # buckets_per_band = kwargs.get('buckets_per_band', 100) # shingle_type = kwargs.get('shingle_type', 'c4') # minhash_modulo = kwargs.get('minhash_modulo', 5000) # dataset_key = dataset_key # # max_hashes = calculate_max_hashes(rows, bands) # dataset = cls.get(dataset_key) # # if not dataset: # dataset = Dataset( # dataset_key = dataset_key, # random_seeds = get_random_bits(max_hashes), # rows = rows, # bands = bands, # buckets_per_band = buckets_per_band, # shingle_type = shingle_type, # minhash_modulo = minhash_modulo, # ) # # return dataset.put() # # @classmethod # def get(cls, key): # return Dataset.query(cls.dataset_key == key).get() # # Path: repositories/gae/dataset.py # def calculate_max_hashes(rows, bands): # return rows * bands # # def get_random_bits(max_hashes): # return [random.getrandbits(get_max_bits()) for _ in xrange(max_hashes)] . Output only the next line.
shingle_type = kwargs.get('shingle_type', 'c4')
Using the snippet: <|code_start|> upload_url = blobstore.create_upload_url("/test_upload_blob") self.response.out.write(self.template_env.get_template("blobs.html").render( {"username": username, "items": items, "length": length, "upload_url": upload_url, "top_form_url": "test_db_datastore"})) def post(self): filename = self.request.get("filename") blob_key = self.request.get("blobkey") ds_key = self.request.get("ds_key") output_link = self.request.get("output_link") if self.request.get("run_lsh"): taskqueue.add(url='/test_zip_worker', params={'filename': filename, 'blob_key': blob_key, }) else: pass time.sleep(1) self.get() class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads("file") blob_info = upload_files[0] <|code_end|> , determine the next line of code. You have imports: import sys, re, math, random, struct, zipfile, json import webapp2, hashlib, urllib import logging, inspect import operator, datetime, time import jinja2 from collections import defaultdict from google.appengine.api import taskqueue from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext import ndb from google.appengine.api import users from lsh_matrix import * from serial import lsh_zipfile, PeerbeltLine from lsh.utils.similarity import compute_positive_hash from lsh.shingles.shingles import _get_list_of_shingles and context (class names, function names, or code) available: # Path: serial.py # def lsh_zipfile(LineFormat, zip_reader, source, filename, file_key = ''): # infolist = zip_reader.infolist() # dummydoc = MatrixRow.create() # force the creation of the table # dataset = Matrix.create(source, filename, file_key) # force the creation of the table and filling it with a row # dataset = Matrix.find(dataset.ds_key) # start = time.time() # all_stats = defaultdict(float) # new_docs_count = 0 # docs_cache = Cache(max_size = 15) # for info in infolist: # with zip_reader.open(info) as text_reader: # logging.debug('Reading file %s', info.filename) # deferred.defer(lsh_text, LineFormat, zip_reader, filename, matrix_key = dataset.ds_key, text_filename = info.filename) # return # # class PeerbeltLine(object): # text_file_pattern = re.compile('^{"id":"([^"]*):html","text":"(.*)}', flags=re.DOTALL) # @staticmethod # def parse(line): # found_pattern = PeerbeltLine.text_file_pattern.search(line) # doc_id = found_pattern.group(1) # text = found_pattern.group(2) # udata = text.decode("utf-8") # text = udata.encode("ascii","ignore") # text = text.replace('\\n',' ').replace('\\t',' ').replace("'", "''") # soup = BeautifulSoup(text.replace('\\n',' ')) # [s.extract() for s in soup(['script', 'style'])] # text = soup.get_text(separator=' ', strip=True) # text = symbols.sub(' ', text.lower()) # text = ' '.join(text.split()) # return doc_id, text # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] . Output only the next line.
blob_key = blob_info.key()
Here is a snippet: <|code_start|> time.sleep(1) self.get() class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads("file") blob_info = upload_files[0] blob_key = blob_info.key() logging.info('filename %s key %s', blob_info.filename, blob_key) Matrix.create('gae_test', blob_info.filename, file_key = blob_key) time.sleep(1) self.redirect('/test_db_datastore') class ZipWorker(webapp2.RequestHandler): def post(self): blob_key = self.request.get('blob_key') filename = self.request.get("filename") blob_reader = blobstore.BlobReader(blob_key) zip_reader = zipfile.ZipFile(blob_reader) lsh_zipfile(PeerbeltLine, zip_reader, 'gae_test', filename, file_key = blob_key) return def all(cls): cls._initialize() items = [result for result in cls._instances[cls].StorageProxy.query().fetch()] for item in items: valnames = vars(item)['_values'].keys() logging.info('vals %s', valnames) attributes = {} <|code_end|> . Write the next line using the current file imports: import sys, re, math, random, struct, zipfile, json import webapp2, hashlib, urllib import logging, inspect import operator, datetime, time import jinja2 from collections import defaultdict from google.appengine.api import taskqueue from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext import ndb from google.appengine.api import users from lsh_matrix import * from serial import lsh_zipfile, PeerbeltLine from lsh.utils.similarity import compute_positive_hash from lsh.shingles.shingles import _get_list_of_shingles and context from other files: # Path: serial.py # def lsh_zipfile(LineFormat, zip_reader, source, filename, file_key = ''): # infolist = zip_reader.infolist() # dummydoc = MatrixRow.create() # force the creation of the table # dataset = Matrix.create(source, filename, file_key) # force the creation of the table and filling it with a row # dataset = Matrix.find(dataset.ds_key) # start = time.time() # all_stats = defaultdict(float) # new_docs_count = 0 # docs_cache = Cache(max_size = 15) # for info in infolist: # with zip_reader.open(info) as text_reader: # logging.debug('Reading file %s', info.filename) # deferred.defer(lsh_text, LineFormat, zip_reader, filename, matrix_key = dataset.ds_key, text_filename = info.filename) # return # # class PeerbeltLine(object): # text_file_pattern = re.compile('^{"id":"([^"]*):html","text":"(.*)}', flags=re.DOTALL) # @staticmethod # def parse(line): # found_pattern = PeerbeltLine.text_file_pattern.search(line) # doc_id = found_pattern.group(1) # text = found_pattern.group(2) # udata = text.decode("utf-8") # text = udata.encode("ascii","ignore") # text = text.replace('\\n',' ').replace('\\t',' ').replace("'", "''") # soup = BeautifulSoup(text.replace('\\n',' ')) # [s.extract() for s in soup(['script', 'style'])] # text = soup.get_text(separator=' ', strip=True) # text = symbols.sub(' ', text.lower()) # text = ' '.join(text.split()) # return doc_id, text # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] , which may include functions, classes, or code. Output only the next line.
for name in valnames:
Given the following code snippet before the placeholder: <|code_start|> class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads("file") blob_info = upload_files[0] blob_key = blob_info.key() <|code_end|> , predict the next line using imports from the current file: import logging from repositories.gae.blob_dataset import BlobDataset from google.appengine.ext.webapp import blobstore_handlers and context including class names, function names, and sometimes code from other files: # Path: repositories/gae/blob_dataset.py # class BlobDataset(Dataset): # # filename = ndb.StringProperty() # blob_key = ndb.BlobKeyProperty() # # @classmethod # def create(cls, blob_key, **kwargs): # # blob_key = blob_key # filename = kwargs.get('filename') # rows = kwargs.get('rows', 5) # bands = kwargs.get('bands', 40) # buckets_per_band = kwargs.get('buckets_per_band', 100) # shingle_type = kwargs.get('shingle_type', 'c4') # minhash_modulo = kwargs.get('minhash_modulo', 5000) # # max_hashes = calculate_max_hashes(rows, bands) # dataset = cls.get(blob_key) # # if not dataset: # dataset = BlobDataset( # filename = filename, # blob_key = blob_key, # random_seeds = get_random_bits(max_hashes), # rows = rows, # bands = bands, # buckets_per_band = buckets_per_band, # shingle_type = shingle_type, # minhash_modulo = minhash_modulo) # else: # dataset.filename = filename # # return dataset.put() # # @classmethod # def get(cls, key): # return Dataset.query(cls.blob_key == key).get() . Output only the next line.
logging.info('(REFACTORED) filename %s key %s', blob_info.filename, blob_key)
Continue the code snippet: <|code_start|>dir_path = os.path.dirname([p for p in sys.path if p][0]) sys.path.insert(0, 'libs') LOG_FILENAME = dir_path+'/CassDriver.log' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) shingle_cache = Cache(max_size = 1) max_bits = 32 max_mask = 2**max_bits - 1 text_file_pattern = re.compile('^{"id":"([^"]*):html","text":"(.*)}', flags=re.DOTALL) symbols = re.compile('\W+') class UnableToCreateTable(Exception): pass <|code_end|> . Use current file imports: import sys, os, re, time, math, random, struct, zipfile, operator, csv, hashlib, uuid, pdb import logging from collections import defaultdict from lsh.shingles.shingles import _get_list_of_shingles from lsh.utils.similarity import compute_positive_hash from bs4 import BeautifulSoup from cassandra.cluster import Cluster from cassandra.query import SimpleStatement, dict_factory from cassandra import ConsistencyLevel, InvalidRequest from utils.procache import Cache from utils.levenshtein import levenshtein and context (classes, functions, or code) from other files: # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: utils/procache.py # class Cache(): # """ # In process memory cache. Not thread safe. # Usage: # # cache = Cache(max_size=5) # cache.set("python", "perfect", timeout=10) # cache.get("python") # >>> perfect # time.sleep(11) # cache.get("python") # >>> None # cache.get("python", "perfect anyway") # >>> perfect anyway # cache.clear() # """ # def __init__(self, max_size=1000, timeout=None): # self._store = OrderedDict() # self._max_size = max_size # self._timeout = timeout # # def set(self, key, value, timeout=None): # self._check_limit() # if not timeout: # timeout = self._timeout # if timeout: # timeout = time.time() + timeout # self._store[key] = (value, timeout) # # def get(self, key, default=None): # data = self._store.get(key) # if not data: # return default # value, expire = data # if expire and time.time() > expire: # del self._store[key] # return default # return value # # def _check_limit(self): # """ # check if current cache size exceeds maximum cache # size and pop the oldest item in this case # """ # if len(self._store) >= self._max_size: # self._store.popitem(last=False) # # def clear(self): # """ # clear all cache # """ # self._store = OrderedDict() # # def keys(self): # return self._store.keys() # # Path: utils/levenshtein.py # def levenshtein(a,b): # "Calculates the Levenshtein distance between a and b." # n, m = len(a), len(b) # if n > m: # # Make sure n <= m, to use O(min(n,m)) space # a,b = b,a # n,m = m,n # # current = range(n+1) # for i in range(1,m+1): # previous, current = current, [i]+[0]*n # for j in range(1,n+1): # add, delete = previous[j]+1, current[j-1]+1 # change = previous[j-1] # if a[j-1] != b[i-1]: # change = change + 1 # current[j] = min(add, delete, change) # # return current[n] . Output only the next line.
class UnknownException(Exception):
Given the following code snippet before the placeholder: <|code_start|>dir_path = os.path.dirname([p for p in sys.path if p][0]) sys.path.insert(0, 'libs') LOG_FILENAME = dir_path+'/CassDriver.log' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) shingle_cache = Cache(max_size = 1) max_bits = 32 max_mask = 2**max_bits - 1 text_file_pattern = re.compile('^{"id":"([^"]*):html","text":"(.*)}', flags=re.DOTALL) symbols = re.compile('\W+') class UnableToCreateTable(Exception): pass class UnknownException(Exception): pass <|code_end|> , predict the next line using imports from the current file: import sys, os, re, time, math, random, struct, zipfile, operator, csv, hashlib, uuid, pdb import logging from collections import defaultdict from lsh.shingles.shingles import _get_list_of_shingles from lsh.utils.similarity import compute_positive_hash from bs4 import BeautifulSoup from cassandra.cluster import Cluster from cassandra.query import SimpleStatement, dict_factory from cassandra import ConsistencyLevel, InvalidRequest from utils.procache import Cache from utils.levenshtein import levenshtein and context including class names, function names, and sometimes code from other files: # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: utils/procache.py # class Cache(): # """ # In process memory cache. Not thread safe. # Usage: # # cache = Cache(max_size=5) # cache.set("python", "perfect", timeout=10) # cache.get("python") # >>> perfect # time.sleep(11) # cache.get("python") # >>> None # cache.get("python", "perfect anyway") # >>> perfect anyway # cache.clear() # """ # def __init__(self, max_size=1000, timeout=None): # self._store = OrderedDict() # self._max_size = max_size # self._timeout = timeout # # def set(self, key, value, timeout=None): # self._check_limit() # if not timeout: # timeout = self._timeout # if timeout: # timeout = time.time() + timeout # self._store[key] = (value, timeout) # # def get(self, key, default=None): # data = self._store.get(key) # if not data: # return default # value, expire = data # if expire and time.time() > expire: # del self._store[key] # return default # return value # # def _check_limit(self): # """ # check if current cache size exceeds maximum cache # size and pop the oldest item in this case # """ # if len(self._store) >= self._max_size: # self._store.popitem(last=False) # # def clear(self): # """ # clear all cache # """ # self._store = OrderedDict() # # def keys(self): # return self._store.keys() # # Path: utils/levenshtein.py # def levenshtein(a,b): # "Calculates the Levenshtein distance between a and b." # n, m = len(a), len(b) # if n > m: # # Make sure n <= m, to use O(min(n,m)) space # a,b = b,a # n,m = m,n # # current = range(n+1) # for i in range(1,m+1): # previous, current = current, [i]+[0]*n # for j in range(1,n+1): # add, delete = previous[j]+1, current[j-1]+1 # change = previous[j-1] # if a[j-1] != b[i-1]: # change = change + 1 # current[j] = min(add, delete, change) # # return current[n] . Output only the next line.
class CassandraInt(object):
Continue the code snippet: <|code_start|>dir_path = os.path.dirname([p for p in sys.path if p][0]) sys.path.insert(0, 'libs') LOG_FILENAME = dir_path+'/CassDriver.log' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) shingle_cache = Cache(max_size = 1) max_bits = 32 max_mask = 2**max_bits - 1 <|code_end|> . Use current file imports: import sys, os, re, time, math, random, struct, zipfile, operator, csv, hashlib, uuid, pdb import logging from collections import defaultdict from lsh.shingles.shingles import _get_list_of_shingles from lsh.utils.similarity import compute_positive_hash from bs4 import BeautifulSoup from cassandra.cluster import Cluster from cassandra.query import SimpleStatement, dict_factory from cassandra import ConsistencyLevel, InvalidRequest from utils.procache import Cache from utils.levenshtein import levenshtein and context (classes, functions, or code) from other files: # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: utils/procache.py # class Cache(): # """ # In process memory cache. Not thread safe. # Usage: # # cache = Cache(max_size=5) # cache.set("python", "perfect", timeout=10) # cache.get("python") # >>> perfect # time.sleep(11) # cache.get("python") # >>> None # cache.get("python", "perfect anyway") # >>> perfect anyway # cache.clear() # """ # def __init__(self, max_size=1000, timeout=None): # self._store = OrderedDict() # self._max_size = max_size # self._timeout = timeout # # def set(self, key, value, timeout=None): # self._check_limit() # if not timeout: # timeout = self._timeout # if timeout: # timeout = time.time() + timeout # self._store[key] = (value, timeout) # # def get(self, key, default=None): # data = self._store.get(key) # if not data: # return default # value, expire = data # if expire and time.time() > expire: # del self._store[key] # return default # return value # # def _check_limit(self): # """ # check if current cache size exceeds maximum cache # size and pop the oldest item in this case # """ # if len(self._store) >= self._max_size: # self._store.popitem(last=False) # # def clear(self): # """ # clear all cache # """ # self._store = OrderedDict() # # def keys(self): # return self._store.keys() # # Path: utils/levenshtein.py # def levenshtein(a,b): # "Calculates the Levenshtein distance between a and b." # n, m = len(a), len(b) # if n > m: # # Make sure n <= m, to use O(min(n,m)) space # a,b = b,a # n,m = m,n # # current = range(n+1) # for i in range(1,m+1): # previous, current = current, [i]+[0]*n # for j in range(1,n+1): # add, delete = previous[j]+1, current[j-1]+1 # change = previous[j-1] # if a[j-1] != b[i-1]: # change = change + 1 # current[j] = min(add, delete, change) # # return current[n] . Output only the next line.
text_file_pattern = re.compile('^{"id":"([^"]*):html","text":"(.*)}', flags=re.DOTALL)
Predict the next line after this snippet: <|code_start|> # this will be the number of signatures in a vector to be hashed self.num_rows_per_band = rows_per_band #should be thread safe if one instance of this class is used by threads in a pool for example #we may need to make a centralized resource to implement this...for now this is good enough. self.bands = self._create_band_dicts() #note, the default settings give you a threshold ~.74 if threshold == 0.0: self.threshold = self._calculate_threshold() else: self.threshold = threshold def run(self, document_to_examine): #step 1: get document hash signature list signatures = list(document_to_examine.get_signatures_list()) start = 0 #get current band for band_idx in xrange(0, self.num_bands): #step 2: get minhash signature vector for current band vector = self._get_vector(signatures, self.num_rows_per_band, start) #step 3: hash current vector and add to it a new bucket or compare and record the document (and vector) # that hashed to an existing bucket if vector: # note, wrapping in tuple as it will maintain order and is immutable # immutability enables us to calculate a hash for it <|code_end|> using the current file's imports: from lsh.lsh.lsh_base import LshBase from lsh.utils.similarity import jaccard_similarity from lsh.utils.similarity import compute_positive_hash from lsh.models.documents.jaccard_document import JaccardDocument import copy and any relevant context from other files: # Path: lsh/lsh/lsh_base.py # class LshBase(object): # # def run(self, docuemnt): # raise NotImplementedError("Subclasses should implement run()") # # Path: lsh/utils/similarity.py # def jaccard_similarity(set1, set2): # return __calculate_jaccard_similairty(set1, set2) # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/models/documents/jaccard_document.py # class JaccardDocument(DocumentBase): # """ # This class represents documents used in LSH families for Jaccard Distance # based implementations and their corresponding components in this platform. # """ # # def __init__(self, original_doc, shingles_list=None, minhash_signatures=None): # self.__shingles = shingles_list # self.__signatures = minhash_signatures # # super(JaccardDocument, self).__init__(original_doc) # # def get_signatures_list(self): # return self.__signatures # # def get_shingles_list(self): # return self.__shingles # # def set_signatures_list(self, value): # self.__signatures = value # # def set_shingles_lists(self, value): # self.__shingles = value # # def get_shingles_as_set(self): # return set(self.__shingles) . Output only the next line.
vector_tuple = tuple(vector)
Based on the snippet: <|code_start|>def _get_documents(hash_code, band_dict): if hash_code and band_dict: return band_dict.get(hash_code, None) return None def _update_bucket(hash_code, band_dict, new_document): docs = band_dict.get(hash_code, None) if docs: updated_docs = copy.deepcopy(docs) updated_docs.append(new_document) band_dict[hash_code] = updated_docs # print "updated!!" # for doc in updated_docs: # print doc.get_original_document() class LshJaccard(LshBase): def __init__(self, num_bands=20, rows_per_band=10, threshold=0.0): # number of bands (i.e. buckets) to create self.num_bands = num_bands # this will be the number of signatures in a vector to be hashed self.num_rows_per_band = rows_per_band #should be thread safe if one instance of this class is used by threads in a pool for example #we may need to make a centralized resource to implement this...for now this is good enough. self.bands = self._create_band_dicts() #note, the default settings give you a threshold ~.74 <|code_end|> , predict the immediate next line with the help of imports: from lsh.lsh.lsh_base import LshBase from lsh.utils.similarity import jaccard_similarity from lsh.utils.similarity import compute_positive_hash from lsh.models.documents.jaccard_document import JaccardDocument import copy and context (classes, functions, sometimes code) from other files: # Path: lsh/lsh/lsh_base.py # class LshBase(object): # # def run(self, docuemnt): # raise NotImplementedError("Subclasses should implement run()") # # Path: lsh/utils/similarity.py # def jaccard_similarity(set1, set2): # return __calculate_jaccard_similairty(set1, set2) # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/models/documents/jaccard_document.py # class JaccardDocument(DocumentBase): # """ # This class represents documents used in LSH families for Jaccard Distance # based implementations and their corresponding components in this platform. # """ # # def __init__(self, original_doc, shingles_list=None, minhash_signatures=None): # self.__shingles = shingles_list # self.__signatures = minhash_signatures # # super(JaccardDocument, self).__init__(original_doc) # # def get_signatures_list(self): # return self.__signatures # # def get_shingles_list(self): # return self.__shingles # # def set_signatures_list(self, value): # self.__signatures = value # # def set_shingles_lists(self, value): # self.__shingles = value # # def get_shingles_as_set(self): # return set(self.__shingles) . Output only the next line.
if threshold == 0.0:
Based on the snippet: <|code_start|> def _get_documents(hash_code, band_dict): if hash_code and band_dict: return band_dict.get(hash_code, None) return None def _update_bucket(hash_code, band_dict, new_document): docs = band_dict.get(hash_code, None) if docs: updated_docs = copy.deepcopy(docs) updated_docs.append(new_document) band_dict[hash_code] = updated_docs # print "updated!!" # for doc in updated_docs: # print doc.get_original_document() class LshJaccard(LshBase): def __init__(self, num_bands=20, rows_per_band=10, threshold=0.0): # number of bands (i.e. buckets) to create self.num_bands = num_bands # this will be the number of signatures in a vector to be hashed <|code_end|> , predict the immediate next line with the help of imports: from lsh.lsh.lsh_base import LshBase from lsh.utils.similarity import jaccard_similarity from lsh.utils.similarity import compute_positive_hash from lsh.models.documents.jaccard_document import JaccardDocument import copy and context (classes, functions, sometimes code) from other files: # Path: lsh/lsh/lsh_base.py # class LshBase(object): # # def run(self, docuemnt): # raise NotImplementedError("Subclasses should implement run()") # # Path: lsh/utils/similarity.py # def jaccard_similarity(set1, set2): # return __calculate_jaccard_similairty(set1, set2) # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) # # Path: lsh/models/documents/jaccard_document.py # class JaccardDocument(DocumentBase): # """ # This class represents documents used in LSH families for Jaccard Distance # based implementations and their corresponding components in this platform. # """ # # def __init__(self, original_doc, shingles_list=None, minhash_signatures=None): # self.__shingles = shingles_list # self.__signatures = minhash_signatures # # super(JaccardDocument, self).__init__(original_doc) # # def get_signatures_list(self): # return self.__signatures # # def get_shingles_list(self): # return self.__shingles # # def set_signatures_list(self, value): # self.__signatures = value # # def set_shingles_lists(self, value): # self.__shingles = value # # def get_shingles_as_set(self): # return set(self.__shingles) . Output only the next line.
self.num_rows_per_band = rows_per_band
Predict the next line for this snippet: <|code_start|>logging.basicConfig(filename=settings.LOG_FILENAME, level=logging.DEBUG) DbType = settings.DATABASES['default']['ENGINE'] if DbType == 'cassandra': elif DbType == 'datastore': else: class UnknownException(Exception): pass class Matrix(object): __metaclass__ = Table attrs = [ 'ds_key text', 'source text', 'filename text', 'file_key text', 'lsh_output text', 'eval_output text', 'count_output text', 'random_seeds list<bigint>', <|code_end|> with the help of current file imports: import sys, struct, os, time, types, re, math, random, operator, hashlib, pdb import logging, settings from lsh.shingles.shingles import _get_list_of_shingles from lsh.utils.similarity import compute_positive_hash from db_cassandra import DbInt, Table from db_datastore import DbInt, Table from db_in_memory import DbInt, Table and context from other files: # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) , which may contain function names, class names, or code. Output only the next line.
'buckets list<int>',
Given the code snippet: <|code_start|>class UnknownException(Exception): pass class Matrix(object): __metaclass__ = Table attrs = [ 'ds_key text', 'source text', 'filename text', 'file_key text', 'lsh_output text', 'eval_output text', 'count_output text', 'random_seeds list<bigint>', 'buckets list<int>', 'rows int', 'bands int', 'shingle_type ascii', 'minhash_modulo int', ] p_keys = ['ds_key'] def __init__(self): return @classmethod def get(cls, ds_key): cls._initialize() if ds_key: ds = cls.select_row(ds_key = ds_key) <|code_end|> , generate the next line using the imports in this file: import sys, struct, os, time, types, re, math, random, operator, hashlib, pdb import logging, settings from lsh.shingles.shingles import _get_list_of_shingles from lsh.utils.similarity import compute_positive_hash from db_cassandra import DbInt, Table from db_datastore import DbInt, Table from db_in_memory import DbInt, Table and context (functions, classes, or occasionally code) from other files: # Path: lsh/shingles/shingles.py # def _get_list_of_shingles(doc, size=DEFAULT_SHINGLE_SIZE): # """ # Creates a list of shingles (strings) # :param doc: doc to create shingles from # :type doc: string # :param size: size of shingle # :type size: int # :return: list of shingles (strings), will return an empty list if doc is None or empty # """ # # if doc: # return [doc[i:i + size] for i in range(len(doc) - size + 1)] # else: # return [] # # Path: lsh/utils/similarity.py # def compute_positive_hash(value): # return hash(value) % ((sys.maxsize + 1) * 2) . Output only the next line.
if ds:
Predict the next line after this snippet: <|code_start|> BC = Register("BC") DE = Register("DE") HL = Register("HL") SP = Register("SP") AF = Register("AF") B = Register("B") C = Register("C") D = Register("D") E = Register("E") H = Register("H") L = Register("L") A = Register("A") deref_HL = Dereference(HL, address.fromVirtual(0)) # XXX: TODO: very very bad FNZ = Condition("FNZ") FZ = Condition("FZ") FNC = Condition("FNC") FC = Condition("FC") ALWAYS = Condition("ALWAYS") ROMBANK = Register('ROMBANK') tab = dict( R=[BC, DE, HL, SP], Q=[BC, DE, HL, AF], S=[B, C, D, E, H, L, deref_HL, A], Z=[B, C, D, E, H, L, deref_HL, A], F=[FNZ, FZ, FNC, FC], <|code_end|> using the current file's imports: from awake import address from awake.operand import Constant, Condition, Dereference, Register and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Condition(Register): # bits = 1 # # def negated(self): # return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name]) # # def alwaysTrue(self): # return self.name == 'ALWAYS' # # @property # def value(self): # if self.alwaysTrue(): # return 1 # else: # return None # # class Dereference(Operand): # def __init__(self, target, addr=None): # self.addr = addr # if hasattr(target, "getAddress"): # self.target = target # elif target.value is not None: # if addr is not None: # self.target = DataAddress(address.fromVirtualAndCurrent(target.value, addr)) # else: # self.target = DataAddress(address.fromVirtual(target.value)) # else: # self.target = target # # self.childs = (self.target,) # # def __str__(self): # return '[{0}]'.format(self.target) # # def render(self, renderer): # renderer.add('[') # self.target.render(renderer) # renderer.add(']') # # def optimizedWithContext(self, ctx): # target = self.target.optimizedWithContext(ctx) # if not hasattr(target, 'getAddress') and target.value is not None: # target = DataAddress(address.fromVirtual(target.value)).optimizedWithContext(ctx) # return Dereference(target, self.addr) # # def getDependencies(self): # out = set(['mem']) | self.target.getDependencies() # if hasattr(self.target, 'getAddress'): # out |= set([self.target.getAddress()]) # return out # # def __hash__(self): # return hash((Dereference, self.target)) # # def __eq__(self, other): # return isinstance(other, Dereference) and self.target == other.target # # # XXX # #def getMemreads(self): # # if hasattr(self.target, 'getAddress'): # # return set([self.target.getAddress()]) # # return set() # # class Register(Operand): # def __init__(self, name): # self.name = name # # def __str__(self): # return self.name # # def render(self, renderer): # renderer.add(str(self), 'register') # # def optimizedWithContext(self, ctx): # if ctx.hasValue(self.name): # return ctx.getValue(self.name) # return self # # def getDependencies(self): # return splitRegister(self.name) # # def __hash__(self): # return hash((Register, self.name)) # # def __eq__(self, other): # return isinstance(other, Register) and self.name == other.name # # @property # def bits(self): # if self.name in REGS16: # return 16 # else: # return 8 . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|>SP = Register("SP") AF = Register("AF") B = Register("B") C = Register("C") D = Register("D") E = Register("E") H = Register("H") L = Register("L") A = Register("A") deref_HL = Dereference(HL, address.fromVirtual(0)) # XXX: TODO: very very bad FNZ = Condition("FNZ") FZ = Condition("FZ") FNC = Condition("FNC") FC = Condition("FC") ALWAYS = Condition("ALWAYS") ROMBANK = Register('ROMBANK') tab = dict( R=[BC, DE, HL, SP], Q=[BC, DE, HL, AF], S=[B, C, D, E, H, L, deref_HL, A], Z=[B, C, D, E, H, L, deref_HL, A], F=[FNZ, FZ, FNC, FC], ) def get(name, value): if name in tab: <|code_end|> , predict the next line using imports from the current file: from awake import address from awake.operand import Constant, Condition, Dereference, Register and context including class names, function names, and sometimes code from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Condition(Register): # bits = 1 # # def negated(self): # return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name]) # # def alwaysTrue(self): # return self.name == 'ALWAYS' # # @property # def value(self): # if self.alwaysTrue(): # return 1 # else: # return None # # class Dereference(Operand): # def __init__(self, target, addr=None): # self.addr = addr # if hasattr(target, "getAddress"): # self.target = target # elif target.value is not None: # if addr is not None: # self.target = DataAddress(address.fromVirtualAndCurrent(target.value, addr)) # else: # self.target = DataAddress(address.fromVirtual(target.value)) # else: # self.target = target # # self.childs = (self.target,) # # def __str__(self): # return '[{0}]'.format(self.target) # # def render(self, renderer): # renderer.add('[') # self.target.render(renderer) # renderer.add(']') # # def optimizedWithContext(self, ctx): # target = self.target.optimizedWithContext(ctx) # if not hasattr(target, 'getAddress') and target.value is not None: # target = DataAddress(address.fromVirtual(target.value)).optimizedWithContext(ctx) # return Dereference(target, self.addr) # # def getDependencies(self): # out = set(['mem']) | self.target.getDependencies() # if hasattr(self.target, 'getAddress'): # out |= set([self.target.getAddress()]) # return out # # def __hash__(self): # return hash((Dereference, self.target)) # # def __eq__(self, other): # return isinstance(other, Dereference) and self.target == other.target # # # XXX # #def getMemreads(self): # # if hasattr(self.target, 'getAddress'): # # return set([self.target.getAddress()]) # # return set() # # class Register(Operand): # def __init__(self, name): # self.name = name # # def __str__(self): # return self.name # # def render(self, renderer): # renderer.add(str(self), 'register') # # def optimizedWithContext(self, ctx): # if ctx.hasValue(self.name): # return ctx.getValue(self.name) # return self # # def getDependencies(self): # return splitRegister(self.name) # # def __hash__(self): # return hash((Register, self.name)) # # def __eq__(self, other): # return isinstance(other, Register) and self.name == other.name # # @property # def bits(self): # if self.name in REGS16: # return 16 # else: # return 8 . Output only the next line.
return tab[name][value]
Predict the next line for this snippet: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>. BC = Register("BC") DE = Register("DE") HL = Register("HL") SP = Register("SP") AF = Register("AF") B = Register("B") C = Register("C") D = Register("D") E = Register("E") H = Register("H") L = Register("L") A = Register("A") deref_HL = Dereference(HL, address.fromVirtual(0)) # XXX: TODO: very very bad FNZ = Condition("FNZ") FZ = Condition("FZ") FNC = Condition("FNC") FC = Condition("FC") ALWAYS = Condition("ALWAYS") ROMBANK = Register('ROMBANK') tab = dict( R=[BC, DE, HL, SP], Q=[BC, DE, HL, AF], S=[B, C, D, E, H, L, deref_HL, A], <|code_end|> with the help of current file imports: from awake import address from awake.operand import Constant, Condition, Dereference, Register and context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Condition(Register): # bits = 1 # # def negated(self): # return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name]) # # def alwaysTrue(self): # return self.name == 'ALWAYS' # # @property # def value(self): # if self.alwaysTrue(): # return 1 # else: # return None # # class Dereference(Operand): # def __init__(self, target, addr=None): # self.addr = addr # if hasattr(target, "getAddress"): # self.target = target # elif target.value is not None: # if addr is not None: # self.target = DataAddress(address.fromVirtualAndCurrent(target.value, addr)) # else: # self.target = DataAddress(address.fromVirtual(target.value)) # else: # self.target = target # # self.childs = (self.target,) # # def __str__(self): # return '[{0}]'.format(self.target) # # def render(self, renderer): # renderer.add('[') # self.target.render(renderer) # renderer.add(']') # # def optimizedWithContext(self, ctx): # target = self.target.optimizedWithContext(ctx) # if not hasattr(target, 'getAddress') and target.value is not None: # target = DataAddress(address.fromVirtual(target.value)).optimizedWithContext(ctx) # return Dereference(target, self.addr) # # def getDependencies(self): # out = set(['mem']) | self.target.getDependencies() # if hasattr(self.target, 'getAddress'): # out |= set([self.target.getAddress()]) # return out # # def __hash__(self): # return hash((Dereference, self.target)) # # def __eq__(self, other): # return isinstance(other, Dereference) and self.target == other.target # # # XXX # #def getMemreads(self): # # if hasattr(self.target, 'getAddress'): # # return set([self.target.getAddress()]) # # return set() # # class Register(Operand): # def __init__(self, name): # self.name = name # # def __str__(self): # return self.name # # def render(self, renderer): # renderer.add(str(self), 'register') # # def optimizedWithContext(self, ctx): # if ctx.hasValue(self.name): # return ctx.getValue(self.name) # return self # # def getDependencies(self): # return splitRegister(self.name) # # def __hash__(self): # return hash((Register, self.name)) # # def __eq__(self, other): # return isinstance(other, Register) and self.name == other.name # # @property # def bits(self): # if self.name in REGS16: # return 16 # else: # return 8 , which may contain function names, class names, or code. Output only the next line.
Z=[B, C, D, E, H, L, deref_HL, A],
Given the code snippet: <|code_start|>B = Register("B") C = Register("C") D = Register("D") E = Register("E") H = Register("H") L = Register("L") A = Register("A") deref_HL = Dereference(HL, address.fromVirtual(0)) # XXX: TODO: very very bad FNZ = Condition("FNZ") FZ = Condition("FZ") FNC = Condition("FNC") FC = Condition("FC") ALWAYS = Condition("ALWAYS") ROMBANK = Register('ROMBANK') tab = dict( R=[BC, DE, HL, SP], Q=[BC, DE, HL, AF], S=[B, C, D, E, H, L, deref_HL, A], Z=[B, C, D, E, H, L, deref_HL, A], F=[FNZ, FZ, FNC, FC], ) def get(name, value): if name in tab: return tab[name][value] elif name == "N": return Constant(value * 0x08) <|code_end|> , generate the next line using the imports in this file: from awake import address from awake.operand import Constant, Condition, Dereference, Register and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Condition(Register): # bits = 1 # # def negated(self): # return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name]) # # def alwaysTrue(self): # return self.name == 'ALWAYS' # # @property # def value(self): # if self.alwaysTrue(): # return 1 # else: # return None # # class Dereference(Operand): # def __init__(self, target, addr=None): # self.addr = addr # if hasattr(target, "getAddress"): # self.target = target # elif target.value is not None: # if addr is not None: # self.target = DataAddress(address.fromVirtualAndCurrent(target.value, addr)) # else: # self.target = DataAddress(address.fromVirtual(target.value)) # else: # self.target = target # # self.childs = (self.target,) # # def __str__(self): # return '[{0}]'.format(self.target) # # def render(self, renderer): # renderer.add('[') # self.target.render(renderer) # renderer.add(']') # # def optimizedWithContext(self, ctx): # target = self.target.optimizedWithContext(ctx) # if not hasattr(target, 'getAddress') and target.value is not None: # target = DataAddress(address.fromVirtual(target.value)).optimizedWithContext(ctx) # return Dereference(target, self.addr) # # def getDependencies(self): # out = set(['mem']) | self.target.getDependencies() # if hasattr(self.target, 'getAddress'): # out |= set([self.target.getAddress()]) # return out # # def __hash__(self): # return hash((Dereference, self.target)) # # def __eq__(self, other): # return isinstance(other, Dereference) and self.target == other.target # # # XXX # #def getMemreads(self): # # if hasattr(self.target, 'getAddress'): # # return set([self.target.getAddress()]) # # return set() # # class Register(Operand): # def __init__(self, name): # self.name = name # # def __str__(self): # return self.name # # def render(self, renderer): # renderer.add(str(self), 'register') # # def optimizedWithContext(self, ctx): # if ctx.hasValue(self.name): # return ctx.getValue(self.name) # return self # # def getDependencies(self): # return splitRegister(self.name) # # def __hash__(self): # return hash((Register, self.name)) # # def __eq__(self, other): # return isinstance(other, Register) and self.name == other.name # # @property # def bits(self): # if self.name in REGS16: # return 16 # else: # return 8 . Output only the next line.
elif name == "I":
Predict the next line after this snippet: <|code_start|> BC = Register("BC") DE = Register("DE") HL = Register("HL") SP = Register("SP") AF = Register("AF") B = Register("B") C = Register("C") D = Register("D") E = Register("E") H = Register("H") L = Register("L") A = Register("A") deref_HL = Dereference(HL, address.fromVirtual(0)) # XXX: TODO: very very bad FNZ = Condition("FNZ") FZ = Condition("FZ") FNC = Condition("FNC") FC = Condition("FC") ALWAYS = Condition("ALWAYS") ROMBANK = Register('ROMBANK') tab = dict( R=[BC, DE, HL, SP], Q=[BC, DE, HL, AF], S=[B, C, D, E, H, L, deref_HL, A], Z=[B, C, D, E, H, L, deref_HL, A], <|code_end|> using the current file's imports: from awake import address from awake.operand import Constant, Condition, Dereference, Register and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Condition(Register): # bits = 1 # # def negated(self): # return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name]) # # def alwaysTrue(self): # return self.name == 'ALWAYS' # # @property # def value(self): # if self.alwaysTrue(): # return 1 # else: # return None # # class Dereference(Operand): # def __init__(self, target, addr=None): # self.addr = addr # if hasattr(target, "getAddress"): # self.target = target # elif target.value is not None: # if addr is not None: # self.target = DataAddress(address.fromVirtualAndCurrent(target.value, addr)) # else: # self.target = DataAddress(address.fromVirtual(target.value)) # else: # self.target = target # # self.childs = (self.target,) # # def __str__(self): # return '[{0}]'.format(self.target) # # def render(self, renderer): # renderer.add('[') # self.target.render(renderer) # renderer.add(']') # # def optimizedWithContext(self, ctx): # target = self.target.optimizedWithContext(ctx) # if not hasattr(target, 'getAddress') and target.value is not None: # target = DataAddress(address.fromVirtual(target.value)).optimizedWithContext(ctx) # return Dereference(target, self.addr) # # def getDependencies(self): # out = set(['mem']) | self.target.getDependencies() # if hasattr(self.target, 'getAddress'): # out |= set([self.target.getAddress()]) # return out # # def __hash__(self): # return hash((Dereference, self.target)) # # def __eq__(self, other): # return isinstance(other, Dereference) and self.target == other.target # # # XXX # #def getMemreads(self): # # if hasattr(self.target, 'getAddress'): # # return set([self.target.getAddress()]) # # return set() # # class Register(Operand): # def __init__(self, name): # self.name = name # # def __str__(self): # return self.name # # def render(self, renderer): # renderer.add(str(self), 'register') # # def optimizedWithContext(self, ctx): # if ctx.hasValue(self.name): # return ctx.getValue(self.name) # return self # # def getDependencies(self): # return splitRegister(self.name) # # def __hash__(self): # return hash((Register, self.name)) # # def __eq__(self, other): # return isinstance(other, Register) and self.name == other.name # # @property # def bits(self): # if self.name in REGS16: # return 16 # else: # return 8 . Output only the next line.
F=[FNZ, FZ, FNC, FC],
Next line prediction: <|code_start|># This file is part of Awake - GB decompiler. # Copyright (C) 2012 Wojciech Marczenko (devdri) <wojtek.marczenko@gmail.com> # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. class JumpTable(object): def __init__(self, proj, addr): self.addr = addr self.targets = [] for i in range(256): <|code_end|> . Use current file imports: (from awake import address from awake.operand import ProcAddress) and context including class names, function names, or small code snippets from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" . Output only the next line.
a = addr.offset(i*2)
Given the following code snippet before the placeholder: <|code_start|># 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 this program. If not, see <http://www.gnu.org/licenses/>. class JumpTable(object): def __init__(self, proj, addr): self.addr = addr self.targets = [] for i in range(256): a = addr.offset(i*2) lo = proj.rom.get(a) hi = proj.rom.get(a.offset(1)) value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) if not value.inPhysicalMem(): break self.targets.append(ProcAddress(value)) def render(self, renderer): with renderer.lineAddress(self.addr): with renderer.comment(): renderer.hline() renderer.startNewLine() renderer.write('jumptable ') renderer.writeSymbol(self.addr, 'jumptable') <|code_end|> , predict the next line using imports from the current file: from awake import address from awake.operand import ProcAddress and context including class names, function names, and sometimes code from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" . Output only the next line.
renderer.hline()
Using the snippet: <|code_start|># This program 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 this program. If not, see <http://www.gnu.org/licenses/>. def joinDependencies(first, second): reads = second.reads - first.writes | first.reads writes = first.writes | second.writes return DependencySet(reads, writes) def dependParallel(a, b): reads = a.reads | b.reads writes = a.writes | b.writes return DependencySet(reads, writes) def unknownDependencySet(): return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) class DependencySet: def __init__(self, reads=None, writes=None): if reads: self.reads = reads else: self.reads = set() if writes: self.writes = writes <|code_end|> , determine the next line of code. You have imports: from awake.regutil import joinRegisters, splitRegisters, ALL_REGS and context (class names, function names, or code) available: # Path: awake/regutil.py # def joinRegisters(regs): # out = set(regs) # for big in ('BC', 'DE', 'HL'): # if splitRegister(big) <= out: # out -= splitRegister(big) # out.add(big) # return out # # def splitRegisters(regs): # out = set() # for x in regs: # out |= splitRegister(x) # return out # # ALL_REGS = set(['B', 'C', 'D', 'E', 'H', 'L', 'SP', 'A', 'mem', 'ROMBANK', 'FZ', 'FC', 'FN', 'FH']) . Output only the next line.
else:
Here is a snippet: <|code_start|>def dependParallel(a, b): reads = a.reads | b.reads writes = a.writes | b.writes return DependencySet(reads, writes) def unknownDependencySet(): return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) class DependencySet: def __init__(self, reads=None, writes=None): if reads: self.reads = reads else: self.reads = set() if writes: self.writes = writes else: self.writes = set() def __str__(self): return 'DependencySet({0}, {1})'.format(joinRegisters(self.reads), joinRegisters(self.writes)) def onlyRegisters(self): return DependencySet(self.reads & ALL_REGS, self.writes & ALL_REGS) def encodeDependencySet(depset): return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) def decodeDependencySet(text): if not text: <|code_end|> . Write the next line using the current file imports: from awake.regutil import joinRegisters, splitRegisters, ALL_REGS and context from other files: # Path: awake/regutil.py # def joinRegisters(regs): # out = set(regs) # for big in ('BC', 'DE', 'HL'): # if splitRegister(big) <= out: # out -= splitRegister(big) # out.add(big) # return out # # def splitRegisters(regs): # out = set() # for x in regs: # out |= splitRegister(x) # return out # # ALL_REGS = set(['B', 'C', 'D', 'E', 'H', 'L', 'SP', 'A', 'mem', 'ROMBANK', 'FZ', 'FC', 'FN', 'FH']) , which may include functions, classes, or code. Output only the next line.
return DependencySet()
Next line prediction: <|code_start|>def dependParallel(a, b): reads = a.reads | b.reads writes = a.writes | b.writes return DependencySet(reads, writes) def unknownDependencySet(): return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) class DependencySet: def __init__(self, reads=None, writes=None): if reads: self.reads = reads else: self.reads = set() if writes: self.writes = writes else: self.writes = set() def __str__(self): return 'DependencySet({0}, {1})'.format(joinRegisters(self.reads), joinRegisters(self.writes)) def onlyRegisters(self): return DependencySet(self.reads & ALL_REGS, self.writes & ALL_REGS) def encodeDependencySet(depset): return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) def decodeDependencySet(text): if not text: <|code_end|> . Use current file imports: (from awake.regutil import joinRegisters, splitRegisters, ALL_REGS) and context including class names, function names, or small code snippets from other files: # Path: awake/regutil.py # def joinRegisters(regs): # out = set(regs) # for big in ('BC', 'DE', 'HL'): # if splitRegister(big) <= out: # out -= splitRegister(big) # out.add(big) # return out # # def splitRegisters(regs): # out = set() # for x in regs: # out |= splitRegister(x) # return out # # ALL_REGS = set(['B', 'C', 'D', 'E', 'H', 'L', 'SP', 'A', 'mem', 'ROMBANK', 'FZ', 'FC', 'FN', 'FH']) . Output only the next line.
return DependencySet()
Given the code snippet: <|code_start|> self.assertEquals(str(address.fromPhysical(0x008000)), "0002:4000") self.assertEquals(str(address.fromPhysical(0x008888)), "0002:4888") def testFromVirtual(self): self.assertEquals(str(address.fromVirtual(0x0000)), "0000:0000") self.assertEquals(str(address.fromVirtual(0x2000)), "0000:2000") self.assertEquals(str(address.fromVirtual(0x4000)), "(A):4000") self.assertEquals(str(address.fromVirtual(0x7FFF)), "(A):7FFF") self.assertEquals(str(address.fromVirtual(0x8000)), "VRAM:8000") self.assertEquals(str(address.fromVirtual(0xFFFF)), "IO:FFFF") def testFromVirtualAndCurrent(self): current1 = address.fromPhysical(0x4000) current4 = address.fromPhysical(0x10000) self.assertEquals(str(address.fromVirtualAndCurrent(0x0000, current1)), "0000:0000") self.assertEquals(str(address.fromVirtualAndCurrent(0x0000, current4)), "0000:0000") self.assertEquals(str(address.fromVirtualAndCurrent(0x4000, current1)), "0001:4000") self.assertEquals(str(address.fromVirtualAndCurrent(0x4000, current4)), "0004:4000") self.assertEquals(str(address.fromVirtualAndCurrent(0x7FFF, current1)), "0001:7FFF") self.assertEquals(str(address.fromVirtualAndCurrent(0x7FFF, current4)), "0004:7FFF") self.assertEquals(str(address.fromVirtualAndCurrent(0x8000, current1)), "VRAM:8000") self.assertEquals(str(address.fromVirtualAndCurrent(0xFFFF, current4)), "IO:FFFF") def testOffset(self): zero = address.fromVirtual(0) self.assertEquals(str(zero.offset(0)), "0000:0000") self.assertEquals(str(zero.offset(0x3FFF)), "0000:3FFF") <|code_end|> , generate the next line using the imports in this file: import unittest from awake import address and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): . Output only the next line.
self.assertEquals(str(zero.offset(0x4000)), "(A):4000")
Given the code snippet: <|code_start|> return [x[0] for x in c.fetchall()] def getAllInBank(self, bank): bank_name = "{:04X}".format(bank) with closing(self.connection.cursor()) as c: c.execute('select addr from procs where substr(addr, 0, 5)=? order by addr', (bank_name,)) return [x[0] for x in c.fetchall()] def setInitial(self, initial): c = self.connection.cursor() c.executemany('insert into calls(source, destination) values ("FFFF:0000", ?)', ((x,) for x in initial)) c.close() self.connection.commit() def getAmbigCalls(self): with closing(self.connection.cursor()) as c: c.execute('select addr from procs where has_ambig_calls=1') return [x[0] for x in c.fetchall()] def getDataReferers(self, data_addr): reads = set() writes = set() c = self.connection.cursor() c.execute('select proc, type from memref where addr=?', (data_addr,)) for addr, reftype in c.fetchall(): if reftype == 'read': reads.add(addr) else: writes.add(addr) c.close() <|code_end|> , generate the next line using the imports in this file: import sqlite3 import Image from contextlib import closing from awake import address from awake.depend import decodeDependencySet, encodeDependencySet, unknownDependencySet from awake.operand import ProcAddress from awake.textrenderer import HtmlRenderer and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/depend.py # def decodeDependencySet(text): # if not text: # return DependencySet() # r, w = text.split("->") # reads = set(x.strip() for x in r.split(",")) # writes = set(x.strip() for x in w.split(",")) # return DependencySet(splitRegisters(reads), splitRegisters(writes)) # # def encodeDependencySet(depset): # return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) # # def unknownDependencySet(): # return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # Path: awake/textrenderer.py # class HtmlRenderer(Renderer): # def __init__(self, database): # super(HtmlRenderer, self).__init__(database) # self.content = [] # # def getContents(self): # return '<pre>' + (''.join(self.content)) + '</pre>' # # def _add(self, text, klass=None, url=None): # text = str(text) # if klass: # text = '<span class="{1}">{0}</span>'.format(text, klass) # if url: # text = '<a href="{1}">{0}</a>'.format(text, url) # self.content.append(text) . Output only the next line.
return reads, writes
Predict the next line after this snippet: <|code_start|> 'IO:FF41': 'IO:STAT', 'IO:FF42': 'IO:SCY', 'IO:FF43': 'IO:SCX', 'IO:FF44': 'IO:LY', 'IO:FF45': 'IO:LYC', 'IO:FF46': 'IO:DMA', 'IO:FF47': 'IO:BGP', 'IO:FF48': 'IO:OBP0', 'IO:FF49': 'IO:OBP1', 'IO:FF4A': 'IO:WY', 'IO:FF4B': 'IO:WX', 'IO:FFFF': 'IO:IE', 'IO:FF0F': 'IO:IF', } def __init__(self, filename): self.connection = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES) c = self.connection.cursor() c.execute('create table if not exists procs(addr address, type text, depset text, has_switch integer, suspicious_switch integer, has_suspicious_instr integer, has_nop integer, has_ambig_calls integer, length integer)') c.execute('create table if not exists calls(source address, destination address, type text)') c.execute('create table if not exists memref(addr address, proc address, type text)') c.execute('create table if not exists tags(addr address, name text)') c.close() self.connection.commit() def close(self): self.connection.close() def hasNameForAddress(self, addr): <|code_end|> using the current file's imports: import sqlite3 import Image from contextlib import closing from awake import address from awake.depend import decodeDependencySet, encodeDependencySet, unknownDependencySet from awake.operand import ProcAddress from awake.textrenderer import HtmlRenderer and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/depend.py # def decodeDependencySet(text): # if not text: # return DependencySet() # r, w = text.split("->") # reads = set(x.strip() for x in r.split(",")) # writes = set(x.strip() for x in w.split(",")) # return DependencySet(splitRegisters(reads), splitRegisters(writes)) # # def encodeDependencySet(depset): # return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) # # def unknownDependencySet(): # return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # Path: awake/textrenderer.py # class HtmlRenderer(Renderer): # def __init__(self, database): # super(HtmlRenderer, self).__init__(database) # self.content = [] # # def getContents(self): # return '<pre>' + (''.join(self.content)) + '</pre>' # # def _add(self, text, klass=None, url=None): # text = str(text) # if klass: # text = '<span class="{1}">{0}</span>'.format(text, klass) # if url: # text = '<a href="{1}">{0}</a>'.format(text, url) # self.content.append(text) . Output only the next line.
if str(addr) in self.default_tags:
Here is a snippet: <|code_start|> c.execute('select name from tags where addr=?', (addr,)) return bool(getFirst(c.fetchone())) def nameForAddress(self, addr): if str(addr) in self.default_tags: return self.default_tags[str(addr)] with closing(self.connection.cursor()) as c: c.execute('select name from tags where addr=?', (addr,)) return getFirst(c.fetchone(), str(addr)) def setNameForAddress(self, addr, name): c = self.connection.cursor() c.execute('select name from tags where addr=?', (addr,)) if c.fetchone(): print('updating') c.execute('update tags set name=? where addr=?', (name, addr)) else: print('new') c.execute('insert into tags (addr, name) values (?, ?)', (addr, name)) c.close() self.connection.commit() def procInfo(self, addr): return ProcInfo(self.connection, addr) def reportProc(self, addr): ProcInfo(self.connection, addr).save(self.connection) def getNextOwnedAddress(self, addr): <|code_end|> . Write the next line using the current file imports: import sqlite3 import Image from contextlib import closing from awake import address from awake.depend import decodeDependencySet, encodeDependencySet, unknownDependencySet from awake.operand import ProcAddress from awake.textrenderer import HtmlRenderer and context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/depend.py # def decodeDependencySet(text): # if not text: # return DependencySet() # r, w = text.split("->") # reads = set(x.strip() for x in r.split(",")) # writes = set(x.strip() for x in w.split(",")) # return DependencySet(splitRegisters(reads), splitRegisters(writes)) # # def encodeDependencySet(depset): # return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) # # def unknownDependencySet(): # return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # Path: awake/textrenderer.py # class HtmlRenderer(Renderer): # def __init__(self, database): # super(HtmlRenderer, self).__init__(database) # self.content = [] # # def getContents(self): # return '<pre>' + (''.join(self.content)) + '</pre>' # # def _add(self, text, klass=None, url=None): # text = str(text) # if klass: # text = '<span class="{1}">{0}</span>'.format(text, klass) # if url: # text = '<a href="{1}">{0}</a>'.format(text, url) # self.content.append(text) , which may include functions, classes, or code. Output only the next line.
with closing(self.connection.cursor()) as c:
Based on the snippet: <|code_start|> for addr, reftype in c.fetchall(): if reftype == 'read': reads.add(addr) else: writes.add(addr) c.close() return reads, writes def produce_map(self, proj): romsize = 512*1024 width = 256 height = romsize/width img = Image.new('RGB', (width, height)) for i in range(512*1024): addr = address.fromPhysical(i) if addr.bank() in (0x08, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x1C, 0x1D): color = (0, 0, 255) elif addr.bank() == 0x16 and addr.virtual() >= 0x5700: color = (0, 0, 255) elif addr.bank() == 0x09 and addr.virtual() >= 0x6700: color = (0, 0, 255) elif proj.rom.get(addr) == 0xFF: color = (0, 0, 127) else: color = (0, 0, 0) x = i % width y = i // width <|code_end|> , predict the immediate next line with the help of imports: import sqlite3 import Image from contextlib import closing from awake import address from awake.depend import decodeDependencySet, encodeDependencySet, unknownDependencySet from awake.operand import ProcAddress from awake.textrenderer import HtmlRenderer and context (classes, functions, sometimes code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/depend.py # def decodeDependencySet(text): # if not text: # return DependencySet() # r, w = text.split("->") # reads = set(x.strip() for x in r.split(",")) # writes = set(x.strip() for x in w.split(",")) # return DependencySet(splitRegisters(reads), splitRegisters(writes)) # # def encodeDependencySet(depset): # return ", ".join(str(x) for x in joinRegisters(depset.reads)) + " -> " + ", ".join(str(x) for x in joinRegisters(depset.writes)) # # def unknownDependencySet(): # return DependencySet(ALL_REGS - set(['FZ', 'FC', 'FN', 'FH']), ALL_REGS - set(['ROMBANK'])) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # Path: awake/textrenderer.py # class HtmlRenderer(Renderer): # def __init__(self, database): # super(HtmlRenderer, self).__init__(database) # self.content = [] # # def getContents(self): # return '<pre>' + (''.join(self.content)) + '</pre>' # # def _add(self, text, klass=None, url=None): # text = str(text) # if klass: # text = '<span class="{1}">{0}</span>'.format(text, klass) # if url: # text = '<a href="{1}">{0}</a>'.format(text, url) # self.content.append(text) . Output only the next line.
img.putpixel((x, y), color)
Predict the next line for this snippet: <|code_start|> c.close() class BankSummaryPage(Page): def load(self): p = self.url.split('/') self.bank = int(p[2], 16) def render(self, renderer): bank_name = "{:04X}".format(self.bank) c = self.proj.database.connection.cursor() renderer.startNewLine() renderer.add('public interface:') c.execute('select destination from calls where substr(source, 0, 5)<>? and substr(destination, 0, 5)=? group by destination order by destination', (bank_name, bank_name)) with renderer.indent(): for addr, in c.fetchall(): renderer.startNewLine() ProcAddress(addr).render(renderer) renderer.startNewLine() renderer.add('dependencies:') c.execute('select destination from calls where substr(source, 0, 5)=? and substr(destination, 0, 5)<>? group by source order by source', (bank_name, bank_name)) with renderer.indent(): for addr, in c.fetchall(): renderer.startNewLine() ProcAddress(addr).render(renderer) renderer.startNewLine() renderer.add('reads:') <|code_end|> with the help of current file imports: from awake import address from awake.operand import ProcAddress, DataAddress from awake.procedure import loadProcedureRange from awake.jumptable import JumpTable and context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # class DataAddress(AddressConstant): # link_prefix = "/data/" # html_class = "data-addr" # # Path: awake/procedure.py # def loadProcedureRange(proj, addr): # return ProcedureRangeAnalysis(proj, addr, getLimit(proj, addr)) # # Path: awake/jumptable.py # class JumpTable(object): # def __init__(self, proj, addr): # self.addr = addr # self.targets = [] # # for i in range(256): # a = addr.offset(i*2) # lo = proj.rom.get(a) # hi = proj.rom.get(a.offset(1)) # value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) # # if not value.inPhysicalMem(): # break # # self.targets.append(ProcAddress(value)) # # def render(self, renderer): # with renderer.lineAddress(self.addr): # with renderer.comment(): # renderer.hline() # renderer.startNewLine() # renderer.write('jumptable ') # renderer.writeSymbol(self.addr, 'jumptable') # renderer.hline() # with renderer.indent(): # i = 0 # for t in self.targets: # with renderer.lineAddress(self.addr.offset(i*2)): # renderer.startNewLine() # renderer.write(str(i) + ' -> ') # t.render(renderer) # i += 1 , which may contain function names, class names, or code. Output only the next line.
c.execute('select addr from memref where substr(proc, 0, 5)=? and type=? group by addr order by addr', (bank_name, 'read'))
Predict the next line after this snippet: <|code_start|> def render(self, r): with r.lineAddress(self.addr), r.comment(): r.hline() r.startNewLine() r.write("procedure ") r.writeSymbol(self.addr, 'procedure') r.startNewLine() r.write(" callers: ") r.writeList(ProcAddress(x) for x in sorted(self.info.callers)) r.startNewLine() r.write(" calls: ") r.writeList(ProcAddress(x) for x in sorted(self.info.calls)) r.hline() with r.indent(): self.proc.render(r) class JumptablePage(Page): has_name_form = True def load(self): p = self.url.split('/') self.addr = address.fromConventional(p[2]) self.jumptable = JumpTable(self.proj, self.addr) <|code_end|> using the current file's imports: from awake import address from awake.operand import ProcAddress, DataAddress from awake.procedure import loadProcedureRange from awake.jumptable import JumpTable and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # class DataAddress(AddressConstant): # link_prefix = "/data/" # html_class = "data-addr" # # Path: awake/procedure.py # def loadProcedureRange(proj, addr): # return ProcedureRangeAnalysis(proj, addr, getLimit(proj, addr)) # # Path: awake/jumptable.py # class JumpTable(object): # def __init__(self, proj, addr): # self.addr = addr # self.targets = [] # # for i in range(256): # a = addr.offset(i*2) # lo = proj.rom.get(a) # hi = proj.rom.get(a.offset(1)) # value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) # # if not value.inPhysicalMem(): # break # # self.targets.append(ProcAddress(value)) # # def render(self, renderer): # with renderer.lineAddress(self.addr): # with renderer.comment(): # renderer.hline() # renderer.startNewLine() # renderer.write('jumptable ') # renderer.writeSymbol(self.addr, 'jumptable') # renderer.hline() # with renderer.indent(): # i = 0 # for t in self.targets: # with renderer.lineAddress(self.addr.offset(i*2)): # renderer.startNewLine() # renderer.write(str(i) + ' -> ') # t.render(renderer) # i += 1 . Output only the next line.
def render(self, renderer):
Next line prediction: <|code_start|># 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 this program. If not, see <http://www.gnu.org/licenses/>. class Page(object): has_name_form = False def __init__(self, proj, url): self.proj = proj self.url = url self.load() class ProcedureFlowPage(Page): has_name_form = True def load(self): p = self.url.split('/') self.addr = address.fromConventional(p[2]) self.info = self.proj.database.procInfo(self.addr) self.proj.flow.refresh(self.addr) self.proc = self.proj.flow.at(self.addr) def render(self, r): with r.lineAddress(self.addr), r.comment(): r.hline() <|code_end|> . Use current file imports: (from awake import address from awake.operand import ProcAddress, DataAddress from awake.procedure import loadProcedureRange from awake.jumptable import JumpTable) and context including class names, function names, or small code snippets from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # class DataAddress(AddressConstant): # link_prefix = "/data/" # html_class = "data-addr" # # Path: awake/procedure.py # def loadProcedureRange(proj, addr): # return ProcedureRangeAnalysis(proj, addr, getLimit(proj, addr)) # # Path: awake/jumptable.py # class JumpTable(object): # def __init__(self, proj, addr): # self.addr = addr # self.targets = [] # # for i in range(256): # a = addr.offset(i*2) # lo = proj.rom.get(a) # hi = proj.rom.get(a.offset(1)) # value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) # # if not value.inPhysicalMem(): # break # # self.targets.append(ProcAddress(value)) # # def render(self, renderer): # with renderer.lineAddress(self.addr): # with renderer.comment(): # renderer.hline() # renderer.startNewLine() # renderer.write('jumptable ') # renderer.writeSymbol(self.addr, 'jumptable') # renderer.hline() # with renderer.indent(): # i = 0 # for t in self.targets: # with renderer.lineAddress(self.addr.offset(i*2)): # renderer.startNewLine() # renderer.write(str(i) + ' -> ') # t.render(renderer) # i += 1 . Output only the next line.
r.startNewLine()
Predict the next line after this snippet: <|code_start|> renderer.startNewLine() ProcAddress(addr).render(renderer) renderer.startNewLine() renderer.add('dependencies:') c.execute('select destination from calls where substr(source, 0, 5)=? and substr(destination, 0, 5)<>? group by source order by source', (bank_name, bank_name)) with renderer.indent(): for addr, in c.fetchall(): renderer.startNewLine() ProcAddress(addr).render(renderer) renderer.startNewLine() renderer.add('reads:') c.execute('select addr from memref where substr(proc, 0, 5)=? and type=? group by addr order by addr', (bank_name, 'read')) with renderer.indent(): for addr, in c.fetchall(): renderer.startNewLine() DataAddress(addr).render(renderer) renderer.startNewLine() renderer.add('writes:') c.execute('select addr from memref where substr(proc, 0, 5)=? and type=? group by addr order by addr', (bank_name, 'write')) with renderer.indent(): for addr, in c.fetchall(): renderer.startNewLine() DataAddress(addr).render(renderer) c.close() def dispatchUrl(proj, url): <|code_end|> using the current file's imports: from awake import address from awake.operand import ProcAddress, DataAddress from awake.procedure import loadProcedureRange from awake.jumptable import JumpTable and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # class DataAddress(AddressConstant): # link_prefix = "/data/" # html_class = "data-addr" # # Path: awake/procedure.py # def loadProcedureRange(proj, addr): # return ProcedureRangeAnalysis(proj, addr, getLimit(proj, addr)) # # Path: awake/jumptable.py # class JumpTable(object): # def __init__(self, proj, addr): # self.addr = addr # self.targets = [] # # for i in range(256): # a = addr.offset(i*2) # lo = proj.rom.get(a) # hi = proj.rom.get(a.offset(1)) # value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) # # if not value.inPhysicalMem(): # break # # self.targets.append(ProcAddress(value)) # # def render(self, renderer): # with renderer.lineAddress(self.addr): # with renderer.comment(): # renderer.hline() # renderer.startNewLine() # renderer.write('jumptable ') # renderer.writeSymbol(self.addr, 'jumptable') # renderer.hline() # with renderer.indent(): # i = 0 # for t in self.targets: # with renderer.lineAddress(self.addr.offset(i*2)): # renderer.startNewLine() # renderer.write(str(i) + ' -> ') # t.render(renderer) # i += 1 . Output only the next line.
if url.startswith('/proc/'):
Given the code snippet: <|code_start|> has_name_form = True def load(self): p = self.url.split('/') self.addr = address.fromConventional(p[2]) self.info = self.proj.database.procInfo(self.addr) self.proc = loadProcedureRange(self.proj, self.addr) def render(self, r): with r.lineAddress(self.addr), r.comment(): r.hline() r.startNewLine() r.write("procedure ") r.writeSymbol(self.addr, 'procedure') r.startNewLine() r.write(" callers: ") r.writeList(ProcAddress(x) for x in sorted(self.info.callers)) r.startNewLine() r.write(" calls: ") r.writeList(ProcAddress(x) for x in sorted(self.info.calls)) r.hline() with r.indent(): self.proc.render(r) class JumptablePage(Page): <|code_end|> , generate the next line using the imports in this file: from awake import address from awake.operand import ProcAddress, DataAddress from awake.procedure import loadProcedureRange from awake.jumptable import JumpTable and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" # # class DataAddress(AddressConstant): # link_prefix = "/data/" # html_class = "data-addr" # # Path: awake/procedure.py # def loadProcedureRange(proj, addr): # return ProcedureRangeAnalysis(proj, addr, getLimit(proj, addr)) # # Path: awake/jumptable.py # class JumpTable(object): # def __init__(self, proj, addr): # self.addr = addr # self.targets = [] # # for i in range(256): # a = addr.offset(i*2) # lo = proj.rom.get(a) # hi = proj.rom.get(a.offset(1)) # value = address.fromVirtualAndCurrent((hi<<8) | lo, addr) # # if not value.inPhysicalMem(): # break # # self.targets.append(ProcAddress(value)) # # def render(self, renderer): # with renderer.lineAddress(self.addr): # with renderer.comment(): # renderer.hline() # renderer.startNewLine() # renderer.write('jumptable ') # renderer.writeSymbol(self.addr, 'jumptable') # renderer.hline() # with renderer.indent(): # i = 0 # for t in self.targets: # with renderer.lineAddress(self.addr.offset(i*2)): # renderer.startNewLine() # renderer.write(str(i) + ' -> ') # t.render(renderer) # i += 1 . Output only the next line.
has_name_form = True
Predict the next line for this snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. class OpcodeEffect(object): def __init__(self, text): m = re.search('^\s*read:(.*)write:(.*)$', text) assert m reads = [] for name in m.group(1).split(): reads.append(name.strip()) writes = [] values = dict() for w in m.group(2).split(';'): w = w.strip() if not w: continue if ':' in w: name, value = w.split(':', 2) <|code_end|> with the help of current file imports: import re from awake import placeholders from awake.expression import parse from awake.regutil import splitRegister and context from other files: # Path: awake/placeholders.py # BC = Register("BC") # DE = Register("DE") # HL = Register("HL") # SP = Register("SP") # AF = Register("AF") # B = Register("B") # C = Register("C") # D = Register("D") # E = Register("E") # H = Register("H") # L = Register("L") # A = Register("A") # FNZ = Condition("FNZ") # FZ = Condition("FZ") # FNC = Condition("FNC") # FC = Condition("FC") # ALWAYS = Condition("ALWAYS") # ROMBANK = Register('ROMBANK') # def get(name, value): # # Path: awake/expression.py # def parse(text): # try: # lexer = shlex.shlex(text) # lexer.commenters = '' # lexer.wordchars += '#' # return expression(lexer) # except ExpressionError as e: # print('ERROR:', e.msg, 'in', text) # # Path: awake/regutil.py # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) , which may contain function names, class names, or code. Output only the next line.
values[name] = value
Predict the next line after this snippet: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>. class OpcodeEffect(object): def __init__(self, text): m = re.search('^\s*read:(.*)write:(.*)$', text) assert m reads = [] for name in m.group(1).split(): reads.append(name.strip()) writes = [] values = dict() for w in m.group(2).split(';'): w = w.strip() if not w: continue if ':' in w: name, value = w.split(':', 2) values[name] = value else: name = w writes.append(name) self.reads = reads self.writes = writes self.values = values <|code_end|> using the current file's imports: import re from awake import placeholders from awake.expression import parse from awake.regutil import splitRegister and any relevant context from other files: # Path: awake/placeholders.py # BC = Register("BC") # DE = Register("DE") # HL = Register("HL") # SP = Register("SP") # AF = Register("AF") # B = Register("B") # C = Register("C") # D = Register("D") # E = Register("E") # H = Register("H") # L = Register("L") # A = Register("A") # FNZ = Condition("FNZ") # FZ = Condition("FZ") # FNC = Condition("FNC") # FC = Condition("FC") # ALWAYS = Condition("ALWAYS") # ROMBANK = Register('ROMBANK') # def get(name, value): # # Path: awake/expression.py # def parse(text): # try: # lexer = shlex.shlex(text) # lexer.commenters = '' # lexer.wordchars += '#' # return expression(lexer) # except ExpressionError as e: # print('ERROR:', e.msg, 'in', text) # # Path: awake/regutil.py # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) . Output only the next line.
def filled(self, params, ctx):
Based on the snippet: <|code_start|># # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. class OpcodeEffect(object): def __init__(self, text): m = re.search('^\s*read:(.*)write:(.*)$', text) assert m reads = [] for name in m.group(1).split(): reads.append(name.strip()) writes = [] values = dict() for w in m.group(2).split(';'): w = w.strip() if not w: continue if ':' in w: name, value = w.split(':', 2) values[name] = value else: <|code_end|> , predict the immediate next line with the help of imports: import re from awake import placeholders from awake.expression import parse from awake.regutil import splitRegister and context (classes, functions, sometimes code) from other files: # Path: awake/placeholders.py # BC = Register("BC") # DE = Register("DE") # HL = Register("HL") # SP = Register("SP") # AF = Register("AF") # B = Register("B") # C = Register("C") # D = Register("D") # E = Register("E") # H = Register("H") # L = Register("L") # A = Register("A") # FNZ = Condition("FNZ") # FZ = Condition("FZ") # FNC = Condition("FNC") # FC = Condition("FC") # ALWAYS = Condition("ALWAYS") # ROMBANK = Register('ROMBANK') # def get(name, value): # # Path: awake/expression.py # def parse(text): # try: # lexer = shlex.shlex(text) # lexer.commenters = '' # lexer.wordchars += '#' # return expression(lexer) # except ExpressionError as e: # print('ERROR:', e.msg, 'in', text) # # Path: awake/regutil.py # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) . Output only the next line.
name = w
Given the code snippet: <|code_start|># This file is part of Awake - GB decompiler. # Copyright (C) 2012 Wojciech Marczenko (devdri) <wojtek.marczenko@gmail.com> # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. def addr_symbol(addr): return 'A' + str(addr).replace(':', '_') def save_dot(database, procs): with open('data/graph.dot', 'w') as f: f.write("digraph crossref {\n") for addr in procs: tags = '' <|code_end|> , generate the next line using the imports in this file: from collections import defaultdict from PIL import Image from awake import address and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): . Output only the next line.
info = database.procInfo(addr)
Here is a snippet: <|code_start|> while self.queue or self.jumptable_queue: if self.queue: x = self.queue.pop() self.visitInstruction(proj, x) else: x = self.jumptable_queue.pop() self.tryExpandJumptable(proj, x) def firstGap(self): addr = self.start_addr while addr < self.limit_addr and not self.isAvailableAddr(addr): addr = addr.offset(1) return addr def shrinkLimitAndCut(self, limit_addr): self.limit_addr = limit_addr #self.owned_bytes = set(addr for addr in self.owned_bytes if self.isLocalAddr(addr)) self.owned_bytes = list(filter(self.isLocalAddr, self.owned_bytes)) self.visited = set(addr for addr in self.visited if self.isLocalAddr(addr)) self.labels = set(addr for addr in self.labels if self.isLocalAddr(addr)) self.block_starts = set(addr for addr in self.block_starts if self.isLocalAddr(addr)) self.jumptable_sizes = dict((k, v) for (k, v) in self.jumptable_sizes.items() if self.isLocalAddr(k)) def render(self, renderer): for addr in sorted(self.visited): if addr in self.labels: renderer.label(addr) self.proj.disasm.decodeCache(addr)[0].render(renderer) def getLimit(proj, addr): <|code_end|> . Write the next line using the current file imports: from collections import defaultdict from awake import address from awake.instruction import TailCall from awake.operand import ProcAddress from .flowcontrol import Block from .flowcontrol import Block and context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/instruction.py # class TailCall(CallInstruction): # def __init__(self, proj, target): # super(TailCall, self).__init__(proj, 'tail-call', target, placeholders.ALWAYS, target.getAddress()) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" , which may include functions, classes, or code. Output only the next line.
if addr.inPhysicalMem():
Predict the next line after this snippet: <|code_start|> def dfs(self, proj): while self.queue or self.jumptable_queue: if self.queue: x = self.queue.pop() self.visitInstruction(proj, x) else: x = self.jumptable_queue.pop() self.tryExpandJumptable(proj, x) def firstGap(self): addr = self.start_addr while addr < self.limit_addr and not self.isAvailableAddr(addr): addr = addr.offset(1) return addr def shrinkLimitAndCut(self, limit_addr): self.limit_addr = limit_addr #self.owned_bytes = set(addr for addr in self.owned_bytes if self.isLocalAddr(addr)) self.owned_bytes = list(filter(self.isLocalAddr, self.owned_bytes)) self.visited = set(addr for addr in self.visited if self.isLocalAddr(addr)) self.labels = set(addr for addr in self.labels if self.isLocalAddr(addr)) self.block_starts = set(addr for addr in self.block_starts if self.isLocalAddr(addr)) self.jumptable_sizes = dict((k, v) for (k, v) in self.jumptable_sizes.items() if self.isLocalAddr(k)) def render(self, renderer): for addr in sorted(self.visited): if addr in self.labels: renderer.label(addr) self.proj.disasm.decodeCache(addr)[0].render(renderer) <|code_end|> using the current file's imports: from collections import defaultdict from awake import address from awake.instruction import TailCall from awake.operand import ProcAddress from .flowcontrol import Block from .flowcontrol import Block and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/instruction.py # class TailCall(CallInstruction): # def __init__(self, proj, target): # super(TailCall, self).__init__(proj, 'tail-call', target, placeholders.ALWAYS, target.getAddress()) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" . Output only the next line.
def getLimit(proj, addr):
Given the code snippet: <|code_start|> def __init__(self, proj, addr, limit): self.proj=proj self.start_addr = addr self.limit_addr = limit self.visited = set() self.owned_bytes = set() self.labels = set() self.block_starts = set([self.start_addr]) self.jumptable_sizes = defaultdict(int) self.queue = set([self.start_addr]) self.jumptable_queue = set() self.suspicious_switch = False self.warn = False self.log = list() self.dfs(proj) self.shrinkLimitAndCut(self.firstGap()) def isLocalAddr(self, addr): return self.start_addr <= addr < self.limit_addr def shrinkLimit(self, addr): if self.isLocalAddr(addr): self.limit_addr = addr def isAvailableAddr(self, addr): return self.isLocalAddr(addr) and addr not in self.owned_bytes def ownByte(self, addr): if not self.isAvailableAddr(addr): <|code_end|> , generate the next line using the imports in this file: from collections import defaultdict from awake import address from awake.instruction import TailCall from awake.operand import ProcAddress from .flowcontrol import Block from .flowcontrol import Block and context (functions, classes, or occasionally code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/instruction.py # class TailCall(CallInstruction): # def __init__(self, proj, target): # super(TailCall, self).__init__(proj, 'tail-call', target, placeholders.ALWAYS, target.getAddress()) # # Path: awake/operand.py # class ProcAddress(AddressConstant): # link_prefix = "/proc/" # html_class = "proc-addr" . Output only the next line.
print('byte not available', addr, 'visited:', ', '.join(str(x) for x in self.visited))
Predict the next line after this snippet: <|code_start|> self.setValue(register[0], HighByte(value)) self.setValue(register[1], LowByte(value)) elif register == 'AF': self.setValue('A', HighByte(value)) self.setValueComplex('FZ') self.setValueComplex('FC') self.setValueComplex('FN') self.setValueComplex('FH') else: self.invalidate(register) if register in value.getDependencies(): self.setValueComplex(register) else: self.values[register] = value def invalidate(self, register): delete = set() for x in self.values: if self.values[x] and register in self.values[x].getDependencies(): delete.add(x) for x in delete: del(self.values[x]) def hasValue(self, register): if register in ('BC', 'DE', 'HL'): return self.hasValue(register[0]) and self.hasValue(register[1]) if register == 'FNZ': <|code_end|> using the current file's imports: from awake.operand import ComplexValue from awake.operator import HighByte, LowByte, Word, LogicalNot and any relevant context from other files: # Path: awake/operand.py # class ComplexValue(Operand): # def __init__(self, hint='complex', deps=None): # self.hint = hint # if deps: # self.deps = deps # else: # self.deps = set() # # def isComplex(self): # return True # # def getDependencies(self): # return self.deps # # def __str__(self): # return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' # # Path: awake/operator.py # class HighByte(FuncOperator): # name = 'hi' # # @staticmethod # def calculate(arg): # return arg >> 8 # # class LowByte(FuncOperator): # name = 'lo' # # @staticmethod # def calculate(arg): # return arg & 0xFF # # class Word(FuncOperator): # name = 'word' # bits = 16 # # @staticmethod # def calculate(hi, lo): # return (hi << 8) | lo # # @classmethod # def make(cls, hi, lo): # # merge word # if isinstance(hi, HighByte) and isinstance(lo, LowByte): # if hi.childs[0] == lo.childs[0]: # return hi.childs[0] # # # high zero # if hi.value == 0: # return lo # # if isinstance(hi, Shr) and isinstance(lo, Shl) and hi.left == lo.left and isConstant(hi.right) and isConstant(lo.right): # hi_sh = hi.right.value # lo_sh = lo.right.value # if hi_sh + lo_sh == 8: # return Shl16.make(lo.left, Constant(lo_sh)) # # return super(Word, cls).make(hi, lo) # # class LogicalNot(Operator): # bits = 1 # # def __str__(self): # return 'not '+str(self.childs[0]) # # @classmethod # def make(cls, inner): # try: # return inner.logicalNot() # except AttributeError: # return super(LogicalNot, cls).make(inner) . Output only the next line.
return self.hasValue('FZ')
Predict the next line for this snippet: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>. class Context: def __init__(self, values=None): if not values: self.values = dict() else: self.values = dict(values) def setValueComplex(self, register): if register in ('BC', 'DE', 'HL'): self.setValueComplex(register[0]) self.setValueComplex(register[1]) else: self.invalidate(register) self.values[register] = ComplexValue('ctx') def setValue(self, register, value): assert not isinstance(value, int) # detect common errors if register in ('BC', 'DE', 'HL'): self.setValue(register[0], HighByte(value)) self.setValue(register[1], LowByte(value)) elif register == 'AF': self.setValue('A', HighByte(value)) self.setValueComplex('FZ') self.setValueComplex('FC') self.setValueComplex('FN') self.setValueComplex('FH') <|code_end|> with the help of current file imports: from awake.operand import ComplexValue from awake.operator import HighByte, LowByte, Word, LogicalNot and context from other files: # Path: awake/operand.py # class ComplexValue(Operand): # def __init__(self, hint='complex', deps=None): # self.hint = hint # if deps: # self.deps = deps # else: # self.deps = set() # # def isComplex(self): # return True # # def getDependencies(self): # return self.deps # # def __str__(self): # return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' # # Path: awake/operator.py # class HighByte(FuncOperator): # name = 'hi' # # @staticmethod # def calculate(arg): # return arg >> 8 # # class LowByte(FuncOperator): # name = 'lo' # # @staticmethod # def calculate(arg): # return arg & 0xFF # # class Word(FuncOperator): # name = 'word' # bits = 16 # # @staticmethod # def calculate(hi, lo): # return (hi << 8) | lo # # @classmethod # def make(cls, hi, lo): # # merge word # if isinstance(hi, HighByte) and isinstance(lo, LowByte): # if hi.childs[0] == lo.childs[0]: # return hi.childs[0] # # # high zero # if hi.value == 0: # return lo # # if isinstance(hi, Shr) and isinstance(lo, Shl) and hi.left == lo.left and isConstant(hi.right) and isConstant(lo.right): # hi_sh = hi.right.value # lo_sh = lo.right.value # if hi_sh + lo_sh == 8: # return Shl16.make(lo.left, Constant(lo_sh)) # # return super(Word, cls).make(hi, lo) # # class LogicalNot(Operator): # bits = 1 # # def __str__(self): # return 'not '+str(self.childs[0]) # # @classmethod # def make(cls, inner): # try: # return inner.logicalNot() # except AttributeError: # return super(LogicalNot, cls).make(inner) , which may contain function names, class names, or code. Output only the next line.
else:
Here is a snippet: <|code_start|> assert not isinstance(value, int) # detect common errors if register in ('BC', 'DE', 'HL'): self.setValue(register[0], HighByte(value)) self.setValue(register[1], LowByte(value)) elif register == 'AF': self.setValue('A', HighByte(value)) self.setValueComplex('FZ') self.setValueComplex('FC') self.setValueComplex('FN') self.setValueComplex('FH') else: self.invalidate(register) if register in value.getDependencies(): self.setValueComplex(register) else: self.values[register] = value def invalidate(self, register): delete = set() for x in self.values: if self.values[x] and register in self.values[x].getDependencies(): delete.add(x) for x in delete: del(self.values[x]) def hasValue(self, register): <|code_end|> . Write the next line using the current file imports: from awake.operand import ComplexValue from awake.operator import HighByte, LowByte, Word, LogicalNot and context from other files: # Path: awake/operand.py # class ComplexValue(Operand): # def __init__(self, hint='complex', deps=None): # self.hint = hint # if deps: # self.deps = deps # else: # self.deps = set() # # def isComplex(self): # return True # # def getDependencies(self): # return self.deps # # def __str__(self): # return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' # # Path: awake/operator.py # class HighByte(FuncOperator): # name = 'hi' # # @staticmethod # def calculate(arg): # return arg >> 8 # # class LowByte(FuncOperator): # name = 'lo' # # @staticmethod # def calculate(arg): # return arg & 0xFF # # class Word(FuncOperator): # name = 'word' # bits = 16 # # @staticmethod # def calculate(hi, lo): # return (hi << 8) | lo # # @classmethod # def make(cls, hi, lo): # # merge word # if isinstance(hi, HighByte) and isinstance(lo, LowByte): # if hi.childs[0] == lo.childs[0]: # return hi.childs[0] # # # high zero # if hi.value == 0: # return lo # # if isinstance(hi, Shr) and isinstance(lo, Shl) and hi.left == lo.left and isConstant(hi.right) and isConstant(lo.right): # hi_sh = hi.right.value # lo_sh = lo.right.value # if hi_sh + lo_sh == 8: # return Shl16.make(lo.left, Constant(lo_sh)) # # return super(Word, cls).make(hi, lo) # # class LogicalNot(Operator): # bits = 1 # # def __str__(self): # return 'not '+str(self.childs[0]) # # @classmethod # def make(cls, inner): # try: # return inner.logicalNot() # except AttributeError: # return super(LogicalNot, cls).make(inner) , which may include functions, classes, or code. Output only the next line.
if register in ('BC', 'DE', 'HL'):
Continue the code snippet: <|code_start|> self.setValue(register[1], LowByte(value)) elif register == 'AF': self.setValue('A', HighByte(value)) self.setValueComplex('FZ') self.setValueComplex('FC') self.setValueComplex('FN') self.setValueComplex('FH') else: self.invalidate(register) if register in value.getDependencies(): self.setValueComplex(register) else: self.values[register] = value def invalidate(self, register): delete = set() for x in self.values: if self.values[x] and register in self.values[x].getDependencies(): delete.add(x) for x in delete: del(self.values[x]) def hasValue(self, register): if register in ('BC', 'DE', 'HL'): return self.hasValue(register[0]) and self.hasValue(register[1]) if register == 'FNZ': return self.hasValue('FZ') <|code_end|> . Use current file imports: from awake.operand import ComplexValue from awake.operator import HighByte, LowByte, Word, LogicalNot and context (classes, functions, or code) from other files: # Path: awake/operand.py # class ComplexValue(Operand): # def __init__(self, hint='complex', deps=None): # self.hint = hint # if deps: # self.deps = deps # else: # self.deps = set() # # def isComplex(self): # return True # # def getDependencies(self): # return self.deps # # def __str__(self): # return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' # # Path: awake/operator.py # class HighByte(FuncOperator): # name = 'hi' # # @staticmethod # def calculate(arg): # return arg >> 8 # # class LowByte(FuncOperator): # name = 'lo' # # @staticmethod # def calculate(arg): # return arg & 0xFF # # class Word(FuncOperator): # name = 'word' # bits = 16 # # @staticmethod # def calculate(hi, lo): # return (hi << 8) | lo # # @classmethod # def make(cls, hi, lo): # # merge word # if isinstance(hi, HighByte) and isinstance(lo, LowByte): # if hi.childs[0] == lo.childs[0]: # return hi.childs[0] # # # high zero # if hi.value == 0: # return lo # # if isinstance(hi, Shr) and isinstance(lo, Shl) and hi.left == lo.left and isConstant(hi.right) and isConstant(lo.right): # hi_sh = hi.right.value # lo_sh = lo.right.value # if hi_sh + lo_sh == 8: # return Shl16.make(lo.left, Constant(lo_sh)) # # return super(Word, cls).make(hi, lo) # # class LogicalNot(Operator): # bits = 1 # # def __str__(self): # return 'not '+str(self.childs[0]) # # @classmethod # def make(cls, inner): # try: # return inner.logicalNot() # except AttributeError: # return super(LogicalNot, cls).make(inner) . Output only the next line.
if register == 'FNC':
Given snippet: <|code_start|> assert not isinstance(value, int) # detect common errors if register in ('BC', 'DE', 'HL'): self.setValue(register[0], HighByte(value)) self.setValue(register[1], LowByte(value)) elif register == 'AF': self.setValue('A', HighByte(value)) self.setValueComplex('FZ') self.setValueComplex('FC') self.setValueComplex('FN') self.setValueComplex('FH') else: self.invalidate(register) if register in value.getDependencies(): self.setValueComplex(register) else: self.values[register] = value def invalidate(self, register): delete = set() for x in self.values: if self.values[x] and register in self.values[x].getDependencies(): delete.add(x) for x in delete: del(self.values[x]) def hasValue(self, register): <|code_end|> , continue by predicting the next line. Consider current file imports: from awake.operand import ComplexValue from awake.operator import HighByte, LowByte, Word, LogicalNot and context: # Path: awake/operand.py # class ComplexValue(Operand): # def __init__(self, hint='complex', deps=None): # self.hint = hint # if deps: # self.deps = deps # else: # self.deps = set() # # def isComplex(self): # return True # # def getDependencies(self): # return self.deps # # def __str__(self): # return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' # # Path: awake/operator.py # class HighByte(FuncOperator): # name = 'hi' # # @staticmethod # def calculate(arg): # return arg >> 8 # # class LowByte(FuncOperator): # name = 'lo' # # @staticmethod # def calculate(arg): # return arg & 0xFF # # class Word(FuncOperator): # name = 'word' # bits = 16 # # @staticmethod # def calculate(hi, lo): # return (hi << 8) | lo # # @classmethod # def make(cls, hi, lo): # # merge word # if isinstance(hi, HighByte) and isinstance(lo, LowByte): # if hi.childs[0] == lo.childs[0]: # return hi.childs[0] # # # high zero # if hi.value == 0: # return lo # # if isinstance(hi, Shr) and isinstance(lo, Shl) and hi.left == lo.left and isConstant(hi.right) and isConstant(lo.right): # hi_sh = hi.right.value # lo_sh = lo.right.value # if hi_sh + lo_sh == 8: # return Shl16.make(lo.left, Constant(lo_sh)) # # return super(Word, cls).make(hi, lo) # # class LogicalNot(Operator): # bits = 1 # # def __str__(self): # return 'not '+str(self.childs[0]) # # @classmethod # def make(cls, inner): # try: # return inner.logicalNot() # except AttributeError: # return super(LogicalNot, cls).make(inner) which might include code, classes, or functions. Output only the next line.
if register in ('BC', 'DE', 'HL'):
Given the following code snippet before the placeholder: <|code_start|> def __hash__(self): return hash((self.symbol, self.left, self.right)) def __eq__(self, other): try: return self.symbol == other.symbol and self.left == other.left and self.right == other.right except AttributeError: return False def render(self, renderer): if self.left.needParen(0): renderer.add('(') self.left.render(renderer) if self.left.needParen(0): renderer.add(')') renderer.add(' '+self.symbol+' ') if self.right.needParen(0): renderer.add('(') self.right.render(renderer) if self.right.needParen(0): renderer.add(')') def needParen(self, priority): return True @classmethod def make(cls, left, right): if isConstant(left) and isConstant(right): return Constant(cls.calculate(left.value, right.value)) else: <|code_end|> , predict the next line using imports from the current file: from awake.operand import Constant, Operand and context including class names, function names, and sometimes code from other files: # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Operand(object): # bits = 8 # childs = () # value = None # # @property # def value_mask(self): # if self.value is not None: # return self.value # elif self.bits == 8: # return 0xFF # elif self.bits == 16: # return 0xFFFF # elif self.bits == 1: # return 1 # # def render(self, renderer): # renderer.add(str(self)) # # def optimizedWithContext(self, context): # return self # # def getDependencies(self): # return set.union(set(), *(ch.getDependencies() for ch in self.childs)) # # def needParen(self, priority): # return False # # def getMemreads(self): # return set(dep for dep in self.getDependencies() if isinstance(dep, address.Address)) . Output only the next line.
return super(BinOp, cls).make(left, right)
Given snippet: <|code_start|>class Add(BinOp): symbol = '+' @staticmethod def calculate(left, right): return (left + right) & 0xFF @classmethod def make(cls, left, right): if isConstant(left): left, right = right, left if right.value == 0: return left if left == right: return Shl.make(left, Constant(1)) if isConstant(right) and isinstance(left, Sub) and isConstant(left.right): return Add.make(left.left, Constant(Sub.calculate(right.value, left.right.value))) return super(Add, cls).make(left, right) class Sub(BinOp): symbol = '-' @staticmethod def calculate(left, right): return (left - right) & 0xFF @classmethod def make(cls, left, right): if isConstant(left): left, right = right, left <|code_end|> , continue by predicting the next line. Consider current file imports: from awake.operand import Constant, Operand and context: # Path: awake/operand.py # class Constant(Operand): # def __init__(self, value): # assert isinstance(value, int) # self.value = value # # def __str__(self): # if 0 <= self.value <= 9: # return str(self.value) # return hex(self.value) # # def render(self, renderer): # renderer.add(str(self), 'constant') # # def __hash__(self): # return hash(self.value) # # def __eq__(self, other): # try: # return self.value == other.value # except AttributeError: # return False # # @property # def bits(self): # if self.value > 0xFF: # return 16 # else: # return 8 # # class Operand(object): # bits = 8 # childs = () # value = None # # @property # def value_mask(self): # if self.value is not None: # return self.value # elif self.bits == 8: # return 0xFF # elif self.bits == 16: # return 0xFFFF # elif self.bits == 1: # return 1 # # def render(self, renderer): # renderer.add(str(self)) # # def optimizedWithContext(self, context): # return self # # def getDependencies(self): # return set.union(set(), *(ch.getDependencies() for ch in self.childs)) # # def needParen(self, priority): # return False # # def getMemreads(self): # return set(dep for dep in self.getDependencies() if isinstance(dep, address.Address)) which might include code, classes, or functions. Output only the next line.
if right.value == 0:
Continue the code snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class Test(unittest.TestCase): def testDepend(self): self.assertFalse('A' in operand.Constant(1).getDependencies()) self.assertFalse('B' in operand.LabelAddress(address.fromVirtual(1)).getDependencies()) self.assertTrue('A' in placeholders.A.getDependencies()) self.assertFalse('A' in placeholders.BC.getDependencies()) self.assertTrue(regutil.splitRegister('HL') <= regutil.splitRegisters(placeholders.deref_HL.getDependencies())) def testContext(self): c = Context() self.assertFalse(c.hasValue('A')) c.setValueComplex('A') self.assertFalse(c.hasValue('A')) c.setValue('A', placeholders.B) self.assertTrue(c.hasValue('A')) c.setValue('B', operand.Constant(1)) self.assertFalse(c.hasValue('A')) self.assertTrue(c.hasValue('B')) self.assertEquals(c.getValue('B').value, 1) def testLoadInstructions(self): context = Context() q = instruction.LoadInstruction('LD', placeholders.HL, operand.Constant(0xFFFF)) a = instruction.LoadInstruction('LD', placeholders.A, operand.Constant(1)) b = instruction.LoadInstruction('LD', placeholders.B, placeholders.deref_HL) <|code_end|> . Use current file imports: import unittest from .context import Context from . import address from . import operand from . import placeholders from . import instruction from . import regutil and context (classes, functions, or code) from other files: # Path: awake/context.py # class Context: # def __init__(self, values=None): # if not values: # self.values = dict() # else: # self.values = dict(values) # # def setValueComplex(self, register): # if register in ('BC', 'DE', 'HL'): # self.setValueComplex(register[0]) # self.setValueComplex(register[1]) # else: # self.invalidate(register) # self.values[register] = ComplexValue('ctx') # # def setValue(self, register, value): # assert not isinstance(value, int) # detect common errors # # if register in ('BC', 'DE', 'HL'): # self.setValue(register[0], HighByte(value)) # self.setValue(register[1], LowByte(value)) # elif register == 'AF': # self.setValue('A', HighByte(value)) # self.setValueComplex('FZ') # self.setValueComplex('FC') # self.setValueComplex('FN') # self.setValueComplex('FH') # else: # self.invalidate(register) # # if register in value.getDependencies(): # self.setValueComplex(register) # else: # self.values[register] = value # # def invalidate(self, register): # delete = set() # # for x in self.values: # if self.values[x] and register in self.values[x].getDependencies(): # delete.add(x) # # for x in delete: # del(self.values[x]) # # def hasValue(self, register): # if register in ('BC', 'DE', 'HL'): # return self.hasValue(register[0]) and self.hasValue(register[1]) # if register == 'FNZ': # return self.hasValue('FZ') # if register == 'FNC': # return self.hasValue('FC') # if register not in self.values: # return False # value = self.values[register] # try: # return not value.isComplex() # except AttributeError: # return True # # def hasConstantValue(self, register): # return self.hasValue(register) and self.getValue(register).value is not None # # def getValue(self, register): # if register in ('BC', 'DE', 'HL'): # return Word(self.getValue(register[0]), self.getValue(register[1])).optimizedWithContext(Context()) # if register == 'FNZ': # return LogicalNot(self.getValue('FZ')).optimizedWithContext(Context()) # if register == 'FNC': # return LogicalNot(self.getValue('FC')).optimizedWithContext(Context()) # else: # return self.values[register].optimizedWithContext(Context()) # # def invalidateAll(self): # self.values = dict() # # def invalidateComplex(self): # values = set(self.values) # for v in values: # if not self.hasConstantValue(v): # del self.values[v] # # def clone(self): # return Context(self.values) . Output only the next line.
c = instruction.LoadInstruction('LD', placeholders.deref_HL, placeholders.A)
Predict the next line for this snippet: <|code_start|># Copyright (C) 2012 Wojciech Marczenko (devdri) <wojtek.marczenko@gmail.com> # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. class OpcodeDispatcher(object): def __init__(self, opcodeFormats): self.dispatchTable = dict() for bit_format in opcodeFormats: if not bit_format: continue decoder = SingleOpcodeDecoder(bit_format) for i in range(256): byte = i & 0xFF if decoder.match(byte): self.dispatchTable[byte] = decoder <|code_end|> with the help of current file imports: from awake.instruction import BadOpcode from awake.singledecoder import SingleOpcodeDecoder and context from other files: # Path: awake/instruction.py # class BadOpcode(Instruction): # def __init__(self, opcodes, addr): # super(BadOpcode, self).__init__("BAD-OP", addr) # # def hasContinue(self): # return False # # Path: awake/singledecoder.py # class SingleOpcodeDecoder(object): # def __init__(self, text): # # bit_format, effect_format = text.split('@', 2) # # items = bit_format.split(None, 3) # # self.bitPattern = items[0] # self.cycles = int(items[1]) # self.name = items[2]; # # operandText = ""; # if len(items) >= 4: # operandText = items[3] # # if not operandText: # self.operands = [] # else: # self.operands = [x.strip() for x in operandText.split(", ")] # # if "v16" in operandText: # self.argSize = 2; # elif "v8" in operandText: # self.argSize = 1; # else: # self.argSize = 0; # # assert len(self.bitPattern) == 8 # # self.effect = OpcodeEffect(effect_format) # # # def matchBits(self, opcode): # params = defaultdict(int) # opcode_bits = bin(opcode)[2:].zfill(8) # # for (x, y) in zip(self.bitPattern, opcode_bits): # if x in ('0', '1'): # if x != y: # return None # else: # # update according parameter # params[x] <<= 1 # params[x] |= int(y) # # return params # # def match(self, opcode): # return self.matchBits(opcode) is not None # # def length(self): # return 1 + self.argSize # # def decode(self, proj, opcodes, addr): # assert len(opcodes) == self.length() # # params = self.matchBits(opcodes[0]) # # argument = 0 # if self.argSize == 1: # argument = opcodes[1] # elif self.argSize == 2: # argument = (opcodes[2] << 8) | opcodes[1]; # # next_addr = addr.offset(self.length()) # # out_operands = [ # fillOperand(text, params, argument, next_addr) for text in self.operands # ] # # reads, writes, values, loads = self.effect.filled(params, make_context(params, argument, next_addr)) # # return instruction.make(proj, self.name, out_operands, addr, reads, writes, values, loads), next_addr , which may contain function names, class names, or code. Output only the next line.
def decode(self, proj, addr):
Predict the next line after this snippet: <|code_start|>00010111 1 RLA @ read: A FC write: A:((A<<1) | FC); FC; FN:0; FZ:0; FH:0; 00011111 1 RRA @ read: A FC write: A:((A>>1) | (FC<<7)); FC; FN:0; FZ:0; FH:0; 00100111 1 DAA @ read: A FN FH FC write: A; FZ; FC; FH; 00101111 1 CPL @ read: A write: A:(A ^ 0xFF); FN:1; FH:1; 00110111 1 SCF @ read: write: FC:1; FN:0; FH:0; 00111111 1 CCF @ read: FC write: FC:(FC^1); FN:0; FH:0; 11110011 1 DI @ read: write: IME:0; sideeffects; 11111011 1 EI @ read: write: IME:1; sideeffects; 11QQ0001 3 POP #Q @ read: SP mem write: #Q:popval(SP); SP:popst(SP); 11QQ0101 3 PUSH #Q @ read: SP #Q write: SP:push(SP, #Q); mem; 00000000 1 NOP @ read: write: 00010000 1 STOP @ read: write: sideeffects; 01110110 1 HALT @ read: write: sideeffects; """ cb_ops = """ 00000SSS 2 RLC #S @ read: #S write: FC:(#S>>7); #S:((#S<<1)|(#S>>7)); FZ:(#S == 0); FH:0; FN:0; 00001SSS 2 RRC #S @ read: #S write: FC:(#S & 1); #S:((#S>>1)|(#S<<7)); FZ:(#S == 0); FH:0; FN:0; 00010SSS 2 RL #S @ read: #S FC write: #S:((#S<<1)|FC); FZ:(#S == 0); FC; FH:0; FN:0; 00011SSS 2 RR #S @ read: #S FC write: #S:((#S>>1)|(FC<<7)); FZ:(#S == 0); FC; FH:0; FN:0; 00100SSS 2 SLA #S @ read: #S write: FC:(#S>>7); #S:(#S<<1); FZ:(#S == 0); FH:0; FN:0; 00101SSS 2 SRA #S @ read: #S write: FC:(#S & 1); #S:((#S>>1) | (#S & 0x80)); FZ:(#S == 0); FH:0; FN:0; 00110SSS 2 SWAP #S @ read: #S write: #S:((#S>>4) | (#S<<4)); FZ:(#S == 0); FC:0; FH:0; FN:0; 00111SSS 2 SRL #S @ read: #S write: FC:(#S & 1); #S:(#S>>1); FZ:(#S == 0); FH:0; FN:0; 01IIISSS 2 BIT #I, #S @ read: #S write: FZ:((#S & (1<<#I)) == 0); FH:1; FN:0; 10IIISSS 2 RES #I, #S @ read: #S write: #S:(#S & (0xFF ^ (1<<#I))); <|code_end|> using the current file's imports: from awake.opcodedispatcher import OpcodeDispatcher and any relevant context from other files: # Path: awake/opcodedispatcher.py # class OpcodeDispatcher(object): # # def __init__(self, opcodeFormats): # self.dispatchTable = dict() # for bit_format in opcodeFormats: # if not bit_format: # continue # # decoder = SingleOpcodeDecoder(bit_format) # for i in range(256): # byte = i & 0xFF # if decoder.match(byte): # self.dispatchTable[byte] = decoder # # def decode(self, proj, addr): # entry = proj.rom.get(addr) # if entry not in self.dispatchTable: # print('WARN: bad opcode', addr) # return BadOpcode([entry], addr), None # decoder = self.dispatchTable[entry] # opcodes = proj.rom.read(addr, decoder.length()) # return decoder.decode(proj, opcodes, addr) . Output only the next line.
11IIISSS 2 SET #I, #S @ read: #S write: #S:(#S | (1<<#I));
Based on the snippet: <|code_start|> except AttributeError: return False @property def bits(self): if self.value > 0xFF: return 16 else: return 8 class ComplexValue(Operand): def __init__(self, hint='complex', deps=None): self.hint = hint if deps: self.deps = deps else: self.deps = set() def isComplex(self): return True def getDependencies(self): return self.deps def __str__(self): return '#'+self.hint+':'+(','.join(str(dep) for dep in self.deps if not isinstance(dep, address.Address)))+'#' class AddressConstant(Constant): def __init__(self, addr): <|code_end|> , predict the immediate next line with the help of imports: from awake import address from awake.regutil import REGS16, splitRegister and context (classes, functions, sometimes code) from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/regutil.py # REGS16 = set(['BC', 'DE', 'HL', 'SP', 'AF']) # # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) . Output only the next line.
if not hasattr(addr, 'virtual'):
Predict the next line after this snippet: <|code_start|> return self.name def render(self, renderer): renderer.add(str(self), 'register') def optimizedWithContext(self, ctx): if ctx.hasValue(self.name): return ctx.getValue(self.name) return self def getDependencies(self): return splitRegister(self.name) def __hash__(self): return hash((Register, self.name)) def __eq__(self, other): return isinstance(other, Register) and self.name == other.name @property def bits(self): if self.name in REGS16: return 16 else: return 8 class Condition(Register): bits = 1 def negated(self): <|code_end|> using the current file's imports: from awake import address from awake.regutil import REGS16, splitRegister and any relevant context from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/regutil.py # REGS16 = set(['BC', 'DE', 'HL', 'SP', 'AF']) # # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) . Output only the next line.
return Condition(dict(FZ='FNZ', FNZ='FZ', FC='FNC', FNC='FC')[self.name])
Next line prediction: <|code_start|> return hex(self.value) def render(self, renderer): renderer.add(str(self), 'constant') def __hash__(self): return hash(self.value) def __eq__(self, other): try: return self.value == other.value except AttributeError: return False @property def bits(self): if self.value > 0xFF: return 16 else: return 8 class ComplexValue(Operand): def __init__(self, hint='complex', deps=None): self.hint = hint if deps: self.deps = deps else: self.deps = set() def isComplex(self): <|code_end|> . Use current file imports: (from awake import address from awake.regutil import REGS16, splitRegister) and context including class names, function names, or small code snippets from other files: # Path: awake/address.py # BANK_SIZE = 0x4000 # class BadAddressException(Exception): # class Address(object): # def __init__(self, addr): # def __str__(self): # def fromVirtual(virtual): # def fromVirtualAndBank(virtual, bank): # def fromVirtualAndCurrent(virtual, current): # def fromPhysical(physical): # def fromConventional(conventional): # def __init__(self, address): # def virtual(self): # def bank(self): # def isAmbiguous(self): # def inBankedSpace(self): # def inPhysicalMem(self): # def physical(self): # def offset(self, offset): # def withBankSpecified(self, bank): # def __lt__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __hash__(self): # def __str__(self): # def __repr__(self): # # Path: awake/regutil.py # REGS16 = set(['BC', 'DE', 'HL', 'SP', 'AF']) # # def splitRegister(name): # if name in ('BC', 'DE', 'HL'): # return set([name[0], name[1]]) # elif name == 'AF': # #return set(['A', 'FZ', 'FC', 'FN', 'FH']) # return set(['A']) # elif name == 'FNZ': # return set(['FZ']) # elif name == 'FNC': # return set(['FC']) # elif name == 'FF00+C': # return set(['C']) # return set([name]) . Output only the next line.
return True
Continue the code snippet: <|code_start|> def testBasic(self): e = OpcodeEffect('read: write:') reads, writes, values = e.filled(None) self.assertFalse(reads) self.assertFalse(writes) self.assertFalse(values) e = OpcodeEffect('read: A HL write: BC HL') reads, writes, values = e.filled(None) self.assertEquals(reads, set(['A', 'H', 'L'])) self.assertEquals(writes, set(['B', 'C', 'H', 'L'])) self.assertFalse(values) e = OpcodeEffect('read: FC FN write: FN:0 FZ mem FC:1') reads, writes, values = e.filled(None) self.assertEquals(reads, set(['FC', 'FN'])) self.assertEquals(writes, set(['FN', 'FZ', 'FC', 'mem'])) self.assertEquals(values, dict(FN='0', FC='1')) def testFill(self): params = dict(R=0, S=6, Z=0, F=0) e = OpcodeEffect('read: #R #F write: #S #Z #F:0') reads, writes, values = e.filled(params) self.assertEquals(reads, set(['B', 'C', 'FZ', 'H', 'L'])) self.assertEquals(writes, set(['mem', 'B', 'FZ'])) self.assertEquals(values, dict(FZ='0')) <|code_end|> . Use current file imports: import unittest from .opcodeeffect import OpcodeEffect and context (classes, functions, or code) from other files: # Path: awake/opcodeeffect.py # class OpcodeEffect(object): # def __init__(self, text): # m = re.search('^\s*read:(.*)write:(.*)$', text) # assert m # # reads = [] # for name in m.group(1).split(): # reads.append(name.strip()) # # writes = [] # values = dict() # # for w in m.group(2).split(';'): # w = w.strip() # if not w: # continue # if ':' in w: # name, value = w.split(':', 2) # values[name] = value # else: # name = w # writes.append(name) # # self.reads = reads # self.writes = writes # self.values = values # # def filled(self, params, ctx): # reads = set() # writes = set() # values = dict() # loads = [] # # for x in self.reads: # if x.startswith("#"): # assert(len(x) == 2) # value = params[x[1]] # operand = placeholders.get(x[1], value) # # XXX: solution here: just add operand.getDependencies() # if hasattr(operand, 'target'): # reads.add('mem') # reads |= splitRegister('HL') # TODO: XXX: bad # else: # reads |= splitRegister(operand.name) # else: # reads |= splitRegister(x) # # for x in self.writes: # if x.startswith("#"): # assert(len(x) == 2) # value = params[x[1]] # operand = placeholders.get(x[1], value) # if hasattr(operand, 'target'): # name = '['+operand.target.name+']' # writes.add('mem') # reads |= splitRegister('HL') # TODO: XXX: bad # else: # name = operand.name # writes |= splitRegister(name) # if x in self.values: # e = parse(self.values[x]) # values[name] = e.optimizedWithContext(ctx) # loads.append((name, values[name])) # else: # writes |= splitRegister(x) # if x in self.values: # e = parse(self.values[x]) # values[x] = e.optimizedWithContext(ctx) # loads.append((x, values[x])) # # #values = dict() # TODO: XXX: # #loads = [] # # return reads, writes, values, loads . Output only the next line.
if __name__ == "__main__":
Here is a snippet: <|code_start|># This file is part of Awake - GB decompiler. # Copyright (C) 2012 Wojciech Marczenko (devdri) <wojtek.marczenko@gmail.com> # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. class Test(unittest.TestCase): def testMatchNop(self): op = SingleOpcodeDecoder("00000000 1 NOP"); self.assertTrue(op.match(0)); self.assertFalse(op.match(1)); <|code_end|> . Write the next line using the current file imports: import unittest from .singledecoder import SingleOpcodeDecoder from . import address and context from other files: # Path: awake/singledecoder.py # class SingleOpcodeDecoder(object): # def __init__(self, text): # # bit_format, effect_format = text.split('@', 2) # # items = bit_format.split(None, 3) # # self.bitPattern = items[0] # self.cycles = int(items[1]) # self.name = items[2]; # # operandText = ""; # if len(items) >= 4: # operandText = items[3] # # if not operandText: # self.operands = [] # else: # self.operands = [x.strip() for x in operandText.split(", ")] # # if "v16" in operandText: # self.argSize = 2; # elif "v8" in operandText: # self.argSize = 1; # else: # self.argSize = 0; # # assert len(self.bitPattern) == 8 # # self.effect = OpcodeEffect(effect_format) # # # def matchBits(self, opcode): # params = defaultdict(int) # opcode_bits = bin(opcode)[2:].zfill(8) # # for (x, y) in zip(self.bitPattern, opcode_bits): # if x in ('0', '1'): # if x != y: # return None # else: # # update according parameter # params[x] <<= 1 # params[x] |= int(y) # # return params # # def match(self, opcode): # return self.matchBits(opcode) is not None # # def length(self): # return 1 + self.argSize # # def decode(self, proj, opcodes, addr): # assert len(opcodes) == self.length() # # params = self.matchBits(opcodes[0]) # # argument = 0 # if self.argSize == 1: # argument = opcodes[1] # elif self.argSize == 2: # argument = (opcodes[2] << 8) | opcodes[1]; # # next_addr = addr.offset(self.length()) # # out_operands = [ # fillOperand(text, params, argument, next_addr) for text in self.operands # ] # # reads, writes, values, loads = self.effect.filled(params, make_context(params, argument, next_addr)) # # return instruction.make(proj, self.name, out_operands, addr, reads, writes, values, loads), next_addr , which may include functions, classes, or code. Output only the next line.
def testMatch(self):
Given the code snippet: <|code_start|> points = [{ "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -87, 36]}}, { "type": "Feature", <|code_end|> , generate the next line using the imports in this file: import pytest import responses from mapbox import DirectionsMatrix from mapbox.errors import MapboxDeprecationWarning and context (functions, classes, or occasionally code) from other files: # Path: mapbox/services/matrix.py # class DirectionsMatrix(Service): # """Access to the Matrix API V1""" # # api_name = 'directions-matrix' # api_version = 'v1' # # valid_profiles = [ # 'mapbox/driving', 'mapbox/cycling', 'mapbox/walking', # 'mapbox/driving-traffic'] # valid_annotations = ['duration', 'distance'] # # @property # def baseuri(self): # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # def _validate_profile(self, profile): # # Support for Distance v1 and Directions v4 profiles # profiles_map = { # 'mapbox.driving': 'mapbox/driving', # 'mapbox.cycling': 'mapbox/cycling', # 'mapbox.walking': 'mapbox/walking', # 'driving': 'mapbox/driving', # 'cycling': 'mapbox/cycling', # 'walking': 'mapbox/walking'} # if profile in profiles_map: # profile = profiles_map[profile] # warnings.warn("Converting deprecated profile, use {} instead".format(profile), # MapboxDeprecationWarning) # if profile not in self.valid_profiles: # raise InvalidProfileError( # "{0} is not a valid profile".format(profile)) # return profile # # def _validate_annotations(self, annotations): # results = [] # if annotations is None: # return None # for annotation in annotations: # if annotation not in self.valid_annotations: # raise errors.InvalidParameterError( # "{0} is not a valid annotation".format(annotation)) # else: # results.append(annotation) # return results # # def _make_query(self, srcindexes, dstindexes): # params = {} # if srcindexes is not None and isinstance(srcindexes, list): # params['sources'] = ';'.join([str(idx) for idx in srcindexes]) # if dstindexes is not None and isinstance(dstindexes, list): # params['destinations'] = ';'.join([str(idx) for idx in dstindexes]) # return params # # def matrix(self, coordinates, profile='mapbox/driving', # sources=None, destinations=None, annotations=None): # """Request a directions matrix for trips between coordinates # # In the default case, the matrix returns a symmetric matrix, # using all input coordinates as sources and destinations. You may # also generate an asymmetric matrix, with only some coordinates # as sources or destinations: # # Parameters # ---------- # coordinates : sequence # A sequence of coordinates, which may be represented as # GeoJSON features, GeoJSON geometries, or (longitude, # latitude) pairs. # profile : str # The trip travel mode. Valid modes are listed in the class's # valid_profiles attribute. # annotations : list # Used to specify the resulting matrices. Possible values are # listed in the class's valid_annotations attribute. # sources : list # Indices of source coordinates to include in the matrix. # Default is all coordinates. # destinations : list # Indices of destination coordinates to include in the # matrix. Default is all coordinates. # # Returns # ------- # requests.Response # # Note: the directions matrix itself is obtained by calling the # response's json() method. The resulting mapping has a code, # the destinations and the sources, and depending of the # annotations specified, it can also contain a durations matrix, # a distances matrix or both of them (by default, only the # durations matrix is provided). # # code : str # Status of the response # sources : list # Results of snapping selected coordinates to the nearest # addresses. # destinations : list # Results of snapping selected coordinates to the nearest # addresses. # durations : list # An array of arrays representing the matrix in row-major # order. durations[i][j] gives the travel time from the i-th # source to the j-th destination. All values are in seconds. # The duration between the same coordinate is always 0. If # a duration can not be found, the result is null. # distances : list # An array of arrays representing the matrix in row-major # order. distances[i][j] gives the distance from the i-th # source to the j-th destination. All values are in meters. # The distance between the same coordinate is always 0. If # a distance can not be found, the result is null. # # """ # annotations = self._validate_annotations(annotations) # profile = self._validate_profile(profile) # coords = encode_waypoints(coordinates) # # params = self._make_query(sources, destinations) # # if annotations is not None: # params.update({'annotations': ','.join(annotations)}) # # uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords) # res = self.session.get(uri, params=params) # self.handle_http_error(res) # return res # # Path: mapbox/errors.py # class MapboxDeprecationWarning(UserWarning): # pass . Output only the next line.
"properties": {},
Based on the snippet: <|code_start|> points = [{ "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -87, 36]}}, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -86, 36]}}, { "type": "Feature", <|code_end|> , predict the immediate next line with the help of imports: import pytest import responses from mapbox import DirectionsMatrix from mapbox.errors import MapboxDeprecationWarning and context (classes, functions, sometimes code) from other files: # Path: mapbox/services/matrix.py # class DirectionsMatrix(Service): # """Access to the Matrix API V1""" # # api_name = 'directions-matrix' # api_version = 'v1' # # valid_profiles = [ # 'mapbox/driving', 'mapbox/cycling', 'mapbox/walking', # 'mapbox/driving-traffic'] # valid_annotations = ['duration', 'distance'] # # @property # def baseuri(self): # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # def _validate_profile(self, profile): # # Support for Distance v1 and Directions v4 profiles # profiles_map = { # 'mapbox.driving': 'mapbox/driving', # 'mapbox.cycling': 'mapbox/cycling', # 'mapbox.walking': 'mapbox/walking', # 'driving': 'mapbox/driving', # 'cycling': 'mapbox/cycling', # 'walking': 'mapbox/walking'} # if profile in profiles_map: # profile = profiles_map[profile] # warnings.warn("Converting deprecated profile, use {} instead".format(profile), # MapboxDeprecationWarning) # if profile not in self.valid_profiles: # raise InvalidProfileError( # "{0} is not a valid profile".format(profile)) # return profile # # def _validate_annotations(self, annotations): # results = [] # if annotations is None: # return None # for annotation in annotations: # if annotation not in self.valid_annotations: # raise errors.InvalidParameterError( # "{0} is not a valid annotation".format(annotation)) # else: # results.append(annotation) # return results # # def _make_query(self, srcindexes, dstindexes): # params = {} # if srcindexes is not None and isinstance(srcindexes, list): # params['sources'] = ';'.join([str(idx) for idx in srcindexes]) # if dstindexes is not None and isinstance(dstindexes, list): # params['destinations'] = ';'.join([str(idx) for idx in dstindexes]) # return params # # def matrix(self, coordinates, profile='mapbox/driving', # sources=None, destinations=None, annotations=None): # """Request a directions matrix for trips between coordinates # # In the default case, the matrix returns a symmetric matrix, # using all input coordinates as sources and destinations. You may # also generate an asymmetric matrix, with only some coordinates # as sources or destinations: # # Parameters # ---------- # coordinates : sequence # A sequence of coordinates, which may be represented as # GeoJSON features, GeoJSON geometries, or (longitude, # latitude) pairs. # profile : str # The trip travel mode. Valid modes are listed in the class's # valid_profiles attribute. # annotations : list # Used to specify the resulting matrices. Possible values are # listed in the class's valid_annotations attribute. # sources : list # Indices of source coordinates to include in the matrix. # Default is all coordinates. # destinations : list # Indices of destination coordinates to include in the # matrix. Default is all coordinates. # # Returns # ------- # requests.Response # # Note: the directions matrix itself is obtained by calling the # response's json() method. The resulting mapping has a code, # the destinations and the sources, and depending of the # annotations specified, it can also contain a durations matrix, # a distances matrix or both of them (by default, only the # durations matrix is provided). # # code : str # Status of the response # sources : list # Results of snapping selected coordinates to the nearest # addresses. # destinations : list # Results of snapping selected coordinates to the nearest # addresses. # durations : list # An array of arrays representing the matrix in row-major # order. durations[i][j] gives the travel time from the i-th # source to the j-th destination. All values are in seconds. # The duration between the same coordinate is always 0. If # a duration can not be found, the result is null. # distances : list # An array of arrays representing the matrix in row-major # order. distances[i][j] gives the distance from the i-th # source to the j-th destination. All values are in meters. # The distance between the same coordinate is always 0. If # a distance can not be found, the result is null. # # """ # annotations = self._validate_annotations(annotations) # profile = self._validate_profile(profile) # coords = encode_waypoints(coordinates) # # params = self._make_query(sources, destinations) # # if annotations is not None: # params.update({'annotations': ','.join(annotations)}) # # uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords) # res = self.session.get(uri, params=params) # self.handle_http_error(res) # return res # # Path: mapbox/errors.py # class MapboxDeprecationWarning(UserWarning): # pass . Output only the next line.
"properties": {},
Next line prediction: <|code_start|> with pytest.raises(ValueError) as exc: encode_waypoints(gj_point_features, max_limit=1) assert 'at most' in str(exc.value) def test_unsupported_geometry(): unsupported = copy.deepcopy(gj_point_features) unsupported[0]['geometry']['type'] = "MultiPolygonnnnnn" with pytest.raises(ValueError) as exc: list(read_points(unsupported)) assert 'Unsupported geometry' in str(exc.value) def test_unknown_object(): unknown = ["foo", "bar"] with pytest.raises(ValueError) as exc: list(read_points(unknown)) assert 'Unknown object' in str(exc.value) def test_encode_polyline(): expected = "wp_~EvdatO{xiAfupD" assert expected == encode_polyline(gj_point_features) assert expected == encode_polyline(gj_multipoint_features) assert expected == encode_polyline(gj_line_features) def test_encode_coordinates_json(): expected = { 'coordinates': [ <|code_end|> . Use current file imports: (import pytest import copy import json from mapbox.encoding import (read_points, encode_waypoints, encode_polyline, encode_coordinates_json)) and context including class names, function names, or small code snippets from other files: # Path: mapbox/encoding.py # def read_points(features): # """ Iterable of features to a sequence of point tuples # Where "features" can be either GeoJSON mappings # or objects implementing the geo_interface # """ # for feature in features: # # if isinstance(feature, (tuple, list)) and len(feature) == 2: # yield feature # # elif hasattr(feature, '__geo_interface__'): # # An object implementing the geo_interface # try: # # Could be a Feature... # geom = feature.__geo_interface__['geometry'] # for pt in _geom_points(geom): # yield pt # except KeyError: # # ... or a geometry directly # for pt in _geom_points(feature.__geo_interface__): # yield pt # # elif 'type' in feature and feature['type'] == 'Feature': # # A GeoJSON-like mapping # geom = feature['geometry'] # for pt in _geom_points(geom): # yield pt # # elif 'coordinates' in feature: # geom = feature # for pt in _geom_points(geom): # yield pt # # else: # raise InvalidFeatureError( # "Unknown object: Not a GeoJSON Point feature or " # "an object with __geo_interface__:\n{0}".format(feature)) # # def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): # """Given an iterable of features # return a string encoded in waypoint-style used by certain mapbox APIs # ("lon,lat" pairs separated by ";") # """ # coords = ['{lon},{lat}'.format( # lon=float(round(lon, precision)), # lat=float(round(lat, precision))) # for lon, lat in read_points(features)] # # if min_limit is not None and len(coords) < min_limit: # raise InvalidFeatureError( # "Not enough features to encode coordinates, " # "need at least {0}".format(min_limit)) # if max_limit is not None and len(coords) > max_limit: # raise InvalidFeatureError( # "Too many features to encode coordinates, " # "need at most {0}".format(max_limit)) # # return ';'.join(coords) # # def encode_polyline(features): # """Encode and iterable of features as a polyline # """ # points = list(read_points(features)) # latlon_points = [(x[1], x[0]) for x in points] # return polyline.encode(latlon_points) # # def encode_coordinates_json(features): # """Given an iterable of features # return a JSON string to be used as the request body for the distance API: # a JSON object, with a key coordinates, # which has an array of [ Longitude, Lattitude ] pairs # """ # coords = { # 'coordinates': list(read_points(features))} # return json.dumps(coords) . Output only the next line.
[-87.33787536621092, 36.539156961321574],
Given snippet: <|code_start|> [-87.33787536621092, 36.539156961321574], [-88.2476806640625, 36.92217534275667]]}}] class GeoThing(object): __geo_interface__ = None def __init__(self, thing): self.__geo_interface__ = thing def test_read_geojson_features(): expected = [(-87.33787536621092, 36.539156961321574), (-88.2476806640625, 36.92217534275667)] assert expected == list(read_points(gj_point_features)) assert expected == list(read_points(gj_multipoint_features)) assert expected == list(read_points(gj_line_features)) def test_geo_interface(): expected = [(-87.33787536621092, 36.539156961321574), (-88.2476806640625, 36.92217534275667)] features = [GeoThing(gj_point_features[0]), GeoThing(gj_point_features[1])] assert expected == list(read_points(features)) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import copy import json from mapbox.encoding import (read_points, encode_waypoints, encode_polyline, encode_coordinates_json) and context: # Path: mapbox/encoding.py # def read_points(features): # """ Iterable of features to a sequence of point tuples # Where "features" can be either GeoJSON mappings # or objects implementing the geo_interface # """ # for feature in features: # # if isinstance(feature, (tuple, list)) and len(feature) == 2: # yield feature # # elif hasattr(feature, '__geo_interface__'): # # An object implementing the geo_interface # try: # # Could be a Feature... # geom = feature.__geo_interface__['geometry'] # for pt in _geom_points(geom): # yield pt # except KeyError: # # ... or a geometry directly # for pt in _geom_points(feature.__geo_interface__): # yield pt # # elif 'type' in feature and feature['type'] == 'Feature': # # A GeoJSON-like mapping # geom = feature['geometry'] # for pt in _geom_points(geom): # yield pt # # elif 'coordinates' in feature: # geom = feature # for pt in _geom_points(geom): # yield pt # # else: # raise InvalidFeatureError( # "Unknown object: Not a GeoJSON Point feature or " # "an object with __geo_interface__:\n{0}".format(feature)) # # def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): # """Given an iterable of features # return a string encoded in waypoint-style used by certain mapbox APIs # ("lon,lat" pairs separated by ";") # """ # coords = ['{lon},{lat}'.format( # lon=float(round(lon, precision)), # lat=float(round(lat, precision))) # for lon, lat in read_points(features)] # # if min_limit is not None and len(coords) < min_limit: # raise InvalidFeatureError( # "Not enough features to encode coordinates, " # "need at least {0}".format(min_limit)) # if max_limit is not None and len(coords) > max_limit: # raise InvalidFeatureError( # "Too many features to encode coordinates, " # "need at most {0}".format(max_limit)) # # return ';'.join(coords) # # def encode_polyline(features): # """Encode and iterable of features as a polyline # """ # points = list(read_points(features)) # latlon_points = [(x[1], x[0]) for x in points] # return polyline.encode(latlon_points) # # def encode_coordinates_json(features): # """Given an iterable of features # return a JSON string to be used as the request body for the distance API: # a JSON object, with a key coordinates, # which has an array of [ Longitude, Lattitude ] pairs # """ # coords = { # 'coordinates': list(read_points(features))} # return json.dumps(coords) which might include code, classes, or functions. Output only the next line.
geoms = [GeoThing(gj_point_features[0]['geometry']),
Continue the code snippet: <|code_start|> gj_point_features = [{ "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -87.33787536621092, 36.539156961321574]}}, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -88.2476806640625, 36.92217534275667]}}] gj_multipoint_features = [{ "type": "Feature", "properties": {}, "geometry": { <|code_end|> . Use current file imports: import pytest import copy import json from mapbox.encoding import (read_points, encode_waypoints, encode_polyline, encode_coordinates_json) and context (classes, functions, or code) from other files: # Path: mapbox/encoding.py # def read_points(features): # """ Iterable of features to a sequence of point tuples # Where "features" can be either GeoJSON mappings # or objects implementing the geo_interface # """ # for feature in features: # # if isinstance(feature, (tuple, list)) and len(feature) == 2: # yield feature # # elif hasattr(feature, '__geo_interface__'): # # An object implementing the geo_interface # try: # # Could be a Feature... # geom = feature.__geo_interface__['geometry'] # for pt in _geom_points(geom): # yield pt # except KeyError: # # ... or a geometry directly # for pt in _geom_points(feature.__geo_interface__): # yield pt # # elif 'type' in feature and feature['type'] == 'Feature': # # A GeoJSON-like mapping # geom = feature['geometry'] # for pt in _geom_points(geom): # yield pt # # elif 'coordinates' in feature: # geom = feature # for pt in _geom_points(geom): # yield pt # # else: # raise InvalidFeatureError( # "Unknown object: Not a GeoJSON Point feature or " # "an object with __geo_interface__:\n{0}".format(feature)) # # def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): # """Given an iterable of features # return a string encoded in waypoint-style used by certain mapbox APIs # ("lon,lat" pairs separated by ";") # """ # coords = ['{lon},{lat}'.format( # lon=float(round(lon, precision)), # lat=float(round(lat, precision))) # for lon, lat in read_points(features)] # # if min_limit is not None and len(coords) < min_limit: # raise InvalidFeatureError( # "Not enough features to encode coordinates, " # "need at least {0}".format(min_limit)) # if max_limit is not None and len(coords) > max_limit: # raise InvalidFeatureError( # "Too many features to encode coordinates, " # "need at most {0}".format(max_limit)) # # return ';'.join(coords) # # def encode_polyline(features): # """Encode and iterable of features as a polyline # """ # points = list(read_points(features)) # latlon_points = [(x[1], x[0]) for x in points] # return polyline.encode(latlon_points) # # def encode_coordinates_json(features): # """Given an iterable of features # return a JSON string to be used as the request body for the distance API: # a JSON object, with a key coordinates, # which has an array of [ Longitude, Lattitude ] pairs # """ # coords = { # 'coordinates': list(read_points(features))} # return json.dumps(coords) . Output only the next line.
"type": "MultiPoint",
Predict the next line for this snippet: <|code_start|> 36.539156961321574], [-88.2476806640625, 36.92217534275667]]}}] class GeoThing(object): __geo_interface__ = None def __init__(self, thing): self.__geo_interface__ = thing def test_read_geojson_features(): expected = [(-87.33787536621092, 36.539156961321574), (-88.2476806640625, 36.92217534275667)] assert expected == list(read_points(gj_point_features)) assert expected == list(read_points(gj_multipoint_features)) assert expected == list(read_points(gj_line_features)) def test_geo_interface(): expected = [(-87.33787536621092, 36.539156961321574), (-88.2476806640625, 36.92217534275667)] features = [GeoThing(gj_point_features[0]), GeoThing(gj_point_features[1])] assert expected == list(read_points(features)) geoms = [GeoThing(gj_point_features[0]['geometry']), <|code_end|> with the help of current file imports: import pytest import copy import json from mapbox.encoding import (read_points, encode_waypoints, encode_polyline, encode_coordinates_json) and context from other files: # Path: mapbox/encoding.py # def read_points(features): # """ Iterable of features to a sequence of point tuples # Where "features" can be either GeoJSON mappings # or objects implementing the geo_interface # """ # for feature in features: # # if isinstance(feature, (tuple, list)) and len(feature) == 2: # yield feature # # elif hasattr(feature, '__geo_interface__'): # # An object implementing the geo_interface # try: # # Could be a Feature... # geom = feature.__geo_interface__['geometry'] # for pt in _geom_points(geom): # yield pt # except KeyError: # # ... or a geometry directly # for pt in _geom_points(feature.__geo_interface__): # yield pt # # elif 'type' in feature and feature['type'] == 'Feature': # # A GeoJSON-like mapping # geom = feature['geometry'] # for pt in _geom_points(geom): # yield pt # # elif 'coordinates' in feature: # geom = feature # for pt in _geom_points(geom): # yield pt # # else: # raise InvalidFeatureError( # "Unknown object: Not a GeoJSON Point feature or " # "an object with __geo_interface__:\n{0}".format(feature)) # # def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): # """Given an iterable of features # return a string encoded in waypoint-style used by certain mapbox APIs # ("lon,lat" pairs separated by ";") # """ # coords = ['{lon},{lat}'.format( # lon=float(round(lon, precision)), # lat=float(round(lat, precision))) # for lon, lat in read_points(features)] # # if min_limit is not None and len(coords) < min_limit: # raise InvalidFeatureError( # "Not enough features to encode coordinates, " # "need at least {0}".format(min_limit)) # if max_limit is not None and len(coords) > max_limit: # raise InvalidFeatureError( # "Too many features to encode coordinates, " # "need at most {0}".format(max_limit)) # # return ';'.join(coords) # # def encode_polyline(features): # """Encode and iterable of features as a polyline # """ # points = list(read_points(features)) # latlon_points = [(x[1], x[0]) for x in points] # return polyline.encode(latlon_points) # # def encode_coordinates_json(features): # """Given an iterable of features # return a JSON string to be used as the request body for the distance API: # a JSON object, with a key coordinates, # which has an array of [ Longitude, Lattitude ] pairs # """ # coords = { # 'coordinates': list(read_points(features))} # return json.dumps(coords) , which may contain function names, class names, or code. Output only the next line.
GeoThing(gj_point_features[1]['geometry'])]
Using the snippet: <|code_start|> def validate_lat(val): if val < -85.0511 or val > 85.0511: raise errors.InvalidCoordError( "Latitude must be between -85.0511 and 85.0511") return val def validate_lon(val): if val < -180 or val > 180: raise errors.InvalidCoordError( "Longitude must be between -180 and 180") <|code_end|> , determine the next line of code. You have imports: import json import warnings from uritemplate import URITemplate from mapbox import errors from mapbox.services.base import Service from mapbox.utils import normalize_geojson_featurecollection and context (class names, function names, or code) available: # Path: mapbox/errors.py # class ValidationError(ValueError): # class InvalidCountryCodeError(ValidationError): # class InvalidPlaceTypeError(ValidationError): # class InvalidProfileError(ValidationError): # class InvalidFeatureError(ValidationError): # class HTTPError(ValidationError): # class InvalidCoordError(ValidationError): # class InputSizeError(ValidationError): # class ImageSizeError(ValidationError): # class TokenError(ValidationError): # class InvalidParameterError(ValidationError): # class InvalidFileError(ValidationError): # class InvalidResourceTypeError(ValidationError): # class InvalidPeriodError(ValidationError): # class InvalidUsernameError(ValidationError): # class InvalidId(ValidationError): # class MapboxDeprecationWarning(UserWarning): # class InvalidZoomError(ValidationError): # class InvalidColumnError(ValidationError): # class InvalidRowError(ValidationError): # class InvalidFileFormatError(ValidationError): # class InvalidFeatureFormatError(ValidationError): # class InvalidMarkerNameError(ValidationError): # class InvalidLabelError(ValidationError): # class InvalidColorError(ValidationError): # # Path: mapbox/services/base.py # class Service(object): # """Service base class # # Attributes # ---------- # default_host : str # Default service hostname: api.mapbox.com. # api_name : str # Mapbox API name. # api_version : str # API version string such as "v1" or "v5". # baseuri # username # # Methods # ------- # handle_http_errors(response, custom_messages=None, raise_for_status=False) # Converts service errors to Python exceptions. # """ # # default_host = 'api.mapbox.com' # api_name = 'hors service' # api_version = 'v0' # # def __init__(self, access_token=None, host=None, cache=None): # """Constructs a Service object # # This method should be overridden by subclasses. # # Parameters # ---------- # access_token : str # Mapbox access token string. # host : str, optional # Mapbox API host (advanced usage only). # cache : CacheControl cache instance (Dict or FileCache), optional # Optional caching, not generally needed. # # Returns # ------- # Service # """ # self.session = Session(access_token) # self.host = host or os.environ.get('MAPBOX_HOST', self.default_host) # if cache: # self.session = CacheControl(self.session, cache=cache) # # @property # def baseuri(self): # """The service's base URI # # Returns # ------- # str # """ # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # @property # def username(self): # """The username in the service's access token # # Returns # ------- # str # """ # token = self.session.params.get('access_token') # if not token: # raise errors.TokenError( # "session does not have a valid access_token param") # data = token.split('.')[1] # # replace url chars and add padding # # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770) # data = data.replace('-', '+').replace('_', '/') + "===" # try: # return json.loads(base64.b64decode(data).decode('utf-8'))['u'] # except (ValueError, KeyError): # raise errors.TokenError( # "access_token does not contain username") # # def handle_http_error(self, response, custom_messages=None, # raise_for_status=False): # """Converts service errors to Python exceptions # # Parameters # ---------- # response : requests.Response # A service response. # custom_messages : dict, optional # A mapping of custom exception messages to HTTP status codes. # raise_for_status : bool, optional # If True, the requests library provides Python exceptions. # # Returns # ------- # None # """ # if not custom_messages: # custom_messages = {} # if response.status_code in custom_messages.keys(): # raise errors.HTTPError(custom_messages[response.status_code]) # if raise_for_status: # response.raise_for_status() # # Path: mapbox/utils.py # def normalize_geojson_featurecollection(obj): # """Takes a geojson-like mapping representing # geometry, Feature or FeatureCollection (or a sequence of such objects) # and returns a FeatureCollection-like dict # """ # if not isinstance(obj, Sequence): # obj = [obj] # # features = [] # for x in obj: # if not isinstance(x, Mapping) or 'type' not in x: # raise ValueError( # "Expecting a geojson-like mapping or sequence of them") # # if 'features' in x: # features.extend(x['features']) # elif 'geometry' in x: # features.append(x) # elif 'coordinates' in x: # feat = {'type': 'Feature', # 'properties': {}, # 'geometry': x} # features.append(feat) # else: # raise ValueError( # "Expecting a geojson-like mapping or sequence of them") # # return {'type': 'FeatureCollection', 'features': features} . Output only the next line.
return val
Given the following code snippet before the placeholder: <|code_start|> def validate_lat(val): if val < -85.0511 or val > 85.0511: raise errors.InvalidCoordError( "Latitude must be between -85.0511 and 85.0511") return val def validate_lon(val): if val < -180 or val > 180: raise errors.InvalidCoordError( "Longitude must be between -180 and 180") return val def validate_image_size(val): if not 1 < val < 1280: raise errors.ImageSizeError( "Image height and width must be between 1 and 1280") return val def validate_overlay(val): if len(val) > 2073: # limit is 2083 minus the 'geojson()' raise errors.InputSizeError( <|code_end|> , predict the next line using imports from the current file: import json import warnings from uritemplate import URITemplate from mapbox import errors from mapbox.services.base import Service from mapbox.utils import normalize_geojson_featurecollection and context including class names, function names, and sometimes code from other files: # Path: mapbox/errors.py # class ValidationError(ValueError): # class InvalidCountryCodeError(ValidationError): # class InvalidPlaceTypeError(ValidationError): # class InvalidProfileError(ValidationError): # class InvalidFeatureError(ValidationError): # class HTTPError(ValidationError): # class InvalidCoordError(ValidationError): # class InputSizeError(ValidationError): # class ImageSizeError(ValidationError): # class TokenError(ValidationError): # class InvalidParameterError(ValidationError): # class InvalidFileError(ValidationError): # class InvalidResourceTypeError(ValidationError): # class InvalidPeriodError(ValidationError): # class InvalidUsernameError(ValidationError): # class InvalidId(ValidationError): # class MapboxDeprecationWarning(UserWarning): # class InvalidZoomError(ValidationError): # class InvalidColumnError(ValidationError): # class InvalidRowError(ValidationError): # class InvalidFileFormatError(ValidationError): # class InvalidFeatureFormatError(ValidationError): # class InvalidMarkerNameError(ValidationError): # class InvalidLabelError(ValidationError): # class InvalidColorError(ValidationError): # # Path: mapbox/services/base.py # class Service(object): # """Service base class # # Attributes # ---------- # default_host : str # Default service hostname: api.mapbox.com. # api_name : str # Mapbox API name. # api_version : str # API version string such as "v1" or "v5". # baseuri # username # # Methods # ------- # handle_http_errors(response, custom_messages=None, raise_for_status=False) # Converts service errors to Python exceptions. # """ # # default_host = 'api.mapbox.com' # api_name = 'hors service' # api_version = 'v0' # # def __init__(self, access_token=None, host=None, cache=None): # """Constructs a Service object # # This method should be overridden by subclasses. # # Parameters # ---------- # access_token : str # Mapbox access token string. # host : str, optional # Mapbox API host (advanced usage only). # cache : CacheControl cache instance (Dict or FileCache), optional # Optional caching, not generally needed. # # Returns # ------- # Service # """ # self.session = Session(access_token) # self.host = host or os.environ.get('MAPBOX_HOST', self.default_host) # if cache: # self.session = CacheControl(self.session, cache=cache) # # @property # def baseuri(self): # """The service's base URI # # Returns # ------- # str # """ # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # @property # def username(self): # """The username in the service's access token # # Returns # ------- # str # """ # token = self.session.params.get('access_token') # if not token: # raise errors.TokenError( # "session does not have a valid access_token param") # data = token.split('.')[1] # # replace url chars and add padding # # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770) # data = data.replace('-', '+').replace('_', '/') + "===" # try: # return json.loads(base64.b64decode(data).decode('utf-8'))['u'] # except (ValueError, KeyError): # raise errors.TokenError( # "access_token does not contain username") # # def handle_http_error(self, response, custom_messages=None, # raise_for_status=False): # """Converts service errors to Python exceptions # # Parameters # ---------- # response : requests.Response # A service response. # custom_messages : dict, optional # A mapping of custom exception messages to HTTP status codes. # raise_for_status : bool, optional # If True, the requests library provides Python exceptions. # # Returns # ------- # None # """ # if not custom_messages: # custom_messages = {} # if response.status_code in custom_messages.keys(): # raise errors.HTTPError(custom_messages[response.status_code]) # if raise_for_status: # response.raise_for_status() # # Path: mapbox/utils.py # def normalize_geojson_featurecollection(obj): # """Takes a geojson-like mapping representing # geometry, Feature or FeatureCollection (or a sequence of such objects) # and returns a FeatureCollection-like dict # """ # if not isinstance(obj, Sequence): # obj = [obj] # # features = [] # for x in obj: # if not isinstance(x, Mapping) or 'type' not in x: # raise ValueError( # "Expecting a geojson-like mapping or sequence of them") # # if 'features' in x: # features.extend(x['features']) # elif 'geometry' in x: # features.append(x) # elif 'coordinates' in x: # feat = {'type': 'Feature', # 'properties': {}, # 'geometry': x} # features.append(feat) # else: # raise ValueError( # "Expecting a geojson-like mapping or sequence of them") # # return {'type': 'FeatureCollection', 'features': features} . Output only the next line.
"GeoJSON is too large for the static maps API, "
Here is a snippet: <|code_start|> for pt in types: if pt not in self.place_types: raise InvalidPlaceTypeError(pt) return {'types': ",".join(types)} def forward(self, address, types=None, lon=None, lat=None, country=None, bbox=None, limit=None, languages=None): """Returns a Requests response object that contains a GeoJSON collection of places matching the given address. `response.geojson()` returns the geocoding result as GeoJSON. `response.status_code` returns the HTTP API status code. Place results may be constrained to those of one or more types or be biased toward a given longitude and latitude. See: https://www.mapbox.com/api-documentation/search/#geocoding.""" uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand( dataset=self.name, query=address.encode('utf-8')) params = {} if country: params.update(self._validate_country_codes(country)) if types: params.update(self._validate_place_types(types)) if lon is not None and lat is not None: params.update(proximity='{0},{1}'.format( round(float(lon), self.precision.get('proximity', 3)), round(float(lat), self.precision.get('proximity', 3)))) if languages: params.update(language=','.join(languages)) <|code_end|> . Write the next line using the current file imports: from iso3166 import countries from uritemplate import URITemplate from mapbox.errors import InvalidCountryCodeError, InvalidPlaceTypeError from mapbox.services.base import Service and context from other files: # Path: mapbox/errors.py # class InvalidCountryCodeError(ValidationError): # pass # # class InvalidPlaceTypeError(ValidationError): # pass # # Path: mapbox/services/base.py # class Service(object): # """Service base class # # Attributes # ---------- # default_host : str # Default service hostname: api.mapbox.com. # api_name : str # Mapbox API name. # api_version : str # API version string such as "v1" or "v5". # baseuri # username # # Methods # ------- # handle_http_errors(response, custom_messages=None, raise_for_status=False) # Converts service errors to Python exceptions. # """ # # default_host = 'api.mapbox.com' # api_name = 'hors service' # api_version = 'v0' # # def __init__(self, access_token=None, host=None, cache=None): # """Constructs a Service object # # This method should be overridden by subclasses. # # Parameters # ---------- # access_token : str # Mapbox access token string. # host : str, optional # Mapbox API host (advanced usage only). # cache : CacheControl cache instance (Dict or FileCache), optional # Optional caching, not generally needed. # # Returns # ------- # Service # """ # self.session = Session(access_token) # self.host = host or os.environ.get('MAPBOX_HOST', self.default_host) # if cache: # self.session = CacheControl(self.session, cache=cache) # # @property # def baseuri(self): # """The service's base URI # # Returns # ------- # str # """ # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # @property # def username(self): # """The username in the service's access token # # Returns # ------- # str # """ # token = self.session.params.get('access_token') # if not token: # raise errors.TokenError( # "session does not have a valid access_token param") # data = token.split('.')[1] # # replace url chars and add padding # # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770) # data = data.replace('-', '+').replace('_', '/') + "===" # try: # return json.loads(base64.b64decode(data).decode('utf-8'))['u'] # except (ValueError, KeyError): # raise errors.TokenError( # "access_token does not contain username") # # def handle_http_error(self, response, custom_messages=None, # raise_for_status=False): # """Converts service errors to Python exceptions # # Parameters # ---------- # response : requests.Response # A service response. # custom_messages : dict, optional # A mapping of custom exception messages to HTTP status codes. # raise_for_status : bool, optional # If True, the requests library provides Python exceptions. # # Returns # ------- # None # """ # if not custom_messages: # custom_messages = {} # if response.status_code in custom_messages.keys(): # raise errors.HTTPError(custom_messages[response.status_code]) # if raise_for_status: # response.raise_for_status() , which may include functions, classes, or code. Output only the next line.
if bbox is not None:
Predict the next line after this snippet: <|code_start|> collection of places matching the given address. `response.geojson()` returns the geocoding result as GeoJSON. `response.status_code` returns the HTTP API status code. Place results may be constrained to those of one or more types or be biased toward a given longitude and latitude. See: https://www.mapbox.com/api-documentation/search/#geocoding.""" uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand( dataset=self.name, query=address.encode('utf-8')) params = {} if country: params.update(self._validate_country_codes(country)) if types: params.update(self._validate_place_types(types)) if lon is not None and lat is not None: params.update(proximity='{0},{1}'.format( round(float(lon), self.precision.get('proximity', 3)), round(float(lat), self.precision.get('proximity', 3)))) if languages: params.update(language=','.join(languages)) if bbox is not None: params.update(bbox='{0},{1},{2},{3}'.format(*bbox)) if limit is not None: params.update(limit='{0}'.format(limit)) resp = self.session.get(uri, params=params) self.handle_http_error(resp) # for consistency with other services <|code_end|> using the current file's imports: from iso3166 import countries from uritemplate import URITemplate from mapbox.errors import InvalidCountryCodeError, InvalidPlaceTypeError from mapbox.services.base import Service and any relevant context from other files: # Path: mapbox/errors.py # class InvalidCountryCodeError(ValidationError): # pass # # class InvalidPlaceTypeError(ValidationError): # pass # # Path: mapbox/services/base.py # class Service(object): # """Service base class # # Attributes # ---------- # default_host : str # Default service hostname: api.mapbox.com. # api_name : str # Mapbox API name. # api_version : str # API version string such as "v1" or "v5". # baseuri # username # # Methods # ------- # handle_http_errors(response, custom_messages=None, raise_for_status=False) # Converts service errors to Python exceptions. # """ # # default_host = 'api.mapbox.com' # api_name = 'hors service' # api_version = 'v0' # # def __init__(self, access_token=None, host=None, cache=None): # """Constructs a Service object # # This method should be overridden by subclasses. # # Parameters # ---------- # access_token : str # Mapbox access token string. # host : str, optional # Mapbox API host (advanced usage only). # cache : CacheControl cache instance (Dict or FileCache), optional # Optional caching, not generally needed. # # Returns # ------- # Service # """ # self.session = Session(access_token) # self.host = host or os.environ.get('MAPBOX_HOST', self.default_host) # if cache: # self.session = CacheControl(self.session, cache=cache) # # @property # def baseuri(self): # """The service's base URI # # Returns # ------- # str # """ # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # @property # def username(self): # """The username in the service's access token # # Returns # ------- # str # """ # token = self.session.params.get('access_token') # if not token: # raise errors.TokenError( # "session does not have a valid access_token param") # data = token.split('.')[1] # # replace url chars and add padding # # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770) # data = data.replace('-', '+').replace('_', '/') + "===" # try: # return json.loads(base64.b64decode(data).decode('utf-8'))['u'] # except (ValueError, KeyError): # raise errors.TokenError( # "access_token does not contain username") # # def handle_http_error(self, response, custom_messages=None, # raise_for_status=False): # """Converts service errors to Python exceptions # # Parameters # ---------- # response : requests.Response # A service response. # custom_messages : dict, optional # A mapping of custom exception messages to HTTP status codes. # raise_for_status : bool, optional # If True, the requests library provides Python exceptions. # # Returns # ------- # None # """ # if not custom_messages: # custom_messages = {} # if response.status_code in custom_messages.keys(): # raise errors.HTTPError(custom_messages[response.status_code]) # if raise_for_status: # response.raise_for_status() . Output only the next line.
def geojson():
Continue the code snippet: <|code_start|> return {'types': ",".join(types)} def forward(self, address, types=None, lon=None, lat=None, country=None, bbox=None, limit=None, languages=None): """Returns a Requests response object that contains a GeoJSON collection of places matching the given address. `response.geojson()` returns the geocoding result as GeoJSON. `response.status_code` returns the HTTP API status code. Place results may be constrained to those of one or more types or be biased toward a given longitude and latitude. See: https://www.mapbox.com/api-documentation/search/#geocoding.""" uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand( dataset=self.name, query=address.encode('utf-8')) params = {} if country: params.update(self._validate_country_codes(country)) if types: params.update(self._validate_place_types(types)) if lon is not None and lat is not None: params.update(proximity='{0},{1}'.format( round(float(lon), self.precision.get('proximity', 3)), round(float(lat), self.precision.get('proximity', 3)))) if languages: params.update(language=','.join(languages)) if bbox is not None: params.update(bbox='{0},{1},{2},{3}'.format(*bbox)) if limit is not None: <|code_end|> . Use current file imports: from iso3166 import countries from uritemplate import URITemplate from mapbox.errors import InvalidCountryCodeError, InvalidPlaceTypeError from mapbox.services.base import Service and context (classes, functions, or code) from other files: # Path: mapbox/errors.py # class InvalidCountryCodeError(ValidationError): # pass # # class InvalidPlaceTypeError(ValidationError): # pass # # Path: mapbox/services/base.py # class Service(object): # """Service base class # # Attributes # ---------- # default_host : str # Default service hostname: api.mapbox.com. # api_name : str # Mapbox API name. # api_version : str # API version string such as "v1" or "v5". # baseuri # username # # Methods # ------- # handle_http_errors(response, custom_messages=None, raise_for_status=False) # Converts service errors to Python exceptions. # """ # # default_host = 'api.mapbox.com' # api_name = 'hors service' # api_version = 'v0' # # def __init__(self, access_token=None, host=None, cache=None): # """Constructs a Service object # # This method should be overridden by subclasses. # # Parameters # ---------- # access_token : str # Mapbox access token string. # host : str, optional # Mapbox API host (advanced usage only). # cache : CacheControl cache instance (Dict or FileCache), optional # Optional caching, not generally needed. # # Returns # ------- # Service # """ # self.session = Session(access_token) # self.host = host or os.environ.get('MAPBOX_HOST', self.default_host) # if cache: # self.session = CacheControl(self.session, cache=cache) # # @property # def baseuri(self): # """The service's base URI # # Returns # ------- # str # """ # return 'https://{0}/{1}/{2}'.format( # self.host, self.api_name, self.api_version) # # @property # def username(self): # """The username in the service's access token # # Returns # ------- # str # """ # token = self.session.params.get('access_token') # if not token: # raise errors.TokenError( # "session does not have a valid access_token param") # data = token.split('.')[1] # # replace url chars and add padding # # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770) # data = data.replace('-', '+').replace('_', '/') + "===" # try: # return json.loads(base64.b64decode(data).decode('utf-8'))['u'] # except (ValueError, KeyError): # raise errors.TokenError( # "access_token does not contain username") # # def handle_http_error(self, response, custom_messages=None, # raise_for_status=False): # """Converts service errors to Python exceptions # # Parameters # ---------- # response : requests.Response # A service response. # custom_messages : dict, optional # A mapping of custom exception messages to HTTP status codes. # raise_for_status : bool, optional # If True, the requests library provides Python exceptions. # # Returns # ------- # None # """ # if not custom_messages: # custom_messages = {} # if response.status_code in custom_messages.keys(): # raise errors.HTTPError(custom_messages[response.status_code]) # if raise_for_status: # response.raise_for_status() . Output only the next line.
params.update(limit='{0}'.format(limit))
Next line prediction: <|code_start|> class BaseSystem: endian_id: Endian = Endian.UNKNOWN processor_id: Processor = Processor.UNKNOWN def __init__(self, system_name: str) -> None: self.system_name = system_name def get_processor_id(self) -> Processor: <|code_end|> . Use current file imports: (from .constants import Endian, Processor) and context including class names, function names, or small code snippets from other files: # Path: python/loaderlib/constants.py # class Endian(IntEnum): # UNKNOWN = 0 # BIG = 1 # LITTLE = 2 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
return self.processor_id
Given snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 which might include code, classes, or functions. Output only the next line.
line_data: Optional[List[Any]] = None
Predict the next line after this snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> using the current file's imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and any relevant context from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
line_data: Optional[List[Any]] = None
Here is a snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> . Write the next line using the current file imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 , which may include functions, classes, or code. Output only the next line.
line_data: Optional[List[Any]] = None
Predict the next line for this snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> with the help of current file imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 , which may contain function names, class names, or code. Output only the next line.
line_data: Optional[List[Any]] = None
Here is a snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> . Write the next line using the current file imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 , which may include functions, classes, or code. Output only the next line.
line_data: Optional[List[Any]] = None
Given the code snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> , generate the next line using the imports in this file: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context (functions, classes, or occasionally code) from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
line_data: Optional[List[Any]] = None
Continue the code snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> . Use current file imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context (classes, functions, or code) from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
line_data: Optional[List[Any]] = None
Based on the snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> , predict the immediate next line with the help of imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and context (classes, functions, sometimes code) from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
line_data: Optional[List[Any]] = None
Predict the next line after this snippet: <|code_start|> self.dis_disassemble_one_line_func = None self.dis_disassemble_as_data_func = None self.dis_constant_pc_offset = None self.dis_get_default_symbol_name_func = None self.dis_is_operand_pointer_sized = None # loaderlib: self.loader_data_types = None # persistence exposed information: """ Whether the saved project embeds the input file in it's entirety. """ self.input_file_cached = False class SegmentBlock(object): """ Sequential numbering in order of creation. """ sequence_id: Optional[int] = None last_sequence_id = 0 """ The number of this segment in the file. """ segment_id: Optional[int] = None """ The offset of this block in its segment. """ segment_offset: Optional[int] = None """ All segments appear as one contiguous address space. This is the offset of this block in that space. """ address: Optional[int] = None """ The number of bytes data that this block contains. """ length: Optional[int] = None """ The data type of this block (DATA_TYPE_*) and more """ flags = 0 """ DATA_TYPE_CODE: [ line0_match, ... lineN_match ]. DATA_TYPE_ASCII: [ (offset, length), ... ]. """ <|code_end|> using the current file's imports: import io from typing import Any, Dict, List, Optional, Tuple from .loaderlib.constants import DATA_TYPE_BIT0, DATA_TYPE_BITCOUNT, DATA_TYPE_BITMASK, \ DATA_TYPE_DATA08, DATA_TYPE_DATA16, DATA_TYPE_DATA32, DATA_TYPE_SIZES, FileFormat, Processor and any relevant context from other files: # Path: python/loaderlib/constants.py # DATA_TYPE_BIT0 = DATA_TYPE_CODE - 1 # # DATA_TYPE_BITCOUNT = _count_bits(DATA_TYPE_DATA32) # # DATA_TYPE_BITMASK = _make_bitmask(DATA_TYPE_BITCOUNT) # # DATA_TYPE_DATA08 = 3 # # DATA_TYPE_DATA16 = 4 # # DATA_TYPE_DATA32 = 5 # # DATA_TYPE_SIZES = [ # (DATA_TYPE_DATA32, 4), # (DATA_TYPE_DATA16, 2), # (DATA_TYPE_DATA08, 1), # ] # # class FileFormat(IntEnum): # UNKNOWN = 0 # AMIGA_HUNK_EXECUTABLE = PLATFORM_AMIGA + 1 # AMIGA_HUNK_LIBRARY = PLATFORM_AMIGA + 2 # ATARIST_GEMDOS_EXECUTABLE = PLATFORM_ATARIST + 1 # SNES_SMC = PLATFORM_SNES + 1 # X68000_X_EXECUTABLE = PLATFORM_X68000 + 1 # ZXSPECTRUM_Z80_1 = PLATFORM_ZXSPECTRUM + 1 # ZXSPECTRUM_Z80_2 = PLATFORM_ZXSPECTRUM + 2 # ZXSPECTRUM_Z80_3 = PLATFORM_ZXSPECTRUM + 3 # # class Processor(IntEnum): # UNKNOWN = 0 # M680x0 = 100 # M68000 = 101 # M68010 = 102 # M68020 = 103 # M68030 = 104 # M68040 = 105 # M68060 = 106 # MIPS = 200 # P65c816 = 300 # This gets a P prefix to account for the numeric name. # Z80 = 400 . Output only the next line.
line_data: Optional[List[Any]] = None
Using the snippet: <|code_start|> data = b"testdata" signature = keyhandler.key.sign(data) pkey = keyhandler.key.public_key() self.assertIsNotNone(pkey) # would throw InvalidSignature if not correct pkey.verify(signature, data) self.assertIsNotNone(keyhandler.key) def test_serialize_keys_passphrase(self): key = Key() key.create_key("ed25519", None) pem = key.serialize("test_store_keys_passphrase") prvkey = key.load(pem, "test_store_keys_passphrase") self.assertIsInstance(prvkey.key, ed25519.Ed25519PrivateKey) def test_store_keys_no_object(self): key = Key() with self.assertRaisesMessage(RuntimeError, "No key object"): key.serialize("test_store_keys_passphrase") def test_store_keys_no_passphrase(self): key = Key() key.create_key("ed25519", None) pem = key.serialize() key = Key() prvkey = key.load(pem) self.assertIsInstance(prvkey.key, ed25519.Ed25519PrivateKey) def test_store_keys_wrong_passphrase(self): key = Key() <|code_end|> , determine the next line of code. You have imports: from cryptography.hazmat.primitives.asymmetric import ed25519 from django.test import TestCase from certificate_engine.ssl.key import Key and context (class names, function names, or code) available: # Path: certificate_engine/ssl/key.py # class Key(object): # _key: Optional[PRIVATE_KEY_TYPES] = None # # @property # def key(self) -> PRIVATE_KEY_TYPES: # if self._key is None: # raise RuntimeError("No key object") # return self._key # # def create_key(self, key_algorithm: str, key_size: int) -> "Key": # """ # Create a public/private key pair. # # Arguments: key_size - Number of bits to use in the key (only RSA) # key_algorithm = the used key algorithm, currently rsa, ed25519 supported # Returns: The private key # """ # if key_algorithm == "ed25519": # self._key = ed25519.Ed25519PrivateKey.generate() # elif key_algorithm == "rsa": # self._key = rsa.generate_private_key(public_exponent=65537, key_size=key_size, backend=default_backend()) # else: # raise NotImplementedError(f"Key algorithm {key_algorithm} not implemented") # return self # # def serialize_pkcs12( # self, # name: str = None, # certificate: x509.Certificate = None, # passphrase: str = None, # cas: Optional[List[x509.Certificate]] = None, # ) -> bytes: # """ # Serialize key # # Arguments: name - Name to use for the supplied certificate and key. # certificate - Certificate to contain in pkcs12 # passphrase - optional passphrase (must be string) # cas (list of Certificate or None) – An optional set of certificates to also include in the structure. # Returns: bytes # """ # # if not self._key: # raise RuntimeError("No key object") # # if not isinstance(self._key, get_args(serialization.pkcs12._ALLOWED_PKCS12_TYPES)): # raise RuntimeError(f"Key object type {type(self._key).__name__} not supported") # key = cast(serialization.pkcs12._ALLOWED_PKCS12_TYPES, self._key) # # if not name: # raise ValueError("No name provided") # # if not certificate: # raise ValueError("No certificate provided") # # encryption = ( # serialization.BestAvailableEncryption(passphrase.encode("utf-8")) # if passphrase # else serialization.NoEncryption() # ) # return serialization.pkcs12.serialize_key_and_certificates( # name.encode("utf-8"), key, certificate, cas, encryption # ) # # def serialize(self, passphrase: str = None, encoding: serialization.Encoding = serialization.Encoding.PEM) -> str: # """ # Serialize key # # Arguments: passphrase - optional passphrase (must be string) # encoding - optional different encoding # Returns: string # """ # # if not self._key: # raise RuntimeError("No key object") # # encryption = ( # serialization.BestAvailableEncryption(passphrase.encode("utf-8")) # if passphrase # else serialization.NoEncryption() # ) # return self._key.private_bytes( # encoding=encoding, # format=serialization.PrivateFormat.PKCS8, # encryption_algorithm=encryption, # ).decode("utf-8") # # def load(self, pem: str, passphrase: str = None) -> "Key": # """ # Read key from pem # # Arguments: pem - bytes with key # passphrase - optional passphrase (must be string) # Returns: Self # """ # try: # self._key = serialization.load_pem_private_key( # pem.encode("utf-8"), passphrase.encode("utf-8") if passphrase else None, backend=default_backend() # ) # except ValueError: # raise ValueError("Bad decrypt. Incorrect password?") # return self # # @staticmethod # def check_passphrase(pem: str, passphrase: str = None) -> bool: # """ # Checks passphrase of a pem key file # # Arguments: pem - string with key # passphrase - passphrase (must be string) # Returns: true if passphrase is ok # """ # try: # serialization.load_pem_private_key( # pem.encode("utf-8"), passphrase.encode("utf-8") if passphrase else None, backend=default_backend() # ) # return True # except ValueError as e: # if str(e) == "Bad decrypt. Incorrect password?": # return False # raise e . Output only the next line.
key.create_key("ed25519", None)
Given the following code snippet before the placeholder: <|code_start|> class CreateSuperUserView(SignupView): form_class = SuperUserSignupForm success_url = reverse_lazy("admin:index") def dispatch(self, request, *args, **kwargs): if User.objects.exists(): return HttpResponseNotFound() return super(SignupView, self).dispatch(request, args, kwargs) def get_context_data(self, **kwargs): ret = super(CreateSuperUserView, self).get_context_data(**kwargs) ret.update({"title": _("Register Super User")}) return ret def form_valid(self, form): # no email verification required self.user = form.save(self.request) try: <|code_end|> , predict the next line using imports from the current file: from allauth.account.utils import complete_signup from allauth.account.views import SignupView from allauth.exceptions import ImmediateHttpResponse from django.contrib.auth.models import User from django.http import HttpResponseNotFound from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ from superuser_signup.forms import SuperUserSignupForm and context including class names, function names, and sometimes code from other files: # Path: superuser_signup/forms.py # class SuperUserSignupForm(SignupForm): # def save(self, request): # user = super(SuperUserSignupForm, self).save(request) # user.is_staff = True # user.is_superuser = True # user.save() # return user . Output only the next line.
return complete_signup(
Next line prediction: <|code_start|> class CategorySchema(ModelSchema): class Meta: model = Category class PetSchema(ModelSchema): category = ma.fields.Nested(CategorySchema) <|code_end|> . Use current file imports: (import marshmallow as ma from marshmallow_peewee import ModelSchema from .models import Pet, Category) and context including class names, function names, or small code snippets from other files: # Path: examples/peewee_orm/models.py # class Pet(pw.Model): # # created = pw.DateTimeField(default=dt.datetime.utcnow) # name = pw.CharField() # image = pw.CharField(null=True) # status = pw.CharField(choices=[ # ('available', 'available'), ('pending', 'pending'), ('sold', 'sold')]) # # category = pw.ForeignKeyField(Category) # # class Category(pw.Model): # name = pw.CharField() . Output only the next line.
class Meta:
Predict the next line for this snippet: <|code_start|> class CategorySchema(ModelSchema): class Meta: model = Category class PetSchema(ModelSchema): category = ma.fields.Nested(CategorySchema) class Meta: model = Pet dump_only = 'created', <|code_end|> with the help of current file imports: import marshmallow as ma from marshmallow_peewee import ModelSchema from .models import Pet, Category and context from other files: # Path: examples/peewee_orm/models.py # class Pet(pw.Model): # # created = pw.DateTimeField(default=dt.datetime.utcnow) # name = pw.CharField() # image = pw.CharField(null=True) # status = pw.CharField(choices=[ # ('available', 'available'), ('pending', 'pending'), ('sold', 'sold')]) # # category = pw.ForeignKeyField(Category) # # class Category(pw.Model): # name = pw.CharField() , which may contain function names, class names, or code. Output only the next line.
@ma.post_load
Continue the code snippet: <|code_start|>def read_dir(startdir, *, excludes=(), binary=False): assert isinstance(excludes, list) or isinstance(excludes, tuple), \ "excludes must be a list or a tuple, not " + repr(type(excludes)) startdir = Path(startdir) exclude_tuples = [Path(e).parts for e in excludes] contents = {} for p in startdir.glob('**/*'): if not p.is_file(): continue relpath = p.relative_to(startdir) if any(relpath.parts[:len(tup)] == tup for tup in exclude_tuples): continue # Open in binary mode to avoid newline conversions. with p.open('rb' if binary else 'r') as f: try: contents[relpath] = f.read() except UnicodeDecodeError: contents[relpath] = '<BINARY>' return contents def _format_contents(contents): return [ '{}: {}\n'.format(file, repr(contents[file])) for file in sorted(contents.keys()) ] def assert_contents(dir, expected_contents, <|code_end|> . Use current file imports: import difflib import functools import inspect import io import os import stat import subprocess import sys import tempfile import textwrap import unittest import peru.main from pathlib import Path from peru.async_helpers import run_task from peru.compat import makedirs and context (classes, functions, or code) from other files: # Path: peru/async_helpers.py # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) # # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) . Output only the next line.
*,
Using the snippet: <|code_start|> assert ret in allowed_returns, \ 'run_peru_command() returned an error: ' + repr(ret) return capture_stream.getvalue() class Repo: def __init__(self, path): self.path = path def run(self, *command): output = subprocess.check_output(command, cwd=self.path) return output.decode('utf8').strip() class GitRepo(Repo): def __init__(self, content_dir, init_default_branch='master'): super().__init__(content_dir) self.run('git', 'init', '--initial-branch', init_default_branch) self.run('git', 'config', 'user.name', 'peru') self.run('git', 'config', 'user.email', 'peru') self.run('git', 'add', '-A') self.run('git', 'commit', '--allow-empty', '-m', 'first commit') class HgRepo(Repo): def __init__(self, content_dir): super().__init__(content_dir) self.run('hg', 'init') <|code_end|> , determine the next line of code. You have imports: import difflib import functools import inspect import io import os import stat import subprocess import sys import tempfile import textwrap import unittest import peru.main from pathlib import Path from peru.async_helpers import run_task from peru.compat import makedirs and context (class names, function names, or code) available: # Path: peru/async_helpers.py # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) # # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) . Output only the next line.
hgrc_path = os.path.join(content_dir, '.hg', 'hgrc')
Based on the snippet: <|code_start|> _set_last_imports(runtime, imports_tree) async def get_imports_tree(runtime, scope, imports, base_tree=None): target_trees = await get_trees(runtime, scope, imports.keys()) imports_tree = await merge_imports_tree(runtime.cache, imports, target_trees, base_tree) return imports_tree async def get_trees(runtime, scope, targets): futures = [get_tree(runtime, scope, target) for target in targets] trees = await gather_coalescing_exceptions( futures, runtime.display, verbose=runtime.verbose) return dict(zip(targets, trees)) async def get_tree(runtime, scope, target_str): module, rules = await scope.parse_target(runtime, target_str) context = 'target "{}"'.format(target_str) with error_context(context): tree = await module.get_tree(runtime) if module.default_rule: tree = await module.default_rule.get_tree(runtime, tree) for rule in rules: tree = await rule.get_tree(runtime, tree) return tree def _last_imports_path(runtime): <|code_end|> , predict the immediate next line with the help of imports: import os from pathlib import Path from .async_helpers import gather_coalescing_exceptions from . import compat from .error import error_context from .merge import merge_imports_tree and context (classes, functions, sometimes code) from other files: # Path: peru/async_helpers.py # async def gather_coalescing_exceptions(coros, display, *, verbose): # '''The tricky thing about running multiple coroutines in parallel is what # we're supposed to do when one of them raises an exception. The approach # we're using here is to catch exceptions and keep waiting for other tasks to # finish. At the end, we reraise a GatheredExceptions error, if any # exceptions were caught. # # Another minor detail: We also want to make sure to start coroutines in the # order given, so that they end up appearing to the user alphabetically in # the fancy display. Note that asyncio.gather() puts coroutines in a set # internally, so we schedule coroutines *before* we give them to gather(). # ''' # # exceptions = [] # reprs = [] # # async def catching_wrapper(coro): # try: # return (await coro) # except Exception as e: # exceptions.append(e) # if isinstance(e, PrintableError) and not verbose: # reprs.append(e.message) # else: # reprs.append(traceback.format_exc()) # return None # # # Suppress a deprecation warning in Python 3.5, while continuing to support # # 3.3 and early 3.4 releases. # if hasattr(asyncio, 'ensure_future'): # schedule = getattr(asyncio, 'ensure_future') # else: # schedule = getattr(asyncio, 'async') # # futures = [schedule(catching_wrapper(coro)) for coro in coros] # # results = await asyncio.gather(*futures) # # if exceptions: # raise GatheredExceptions(exceptions, reprs) # else: # return results # # Path: peru/merge.py # async def merge_imports_tree(cache, imports, target_trees, base_tree=None): # '''Take an Imports struct and a dictionary of resolved trees and merge the # unified imports tree. If base_tree is supplied, merge that too. There are a # couple reasons for structuring this function the way it is: # - We want to cache merged trees, so that we don't have to do expensive # git operations just to check whether a module is in cache. # - We want tree merging to know about target names, so that it can write # good error messages when there are conflicts. # - We need to use this for both toplevel imports and recursive module # imports. # ''' # key = _cache_key(imports, target_trees, base_tree) # if key in cache.keyval: # return cache.keyval[key] # # We always want to merge imports in the same order, so that any conflicts # # we run into will be deterministic. Sort the imports alphabetically by # # target name. # unified_tree = base_tree or (await cache.get_empty_tree()) # for target, paths in imports.items(): # for path in paths: # try: # unified_tree = await cache.merge_trees( # unified_tree, target_trees[target], path) # except MergeConflictError as e: # message = 'Merge conflict in import "{}" at "{}":\n\n{}' # e.message = message.format(target, path, # textwrap.indent(e.message, ' ')) # raise # cache.keyval[key] = unified_tree # return unified_tree . Output only the next line.
return Path(runtime.state_dir) / 'lastimports'
Given snippet: <|code_start|> module, rules = await scope.parse_target(runtime, target_str) context = 'target "{}"'.format(target_str) with error_context(context): tree = await module.get_tree(runtime) if module.default_rule: tree = await module.default_rule.get_tree(runtime, tree) for rule in rules: tree = await rule.get_tree(runtime, tree) return tree def _last_imports_path(runtime): return Path(runtime.state_dir) / 'lastimports' def _get_last_imports(runtime): last_imports_tree = None if _last_imports_path(runtime).exists(): with _last_imports_path(runtime).open() as f: last_imports_tree = f.read() return last_imports_tree def _set_last_imports(runtime, tree): if tree == _get_last_imports(runtime): # Don't modify the lastimports file if the imports haven't changed. # This lets you use it as a build stamp for Make. return compat.makedirs(_last_imports_path(runtime).parent) with _last_imports_path(runtime).open('w') as f: <|code_end|> , continue by predicting the next line. Consider current file imports: import os from pathlib import Path from .async_helpers import gather_coalescing_exceptions from . import compat from .error import error_context from .merge import merge_imports_tree and context: # Path: peru/async_helpers.py # async def gather_coalescing_exceptions(coros, display, *, verbose): # '''The tricky thing about running multiple coroutines in parallel is what # we're supposed to do when one of them raises an exception. The approach # we're using here is to catch exceptions and keep waiting for other tasks to # finish. At the end, we reraise a GatheredExceptions error, if any # exceptions were caught. # # Another minor detail: We also want to make sure to start coroutines in the # order given, so that they end up appearing to the user alphabetically in # the fancy display. Note that asyncio.gather() puts coroutines in a set # internally, so we schedule coroutines *before* we give them to gather(). # ''' # # exceptions = [] # reprs = [] # # async def catching_wrapper(coro): # try: # return (await coro) # except Exception as e: # exceptions.append(e) # if isinstance(e, PrintableError) and not verbose: # reprs.append(e.message) # else: # reprs.append(traceback.format_exc()) # return None # # # Suppress a deprecation warning in Python 3.5, while continuing to support # # 3.3 and early 3.4 releases. # if hasattr(asyncio, 'ensure_future'): # schedule = getattr(asyncio, 'ensure_future') # else: # schedule = getattr(asyncio, 'async') # # futures = [schedule(catching_wrapper(coro)) for coro in coros] # # results = await asyncio.gather(*futures) # # if exceptions: # raise GatheredExceptions(exceptions, reprs) # else: # return results # # Path: peru/merge.py # async def merge_imports_tree(cache, imports, target_trees, base_tree=None): # '''Take an Imports struct and a dictionary of resolved trees and merge the # unified imports tree. If base_tree is supplied, merge that too. There are a # couple reasons for structuring this function the way it is: # - We want to cache merged trees, so that we don't have to do expensive # git operations just to check whether a module is in cache. # - We want tree merging to know about target names, so that it can write # good error messages when there are conflicts. # - We need to use this for both toplevel imports and recursive module # imports. # ''' # key = _cache_key(imports, target_trees, base_tree) # if key in cache.keyval: # return cache.keyval[key] # # We always want to merge imports in the same order, so that any conflicts # # we run into will be deterministic. Sort the imports alphabetically by # # target name. # unified_tree = base_tree or (await cache.get_empty_tree()) # for target, paths in imports.items(): # for path in paths: # try: # unified_tree = await cache.merge_trees( # unified_tree, target_trees[target], path) # except MergeConflictError as e: # message = 'Merge conflict in import "{}" at "{}":\n\n{}' # e.message = message.format(target, path, # textwrap.indent(e.message, ' ')) # raise # cache.keyval[key] = unified_tree # return unified_tree which might include code, classes, or functions. Output only the next line.
f.write(tree)
Given the following code snippet before the placeholder: <|code_start|> cache_dir = shared.create_dir() shared.run_peru_command(['sync'], self.cwd, env={ 'PERU_CACHE_DIR': cache_dir, }) self.assert_success(self.project_dir, self.state_dir, cache_dir) def test_flags_override_vars(self): flag_cache_dir = shared.create_dir() env_cache_dir = shared.create_dir() shared.run_peru_command(['--cache-dir', flag_cache_dir, 'sync'], self.cwd, env={'PERU_CACHE_DIR': env_cache_dir}) self.assert_success(self.project_dir, self.state_dir, flag_cache_dir) def test_relative_paths(self): '''We ran into a bug where calling os.path.dirname(peru_file) was returning "", which got passed as the cwd of a plugin job and blew up. This test repros that case. We've switched to pathlib.Path.parent to fix the issue.''' shared.run_peru_command( ['--file', 'peru.yaml', '--sync-dir', '.', 'sync'], cwd=self.project_dir) self.assert_success(self.project_dir, self.state_dir, self.cache_dir) def test_default_file_name(self): shutil.move(self.peru_file, os.path.join(self.project_dir, 'xxx')) shared.run_peru_command(['--file-basename', 'xxx', 'sync'], cwd=self.cwd) <|code_end|> , predict the next line using imports from the current file: import os import shutil import textwrap import shared from peru.compat import makedirs from peru.runtime import CommandLineError and context including class names, function names, and sometimes code from other files: # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) # # Path: peru/runtime.py # class CommandLineError(PrintableError): # pass . Output only the next line.
self.assert_success(
Predict the next line after this snippet: <|code_start|> cache_dir = shared.create_dir() shared.run_peru_command(['sync'], self.cwd, env={ 'PERU_CACHE_DIR': cache_dir, }) self.assert_success(self.project_dir, self.state_dir, cache_dir) def test_flags_override_vars(self): flag_cache_dir = shared.create_dir() env_cache_dir = shared.create_dir() shared.run_peru_command(['--cache-dir', flag_cache_dir, 'sync'], self.cwd, env={'PERU_CACHE_DIR': env_cache_dir}) self.assert_success(self.project_dir, self.state_dir, flag_cache_dir) def test_relative_paths(self): '''We ran into a bug where calling os.path.dirname(peru_file) was returning "", which got passed as the cwd of a plugin job and blew up. This test repros that case. We've switched to pathlib.Path.parent to fix the issue.''' shared.run_peru_command( ['--file', 'peru.yaml', '--sync-dir', '.', 'sync'], cwd=self.project_dir) self.assert_success(self.project_dir, self.state_dir, self.cache_dir) def test_default_file_name(self): shutil.move(self.peru_file, os.path.join(self.project_dir, 'xxx')) shared.run_peru_command(['--file-basename', 'xxx', 'sync'], cwd=self.cwd) <|code_end|> using the current file's imports: import os import shutil import textwrap import shared from peru.compat import makedirs from peru.runtime import CommandLineError and any relevant context from other files: # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) # # Path: peru/runtime.py # class CommandLineError(PrintableError): # pass . Output only the next line.
self.assert_success(
Given snippet: <|code_start|> class MergeTest(PeruTest): @make_synchronous async def setUp(self): self.cache_dir = create_dir() self.cache = await Cache(self.cache_dir) # These tests use this simple one-file tree as module contents. content = {'a': 'a'} content_dir = create_dir(content) self.content_tree = await self.cache.import_tree(content_dir) @make_synchronous async def test_merge_from_map(self): imports = {'foo': ('path1', ), 'bar': ('path2', )} target_trees = {'foo': self.content_tree, 'bar': self.content_tree} merged_tree = await merge_imports_tree(self.cache, imports, target_trees) merged_dir = create_dir() await self.cache.export_tree(merged_tree, merged_dir) expected_content = {'path1/a': 'a', 'path2/a': 'a'} assert_contents(merged_dir, expected_content) <|code_end|> , continue by predicting the next line. Consider current file imports: from peru.cache import Cache from peru.merge import merge_imports_tree from shared import create_dir, assert_contents, PeruTest, make_synchronous and context: # Path: peru/cache.py # async def Cache(root): # 'This is the async constructor for the _Cache class.' # cache = _Cache(root) # await cache._init_trees() # return cache # # Path: peru/merge.py # async def merge_imports_tree(cache, imports, target_trees, base_tree=None): # '''Take an Imports struct and a dictionary of resolved trees and merge the # unified imports tree. If base_tree is supplied, merge that too. There are a # couple reasons for structuring this function the way it is: # - We want to cache merged trees, so that we don't have to do expensive # git operations just to check whether a module is in cache. # - We want tree merging to know about target names, so that it can write # good error messages when there are conflicts. # - We need to use this for both toplevel imports and recursive module # imports. # ''' # key = _cache_key(imports, target_trees, base_tree) # if key in cache.keyval: # return cache.keyval[key] # # We always want to merge imports in the same order, so that any conflicts # # we run into will be deterministic. Sort the imports alphabetically by # # target name. # unified_tree = base_tree or (await cache.get_empty_tree()) # for target, paths in imports.items(): # for path in paths: # try: # unified_tree = await cache.merge_trees( # unified_tree, target_trees[target], path) # except MergeConflictError as e: # message = 'Merge conflict in import "{}" at "{}":\n\n{}' # e.message = message.format(target, path, # textwrap.indent(e.message, ' ')) # raise # cache.keyval[key] = unified_tree # return unified_tree which might include code, classes, or functions. Output only the next line.
@make_synchronous
Using the snippet: <|code_start|> class MergeTest(PeruTest): @make_synchronous async def setUp(self): self.cache_dir = create_dir() self.cache = await Cache(self.cache_dir) # These tests use this simple one-file tree as module contents. content = {'a': 'a'} content_dir = create_dir(content) self.content_tree = await self.cache.import_tree(content_dir) @make_synchronous async def test_merge_from_map(self): <|code_end|> , determine the next line of code. You have imports: from peru.cache import Cache from peru.merge import merge_imports_tree from shared import create_dir, assert_contents, PeruTest, make_synchronous and context (class names, function names, or code) available: # Path: peru/cache.py # async def Cache(root): # 'This is the async constructor for the _Cache class.' # cache = _Cache(root) # await cache._init_trees() # return cache # # Path: peru/merge.py # async def merge_imports_tree(cache, imports, target_trees, base_tree=None): # '''Take an Imports struct and a dictionary of resolved trees and merge the # unified imports tree. If base_tree is supplied, merge that too. There are a # couple reasons for structuring this function the way it is: # - We want to cache merged trees, so that we don't have to do expensive # git operations just to check whether a module is in cache. # - We want tree merging to know about target names, so that it can write # good error messages when there are conflicts. # - We need to use this for both toplevel imports and recursive module # imports. # ''' # key = _cache_key(imports, target_trees, base_tree) # if key in cache.keyval: # return cache.keyval[key] # # We always want to merge imports in the same order, so that any conflicts # # we run into will be deterministic. Sort the imports alphabetically by # # target name. # unified_tree = base_tree or (await cache.get_empty_tree()) # for target, paths in imports.items(): # for path in paths: # try: # unified_tree = await cache.merge_trees( # unified_tree, target_trees[target], path) # except MergeConflictError as e: # message = 'Merge conflict in import "{}" at "{}":\n\n{}' # e.message = message.format(target, path, # textwrap.indent(e.message, ' ')) # raise # cache.keyval[key] = unified_tree # return unified_tree . Output only the next line.
imports = {'foo': ('path1', ), 'bar': ('path2', )}
Predict the next line after this snippet: <|code_start|> 'b/c': 'foo', 'x': 'foo', 'y/c': 'bar', COLON + 'd': 'baz', }) @shared.make_synchronous async def test_move(self): # Same semantics as copy above. Also, make sure that move deletes move # sources, but does not delete sources that were overwritten by the # target of another move. moves = {'a': 'b', 'b': 'a'} tree = await rule.move_files(self.cache, self.content_tree, moves) await shared.assert_tree_contents(self.cache, tree, { 'a/c': 'bar', 'b/a': 'foo', COLON + 'd': 'baz', }) @shared.make_synchronous async def test_drop(self): drop_dir = await rule.drop_files(self.cache, self.content_tree, ['b']) await shared.assert_tree_contents(self.cache, drop_dir, { 'a': 'foo', COLON + 'd': 'baz' }) drop_file = await rule.drop_files(self.cache, self.content_tree, ['a']) await shared.assert_tree_contents(self.cache, drop_file, { 'b/c': 'bar', <|code_end|> using the current file's imports: import os import shared from peru import cache from peru import rule from shared import COLON and any relevant context from other files: # Path: peru/cache.py # TEXT_MODE = object() # BINARY_MODE = object() # DEBUG_GIT_COMMAND_COUNT = 0 # LINES_TO_SHOW = 10 # BLOB_TYPE = 'blob' # TREE_TYPE = 'tree' # NONEXECUTABLE_FILE_MODE = '100644' # EXECUTABLE_FILE_MODE = '100755' # TREE_MODE = '040000' # DOTPERU_CAPITALIZATIONS = [ # '.peru', # '.Peru', # '.pEru', # '.peRu', # '.perU', # '.PEru', # '.PeRu', # '.PerU', # '.pERu', # '.pErU', # '.peRU', # '.PERu', # '.PErU', # '.PeRU', # '.pERU', # '.PERU', # ] # def compute_key(data): # def __init__(self, git_dir, index_file, working_copy): # async def git(self, *args, input=None, output_mode=TEXT_MODE, cwd=None): # def git_env(self): # async def init_git_dir(self): # async def read_tree_into_index(self, tree): # async def read_tree_and_stats_into_index(self, tree): # async def make_tree_from_index(self): # async def read_working_copy_into_index(self, picks): # async def drop_paths_from_index(self, paths): # async def merge_tree_into_index(self, tree, prefix): # async def working_copy_matches_index(self): # async def get_modified_files_skipping_deletes(self): # async def get_new_files_in_tree(self, previous_tree, new_tree): # async def read_tree_updating_working_copy(self, tree, force): # async def checkout_files_from_index(self): # async def get_info_for_path(self, tree, path): # async def read_bytes_from_file_hash(self, sha1): # async def list_tree_entries(self, tree, path, recursive): # async def make_tree_from_entries(self, entries): # async def Cache(root): # def __init__(self, root): # async def _init_trees(self): # def clean_git_session(self, working_copy=None): # def no_index_git_session(self): # async def get_empty_tree(self): # async def import_tree(self, src, *, picks=None, excludes=None): # async def merge_trees(self, base_tree, merge_tree, merge_path='.'): # async def export_tree(self, # tree, # dest, # previous_tree=None, # *, # force=False, # previous_index_file=None): # async def read_file(self, tree, path): # async def ls_tree(self, tree, path=None, *, recursive=False): # async def modify_tree(self, tree, modifications): # def delete_if_error(path): # def _format_file_lines(files): # def __init__(self, command, errorcode, stdout, stderr): # def dotperu_exclude_case_insensitive_git_globs(): # class GitSession: # class _Cache: # class GitError(Exception): # class ModifyTreeError(PrintableError): # class DirtyWorkingCopyError(PrintableError): # class MergeConflictError(PrintableError): # # Path: peru/rule.py # class Rule: # class NoMatchingFilesError(PrintableError): # def __init__(self, name, copy, move, executable, drop, pick, export): # def _cache_key(self, input_tree): # async def get_tree(self, runtime, input_tree): # async def _copy_files_modifications(_cache, tree, paths_multimap): # async def copy_files(_cache, tree, paths_multimap): # async def move_files(_cache, tree, paths_multimap): # async def _get_glob_entries(_cache, tree, globs_list): # async def pick_files(_cache, tree, globs_list): # async def drop_files(_cache, tree, globs_list): # async def make_files_executable(_cache, tree, globs_list): # async def get_export_tree(_cache, tree, export_path): . Output only the next line.
COLON + 'd': 'baz'
Here is a snippet: <|code_start|> class AsyncTest(PeruTest): @make_synchronous async def test_safe_communicate(self): # Test safe_communicate with both empty and non-empty input. cat_command = [ sys.executable, "-c", "import sys; sys.stdout.write(sys.stdin.read())" ] proc_empty = await asyncio.create_subprocess_exec( *cat_command, stdin=PIPE, stdout=PIPE) stdout, _ = await safe_communicate(proc_empty, b"") self.assertEqual(stdout, b"") proc_nonempty = await asyncio.create_subprocess_exec( *cat_command, stdin=PIPE, stdout=PIPE) stdout, _ = await safe_communicate(proc_nonempty, b"foo bar baz") self.assertEqual(stdout, b"foo bar baz") # And test a case with None input as well. true_command = [sys.executable, "-c", ""] proc_true = await asyncio.create_subprocess_exec( *true_command, stdin=PIPE, stdout=PIPE) stdout, _ = await safe_communicate(proc_true) <|code_end|> . Write the next line using the current file imports: import asyncio import sys from asyncio.subprocess import PIPE from peru.async_helpers import safe_communicate from shared import PeruTest, make_synchronous and context from other files: # Path: peru/async_helpers.py # async def safe_communicate(process, input=None): # '''Asyncio's communicate method has a bug where `communicate(input=b"")` is # treated the same as `communicate(). That means that child processes can # hang waiting for input, when their stdin should be closed. See # https://bugs.python.org/issue26848. The issue is fixed upstream in # https://github.com/python/asyncio/commit/915b6eaa30e1e3744e6f8223f996e197c1c9b91d, # but we will probably always need this workaround for old versions.''' # if input is not None and len(input) == 0: # process.stdin.close() # return (await process.communicate()) # else: # return (await process.communicate(input)) , which may include functions, classes, or code. Output only the next line.
self.assertEqual(stdout, b"")
Predict the next line after this snippet: <|code_start|> # The --prefix argument to read-tree chokes on paths that contain dot # or dot-dot. Instead of './', it wants the empty string. Oblige it. # NOTE: This parameter must be forward-slash-separated, even on # Windows. os.path.normpath() is not correct here! prefix_path = pathlib.PurePosixPath(prefix) assert '..' not in prefix_path.parts prefix_arg = prefix_path.as_posix() prefix_arg = '' if prefix_arg == '.' else prefix_arg # The git docs say that a --prefix value must end in a slash. That # doesn't seem to be true in practice, but better safe than sorry. Note # that git treats '--prefix=/' as the root of the tree, so this doesn't # break that case. if not prefix_arg.endswith('/'): prefix_arg += '/' # Normally read-tree with --prefix wants to make sure changes don't # stomp on the working copy. The -i flag ignores the working copy. await self.git('read-tree', '-i', '--prefix', prefix_arg, tree) async def working_copy_matches_index(self): diff_output = await self.git('diff-files', output_mode=BINARY_MODE) return len(diff_output) == 0 async def get_modified_files_skipping_deletes(self): # We want to ignore deleted files, so we exclude only deletes using # 'd' instead of including all of the capital letter forms. # https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203 diff_output = await self.git('diff-files', '-z', '--name-only', '--diff-filter=d') return [name for name in diff_output.split('\x00') if name] <|code_end|> using the current file's imports: import asyncio import contextlib import collections import hashlib import json import os import pathlib import re import textwrap from .async_helpers import safe_communicate from .compat import makedirs from .error import PrintableError from .keyval import KeyVal and any relevant context from other files: # Path: peru/async_helpers.py # async def safe_communicate(process, input=None): # '''Asyncio's communicate method has a bug where `communicate(input=b"")` is # treated the same as `communicate(). That means that child processes can # hang waiting for input, when their stdin should be closed. See # https://bugs.python.org/issue26848. The issue is fixed upstream in # https://github.com/python/asyncio/commit/915b6eaa30e1e3744e6f8223f996e197c1c9b91d, # but we will probably always need this workaround for old versions.''' # if input is not None and len(input) == 0: # process.stdin.close() # return (await process.communicate()) # else: # return (await process.communicate(input)) # # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) . Output only the next line.
async def get_new_files_in_tree(self, previous_tree, new_tree):
Given the following code snippet before the placeholder: <|code_start|> elif path.parts[0] == '/': raise ModifyTreeError('Cannot modify an absolute path.') elif '..' in path.parts: raise ModifyTreeError('.. is not allowed in tree paths.') if len(path.parts) == 1: modifications_at_base[str(path)] = entry else: first_dir = path.parts[0] rest = str(pathlib.PurePosixPath(*path.parts[1:])) modifications_in_subtrees[first_dir][rest] = entry # Insert or delete entries in the base tree. Note that this happens # before any subtree operations. for name, entry in modifications_at_base.items(): if entry is None: entries.pop(name, None) else: entries[name] = entry # Recurse to compute modified subtrees. Note how we handle deletions: # If 'a' is a file, inserting a new file at 'a/b' will implicitly # delete 'a', but trying to delete 'a/b' will be a no-op and will not # delete 'a'. empty_tree = (await self.get_empty_tree()) for name, sub_modifications in modifications_in_subtrees.items(): subtree_base = None if name in entries and entries[name].type == TREE_TYPE: subtree_base = entries[name].hash new_subtree = await self.modify_tree(subtree_base, <|code_end|> , predict the next line using imports from the current file: import asyncio import contextlib import collections import hashlib import json import os import pathlib import re import textwrap from .async_helpers import safe_communicate from .compat import makedirs from .error import PrintableError from .keyval import KeyVal and context including class names, function names, and sometimes code from other files: # Path: peru/async_helpers.py # async def safe_communicate(process, input=None): # '''Asyncio's communicate method has a bug where `communicate(input=b"")` is # treated the same as `communicate(). That means that child processes can # hang waiting for input, when their stdin should be closed. See # https://bugs.python.org/issue26848. The issue is fixed upstream in # https://github.com/python/asyncio/commit/915b6eaa30e1e3744e6f8223f996e197c1c9b91d, # but we will probably always need this workaround for old versions.''' # if input is not None and len(input) == 0: # process.stdin.close() # return (await process.communicate()) # else: # return (await process.communicate(input)) # # Path: peru/compat.py # def makedirs(path): # '''os.makedirs() has an exist_ok param, but it still throws errors when the # path exists with non-default permissions. This isn't fixed until 3.4. # Pathlib won't be getting an exist_ok param until 3.5.''' # path = str(path) # compatibility with pathlib # # Use isdir to avoid silently returning if the path exists but isn't a dir. # if not os.path.isdir(path): # os.makedirs(path) . Output only the next line.
sub_modifications)
Using the snippet: <|code_start|> plugin_fields) self.assertDictEqual({'rev': '1'}, output) def test_git_plugin_with_submodule(self): content_repo = GitRepo(self.content_dir) # Git has a small bug: The .gitmodules file is always created with "\n" # line endings, even on Windows. With core.autocrlf turned on, that # causes a warning when the file is added/committed, because those line # endings would get replaced with "\r\n" when the file was checked out. # We can just turn autocrlf off for this test to silence the warning. content_repo.run('git', 'config', 'core.autocrlf', 'false') submodule_dir = shared.create_dir({'another': 'file'}) submodule_repo = GitRepo(submodule_dir) content_repo.run('git', 'submodule', 'add', '-q', submodule_dir, 'subdir/') content_repo.run('git', 'commit', '-m', 'submodule commit') expected_content = self.content.copy() expected_content['subdir/another'] = 'file' with open(os.path.join(self.content_dir, '.gitmodules')) as f: expected_content['.gitmodules'] = f.read() self.do_plugin_test('git', {'url': self.content_dir}, expected_content) # Now move the submodule forward. Make sure it gets fetched again. shared.write_files(submodule_dir, {'more': 'stuff'}) submodule_repo.run('git', 'add', '-A') submodule_repo.run('git', 'commit', '-m', 'more stuff') subprocess.check_output(['git', 'pull', '-q'], cwd=os.path.join(self.content_dir, 'subdir')) content_repo.run('git', 'commit', '-am', 'submodule update') expected_content['subdir/more'] = 'stuff' <|code_end|> , determine the next line of code. You have imports: import asyncio import contextlib import hashlib import io import os import shutil import subprocess import textwrap import unittest import peru.plugin as plugin import shared from collections import defaultdict from pathlib import Path from peru.async_helpers import run_task from shared import SvnRepo, GitRepo, HgRepo, assert_contents and context (class names, function names, or code) available: # Path: peru/async_helpers.py # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) . Output only the next line.
self.do_plugin_test('git', {'url': self.content_dir}, expected_content)
Here is a snippet: <|code_start|>#! /usr/bin/env python3 # Unfortunately we need to make sure to keep this import above the others, # because async_helpers needs to set the global event loop at import time. __doc__ = '''\ Usage: peru [-hqv] [--file=<file>] [--sync-dir=<dir>] [--state-dir=<dir>] [--cache-dir=<dir>] [--file-basename=<name>] <command> [<args>...] peru [--help|--version] Commands: sync fetch imports and copy them to your project reup update revision information for your modules clean delete imports from your project copy copy files directly from a module to somewhere else <|code_end|> . Write the next line using the current file imports: import collections import json import os import sys import tempfile import docopt from .async_helpers import gather_coalescing_exceptions, run_task from . import compat from .error import PrintableError from . import imports from . import parser from .runtime import Runtime and context from other files: # Path: peru/async_helpers.py # async def gather_coalescing_exceptions(coros, display, *, verbose): # '''The tricky thing about running multiple coroutines in parallel is what # we're supposed to do when one of them raises an exception. The approach # we're using here is to catch exceptions and keep waiting for other tasks to # finish. At the end, we reraise a GatheredExceptions error, if any # exceptions were caught. # # Another minor detail: We also want to make sure to start coroutines in the # order given, so that they end up appearing to the user alphabetically in # the fancy display. Note that asyncio.gather() puts coroutines in a set # internally, so we schedule coroutines *before* we give them to gather(). # ''' # # exceptions = [] # reprs = [] # # async def catching_wrapper(coro): # try: # return (await coro) # except Exception as e: # exceptions.append(e) # if isinstance(e, PrintableError) and not verbose: # reprs.append(e.message) # else: # reprs.append(traceback.format_exc()) # return None # # # Suppress a deprecation warning in Python 3.5, while continuing to support # # 3.3 and early 3.4 releases. # if hasattr(asyncio, 'ensure_future'): # schedule = getattr(asyncio, 'ensure_future') # else: # schedule = getattr(asyncio, 'async') # # futures = [schedule(catching_wrapper(coro)) for coro in coros] # # results = await asyncio.gather(*futures) # # if exceptions: # raise GatheredExceptions(exceptions, reprs) # else: # return results # # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) # # Path: peru/runtime.py # async def Runtime(args, env): # 'This is the async constructor for the _Runtime class.' # r = _Runtime(args, env) # await r._init_cache() # return r , which may include functions, classes, or code. Output only the next line.
override substitute a local directory for the contents of a module
Given snippet: <|code_start|> sys.stdout = open( sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1) sys.stderr = open( sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1) # Called as a setup.py entry point, or from __main__.py (`python3 -m peru`). def main(*, argv=None, env=None, nocatch=False): force_utf8_in_ascii_mode_hack() if argv is None: argv = sys.argv[1:] if env is None: env = os.environ.copy() args = docopt_parse_args(argv) command = args['<command>'] ret = maybe_print_help_and_return(args) if ret is not None: return ret try: runtime = run_task(Runtime(args, env)) if not args['--quiet']: parser.warn_duplicate_keys(runtime.peru_file) scope, imports = parser.parse_file(runtime.peru_file) params = CommandParams(args, runtime, scope, imports) command_fn = COMMAND_FNS[command] run_task(command_fn(params)) <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import json import os import sys import tempfile import docopt from .async_helpers import gather_coalescing_exceptions, run_task from . import compat from .error import PrintableError from . import imports from . import parser from .runtime import Runtime and context: # Path: peru/async_helpers.py # async def gather_coalescing_exceptions(coros, display, *, verbose): # '''The tricky thing about running multiple coroutines in parallel is what # we're supposed to do when one of them raises an exception. The approach # we're using here is to catch exceptions and keep waiting for other tasks to # finish. At the end, we reraise a GatheredExceptions error, if any # exceptions were caught. # # Another minor detail: We also want to make sure to start coroutines in the # order given, so that they end up appearing to the user alphabetically in # the fancy display. Note that asyncio.gather() puts coroutines in a set # internally, so we schedule coroutines *before* we give them to gather(). # ''' # # exceptions = [] # reprs = [] # # async def catching_wrapper(coro): # try: # return (await coro) # except Exception as e: # exceptions.append(e) # if isinstance(e, PrintableError) and not verbose: # reprs.append(e.message) # else: # reprs.append(traceback.format_exc()) # return None # # # Suppress a deprecation warning in Python 3.5, while continuing to support # # 3.3 and early 3.4 releases. # if hasattr(asyncio, 'ensure_future'): # schedule = getattr(asyncio, 'ensure_future') # else: # schedule = getattr(asyncio, 'async') # # futures = [schedule(catching_wrapper(coro)) for coro in coros] # # results = await asyncio.gather(*futures) # # if exceptions: # raise GatheredExceptions(exceptions, reprs) # else: # return results # # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) # # Path: peru/runtime.py # async def Runtime(args, env): # 'This is the async constructor for the _Runtime class.' # r = _Runtime(args, env) # await r._init_cache() # return r which might include code, classes, or functions. Output only the next line.
except PrintableError as e:
Given the following code snippet before the placeholder: <|code_start|> ['args', 'runtime', 'scope', 'imports']) def force_utf8_in_ascii_mode_hack(): '''In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru inside of Docker. This is a hack to force emitting UTF8 in that case. Hopefully it doesn't break anything important.''' if sys.stdout.encoding == 'ANSI_X3.4-1968': sys.stdout = open( sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1) sys.stderr = open( sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1) # Called as a setup.py entry point, or from __main__.py (`python3 -m peru`). def main(*, argv=None, env=None, nocatch=False): force_utf8_in_ascii_mode_hack() if argv is None: argv = sys.argv[1:] if env is None: env = os.environ.copy() args = docopt_parse_args(argv) command = args['<command>'] ret = maybe_print_help_and_return(args) if ret is not None: <|code_end|> , predict the next line using imports from the current file: import collections import json import os import sys import tempfile import docopt from .async_helpers import gather_coalescing_exceptions, run_task from . import compat from .error import PrintableError from . import imports from . import parser from .runtime import Runtime and context including class names, function names, and sometimes code from other files: # Path: peru/async_helpers.py # async def gather_coalescing_exceptions(coros, display, *, verbose): # '''The tricky thing about running multiple coroutines in parallel is what # we're supposed to do when one of them raises an exception. The approach # we're using here is to catch exceptions and keep waiting for other tasks to # finish. At the end, we reraise a GatheredExceptions error, if any # exceptions were caught. # # Another minor detail: We also want to make sure to start coroutines in the # order given, so that they end up appearing to the user alphabetically in # the fancy display. Note that asyncio.gather() puts coroutines in a set # internally, so we schedule coroutines *before* we give them to gather(). # ''' # # exceptions = [] # reprs = [] # # async def catching_wrapper(coro): # try: # return (await coro) # except Exception as e: # exceptions.append(e) # if isinstance(e, PrintableError) and not verbose: # reprs.append(e.message) # else: # reprs.append(traceback.format_exc()) # return None # # # Suppress a deprecation warning in Python 3.5, while continuing to support # # 3.3 and early 3.4 releases. # if hasattr(asyncio, 'ensure_future'): # schedule = getattr(asyncio, 'ensure_future') # else: # schedule = getattr(asyncio, 'async') # # futures = [schedule(catching_wrapper(coro)) for coro in coros] # # results = await asyncio.gather(*futures) # # if exceptions: # raise GatheredExceptions(exceptions, reprs) # else: # return results # # def run_task(coro): # return EVENT_LOOP.run_until_complete(coro) # # Path: peru/runtime.py # async def Runtime(args, env): # 'This is the async constructor for the _Runtime class.' # r = _Runtime(args, env) # await r._init_cache() # return r . Output only the next line.
return ret