Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> print "Copying /static..." outdir = os.path.join(get_output_dir(), 'static') if os.path.isdir(outdir): shutil.rmtree(outdir) shutil.copytree(app.static_folder, outdir) freeze_request('/index.html') freeze_request('/faq.html') freeze_request('/api.html') freeze_request('/contact.html') for catalog in ['regional']: freeze_request('/%s/index.html' % catalog) for dimension in get_all_dimensions(): freeze_request('/%s/dimensions/%s.html' % (catalog, dimension['name'])) for statistic in get_all_statistics(): slug = slugify(statistic['title_de']) freeze_request('/%s/statistics/%s.%s.html' % (catalog, slug, statistic['name'])) def freeze_data(): print "Freezing dimension values..." prefix = os.path.join(get_output_dir(), 'data', 'dimensions') freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.csv', format='csv') freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.json', format='json') print "Freezing cubes..." for cube in get_cubes(): prefix = os.path.join(get_output_dir(), 'data', cube['statistic_name'], cube['cube_name']) slug = slugify(cube['statistic_title_de']) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import shutil from dataset import freeze from regenesis.queries import get_all_statistics, get_all_dimensions from regenesis.queries import get_cubes, query_cube from regenesis.database import value_table from regenesis.util import slugify from regenesis.web import app from regenesis.core import engine and context: # Path: regenesis/queries.py # def get_all_statistics(): # return list(statistic_table) # # def get_all_dimensions(): # return list(dimension_table) # # Path: regenesis/queries.py # def get_cubes(cube_name=None): # ct = cube_table.table.alias('cube') # st = statistic_table.table.alias('statistic') # q = ct.join(st, st.c.name==ct.c.statistic_name) # q = q.select(use_labels=True) # if cube_name is not None: # q = q.where(ct.c.name==cube_name) # return list(engine.query(q)) # # def query_cube(cube_name, readable=True): # cube = get_cube(cube_name) # dimensions = get_dimensions(cube_name) # # fact_table = get_fact_table(cube_name).table.alias('fact') # q = fact_table.select() # selects, wheres, tables = [], [], [fact_table] # # if not readable: # selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID')) # # params = {} # for dim in dimensions: # name = dim.get('dim_name') # field = name.upper() # title = dim.get('dim_title_de') # # if readable: # unit = dim.get('ref_unit_name') # if unit is not None: # field = '%s; %s' % (field, unit) # field = '%s (%s)' % (title, field) # # type_ = dim.get('ref_type') # if type_ == 'measure': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY')) # selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR')) # if type_ == 'time': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + '_from'].label(field + '_FROM')) # selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL')) # elif type_ == 'axis': # vt = value_table.table.alias('value_%s' % name) # id_col = field + ' - ID' if readable else field + '_CODE' # selects.append(vt.c.name.label(id_col)) # selects.append(vt.c.title_de.label(field)) # tables.append(vt) # params[name] = name # wheres.append(vt.c.dimension_name==bindparam(name, value=name)) # wheres.append(vt.c.value_id==fact_table.c[name]) # # q = select(selects, and_(*wheres), tables) # return q, params # #return engine.query(q) # #pprint(list(engine.query(q))) # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/util.py # def make_key(*a): # def flatten(d, sep='_'): # # Path: regenesis/web.py # def text_filter(s): # def text_filter_wrapped(s): # def slugify(text): # def set_template_globals(): # def dimension_type_text(type_name): # def nop(): # def page_api(): # def page_faq(): # def page_contact(): # def index(): # # Path: regenesis/core.py # def get_catalog(catalog_name): which might include code, classes, or functions. Output only the next line.
for (text, rb) in [('labeled', True), ('raw', False)]:
Given the code snippet: <|code_start|> client = app.test_client() def get_output_dir(): return os.path.join( app.root_path, '..', 'build') #return '/Users/fl/tmp/regenesis' def freeze_request(req_path): print "Freezing %s..." % req_path path = os.path.join(get_output_dir(), req_path.lstrip('/')) dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) fh = open(path, 'w') res = client.get(req_path) fh.write(res.data) fh.close() def freeze_html(): print "Copying /static..." outdir = os.path.join(get_output_dir(), 'static') if os.path.isdir(outdir): shutil.rmtree(outdir) shutil.copytree(app.static_folder, outdir) freeze_request('/index.html') freeze_request('/faq.html') freeze_request('/api.html') freeze_request('/contact.html') for catalog in ['regional']: <|code_end|> , generate the next line using the imports in this file: import os import shutil from dataset import freeze from regenesis.queries import get_all_statistics, get_all_dimensions from regenesis.queries import get_cubes, query_cube from regenesis.database import value_table from regenesis.util import slugify from regenesis.web import app from regenesis.core import engine and context (functions, classes, or occasionally code) from other files: # Path: regenesis/queries.py # def get_all_statistics(): # return list(statistic_table) # # def get_all_dimensions(): # return list(dimension_table) # # Path: regenesis/queries.py # def get_cubes(cube_name=None): # ct = cube_table.table.alias('cube') # st = statistic_table.table.alias('statistic') # q = ct.join(st, st.c.name==ct.c.statistic_name) # q = q.select(use_labels=True) # if cube_name is not None: # q = q.where(ct.c.name==cube_name) # return list(engine.query(q)) # # def query_cube(cube_name, readable=True): # cube = get_cube(cube_name) # dimensions = get_dimensions(cube_name) # # fact_table = get_fact_table(cube_name).table.alias('fact') # q = fact_table.select() # selects, wheres, tables = [], [], [fact_table] # # if not readable: # selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID')) # # params = {} # for dim in dimensions: # name = dim.get('dim_name') # field = name.upper() # title = dim.get('dim_title_de') # # if readable: # unit = dim.get('ref_unit_name') # if unit is not None: # field = '%s; %s' % (field, unit) # field = '%s (%s)' % (title, field) # # type_ = dim.get('ref_type') # if type_ == 'measure': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY')) # selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR')) # if type_ == 'time': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + '_from'].label(field + '_FROM')) # selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL')) # elif type_ == 'axis': # vt = value_table.table.alias('value_%s' % name) # id_col = field + ' - ID' if readable else field + '_CODE' # selects.append(vt.c.name.label(id_col)) # selects.append(vt.c.title_de.label(field)) # tables.append(vt) # params[name] = name # wheres.append(vt.c.dimension_name==bindparam(name, value=name)) # wheres.append(vt.c.value_id==fact_table.c[name]) # # q = select(selects, and_(*wheres), tables) # return q, params # #return engine.query(q) # #pprint(list(engine.query(q))) # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/util.py # def make_key(*a): # def flatten(d, sep='_'): # # Path: regenesis/web.py # def text_filter(s): # def text_filter_wrapped(s): # def slugify(text): # def set_template_globals(): # def dimension_type_text(type_name): # def nop(): # def page_api(): # def page_faq(): # def page_contact(): # def index(): # # Path: regenesis/core.py # def get_catalog(catalog_name): . Output only the next line.
freeze_request('/%s/index.html' % catalog)
Given the code snippet: <|code_start|> client = app.test_client() def get_output_dir(): return os.path.join( app.root_path, '..', 'build') #return '/Users/fl/tmp/regenesis' def freeze_request(req_path): print "Freezing %s..." % req_path path = os.path.join(get_output_dir(), req_path.lstrip('/')) <|code_end|> , generate the next line using the imports in this file: import os import shutil from dataset import freeze from regenesis.queries import get_all_statistics, get_all_dimensions from regenesis.queries import get_cubes, query_cube from regenesis.database import value_table from regenesis.util import slugify from regenesis.web import app from regenesis.core import engine and context (functions, classes, or occasionally code) from other files: # Path: regenesis/queries.py # def get_all_statistics(): # return list(statistic_table) # # def get_all_dimensions(): # return list(dimension_table) # # Path: regenesis/queries.py # def get_cubes(cube_name=None): # ct = cube_table.table.alias('cube') # st = statistic_table.table.alias('statistic') # q = ct.join(st, st.c.name==ct.c.statistic_name) # q = q.select(use_labels=True) # if cube_name is not None: # q = q.where(ct.c.name==cube_name) # return list(engine.query(q)) # # def query_cube(cube_name, readable=True): # cube = get_cube(cube_name) # dimensions = get_dimensions(cube_name) # # fact_table = get_fact_table(cube_name).table.alias('fact') # q = fact_table.select() # selects, wheres, tables = [], [], [fact_table] # # if not readable: # selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID')) # # params = {} # for dim in dimensions: # name = dim.get('dim_name') # field = name.upper() # title = dim.get('dim_title_de') # # if readable: # unit = dim.get('ref_unit_name') # if unit is not None: # field = '%s; %s' % (field, unit) # field = '%s (%s)' % (title, field) # # type_ = dim.get('ref_type') # if type_ == 'measure': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY')) # selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR')) # if type_ == 'time': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + '_from'].label(field + '_FROM')) # selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL')) # elif type_ == 'axis': # vt = value_table.table.alias('value_%s' % name) # id_col = field + ' - ID' if readable else field + '_CODE' # selects.append(vt.c.name.label(id_col)) # selects.append(vt.c.title_de.label(field)) # tables.append(vt) # params[name] = name # wheres.append(vt.c.dimension_name==bindparam(name, value=name)) # wheres.append(vt.c.value_id==fact_table.c[name]) # # q = select(selects, and_(*wheres), tables) # return q, params # #return engine.query(q) # #pprint(list(engine.query(q))) # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/util.py # def make_key(*a): # def flatten(d, sep='_'): # # Path: regenesis/web.py # def text_filter(s): # def text_filter_wrapped(s): # def slugify(text): # def set_template_globals(): # def dimension_type_text(type_name): # def nop(): # def page_api(): # def page_faq(): # def page_contact(): # def index(): # # Path: regenesis/core.py # def get_catalog(catalog_name): . Output only the next line.
dirname = os.path.dirname(path)
Here is a snippet: <|code_start|> def freeze_html(): print "Copying /static..." outdir = os.path.join(get_output_dir(), 'static') if os.path.isdir(outdir): shutil.rmtree(outdir) shutil.copytree(app.static_folder, outdir) freeze_request('/index.html') freeze_request('/faq.html') freeze_request('/api.html') freeze_request('/contact.html') for catalog in ['regional']: freeze_request('/%s/index.html' % catalog) for dimension in get_all_dimensions(): freeze_request('/%s/dimensions/%s.html' % (catalog, dimension['name'])) for statistic in get_all_statistics(): slug = slugify(statistic['title_de']) freeze_request('/%s/statistics/%s.%s.html' % (catalog, slug, statistic['name'])) def freeze_data(): print "Freezing dimension values..." prefix = os.path.join(get_output_dir(), 'data', 'dimensions') freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.csv', format='csv') freeze(value_table.all(), prefix=prefix, filename='{{dimension_name}}.json', format='json') print "Freezing cubes..." for cube in get_cubes(): prefix = os.path.join(get_output_dir(), 'data', cube['statistic_name'], <|code_end|> . Write the next line using the current file imports: import os import shutil from dataset import freeze from regenesis.queries import get_all_statistics, get_all_dimensions from regenesis.queries import get_cubes, query_cube from regenesis.database import value_table from regenesis.util import slugify from regenesis.web import app from regenesis.core import engine and context from other files: # Path: regenesis/queries.py # def get_all_statistics(): # return list(statistic_table) # # def get_all_dimensions(): # return list(dimension_table) # # Path: regenesis/queries.py # def get_cubes(cube_name=None): # ct = cube_table.table.alias('cube') # st = statistic_table.table.alias('statistic') # q = ct.join(st, st.c.name==ct.c.statistic_name) # q = q.select(use_labels=True) # if cube_name is not None: # q = q.where(ct.c.name==cube_name) # return list(engine.query(q)) # # def query_cube(cube_name, readable=True): # cube = get_cube(cube_name) # dimensions = get_dimensions(cube_name) # # fact_table = get_fact_table(cube_name).table.alias('fact') # q = fact_table.select() # selects, wheres, tables = [], [], [fact_table] # # if not readable: # selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID')) # # params = {} # for dim in dimensions: # name = dim.get('dim_name') # field = name.upper() # title = dim.get('dim_title_de') # # if readable: # unit = dim.get('ref_unit_name') # if unit is not None: # field = '%s; %s' % (field, unit) # field = '%s (%s)' % (title, field) # # type_ = dim.get('ref_type') # if type_ == 'measure': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY')) # selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR')) # if type_ == 'time': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + '_from'].label(field + '_FROM')) # selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL')) # elif type_ == 'axis': # vt = value_table.table.alias('value_%s' % name) # id_col = field + ' - ID' if readable else field + '_CODE' # selects.append(vt.c.name.label(id_col)) # selects.append(vt.c.title_de.label(field)) # tables.append(vt) # params[name] = name # wheres.append(vt.c.dimension_name==bindparam(name, value=name)) # wheres.append(vt.c.value_id==fact_table.c[name]) # # q = select(selects, and_(*wheres), tables) # return q, params # #return engine.query(q) # #pprint(list(engine.query(q))) # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/util.py # def make_key(*a): # def flatten(d, sep='_'): # # Path: regenesis/web.py # def text_filter(s): # def text_filter_wrapped(s): # def slugify(text): # def set_template_globals(): # def dimension_type_text(type_name): # def nop(): # def page_api(): # def page_faq(): # def page_contact(): # def index(): # # Path: regenesis/core.py # def get_catalog(catalog_name): , which may include functions, classes, or code. Output only the next line.
cube['cube_name'])
Next line prediction: <|code_start|> client = app.test_client() def get_output_dir(): return os.path.join( app.root_path, '..', 'build') #return '/Users/fl/tmp/regenesis' def freeze_request(req_path): print "Freezing %s..." % req_path path = os.path.join(get_output_dir(), req_path.lstrip('/')) dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) fh = open(path, 'w') res = client.get(req_path) fh.write(res.data) fh.close() <|code_end|> . Use current file imports: (import os import shutil from dataset import freeze from regenesis.queries import get_all_statistics, get_all_dimensions from regenesis.queries import get_cubes, query_cube from regenesis.database import value_table from regenesis.util import slugify from regenesis.web import app from regenesis.core import engine) and context including class names, function names, or small code snippets from other files: # Path: regenesis/queries.py # def get_all_statistics(): # return list(statistic_table) # # def get_all_dimensions(): # return list(dimension_table) # # Path: regenesis/queries.py # def get_cubes(cube_name=None): # ct = cube_table.table.alias('cube') # st = statistic_table.table.alias('statistic') # q = ct.join(st, st.c.name==ct.c.statistic_name) # q = q.select(use_labels=True) # if cube_name is not None: # q = q.where(ct.c.name==cube_name) # return list(engine.query(q)) # # def query_cube(cube_name, readable=True): # cube = get_cube(cube_name) # dimensions = get_dimensions(cube_name) # # fact_table = get_fact_table(cube_name).table.alias('fact') # q = fact_table.select() # selects, wheres, tables = [], [], [fact_table] # # if not readable: # selects.append(fact_table.columns['fact_id'].label('REGENESIS_ID')) # # params = {} # for dim in dimensions: # name = dim.get('dim_name') # field = name.upper() # title = dim.get('dim_title_de') # # if readable: # unit = dim.get('ref_unit_name') # if unit is not None: # field = '%s; %s' % (field, unit) # field = '%s (%s)' % (title, field) # # type_ = dim.get('ref_type') # if type_ == 'measure': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + "_quality"].label(field + '_QUALITY')) # selects.append(fact_table.columns[name + "_error"].label(field + '_ERROR')) # if type_ == 'time': # selects.append(fact_table.columns[name].label(field)) # if not readable: # selects.append(fact_table.columns[name + '_from'].label(field + '_FROM')) # selects.append(fact_table.columns[name + '_until'].label(field + '_UNTIL')) # elif type_ == 'axis': # vt = value_table.table.alias('value_%s' % name) # id_col = field + ' - ID' if readable else field + '_CODE' # selects.append(vt.c.name.label(id_col)) # selects.append(vt.c.title_de.label(field)) # tables.append(vt) # params[name] = name # wheres.append(vt.c.dimension_name==bindparam(name, value=name)) # wheres.append(vt.c.value_id==fact_table.c[name]) # # q = select(selects, and_(*wheres), tables) # return q, params # #return engine.query(q) # #pprint(list(engine.query(q))) # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/util.py # def make_key(*a): # def flatten(d, sep='_'): # # Path: regenesis/web.py # def text_filter(s): # def text_filter_wrapped(s): # def slugify(text): # def set_template_globals(): # def dimension_type_text(type_name): # def nop(): # def page_api(): # def page_faq(): # def page_contact(): # def index(): # # Path: regenesis/core.py # def get_catalog(catalog_name): . Output only the next line.
def freeze_html():
Continue the code snippet: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] wheres = [ st.c.name==ct.c.statistic_name, rt.c.cube_name==ct.c.name, rt.c.dimension_name==dimension_name ] q = select([st], and_(*wheres), tables, distinct=True) return list(engine.query(q)) @blueprint.route('/<catalog>/dimensions/<name>.html') def view(catalog, name): catalog = get_catalog(catalog) dimension = dimension_table.find_one(name=name) values = list(value_table.find(dimension_name=name, order_by='title_de')) <|code_end|> . Use current file imports: from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table and context (classes, functions, or code) from other files: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): . Output only the next line.
has_values = len(values) > 0
Given the following code snippet before the placeholder: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] <|code_end|> , predict the next line using imports from the current file: from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table and context including class names, function names, and sometimes code from other files: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): . Output only the next line.
wheres = [
Next line prediction: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] <|code_end|> . Use current file imports: (from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table) and context including class names, function names, or small code snippets from other files: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): . Output only the next line.
wheres = [
Predict the next line for this snippet: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] wheres = [ st.c.name==ct.c.statistic_name, rt.c.cube_name==ct.c.name, rt.c.dimension_name==dimension_name ] q = select([st], and_(*wheres), tables, distinct=True) return list(engine.query(q)) @blueprint.route('/<catalog>/dimensions/<name>.html') def view(catalog, name): catalog = get_catalog(catalog) dimension = dimension_table.find_one(name=name) values = list(value_table.find(dimension_name=name, order_by='title_de')) has_values = len(values) > 0 statistics = get_statistics(name) return render_template('dimension/view.html', catalog=catalog, statistics=statistics, values=values, has_values=has_values, <|code_end|> with the help of current file imports: from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table and context from other files: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): , which may contain function names, class names, or code. Output only the next line.
dimension=dimension)
Given snippet: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] wheres = [ st.c.name==ct.c.statistic_name, rt.c.cube_name==ct.c.name, rt.c.dimension_name==dimension_name ] q = select([st], and_(*wheres), tables, distinct=True) return list(engine.query(q)) <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table and context: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): which might include code, classes, or functions. Output only the next line.
@blueprint.route('/<catalog>/dimensions/<name>.html')
Here is a snippet: <|code_start|> blueprint = Blueprint('dimension', __name__) def get_statistics(dimension_name=None): ct = cube_table.table.alias('cube') st = statistic_table.table.alias('statistic') rt = reference_table.table.alias('reference') tables = [ct, st, rt] wheres = [ st.c.name==ct.c.statistic_name, rt.c.cube_name==ct.c.name, rt.c.dimension_name==dimension_name ] q = select([st], and_(*wheres), tables, distinct=True) return list(engine.query(q)) @blueprint.route('/<catalog>/dimensions/<name>.html') def view(catalog, name): catalog = get_catalog(catalog) dimension = dimension_table.find_one(name=name) values = list(value_table.find(dimension_name=name, order_by='title_de')) <|code_end|> . Write the next line using the current file imports: from flask import Blueprint, render_template from sqlalchemy import func, select, and_ from regenesis.core import app, engine, get_catalog from regenesis.database import dimension_table, value_table from regenesis.database import cube_table, statistic_table, reference_table and context from other files: # Path: regenesis/core.py # def get_catalog(catalog_name): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): # # Path: regenesis/database.py # def get_fact_table(cube_name): # def load_cube(cube, update=False): , which may include functions, classes, or code. Output only the next line.
has_values = len(values) > 0
Next line prediction: <|code_start|> @pytest.fixture def client(): app.testing = True return app.test_client() def test_binary_request(client): # This data defines a binary cloudevent attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", } data = {"message": "Hello World!"} event = CloudEvent(attributes, data) headers, body = to_binary(event) r = client.post("/", headers=headers, data=body) assert r.status_code == 204 <|code_end|> . Use current file imports: (import pytest from json_sample_server import app from cloudevents.http import CloudEvent, to_binary, to_structured) and context including class names, function names, or small code snippets from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) . Output only the next line.
def test_structured_request(client):
Here is a snippet: <|code_start|> @pytest.fixture def client(): app.testing = True return app.test_client() def test_binary_request(client): # This data defines a binary cloudevent attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", <|code_end|> . Write the next line using the current file imports: import pytest from json_sample_server import app from cloudevents.http import CloudEvent, to_binary, to_structured and context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) , which may include functions, classes, or code. Output only the next line.
}
Using the snippet: <|code_start|> def EventTime(self) -> str: return self.ce__time.get() def Subject(self) -> str: return self.ce__subject.get() def SchemaURL(self) -> str: return self.ce__schemaurl.get() def Data(self) -> object: return self.ce__data.get() def Extensions(self) -> dict: return self.ce__extensions.get() def ContentType(self) -> str: return self.ce__datacontenttype.get() def ContentEncoding(self) -> str: return self.ce__datacontentencoding.get() def SetEventType(self, eventType: str) -> base.BaseEvent: self.Set("type", eventType) return self def SetSource(self, source: str) -> base.BaseEvent: self.Set("source", source) return self def SetEventID(self, eventID: str) -> base.BaseEvent: <|code_end|> , determine the next line of code. You have imports: from cloudevents.sdk.event import base, opt and context (class names, function names, or code) available: # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # # Path: cloudevents/sdk/event/opt.py # class Option(object): # def __init__(self, name, value, is_required): # def set(self, new_value): # def get(self): # def required(self): # def __eq__(self, obj): . Output only the next line.
self.Set("id", eventID)
Predict the next line for this snippet: <|code_start|> def SetExtensions(self, extensions: dict) -> base.BaseEvent: self.Set("extensions", extensions) return self def SetContentType(self, contentType: str) -> base.BaseEvent: self.Set("datacontenttype", contentType) return self def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: self.Set("datacontentencoding", contentEncoding) return self @property def datacontentencoding(self): return self.ContentEncoding() @datacontentencoding.setter def datacontentencoding(self, value: str): self.SetContentEncoding(value) @property def subject(self) -> str: return self.Subject() @subject.setter def subject(self, value: str): self.SetSubject(value) @property <|code_end|> with the help of current file imports: from cloudevents.sdk.event import base, opt and context from other files: # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # # Path: cloudevents/sdk/event/opt.py # class Option(object): # def __init__(self, name, value, is_required): # def set(self, new_value): # def get(self): # def required(self): # def __eq__(self, obj): , which may contain function names, class names, or code. Output only the next line.
def schema_url(self) -> str:
Continue the code snippet: <|code_start|> assert event_dict[key] == val # test data was properly marshalled into data_base64 data_base64 = event_dict["data_base64"].encode() test_data_base64 = base64.b64encode(data) assert data_base64 == test_data_base64 @pytest.mark.parametrize("specversion", ["0.3", "1.0"]) def test_from_json(specversion): payload = { "type": "com.example.string", "source": "https://example.com/event-producer", "id": "1234", "specversion": specversion, "data": {"data-key": "val"}, } event = from_json(json.dumps(payload)) for key, val in payload.items(): if key == "data": assert event.data == payload["data"] else: assert event[key] == val @pytest.mark.parametrize("specversion", ["0.3", "1.0"]) def test_from_json_base64(specversion): # Create base64 encoded data <|code_end|> . Use current file imports: import base64 import json import pytest from cloudevents.http import CloudEvent, from_json, to_json and context (classes, functions, or code) from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/json_methods.py # def from_json( # data: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType = None, # ) -> CloudEvent: # """ # Cast json encoded data into an CloudEvent # :param data: json encoded cloudevent data # :type event: typing.Union[str, bytes] # :param data_unmarshaller: Callable function which will cast data to a # python object # :type data_unmarshaller: typing.Callable # :returns: CloudEvent representing given cloudevent json object # """ # return from_http(headers={}, data=data, data_unmarshaller=data_unmarshaller) # # def to_json( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> typing.Union[str, bytes]: # """ # Cast an CloudEvent into a json object # :param event: CloudEvent which will be converted into a json object # :type event: CloudEvent # :param data_marshaller: Callable function which will cast event.data # into a json object # :type data_marshaller: typing.Callable # :returns: json object representing the given event # """ # return to_structured(event, data_marshaller=data_marshaller)[1] . Output only the next line.
raw_data = {"data-key": "val"}
Given snippet: <|code_start|> event = CloudEvent(test_attributes, data) event_json = to_json(event) event_dict = json.loads(event_json) for key, val in test_attributes.items(): assert event_dict[key] == val # test data was properly marshalled into data_base64 data_base64 = event_dict["data_base64"].encode() test_data_base64 = base64.b64encode(data) assert data_base64 == test_data_base64 @pytest.mark.parametrize("specversion", ["0.3", "1.0"]) def test_from_json(specversion): payload = { "type": "com.example.string", "source": "https://example.com/event-producer", "id": "1234", "specversion": specversion, "data": {"data-key": "val"}, } event = from_json(json.dumps(payload)) for key, val in payload.items(): if key == "data": assert event.data == payload["data"] else: <|code_end|> , continue by predicting the next line. Consider current file imports: import base64 import json import pytest from cloudevents.http import CloudEvent, from_json, to_json and context: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/json_methods.py # def from_json( # data: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType = None, # ) -> CloudEvent: # """ # Cast json encoded data into an CloudEvent # :param data: json encoded cloudevent data # :type event: typing.Union[str, bytes] # :param data_unmarshaller: Callable function which will cast data to a # python object # :type data_unmarshaller: typing.Callable # :returns: CloudEvent representing given cloudevent json object # """ # return from_http(headers={}, data=data, data_unmarshaller=data_unmarshaller) # # def to_json( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> typing.Union[str, bytes]: # """ # Cast an CloudEvent into a json object # :param event: CloudEvent which will be converted into a json object # :type event: CloudEvent # :param data_marshaller: Callable function which will cast event.data # into a json object # :type data_marshaller: typing.Callable # :returns: json object representing the given event # """ # return to_structured(event, data_marshaller=data_marshaller)[1] which might include code, classes, or functions. Output only the next line.
assert event[key] == val
Given the code snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. test_data = json.dumps({"data-key": "val"}) test_attributes = { "type": "com.example.string", "source": "https://example.com/event-producer", } @pytest.mark.parametrize("specversion", ["0.3", "1.0"]) def test_to_json(specversion): event = CloudEvent(test_attributes, test_data) event_json = to_json(event) event_dict = json.loads(event_json) <|code_end|> , generate the next line using the imports in this file: import base64 import json import pytest from cloudevents.http import CloudEvent, from_json, to_json and context (functions, classes, or occasionally code) from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/json_methods.py # def from_json( # data: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType = None, # ) -> CloudEvent: # """ # Cast json encoded data into an CloudEvent # :param data: json encoded cloudevent data # :type event: typing.Union[str, bytes] # :param data_unmarshaller: Callable function which will cast data to a # python object # :type data_unmarshaller: typing.Callable # :returns: CloudEvent representing given cloudevent json object # """ # return from_http(headers={}, data=data, data_unmarshaller=data_unmarshaller) # # def to_json( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> typing.Union[str, bytes]: # """ # Cast an CloudEvent into a json object # :param event: CloudEvent which will be converted into a json object # :type event: CloudEvent # :param data_marshaller: Callable function which will cast event.data # into a json object # :type data_marshaller: typing.Callable # :returns: json object representing the given event # """ # return to_structured(event, data_marshaller=data_marshaller)[1] . Output only the next line.
for key, val in test_attributes.items():
Given the code snippet: <|code_start|># not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def test_set_raise_error(): with pytest.raises(ValueError): o = Option("test", "value", True) o.set(None) def test_options_eq_override(): o = Option("test", "value", True) assert o.required() o2 = Option("test", "value", True) assert o2.required() assert o == o2 o.set("setting to new value") <|code_end|> , generate the next line using the imports in this file: import pytest from cloudevents.sdk.event.opt import Option and context (functions, classes, or occasionally code) from other files: # Path: cloudevents/sdk/event/opt.py # class Option(object): # def __init__(self, name, value, is_required): # self.name = name # self.value = value # self.is_required = is_required # # def set(self, new_value): # is_none = new_value is None # if self.is_required and is_none: # raise ValueError( # "Attribute value error: '{0}', " # "" # "invalid new value.".format(self.name) # ) # # self.value = new_value # # def get(self): # return self.value # # def required(self): # return self.is_required # # def __eq__(self, obj): # return ( # isinstance(obj, Option) # and obj.name == self.name # and obj.value == self.value # and obj.is_required == self.is_required # ) . Output only the next line.
assert o != o2
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. app = Flask(__name__) # create an endpoint at http://localhost:/3000/ @app.route("/", methods=["POST"]) def home(): # create a CloudEvent event = from_http(request.headers, request.get_data()) # you can access cloudevent fields as seen below print( f"Found {event['id']} from {event['source']} with type " <|code_end|> with the help of current file imports: from flask import Flask, request from cloudevents.http import from_http and context from other files: # Path: cloudevents/http/http_methods.py # def from_http( # headers: typing.Dict[str, str], # data: typing.Union[str, bytes, None], # data_unmarshaller: types.UnmarshallerType = None, # ): # """ # Unwrap a CloudEvent (binary or structured) from an HTTP request. # :param headers: the HTTP headers # :type headers: typing.Dict[str, str] # :param data: the HTTP request body. If set to None, "" or b'', the returned # event's data field will be set to None # :type data: typing.IO # :param data_unmarshaller: Callable function to map data to a python object # e.g. lambda x: x or lambda x: json.loads(x) # :type data_unmarshaller: types.UnmarshallerType # """ # if data is None or data == b"": # # Empty string will cause data to be marshalled into None # data = "" # # if not isinstance(data, (str, bytes, bytearray)): # raise cloud_exceptions.InvalidStructuredJSON( # "Expected json of type (str, bytes, bytearray), " # f"but instead found type {type(data)}" # ) # # headers = {key.lower(): value for key, value in headers.items()} # if data_unmarshaller is None: # data_unmarshaller = _json_or_string # # marshall = marshaller.NewDefaultHTTPMarshaller() # # if is_binary(headers): # specversion = headers.get("ce-specversion", None) # else: # try: # raw_ce = json.loads(data) # except json.decoder.JSONDecodeError: # raise cloud_exceptions.MissingRequiredFields( # "Failed to read specversion from both headers and data. " # f"The following can not be parsed as json: {data}" # ) # if hasattr(raw_ce, "get"): # specversion = raw_ce.get("specversion", None) # else: # raise cloud_exceptions.MissingRequiredFields( # "Failed to read specversion from both headers and data. " # f"The following deserialized data has no 'get' method: {raw_ce}" # ) # # if specversion is None: # raise cloud_exceptions.MissingRequiredFields( # "Failed to find specversion in HTTP request" # ) # # event_handler = _obj_by_version.get(specversion, None) # # if event_handler is None: # raise cloud_exceptions.InvalidRequiredFields( # f"Found invalid specversion {specversion}" # ) # # event = marshall.FromRequest( # event_handler(), headers, data, data_unmarshaller=data_unmarshaller # ) # attrs = event.Properties() # attrs.pop("data", None) # attrs.pop("extensions", None) # attrs.update(**event.extensions) # # if event.data == "" or event.data == b"": # # TODO: Check binary unmarshallers to debug why setting data to "" # # returns an event with data set to None, but structured will return "" # data = None # else: # data = event.data # return CloudEvent(attrs, data) , which may contain function names, class names, or code. Output only the next line.
f"{event['type']} and specversion {event['specversion']}"
Next line prediction: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class Converter(object): TYPE = None def read( self, event, headers: dict, body: typing.IO, data_unmarshaller: typing.Callable, ) -> base.BaseEvent: raise Exception("not implemented") def event_supported(self, event: object) -> bool: <|code_end|> . Use current file imports: (import typing from cloudevents.sdk.event import base) and context including class names, function names, or small code snippets from other files: # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): . Output only the next line.
raise Exception("not implemented")
Next line prediction: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. app = Flask(__name__) @app.route("/", methods=["POST"]) def home(): # Create a CloudEvent. # data_unmarshaller will cast event.data into an io.BytesIO object event = from_http( request.headers, request.get_data(), data_unmarshaller=lambda x: io.BytesIO(x), ) # Create image from cloudevent data image = Image.open(event.data) # Print print(f"Found event {event['id']} with image of size {image.size}") return f"Found image of size {image.size}", 200 if __name__ == "__main__": <|code_end|> . Use current file imports: (import io from flask import Flask, request from PIL import Image from cloudevents.http import from_http) and context including class names, function names, or small code snippets from other files: # Path: cloudevents/http/http_methods.py # def from_http( # headers: typing.Dict[str, str], # data: typing.Union[str, bytes, None], # data_unmarshaller: types.UnmarshallerType = None, # ): # """ # Unwrap a CloudEvent (binary or structured) from an HTTP request. # :param headers: the HTTP headers # :type headers: typing.Dict[str, str] # :param data: the HTTP request body. If set to None, "" or b'', the returned # event's data field will be set to None # :type data: typing.IO # :param data_unmarshaller: Callable function to map data to a python object # e.g. lambda x: x or lambda x: json.loads(x) # :type data_unmarshaller: types.UnmarshallerType # """ # if data is None or data == b"": # # Empty string will cause data to be marshalled into None # data = "" # # if not isinstance(data, (str, bytes, bytearray)): # raise cloud_exceptions.InvalidStructuredJSON( # "Expected json of type (str, bytes, bytearray), " # f"but instead found type {type(data)}" # ) # # headers = {key.lower(): value for key, value in headers.items()} # if data_unmarshaller is None: # data_unmarshaller = _json_or_string # # marshall = marshaller.NewDefaultHTTPMarshaller() # # if is_binary(headers): # specversion = headers.get("ce-specversion", None) # else: # try: # raw_ce = json.loads(data) # except json.decoder.JSONDecodeError: # raise cloud_exceptions.MissingRequiredFields( # "Failed to read specversion from both headers and data. " # f"The following can not be parsed as json: {data}" # ) # if hasattr(raw_ce, "get"): # specversion = raw_ce.get("specversion", None) # else: # raise cloud_exceptions.MissingRequiredFields( # "Failed to read specversion from both headers and data. " # f"The following deserialized data has no 'get' method: {raw_ce}" # ) # # if specversion is None: # raise cloud_exceptions.MissingRequiredFields( # "Failed to find specversion in HTTP request" # ) # # event_handler = _obj_by_version.get(specversion, None) # # if event_handler is None: # raise cloud_exceptions.InvalidRequiredFields( # f"Found invalid specversion {specversion}" # ) # # event = marshall.FromRequest( # event_handler(), headers, data, data_unmarshaller=data_unmarshaller # ) # attrs = event.Properties() # attrs.pop("data", None) # attrs.pop("extensions", None) # attrs.update(**event.extensions) # # if event.data == "" or event.data == b"": # # TODO: Check binary unmarshallers to debug why setting data to "" # # returns an event with data set to None, but structured will return "" # data = None # else: # data = event.data # return CloudEvent(attrs, data) . Output only the next line.
app.run(port=3000)
Continue the code snippet: <|code_start|> class BaseEvent(EventGetterSetter): _ce_required_fields = set() _ce_optional_fields = set() def Properties(self, with_nullable=False) -> dict: props = dict() for name, value in self.__dict__.items(): if str(name).startswith("ce__"): v = value.get() if v is not None or with_nullable: props.update({str(name).replace("ce__", ""): value.get()}) return props def Get(self, key: str) -> (object, bool): formatted_key = "ce__{0}".format(key.lower()) ok = hasattr(self, formatted_key) value = getattr(self, formatted_key, None) if not ok: exts = self.Extensions() return exts.get(key), key in exts return value.get(), ok def Set(self, key: str, value: object): formatted_key = "ce__{0}".format(key) key_exists = hasattr(self, formatted_key) if key_exists: attr = getattr(self, formatted_key) <|code_end|> . Use current file imports: import base64 import json import typing import cloudevents.exceptions as cloud_exceptions from cloudevents.sdk import types and context (classes, functions, or code) from other files: # Path: cloudevents/sdk/types.py . Output only the next line.
attr.set(value)
Using the snippet: <|code_start|> def test_v1_time_property(): event = v1.Event() time1 = "1234" event.time = time1 assert event.EventTime() == time1 time2 = "4321" event.SetEventTime(time2) assert event.time == time2 def test_v1_subject_property(): event = v1.Event() subject1 = "<my-subject>" event.subject = subject1 assert event.Subject() == subject1 subject2 = "<my-subject2>" event.SetSubject(subject2) assert event.subject == subject2 def test_v1_schema_property(): event = v1.Event() schema1 = "<my-schema>" <|code_end|> , determine the next line of code. You have imports: from cloudevents.sdk.event import v1 and context (class names, function names, or code) available: # Path: cloudevents/sdk/event/v1.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def Schema(self) -> str: # def ContentType(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchema(self, schema: str) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def schema(self) -> str: # def schema(self, value: str): # def subject(self) -> str: # def subject(self, value: str): . Output only the next line.
event.schema = schema1
Here is a snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. resp = requests.get( "https://raw.githubusercontent.com/cncf/artwork/master/projects/cloudevents/horizontal/color/cloudevents-horizontal-color.png" # noqa ) image_bytes = resp.content def send_binary_cloud_event(url: str): # Create cloudevent attributes = { <|code_end|> . Write the next line using the current file imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) , which may include functions, classes, or code. Output only the next line.
"type": "com.example.string",
Predict the next line after this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. resp = requests.get( "https://raw.githubusercontent.com/cncf/artwork/master/projects/cloudevents/horizontal/color/cloudevents-horizontal-color.png" # noqa ) image_bytes = resp.content def send_binary_cloud_event(url: str): # Create cloudevent <|code_end|> using the current file's imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and any relevant context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) . Output only the next line.
attributes = {
Here is a snippet: <|code_start|># under the License. resp = requests.get( "https://raw.githubusercontent.com/cncf/artwork/master/projects/cloudevents/horizontal/color/cloudevents-horizontal-color.png" # noqa ) image_bytes = resp.content def send_binary_cloud_event(url: str): # Create cloudevent attributes = { "type": "com.example.string", "source": "https://example.com/event-producer", } event = CloudEvent(attributes, image_bytes) # Create cloudevent HTTP headers and content headers, body = to_binary(event) # Send cloudevent requests.post(url, headers=headers, data=body) print(f"Sent {event['id']} of type {event['type']}") def send_structured_cloud_event(url: str): # Create cloudevent attributes = { <|code_end|> . Write the next line using the current file imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) , which may include functions, classes, or code. Output only the next line.
"type": "com.example.base64",
Here is a snippet: <|code_start|> _ce_optional_fields = {"datacontenttype", "dataschema", "subject", "time"} def __init__(self): self.ce__specversion = opt.Option("specversion", "1.0", True) self.ce__id = opt.Option("id", None, True) self.ce__source = opt.Option("source", None, True) self.ce__type = opt.Option("type", None, True) self.ce__datacontenttype = opt.Option("datacontenttype", None, False) self.ce__dataschema = opt.Option("dataschema", None, False) self.ce__subject = opt.Option("subject", None, False) self.ce__time = opt.Option("time", None, False) self.ce__data = opt.Option("data", None, False) self.ce__extensions = opt.Option("extensions", dict(), False) def CloudEventVersion(self) -> str: return self.ce__specversion.get() def EventType(self) -> str: return self.ce__type.get() def Source(self) -> str: return self.ce__source.get() def EventID(self) -> str: return self.ce__id.get() def EventTime(self) -> str: return self.ce__time.get() <|code_end|> . Write the next line using the current file imports: from cloudevents.sdk.event import base, opt and context from other files: # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # # Path: cloudevents/sdk/event/opt.py # class Option(object): # def __init__(self, name, value, is_required): # def set(self, new_value): # def get(self): # def required(self): # def __eq__(self, obj): , which may include functions, classes, or code. Output only the next line.
def Subject(self) -> str:
Using the snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class Event(base.BaseEvent): _ce_required_fields = {"id", "source", "type", "specversion"} _ce_optional_fields = {"datacontenttype", "dataschema", "subject", "time"} def __init__(self): self.ce__specversion = opt.Option("specversion", "1.0", True) self.ce__id = opt.Option("id", None, True) self.ce__source = opt.Option("source", None, True) self.ce__type = opt.Option("type", None, True) self.ce__datacontenttype = opt.Option("datacontenttype", None, False) self.ce__dataschema = opt.Option("dataschema", None, False) self.ce__subject = opt.Option("subject", None, False) self.ce__time = opt.Option("time", None, False) self.ce__data = opt.Option("data", None, False) self.ce__extensions = opt.Option("extensions", dict(), False) def CloudEventVersion(self) -> str: <|code_end|> , determine the next line of code. You have imports: from cloudevents.sdk.event import base, opt and context (class names, function names, or code) available: # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # # Path: cloudevents/sdk/event/opt.py # class Option(object): # def __init__(self, name, value, is_required): # def set(self, new_value): # def get(self): # def required(self): # def __eq__(self, obj): . Output only the next line.
return self.ce__specversion.get()
Given snippet: <|code_start|> contentType = "application/json" ce_type = "word.found.exclamation" ce_id = "16fb5f0b-211e-1102-3dfe-ea6e2806f124" source = "pytest" eventTime = "2018-10-23T12:28:23.3464579Z" body = '{"name":"john"}' headers = { v03.Event: { "ce-specversion": "1.0", "ce-type": ce_type, "ce-id": ce_id, "ce-time": eventTime, "ce-source": source, "Content-Type": contentType, }, v1.Event: { "ce-specversion": "1.0", "ce-type": ce_type, "ce-id": ce_id, "ce-time": eventTime, "ce-source": source, "Content-Type": contentType, }, } json_ce = { v03.Event: { <|code_end|> , continue by predicting the next line. Consider current file imports: from cloudevents.sdk.event import v1, v03 and context: # Path: cloudevents/sdk/event/v1.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def Schema(self) -> str: # def ContentType(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchema(self, schema: str) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def schema(self) -> str: # def schema(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # # Path: cloudevents/sdk/event/v03.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def SchemaURL(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def ContentType(self) -> str: # def ContentEncoding(self) -> str: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchemaURL(self, schemaURL: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: # def datacontentencoding(self): # def datacontentencoding(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # def schema_url(self) -> str: # def schema_url(self, value: str): which might include code, classes, or functions. Output only the next line.
"specversion": "1.0",
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. contentType = "application/json" ce_type = "word.found.exclamation" ce_id = "16fb5f0b-211e-1102-3dfe-ea6e2806f124" source = "pytest" eventTime = "2018-10-23T12:28:23.3464579Z" body = '{"name":"john"}' headers = { v03.Event: { "ce-specversion": "1.0", "ce-type": ce_type, "ce-id": ce_id, "ce-time": eventTime, "ce-source": source, "Content-Type": contentType, }, v1.Event: { <|code_end|> with the help of current file imports: from cloudevents.sdk.event import v1, v03 and context from other files: # Path: cloudevents/sdk/event/v1.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def Schema(self) -> str: # def ContentType(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchema(self, schema: str) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def schema(self) -> str: # def schema(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # # Path: cloudevents/sdk/event/v03.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def SchemaURL(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def ContentType(self) -> str: # def ContentEncoding(self) -> str: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchemaURL(self, schemaURL: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: # def datacontentencoding(self): # def datacontentencoding(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # def schema_url(self) -> str: # def schema_url(self, value: str): , which may contain function names, class names, or code. Output only the next line.
"ce-specversion": "1.0",
Next line prediction: <|code_start|> data = '{"name":"john"}' event1 = CloudEvent(attributes, data) event2 = CloudEvent(attributes, data) assert event1 == event2 # Test different attributes for key in attributes: if key == "specversion": continue else: attributes[key] = f"noise-{key}" event3 = CloudEvent(attributes, data) event2 = CloudEvent(attributes, data) assert event2 == event3 assert event1 != event2 and event3 != event1 # Test different data data = '{"name":"paul"}' event3 = CloudEvent(attributes, data) event2 = CloudEvent(attributes, data) assert event2 == event3 assert event1 != event2 and event3 != event1 @pytest.mark.parametrize("specversion", ["0.3", "1.0"]) def test_http_cloudevent_mutates_equality(specversion): attributes = { "source": "<source>", "specversion": specversion, "id": "my-id", "time": "tomorrow", <|code_end|> . Use current file imports: (import pytest import cloudevents.exceptions as cloud_exceptions from cloudevents.http import CloudEvent from cloudevents.http.util import _json_or_string) and context including class names, function names, or small code snippets from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/util.py # def _json_or_string(content: typing.Union[str, bytes]): # if content is None: # return None # try: # return json.loads(content) # except (json.JSONDecodeError, TypeError): # return content . Output only the next line.
"type": "tests.cloudevents.override",
Based on the snippet: <|code_start|> assert f"Missing required keys: {set(['source'])}" in str(e.value) attributes = {"source": "s"} with pytest.raises(cloud_exceptions.MissingRequiredFields) as e: _ = CloudEvent(attributes, None) assert f"Missing required keys: {set(['type'])}" in str(e.value) def test_cloudevent_general_overrides(): event = CloudEvent( { "source": "my-source", "type": "com.test.overrides", "subject": "my-subject", }, None, ) expected_attributes = [ "time", "source", "id", "specversion", "type", "subject", ] assert len(event) == 6 for attribute in expected_attributes: assert attribute in event del event[attribute] <|code_end|> , predict the immediate next line with the help of imports: import pytest import cloudevents.exceptions as cloud_exceptions from cloudevents.http import CloudEvent from cloudevents.http.util import _json_or_string and context (classes, functions, sometimes code) from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/util.py # def _json_or_string(content: typing.Union[str, bytes]): # if content is None: # return None # try: # return json.loads(content) # except (json.JSONDecodeError, TypeError): # return content . Output only the next line.
assert len(event) == 0
Here is a snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. here = pathlib.Path(__file__).parent.resolve() long_description = (here / "README.md").read_text(encoding="utf-8") setup( name=pypi_config["package_name"], summary="CloudEvents SDK Python", long_description_content_type="text/markdown", long_description=long_description, author="The Cloud Events Contributors", author_email="cncfcloudevents@gmail.com", home_page="https://cloudevents.io", classifiers=[ "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", <|code_end|> . Write the next line using the current file imports: from pypi_packaging import pypi_config from setuptools import setup, find_packages import pathlib and context from other files: # Path: pypi_packaging.py # def read(rel_path): # def get_version(rel_path): # def createTag(): , which may include functions, classes, or code. Output only the next line.
"Programming Language :: Python :: 3.9",
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @pytest.fixture def event(): return CloudEvent({"source": "s", "type": "t"}, None) def test_to_binary_http_deprecated(event): with pytest.deprecated_call(): assert to_binary(event) == to_binary_http(event) def test_to_structured_http_deprecated(event): <|code_end|> with the help of current file imports: import pytest from cloudevents.http import ( CloudEvent, to_binary, to_binary_http, to_structured, to_structured_http, ) and context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # @deprecated(deprecated_in="1.0.2", details="Use to_binary function instead") # def to_binary_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_binary(event, data_marshaller) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) # # @deprecated(deprecated_in="1.0.2", details="Use to_structured function instead") # def to_structured_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_structured(event, data_marshaller) , which may contain function names, class names, or code. Output only the next line.
with pytest.deprecated_call():
Given the following code snippet before the placeholder: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @pytest.fixture def event(): return CloudEvent({"source": "s", "type": "t"}, None) def test_to_binary_http_deprecated(event): <|code_end|> , predict the next line using imports from the current file: import pytest from cloudevents.http import ( CloudEvent, to_binary, to_binary_http, to_structured, to_structured_http, ) and context including class names, function names, and sometimes code from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # @deprecated(deprecated_in="1.0.2", details="Use to_binary function instead") # def to_binary_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_binary(event, data_marshaller) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) # # @deprecated(deprecated_in="1.0.2", details="Use to_structured function instead") # def to_structured_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_structured(event, data_marshaller) . Output only the next line.
with pytest.deprecated_call():
Based on the snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @pytest.fixture def event(): return CloudEvent({"source": "s", "type": "t"}, None) def test_to_binary_http_deprecated(event): with pytest.deprecated_call(): assert to_binary(event) == to_binary_http(event) <|code_end|> , predict the immediate next line with the help of imports: import pytest from cloudevents.http import ( CloudEvent, to_binary, to_binary_http, to_structured, to_structured_http, ) and context (classes, functions, sometimes code) from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # @deprecated(deprecated_in="1.0.2", details="Use to_binary function instead") # def to_binary_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_binary(event, data_marshaller) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) # # @deprecated(deprecated_in="1.0.2", details="Use to_structured function instead") # def to_structured_http( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # return to_structured(event, data_marshaller) . Output only the next line.
def test_to_structured_http_deprecated(event):
Predict the next line for this snippet: <|code_start|> subject1 = "<my-subject>" event.subject = subject1 assert event.Subject() == subject1 subject2 = "<my-subject2>" event.SetSubject(subject2) assert event.subject == subject2 def test_v03_schema_url_property(): event = v03.Event() schema_url1 = "<my-schema>" event.schema_url = schema_url1 assert event.SchemaURL() == schema_url1 schema_url2 = "<my-schema2>" event.SetSchemaURL(schema_url2) assert event.schema_url == schema_url2 def test_v03_datacontentencoding_property(): event = v03.Event() datacontentencoding1 = "<my-datacontentencoding>" event.datacontentencoding = datacontentencoding1 assert event.ContentEncoding() == datacontentencoding1 datacontentencoding2 = "<my-datacontentencoding2>" event.SetContentEncoding(datacontentencoding2) <|code_end|> with the help of current file imports: from cloudevents.sdk.event import v03 and context from other files: # Path: cloudevents/sdk/event/v03.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def SchemaURL(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def ContentType(self) -> str: # def ContentEncoding(self) -> str: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchemaURL(self, schemaURL: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: # def datacontentencoding(self): # def datacontentencoding(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # def schema_url(self) -> str: # def schema_url(self, value: str): , which may contain function names, class names, or code. Output only the next line.
assert event.datacontentencoding == datacontentencoding2
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def test_binary_converter_raise_unsupported(): with pytest.raises(exceptions.UnsupportedEvent): cnvtr = binary.BinaryHTTPCloudEventConverter() cnvtr.read(None, {}, None, None) def test_base_converters_raise_exceptions(): with pytest.raises(Exception): cnvtr = base.Converter() cnvtr.event_supported(None) with pytest.raises(Exception): cnvtr = base.Converter() <|code_end|> with the help of current file imports: import pytest from cloudevents.sdk import exceptions from cloudevents.sdk.converters import base, binary and context from other files: # Path: cloudevents/sdk/exceptions.py # class UnsupportedEvent(Exception): # class InvalidDataUnmarshaller(Exception): # class InvalidDataMarshaller(Exception): # class NoSuchConverter(Exception): # class UnsupportedEventConverter(Exception): # def __init__(self, event_class): # def __init__(self): # def __init__(self): # def __init__(self, converter_type): # def __init__(self, content_type): # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/binary.py # class BinaryHTTPCloudEventConverter(base.Converter): # TYPE = "binary" # SUPPORTED_VERSIONS = [v03.Event, v1.Event] # def can_read( # self, # content_type: str = None, # headers: typing.Dict[str, str] = {"ce-specversion": None}, # ) -> bool: # def event_supported(self, event: object) -> bool: # def read( # self, # event: event_base.BaseEvent, # headers: dict, # body: typing.IO, # data_unmarshaller: types.UnmarshallerType, # ) -> event_base.BaseEvent: # def write( # self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # def NewBinaryHTTPCloudEventConverter() -> BinaryHTTPCloudEventConverter: , which may contain function names, class names, or code. Output only the next line.
cnvtr.can_read(None)
Predict the next line after this snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def test_binary_converter_raise_unsupported(): with pytest.raises(exceptions.UnsupportedEvent): cnvtr = binary.BinaryHTTPCloudEventConverter() cnvtr.read(None, {}, None, None) def test_base_converters_raise_exceptions(): with pytest.raises(Exception): cnvtr = base.Converter() cnvtr.event_supported(None) with pytest.raises(Exception): cnvtr = base.Converter() cnvtr.can_read(None) with pytest.raises(Exception): cnvtr = base.Converter() cnvtr.write(None, None) with pytest.raises(Exception): cnvtr = base.Converter() <|code_end|> using the current file's imports: import pytest from cloudevents.sdk import exceptions from cloudevents.sdk.converters import base, binary and any relevant context from other files: # Path: cloudevents/sdk/exceptions.py # class UnsupportedEvent(Exception): # class InvalidDataUnmarshaller(Exception): # class InvalidDataMarshaller(Exception): # class NoSuchConverter(Exception): # class UnsupportedEventConverter(Exception): # def __init__(self, event_class): # def __init__(self): # def __init__(self): # def __init__(self, converter_type): # def __init__(self, content_type): # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/binary.py # class BinaryHTTPCloudEventConverter(base.Converter): # TYPE = "binary" # SUPPORTED_VERSIONS = [v03.Event, v1.Event] # def can_read( # self, # content_type: str = None, # headers: typing.Dict[str, str] = {"ce-specversion": None}, # ) -> bool: # def event_supported(self, event: object) -> bool: # def read( # self, # event: event_base.BaseEvent, # headers: dict, # body: typing.IO, # data_unmarshaller: types.UnmarshallerType, # ) -> event_base.BaseEvent: # def write( # self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # def NewBinaryHTTPCloudEventConverter() -> BinaryHTTPCloudEventConverter: . Output only the next line.
cnvtr.read(None, None, None, None)
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def test_binary_converter_raise_unsupported(): with pytest.raises(exceptions.UnsupportedEvent): cnvtr = binary.BinaryHTTPCloudEventConverter() cnvtr.read(None, {}, None, None) def test_base_converters_raise_exceptions(): <|code_end|> with the help of current file imports: import pytest from cloudevents.sdk import exceptions from cloudevents.sdk.converters import base, binary and context from other files: # Path: cloudevents/sdk/exceptions.py # class UnsupportedEvent(Exception): # class InvalidDataUnmarshaller(Exception): # class InvalidDataMarshaller(Exception): # class NoSuchConverter(Exception): # class UnsupportedEventConverter(Exception): # def __init__(self, event_class): # def __init__(self): # def __init__(self): # def __init__(self, converter_type): # def __init__(self, content_type): # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/binary.py # class BinaryHTTPCloudEventConverter(base.Converter): # TYPE = "binary" # SUPPORTED_VERSIONS = [v03.Event, v1.Event] # def can_read( # self, # content_type: str = None, # headers: typing.Dict[str, str] = {"ce-specversion": None}, # ) -> bool: # def event_supported(self, event: object) -> bool: # def read( # self, # event: event_base.BaseEvent, # headers: dict, # body: typing.IO, # data_unmarshaller: types.UnmarshallerType, # ) -> event_base.BaseEvent: # def write( # self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType # ) -> (dict, bytes): # def NewBinaryHTTPCloudEventConverter() -> BinaryHTTPCloudEventConverter: , which may contain function names, class names, or code. Output only the next line.
with pytest.raises(Exception):
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # TODO: Singleton? class JSONHTTPCloudEventConverter(base.Converter): TYPE = "structured" MIME_TYPE = "application/cloudevents+json" def can_read( self, content_type: str, headers: typing.Dict[str, str] = {} <|code_end|> with the help of current file imports: import typing from cloudevents.sdk import types from cloudevents.sdk.converters import base from cloudevents.sdk.converters.util import has_binary_headers from cloudevents.sdk.event import base as event_base and context from other files: # Path: cloudevents/sdk/types.py # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/util.py # def has_binary_headers(headers: typing.Dict[str, str]) -> bool: # return ( # "ce-specversion" in headers # and "ce-source" in headers # and "ce-type" in headers # and "ce-id" in headers # ) # # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): , which may contain function names, class names, or code. Output only the next line.
) -> bool:
Here is a snippet: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # TODO: Singleton? class JSONHTTPCloudEventConverter(base.Converter): TYPE = "structured" MIME_TYPE = "application/cloudevents+json" def can_read( self, content_type: str, headers: typing.Dict[str, str] = {} ) -> bool: return ( isinstance(content_type, str) and content_type.startswith(self.MIME_TYPE) or not has_binary_headers(headers) ) def event_supported(self, event: object) -> bool: # structured format supported by both spec 0.1 and 0.2 return True def read( self, event: event_base.BaseEvent, headers: dict, <|code_end|> . Write the next line using the current file imports: import typing from cloudevents.sdk import types from cloudevents.sdk.converters import base from cloudevents.sdk.converters.util import has_binary_headers from cloudevents.sdk.event import base as event_base and context from other files: # Path: cloudevents/sdk/types.py # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/util.py # def has_binary_headers(headers: typing.Dict[str, str]) -> bool: # return ( # "ce-specversion" in headers # and "ce-source" in headers # and "ce-type" in headers # and "ce-id" in headers # ) # # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): , which may include functions, classes, or code. Output only the next line.
body: typing.IO,
Given the following code snippet before the placeholder: <|code_start|>class JSONHTTPCloudEventConverter(base.Converter): TYPE = "structured" MIME_TYPE = "application/cloudevents+json" def can_read( self, content_type: str, headers: typing.Dict[str, str] = {} ) -> bool: return ( isinstance(content_type, str) and content_type.startswith(self.MIME_TYPE) or not has_binary_headers(headers) ) def event_supported(self, event: object) -> bool: # structured format supported by both spec 0.1 and 0.2 return True def read( self, event: event_base.BaseEvent, headers: dict, body: typing.IO, data_unmarshaller: types.UnmarshallerType, ) -> event_base.BaseEvent: event.UnmarshalJSON(body, data_unmarshaller) return event def write( self, event: event_base.BaseEvent, data_marshaller: types.MarshallerType <|code_end|> , predict the next line using imports from the current file: import typing from cloudevents.sdk import types from cloudevents.sdk.converters import base from cloudevents.sdk.converters.util import has_binary_headers from cloudevents.sdk.event import base as event_base and context including class names, function names, and sometimes code from other files: # Path: cloudevents/sdk/types.py # # Path: cloudevents/sdk/converters/base.py # class Converter(object): # TYPE = None # def read( # self, # event, # headers: dict, # body: typing.IO, # data_unmarshaller: typing.Callable, # ) -> base.BaseEvent: # def event_supported(self, event: object) -> bool: # def can_read(self, content_type: str) -> bool: # def write( # self, event: base.BaseEvent, data_marshaller: typing.Callable # ) -> (dict, object): # # Path: cloudevents/sdk/converters/util.py # def has_binary_headers(headers: typing.Dict[str, str]) -> bool: # return ( # "ce-specversion" in headers # and "ce-source" in headers # and "ce-type" in headers # and "ce-id" in headers # ) # # Path: cloudevents/sdk/event/base.py # class EventGetterSetter(object): # pragma: no cover # class BaseEvent(EventGetterSetter): # def CloudEventVersion(self) -> str: # def specversion(self): # def SetCloudEventVersion(self, specversion: str) -> object: # def specversion(self, value: str): # def EventType(self) -> str: # def type(self): # def SetEventType(self, eventType: str) -> object: # def type(self, value: str): # def Source(self) -> str: # def source(self): # def SetSource(self, source: str) -> object: # def source(self, value: str): # def EventID(self) -> str: # def id(self): # def SetEventID(self, eventID: str) -> object: # def id(self, value: str): # def EventTime(self) -> str: # def time(self): # def SetEventTime(self, eventTime: str) -> object: # def time(self, value: str): # def SchemaURL(self) -> str: # def schema(self) -> str: # def SetSchemaURL(self, schemaURL: str) -> object: # def schema(self, value: str): # def Data(self) -> object: # def data(self) -> object: # def SetData(self, data: object) -> object: # def data(self, value: object): # def Extensions(self) -> dict: # def extensions(self) -> dict: # def SetExtensions(self, extensions: dict) -> object: # def extensions(self, value: dict): # def ContentType(self) -> str: # def content_type(self) -> str: # def SetContentType(self, contentType: str) -> object: # def content_type(self, value: str): # def Properties(self, with_nullable=False) -> dict: # def Get(self, key: str) -> (object, bool): # def Set(self, key: str, value: object): # def MarshalJSON(self, data_marshaller: types.MarshallerType) -> str: # def UnmarshalJSON( # self, # b: typing.Union[str, bytes], # data_unmarshaller: types.UnmarshallerType, # ): # def UnmarshalBinary( # self, # headers: dict, # body: typing.Union[bytes, str], # data_unmarshaller: types.UnmarshallerType, # ): # def MarshalBinary( # self, data_marshaller: types.MarshallerType # ) -> (dict, bytes): . Output only the next line.
) -> (dict, bytes):
Predict the next line for this snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @pytest.mark.parametrize("event_class", [v1.Event, v03.Event]) def test_unmarshall_binary_missing_fields(event_class): event = event_class() with pytest.raises(cloud_exceptions.MissingRequiredFields) as e: event.UnmarshalBinary({}, "", lambda x: x) assert "Missing required attributes: " in str(e.value) @pytest.mark.parametrize("event_class", [v1.Event, v03.Event]) def test_get_nonexistent_optional(event_class): event = event_class() event.SetExtensions({"ext1": "val"}) res = event.Get("ext1") <|code_end|> with the help of current file imports: import pytest import cloudevents.exceptions as cloud_exceptions from cloudevents.sdk.event import v1, v03 and context from other files: # Path: cloudevents/sdk/event/v1.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def Schema(self) -> str: # def ContentType(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchema(self, schema: str) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def schema(self) -> str: # def schema(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # # Path: cloudevents/sdk/event/v03.py # class Event(base.BaseEvent): # def __init__(self): # def CloudEventVersion(self) -> str: # def EventType(self) -> str: # def Source(self) -> str: # def EventID(self) -> str: # def EventTime(self) -> str: # def Subject(self) -> str: # def SchemaURL(self) -> str: # def Data(self) -> object: # def Extensions(self) -> dict: # def ContentType(self) -> str: # def ContentEncoding(self) -> str: # def SetEventType(self, eventType: str) -> base.BaseEvent: # def SetSource(self, source: str) -> base.BaseEvent: # def SetEventID(self, eventID: str) -> base.BaseEvent: # def SetEventTime(self, eventTime: str) -> base.BaseEvent: # def SetSubject(self, subject: str) -> base.BaseEvent: # def SetSchemaURL(self, schemaURL: str) -> base.BaseEvent: # def SetData(self, data: object) -> base.BaseEvent: # def SetExtensions(self, extensions: dict) -> base.BaseEvent: # def SetContentType(self, contentType: str) -> base.BaseEvent: # def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: # def datacontentencoding(self): # def datacontentencoding(self, value: str): # def subject(self) -> str: # def subject(self, value: str): # def schema_url(self) -> str: # def schema_url(self, value: str): , which may contain function names, class names, or code. Output only the next line.
assert res[0] == "val" and res[1] is True
Predict the next line after this snippet: <|code_start|> event = CloudEvent(attributes, data) headers, body = to_binary(event) # send and print event requests.post(url, headers=headers, data=body) print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") def send_structured_cloud_event(url): # This data defines a binary cloudevent attributes = { "type": "com.example.sampletype2", "source": "https://example.com/event-producer", } data = {"message": "Hello World!"} event = CloudEvent(attributes, data) headers, body = to_structured(event) # send and print event requests.post(url, headers=headers, data=body) print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") if __name__ == "__main__": # expects a url from command line. # e.g. python3 client.py http://localhost:3000/ if len(sys.argv) < 2: sys.exit( <|code_end|> using the current file's imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and any relevant context from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) . Output only the next line.
"Usage: python with_requests.py " "<CloudEvents controller URL>"
Given snippet: <|code_start|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def send_binary_cloud_event(url): # This data defines a binary cloudevent attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and context: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) which might include code, classes, or functions. Output only the next line.
}
Based on the snippet: <|code_start|> attributes = { "type": "com.example.sampletype1", "source": "https://example.com/event-producer", } data = {"message": "Hello World!"} event = CloudEvent(attributes, data) headers, body = to_binary(event) # send and print event requests.post(url, headers=headers, data=body) print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") def send_structured_cloud_event(url): # This data defines a binary cloudevent attributes = { "type": "com.example.sampletype2", "source": "https://example.com/event-producer", } data = {"message": "Hello World!"} event = CloudEvent(attributes, data) headers, body = to_structured(event) # send and print event requests.post(url, headers=headers, data=body) print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") <|code_end|> , predict the immediate next line with the help of imports: import sys import requests from cloudevents.http import CloudEvent, to_binary, to_structured and context (classes, functions, sometimes code) from other files: # Path: cloudevents/http/event.py # class CloudEvent: # """ # Python-friendly cloudevent class supporting v1 events # Supports both binary and structured mode CloudEvents # """ # # def __init__( # self, attributes: typing.Dict[str, str], data: typing.Any = None # ): # """ # Event Constructor # :param attributes: a dict with cloudevent attributes. Minimally # expects the attributes 'type' and 'source'. If not given the # attributes 'specversion', 'id' or 'time', this will create # those attributes with default values. # e.g. { # "content-type": "application/cloudevents+json", # "id": "16fb5f0b-211e-1102-3dfe-ea6e2806f124", # "source": "<event-source>", # "type": "cloudevent.event.type", # "specversion": "0.2" # } # :type attributes: typing.Dict[str, str] # :param data: The payload of the event, as a python object # :type data: typing.Any # """ # self._attributes = {k.lower(): v for k, v in attributes.items()} # self.data = data # if "specversion" not in self._attributes: # self._attributes["specversion"] = "1.0" # if "id" not in self._attributes: # self._attributes["id"] = str(uuid.uuid4()) # if "time" not in self._attributes: # self._attributes["time"] = datetime.datetime.now( # datetime.timezone.utc # ).isoformat() # # if self._attributes["specversion"] not in _required_by_version: # raise cloud_exceptions.MissingRequiredFields( # f"Invalid specversion: {self._attributes['specversion']}" # ) # # There is no good way to default 'source' and 'type', so this # # checks for those (or any new required attributes). # required_set = _required_by_version[self._attributes["specversion"]] # if not required_set <= self._attributes.keys(): # raise cloud_exceptions.MissingRequiredFields( # f"Missing required keys: {required_set - self._attributes.keys()}" # ) # # def __eq__(self, other): # return self.data == other.data and self._attributes == other._attributes # # # Data access is handled via `.data` member # # Attribute access is managed via Mapping type # def __getitem__(self, key): # return self._attributes[key] # # def __setitem__(self, key, value): # self._attributes[key] = value # # def __delitem__(self, key): # del self._attributes[key] # # def __iter__(self): # return iter(self._attributes) # # def __len__(self): # return len(self._attributes) # # def __contains__(self, key): # return key in self._attributes # # def __repr__(self): # return str({"attributes": self._attributes, "data": self.data}) # # Path: cloudevents/http/http_methods.py # def to_binary( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.UnmarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http( # event=event, # format=converters.TypeBinary, # data_marshaller=data_marshaller, # ) # # def to_structured( # event: CloudEvent, data_marshaller: types.MarshallerType = None # ) -> (dict, typing.Union[bytes, str]): # """ # Returns a tuple of HTTP headers/body dicts representing this cloudevent. If # event.data is a byte object, body will have a data_base64 field instead of # data. # # :param event: CloudEvent to cast into http data # :type event: CloudEvent # :param data_marshaller: Callable function to cast event.data into # either a string or bytes # :type data_marshaller: types.MarshallerType # :returns: (http_headers: dict, http_body: bytes or str) # """ # return _to_http(event=event, data_marshaller=data_marshaller) . Output only the next line.
if __name__ == "__main__":
Given snippet: <|code_start|> except StopIteration: finished = True def nb_voters(self): """Returns the number of voters of the poll (performs a DB query).""" return VotingScore.objects.filter(candidate__poll=self).values('voter__id').distinct().count() def voting_profile_matrix(self): """Returns the voting profile as a matrix. In the matrix returned by the function, each row represents a vote, and each column represents a candidate. Each cell then contains the value given by a vote to a candidate.""" matrix = [] for vote in self.voting_profile(): matrix.append(vote['scores']) return matrix def majority_margin_matrix(self): """Returns the majority matrix of a profile. The value at cell (i, j) is the number of voters that strictly prefer candidate i to candidate j.""" profile = self.voting_profile_matrix() nb_candidates = len(profile[0]) # print(profile) if not profile: nb_candidates = self.candidates.count() matrix = [[0] * nb_candidates for _ in range(nb_candidates)] for i in range(nb_candidates): <|code_end|> , continue by predicting the next line. Consider current file imports: import uuid from datetime import date, timedelta from django.db import models from accounts.models import WhaleUser,User from django.utils.translation import ugettext_lazy as _ from polymorphic.models import PolymorphicModel from django.contrib.contenttypes.models import ContentType from accounts.models import WhaleUser and context: # Path: accounts/models.py # class WhaleUser(User, AbstractBaseUser): # objects = WhaleUserManager() # email = models.EmailField(verbose_name=_('Email address *'), max_length=255, unique=True) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['nickname'] # # def get_full_name(self): # return self.nickname # # def get_short_name(self): # return self.nickname # # def __str__(self): # return self.nickname # # class User(PolymorphicModel): # # id = models.CharField(max_length=100, primary_key=True, default=uuid.uuid4, editable=False) # nickname = models.CharField(verbose_name=_('Nickname *'), max_length=30) # # Path: accounts/models.py # class WhaleUser(User, AbstractBaseUser): # objects = WhaleUserManager() # email = models.EmailField(verbose_name=_('Email address *'), max_length=255, unique=True) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['nickname'] # # def get_full_name(self): # return self.nickname # # def get_short_name(self): # return self.nickname # # def __str__(self): # return self.nickname which might include code, classes, or functions. Output only the next line.
for j in range(i + 1, nb_candidates):
Next line prediction: <|code_start|> return VotingScore.objects.filter(candidate__poll=self).values('voter__id').distinct().count() def voting_profile_matrix(self): """Returns the voting profile as a matrix. In the matrix returned by the function, each row represents a vote, and each column represents a candidate. Each cell then contains the value given by a vote to a candidate.""" matrix = [] for vote in self.voting_profile(): matrix.append(vote['scores']) return matrix def majority_margin_matrix(self): """Returns the majority matrix of a profile. The value at cell (i, j) is the number of voters that strictly prefer candidate i to candidate j.""" profile = self.voting_profile_matrix() nb_candidates = len(profile[0]) # print(profile) if not profile: nb_candidates = self.candidates.count() matrix = [[0] * nb_candidates for _ in range(nb_candidates)] for i in range(nb_candidates): for j in range(i + 1, nb_candidates): for vect in profile: if vect[i] > vect[j]: matrix[i][j] += 1 elif vect[j] > vect[i]: <|code_end|> . Use current file imports: (import uuid from datetime import date, timedelta from django.db import models from accounts.models import WhaleUser,User from django.utils.translation import ugettext_lazy as _ from polymorphic.models import PolymorphicModel from django.contrib.contenttypes.models import ContentType from accounts.models import WhaleUser) and context including class names, function names, or small code snippets from other files: # Path: accounts/models.py # class WhaleUser(User, AbstractBaseUser): # objects = WhaleUserManager() # email = models.EmailField(verbose_name=_('Email address *'), max_length=255, unique=True) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['nickname'] # # def get_full_name(self): # return self.nickname # # def get_short_name(self): # return self.nickname # # def __str__(self): # return self.nickname # # class User(PolymorphicModel): # # id = models.CharField(max_length=100, primary_key=True, default=uuid.uuid4, editable=False) # nickname = models.CharField(verbose_name=_('Nickname *'), max_length=30) # # Path: accounts/models.py # class WhaleUser(User, AbstractBaseUser): # objects = WhaleUserManager() # email = models.EmailField(verbose_name=_('Email address *'), max_length=255, unique=True) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['nickname'] # # def get_full_name(self): # return self.nickname # # def get_short_name(self): # return self.nickname # # def __str__(self): # return self.nickname . Output only the next line.
matrix[j][i] += 1
Based on the snippet: <|code_start|> uuid4 = "[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}" urlpatterns = [ url(r'^login/$', views.login_view, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^register/$', views.Register.as_view(), name='register'), url(r'^contact/$', views.ContactView.as_view(), name='contact'), url(r'^$', home, name='home'), url(r'^accountPoll/(?P<pk>' + uuid4 + ')/$', views.WhaleUserDetail.as_view(), name='accountPoll'), url(r'^password/$', views.change_password, name='change_password'), url(r'^password_reset/$', views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url from accounts import views from polls.views import home from django.contrib.auth import views as auth_views and context (classes, functions, sometimes code) from other files: # Path: accounts/views.py # def password_reset(request): # def change_password(request): # def get_success_url(self): # def login_view(request): # def logout_view(request): # def form_valid(self, form): # def get_context_data(self, **kwargs): # def dispatch(self, *args, **kwargs): # class Register(CreateView): # class ContactView(FormView): # class WhaleUserDetail(DetailView): # # Path: polls/views.py # def home(request): # """Returns the home page.""" # return render(request, 'polls/home.html') . Output only the next line.
auth_views.password_reset_confirm, name='password_reset_confirm'),
Next line prediction: <|code_start|>class LoginForm(forms.Form): email = forms.EmailField(label=_('Email address *'),widget=forms.EmailInput(attrs={ 'placeholder': _('Enter your email')}), max_length=255, required=True) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': _('Enter your password')}),label=_('Password *')) class UserCreationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': _('Enter your password')}),label=_('Password *')) password_confirmation = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': _('Confirm your password')}),label=_('Password confirmation *')) class Meta: model = WhaleUser fields = ['email', 'nickname'] widgets = { 'email': widgets.EmailInput(attrs={'placeholder': _('Enter your email')}), 'nickname': widgets.Input(attrs={ 'placeholder': _('Enter your nickname')}), } def clean_password_confirmation(self): password = self.cleaned_data.get("password") password_confirmation = self.cleaned_data.get("password_confirmation") if password and password_confirmation and password != password_confirmation: raise forms.ValidationError(_("Passwords don't match")) return password_confirmation def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() <|code_end|> . Use current file imports: (from django import forms from django.forms import widgets from accounts.models import WhaleUser from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _) and context including class names, function names, or small code snippets from other files: # Path: accounts/models.py # class WhaleUser(User, AbstractBaseUser): # objects = WhaleUserManager() # email = models.EmailField(verbose_name=_('Email address *'), max_length=255, unique=True) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['nickname'] # # def get_full_name(self): # return self.nickname # # def get_short_name(self): # return self.nickname # # def __str__(self): # return self.nickname . Output only the next line.
return user
Given the following code snippet before the placeholder: <|code_start|> handler400 = 'polls.views.bad_request' handler403 = 'polls.views.permission_denied' handler404 = 'polls.views.page_not_found' handler500 = 'polls.views.server_error' urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls')), <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from polls.views import home from django.conf.urls import handler400,handler403,handler404,handler500 and context including class names, function names, and sometimes code from other files: # Path: polls/views.py # def home(request): # """Returns the home page.""" # return render(request, 'polls/home.html') . Output only the next line.
url(r'^accounts/', include('accounts.urls')),
Predict the next line after this snippet: <|code_start|> uuid4="[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}" urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^redirectPage/$', views.redirect_page, name='redirectPage'), url(r'^choosePollType$', views.choose_poll_type, name='choosePollType'), url(r'^candidateCreate/('+uuid4+')/$', views.candidate_create, name='candidateCreate'), url(r'^dateCandidateCreate/('+uuid4+')/$', views.date_candidate_create, name='dateCandidateCreate'), url(r'^manageCandidate/('+uuid4+')/$', views.manage_candidate, name='manageCandidate'), url(r'^updatePoll/(' + uuid4 +')/$', views.update_voting_poll, name='updatePoll'), url(r'^deleteCandidate/('+uuid4+')/([^/]+)/$', views.delete_candidate, name='deleteCandidate'), url(r'^updateVote/('+uuid4+')/([^/]+)/$', views.update_vote, name='updateVote'), url(r'^deleteVote/('+uuid4+')/([^/]+)/$', views.delete_vote, name='deleteVote'), url(r'^deleteAnonymous/('+uuid4+')/([^/]+)/$', views.delete_anonymous, name='deleteAnonymous'), url(r'^newPoll/(?P<choice>[^/]+)/$', views.new_poll, name='newPoll'), url(r'^viewPoll/('+uuid4+')', views.view_poll, name='viewPoll'), url(r'^status/('+uuid4+')', views.status, name='status'), url(r'^viewPollSecret/('+uuid4+')/([^/]+)/$', views.view_poll_secret, name='viewPollSecret'), url(r'^vote/('+uuid4+')', views.vote, name='vote'), url(r'^invitation/('+uuid4+')/$', views.invitation, name='invitation'), url(r'^admin/('+uuid4+')/$', views.admin_poll, name='admin'), url(r'^resetPoll/('+uuid4+')/$', views.reset_poll, name='resetPoll'), url(r'^advancedParameters/('+uuid4+')/$', views.advanced_parameters, name='advancedParameters'), url(r'^deleteVotingPoll/(' + uuid4 +')/$', views.delete_poll, name='deleteVotingPoll'), url(r'^certificate/('+uuid4+')', views.certificate, name='certificate'), url(r'^results/('+uuid4+')', views.result_all, name='results'), url(r'^viewResult/('+uuid4+')/([^/]+)/$', views.result_view, name='viewResult'), url(r'^scores/('+uuid4+')/([^/]+)/$', views.result_scores, name='scores'), url(r'^data/('+uuid4+')', views.data_page, name='data'), url(r'^allData$', TemplateView.as_view(template_name='polls/all_data.html'), name='allData'), <|code_end|> using the current file's imports: from django.conf.urls import url from django.views.generic import TemplateView from polls import views and any relevant context from other files: # Path: polls/views.py # def with_valid_poll(init_fn): # def _wrapped(request, poll_id, *args, **kwargs): # def with_admin_rights(init_fn): # def _wrapped(request, poll, *args, **kwargs): # def with_voter_rights(init_fn): # def _wrapped(request, poll, voter_id, *args, **kwargs): # def with_viewing_rights(init_fn): # def _wrapped(request, poll, *args, **kwargs): # def certificate_required(init_fn): # def _wrapped(request, poll, *args, **kwargs): # def status_required(init_fn): # def _wrapped(request, poll, *args, **kwargs): # def minimum_candidates_required(init_fn): # def _wrapped(request, poll, *args, **kwargs): # def bad_request(request): # def permission_denied(request): # def page_not_found(request): # def server_error(request): # def home(request): # def redirect_page(request): # def choose_poll_type(request): ################################### PAGE 0 # def new_poll(request, choice): ################################### PAGE 1 # def update_voting_poll(request, poll): ########################### PAGE 1 # def advanced_parameters(request, poll): ######################### PAGE 3 # def invitation(request, poll): ################################### PAGE 4 # def manage_candidate(request, poll): # def candidate_create(request, poll): # def date_candidate_create(request, poll): # def delete_candidate(request, poll, cand_id): # def admin_poll(request, poll): # def reset_poll(request, poll): # def delete_poll(request, poll): # def status(request, poll): # def delete_anonymous(request, poll, voter_id): # def certificate(request, poll): # def vote(request, poll): # def update_vote(request, poll, voter): # def delete_vote(request, poll, voter): # def view_poll(request, poll): # def view_poll_secret(request, pk ,voter): # def _view_poll_as_json(poll, aggregate=None): # def _view_poll_as_csv(poll): # def _view_poll_as_preflib(poll): # def result_all(request, poll): # def result_view(request, poll, method): # def result_scores(request, poll, method): # def data_page(request, poll): . Output only the next line.
url(r'^about$', TemplateView.as_view(template_name='polls/about.html'), name='about'),
Predict the next line after this snippet: <|code_start|> def twitchapi_handler(q_twitchbeagle, q_twitchapi): logger = logging.getLogger("Rotating Log") logger.setLevel(logging.ERROR) handler = RotatingFileHandler("twitchapi-log.txt", maxBytes=10000, backupCount=5) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s' \ <|code_end|> using the current file's imports: import requests import importlib import time import json import ConfigParser import logging import traceback from logging.handlers import RotatingFileHandler from datetime import datetime from twitchapi.krakenv5 import channels and any relevant context from other files: # Path: twitchapi/krakenv5/channels.py # def getChannelFollowers(channel): # def getChannelObject(channel): # def getChannelOauth(channel): # def getLastSeen(channel): # def setChannelTitle(channel, title): # def setChannelGame(channel, game): # def getChannelId(channel): . Output only the next line.
+ ' - %(message)s')
Here is a snippet: <|code_start|> def react_chat_settitle(args): config = ConfigParser.ConfigParser() config.read('config.ini') <|code_end|> . Write the next line using the current file imports: from twitchapi.krakenv5.channels import setChannelTitle, getChannelId import ConfigParser and context from other files: # Path: twitchapi/krakenv5/channels.py # def setChannelTitle(channel, title): # args = [channel] # header = { # u'Accept': u'application/vnd.twitchtv.v5+json', # u'Authorization' : u'OAuth %s' % EDITOR_TOKEN, # u'Content-Type': u'application/json', # } # # data = { # u'channel' : { # u'status' : title # } # } # # if len(title) < 1 or len(title) > 140: # return "Title String is not an appropriate length" # # status = endpoints.endpoint_put('channels', CLIENT_ID, # data=json.dumps(data), header=header, endpoint_args = args) # # return status # # def getChannelId(channel): # return getChannelObject(channel)['_id'] , which may include functions, classes, or code. Output only the next line.
channelName = config.get('CHAT', 'channel')
Predict the next line after this snippet: <|code_start|>@app.route('/streamlabsauth') def slauth(): firsttimecheck = checkforfirstsetup() if firsttimecheck: return firsttimecheck if request.args.get('code'): url = 'https://streamlabs.com/api/v1.0/token' authorize_call = { 'grant_type' : 'authorization_code', 'client_id' : STREAMLABS_ID, 'client_secret' : STREAMLABS_SECRET, 'code' : request.args.get('code'), 'redirect_uri' : STREAMLABS_REDIRECT + "/streamlabsauth" } headers = [] r = requests.post( url, data = authorize_call, headers = headers ) token_data = r.json() r_token = token_data['refresh_token'] a_token = token_data['access_token'] with open('slrefreshtoken', 'w') as f: f.write(r_token) with open('slaccesstoken', 'w') as f: <|code_end|> using the current file's imports: from web.webrun import app from q_twitchbeagle import q_twitchbeagle from flask import render_template, redirect, request from config import STREAMLABS_ID, STREAMLABS_REDIRECT, STREAMLABS_SECRET, \ CLIENT_ID, CLIENT_SECRET import ConfigParser import requests and any relevant context from other files: # Path: web/webrun.py # def web_handler(): . Output only the next line.
f.write(a_token)
Using the snippet: <|code_start|> def addcom(user, args): # Concatenate a list of strings down to a single, space delimited string. queueEvent = {} if len(args) < 2: queueEvent['msg'] = "Proper usage: !addcom <cmd> <Text to send>" else: commandHead = "!" + args[0] commands[commandHead] = { 'limit' : 10, 'userbadge' : 'moderator', 'last_used' : 0 } del args[0] commands[commandHead]['return'] = " ".join(args) <|code_end|> , determine the next line of code. You have imports: from twitchchatbot.lib.commands.parsing import commands import json and context (class names, function names, or code) available: # Path: twitchchatbot/lib/commands/parsing.py # def get_valid_command(command): # def get_command_cooldown(command): # def get_command_userbadge(command): # def get_command_cost(command): # def get_command_last_used(command): # def check_command_is_function(command): # def get_command_arg_length(command): # def update_command_last_used(command): # def check_command_cooled_down(command): # def check_valid_userbadge(command, userBadges): # def check_command(con, msgDict, q_twitchbeagle): # def execute_command(con, msgDict, q_twitchbeagle): # def pass_to_function(command, user): . Output only the next line.
with open("commands.json", "w") as f:
Given the following code snippet before the placeholder: <|code_start|> message_bits = json.loads(message_check['message']) bits_used = str(message_bits['data']['bits_used']) user_name = message_bits['data']['user_name'] channel_name = message_bits['data']['channel_name'] queueEvent = {} queueEvent['eventType'] = 'twitchchatbot' queueEvent['event'] = ("Thank you, %s, for sending %s Bit(s) " "to %s!!" % (user_name, bits_used, channel_name)) q_twitchbeagle.put(queueEvent) elif "topic" in message_check and \ message_check['topic'] == 'channel-subscribe-events-v1.%s' \ % channelId: print ("SUBSCRIBE EVENT DETECTED") queueEvent = {} queueEvent['eventType'] = 'electrical' queueEvent['event'] = 'bits' q_twitchbeagle.put(queueEvent) user_name = message_check['data']['message']['user_name'] channel_name = message_check['data']['message']['channel_name'] queueEvent = {} <|code_end|> , predict the next line using imports from the current file: import websocket import ast import thread import time import json import ConfigParser from twitchapi.krakenv5.channels import getChannelId from config import EDITOR_TOKEN and context including class names, function names, and sometimes code from other files: # Path: twitchapi/krakenv5/channels.py # def getChannelId(channel): # return getChannelObject(channel)['_id'] . Output only the next line.
queueEvent['eventType'] = 'twitchchatbot'
Given snippet: <|code_start|> self._current_font_color = self._font_color self._value = None self._sorting_column = 0 self._t = perf_counter() def __lt__(self, other): if self._sorting_column == 1: self_value = self._value if self_value is None: return True other_value = other._value if other_value is None: return False if self_value.dtype.kind in "fui": if other_value.dtype.kind in "fui": return self_value < other_value else: return True else: if other_value.dtype.kind in "fui": return False else: return super().__lt__(other) else: <|code_end|> , continue by predicting the next line. Consider current file imports: from time import perf_counter from traceback import format_exc from PyQt5 import QtCore, QtGui, QtWidgets from ..utils import get_colors_using_ranges and context: # Path: asammdf/gui/utils.py # def get_colors_using_ranges( # value, ranges, default_background_color, default_font_color # ): # new_background_color = default_background_color # new_font_color = default_font_color # # if value is None: # return new_background_color, new_font_color # # if ranges: # # for base_class in (float, int, np.number): # if isinstance(value, base_class): # for range_info in ranges: # # ( # background_color, # font_color, # op1, # op2, # value1, # value2, # ) = range_info.values() # # result = False # # if isinstance(value1, float): # if op1 == "==": # result = value1 == value # elif op1 == "!=": # result = value1 != value # elif op1 == "<=": # result = value1 <= value # elif op1 == "<": # result = value1 < value # elif op1 == ">=": # result = value1 >= value # elif op1 == ">": # result = value1 > value # # if not result: # continue # # if isinstance(value2, float): # if op2 == "==": # result = value == value2 # elif op2 == "!=": # result = value != value2 # elif op2 == "<=": # result = value <= value2 # elif op2 == "<": # result = value < value2 # elif op2 == ">=": # result = value >= value2 # elif op2 == ">": # result = value > value2 # # if not result: # continue # # if result: # # new_background_color = background_color # new_font_color = font_color # break # break # else: # # str here # # for range_info in ranges: # # ( # background_color, # font_color, # op1, # op2, # value1, # value2, # ) = range_info.values() # # result = False # # if isinstance(value1, str): # if op1 == "==": # result = value1 == value # elif op1 == "!=": # result = value1 != value # elif op1 == "<=": # result = value1 <= value # elif op1 == "<": # result = value1 < value # elif op1 == ">=": # result = value1 >= value # elif op1 == ">": # result = value1 > value # # if not result: # continue # # if isinstance(value2, str): # if op2 == "==": # result = value == value2 # elif op2 == "!=": # result = value != value2 # elif op2 == "<=": # result = value <= value2 # elif op2 == "<": # result = value < value2 # elif op2 == ">=": # result = value >= value2 # elif op2 == ">": # result = value > value2 # # if not result: # continue # # if result: # new_background_color = background_color # new_font_color = font_color # break # # return new_background_color, new_font_color which might include code, classes, or functions. Output only the next line.
return super().__lt__(other)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class ErrorDialog(Ui_ErrorDialog, QtWidgets.QDialog): def __init__(self, title, message, trace, *args, **kwargs): if "remote" in kwargs: remote = kwargs.pop("remote") if "timeout" in kwargs: timeout = kwargs.pop("timeout") else: timeout = 60 else: remote = False super().__init__(*args, **kwargs) self.setupUi(self) self.trace = QtWidgets.QTextEdit() self.layout.insertWidget(2, self.trace) self.trace.hide() self.trace.setText(trace) self.trace.setReadOnly(True) icon = QtGui.QIcon() <|code_end|> using the current file's imports: from threading import Thread from time import sleep from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..ui.error_dialog import Ui_ErrorDialog and any relevant context from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/error_dialog.py # class Ui_ErrorDialog(object): # def setupUi(self, ErrorDialog): # ErrorDialog.setObjectName("ErrorDialog") # ErrorDialog.resize(622, 114) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(":/error.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # ErrorDialog.setWindowIcon(icon) # ErrorDialog.setSizeGripEnabled(True) # self.layout = QtWidgets.QVBoxLayout(ErrorDialog) # self.layout.setObjectName("layout") # self.error_message = QtWidgets.QLabel(ErrorDialog) # self.error_message.setText("") # self.error_message.setObjectName("error_message") # self.layout.addWidget(self.error_message) # self.horizontalLayout_2 = QtWidgets.QHBoxLayout() # self.horizontalLayout_2.setObjectName("horizontalLayout_2") # spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) # self.horizontalLayout_2.addItem(spacerItem) # self.layout.addLayout(self.horizontalLayout_2) # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem1) # self.show_trace_btn = QtWidgets.QPushButton(ErrorDialog) # self.show_trace_btn.setObjectName("show_trace_btn") # self.horizontalLayout.addWidget(self.show_trace_btn) # spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem2) # self.copy_to_clipboard_btn = QtWidgets.QPushButton(ErrorDialog) # self.copy_to_clipboard_btn.setObjectName("copy_to_clipboard_btn") # self.horizontalLayout.addWidget(self.copy_to_clipboard_btn) # self.horizontalLayout.setStretch(0, 1) # self.layout.addLayout(self.horizontalLayout) # self.status = QtWidgets.QLabel(ErrorDialog) # self.status.setText("") # self.status.setObjectName("status") # self.layout.addWidget(self.status) # self.layout.setStretch(1, 1) # # self.retranslateUi(ErrorDialog) # QtCore.QMetaObject.connectSlotsByName(ErrorDialog) # # def retranslateUi(self, ErrorDialog): # _translate = QtCore.QCoreApplication.translate # ErrorDialog.setWindowTitle(_translate("ErrorDialog", "Dialog")) # self.show_trace_btn.setText(_translate("ErrorDialog", "Show error trace")) # self.copy_to_clipboard_btn.setText(_translate("ErrorDialog", "Copy to clipboard")) . Output only the next line.
icon.addPixmap(
Continue the code snippet: <|code_start|> self.layout.setStretch(0, 0) self.layout.setStretch(1, 0) self.layout.setStretch(2, 1) if remote: self._timeout = timeout self._thread = Thread(target=self.count_down, args=()) self._thread.start() QtCore.QTimer.singleShot(self._timeout * 1000, self.close) def copy_to_clipboard(self, event): text = ( f"Error: {self.error_message.text()}\n\nDetails: {self.trace.toPlainText()}" ) QtWidgets.QApplication.instance().clipboard().setText(text) def count_down(self): while self._timeout > 0: sleep(1) self._timeout -= 1 self.status.setText(f"This window will close in {self._timeout:02}s") def show_trace(self, event): if self.trace.isHidden(): self.trace.show() self.show_trace_btn.setText("Hide error trace") else: <|code_end|> . Use current file imports: from threading import Thread from time import sleep from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..ui.error_dialog import Ui_ErrorDialog and context (classes, functions, or code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/error_dialog.py # class Ui_ErrorDialog(object): # def setupUi(self, ErrorDialog): # ErrorDialog.setObjectName("ErrorDialog") # ErrorDialog.resize(622, 114) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(":/error.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # ErrorDialog.setWindowIcon(icon) # ErrorDialog.setSizeGripEnabled(True) # self.layout = QtWidgets.QVBoxLayout(ErrorDialog) # self.layout.setObjectName("layout") # self.error_message = QtWidgets.QLabel(ErrorDialog) # self.error_message.setText("") # self.error_message.setObjectName("error_message") # self.layout.addWidget(self.error_message) # self.horizontalLayout_2 = QtWidgets.QHBoxLayout() # self.horizontalLayout_2.setObjectName("horizontalLayout_2") # spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) # self.horizontalLayout_2.addItem(spacerItem) # self.layout.addLayout(self.horizontalLayout_2) # self.horizontalLayout = QtWidgets.QHBoxLayout() # self.horizontalLayout.setObjectName("horizontalLayout") # spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem1) # self.show_trace_btn = QtWidgets.QPushButton(ErrorDialog) # self.show_trace_btn.setObjectName("show_trace_btn") # self.horizontalLayout.addWidget(self.show_trace_btn) # spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem2) # self.copy_to_clipboard_btn = QtWidgets.QPushButton(ErrorDialog) # self.copy_to_clipboard_btn.setObjectName("copy_to_clipboard_btn") # self.horizontalLayout.addWidget(self.copy_to_clipboard_btn) # self.horizontalLayout.setStretch(0, 1) # self.layout.addLayout(self.horizontalLayout) # self.status = QtWidgets.QLabel(ErrorDialog) # self.status.setText("") # self.status.setObjectName("status") # self.layout.addWidget(self.status) # self.layout.setStretch(1, 1) # # self.retranslateUi(ErrorDialog) # QtCore.QMetaObject.connectSlotsByName(ErrorDialog) # # def retranslateUi(self, ErrorDialog): # _translate = QtCore.QCoreApplication.translate # ErrorDialog.setWindowTitle(_translate("ErrorDialog", "Dialog")) # self.show_trace_btn.setText(_translate("ErrorDialog", "Show error trace")) # self.copy_to_clipboard_btn.setText(_translate("ErrorDialog", "Copy to clipboard")) . Output only the next line.
self.trace.hide()
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class WindowSelectionDialog(Ui_WindowSelectionDialog, QtWidgets.QDialog): def __init__(self, options=("Plot", "Numeric", "Tabular"), *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) for i, name in enumerate(options): radio = QtWidgets.QRadioButton(name) self.selection_layout.addWidget(radio) if i == 0: radio.setChecked(True) def selected_type(self): for i in range(self.selection_layout.count()): radio = self.selection_layout.itemAt(i).widget() if radio.isChecked(): <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtWidgets from ..ui import resource_rc as resource_rc from ..ui.windows_selection_dialog import Ui_WindowSelectionDialog and context (class names, function names, or code) available: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/windows_selection_dialog.py # class Ui_WindowSelectionDialog(object): # def setupUi(self, WindowSelectionDialog): # WindowSelectionDialog.setObjectName("WindowSelectionDialog") # WindowSelectionDialog.resize(306, 300) # self.verticalLayout_2 = QtWidgets.QVBoxLayout(WindowSelectionDialog) # self.verticalLayout_2.setObjectName("verticalLayout_2") # self.groupBox = QtWidgets.QGroupBox(WindowSelectionDialog) # self.groupBox.setFlat(True) # self.groupBox.setObjectName("groupBox") # self.lay = QtWidgets.QVBoxLayout(self.groupBox) # self.lay.setObjectName("lay") # self.scrollArea = QtWidgets.QScrollArea(self.groupBox) # self.scrollArea.setFrameShape(QtWidgets.QFrame.NoFrame) # self.scrollArea.setFrameShadow(QtWidgets.QFrame.Plain) # self.scrollArea.setWidgetResizable(True) # self.scrollArea.setObjectName("scrollArea") # self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() # self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 268, 220)) # self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") # self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents_2) # self.verticalLayout_3.setContentsMargins(1, 1, 1, 1) # self.verticalLayout_3.setObjectName("verticalLayout_3") # self.selection_layout = QtWidgets.QVBoxLayout() # self.selection_layout.setObjectName("selection_layout") # self.verticalLayout_3.addLayout(self.selection_layout) # self.scrollArea.setWidget(self.scrollAreaWidgetContents_2) # self.lay.addWidget(self.scrollArea) # self.verticalLayout_2.addWidget(self.groupBox) # self.buttonBox = QtWidgets.QDialogButtonBox(WindowSelectionDialog) # self.buttonBox.setOrientation(QtCore.Qt.Horizontal) # self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) # self.buttonBox.setObjectName("buttonBox") # self.verticalLayout_2.addWidget(self.buttonBox) # # self.retranslateUi(WindowSelectionDialog) # self.buttonBox.accepted.connect(WindowSelectionDialog.accept) # self.buttonBox.rejected.connect(WindowSelectionDialog.reject) # QtCore.QMetaObject.connectSlotsByName(WindowSelectionDialog) # # def retranslateUi(self, WindowSelectionDialog): # _translate = QtCore.QCoreApplication.translate # WindowSelectionDialog.setWindowTitle(_translate("WindowSelectionDialog", "Select window type")) # self.groupBox.setTitle(_translate("WindowSelectionDialog", "Available window types")) . Output only the next line.
return radio.text()
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class WindowSelectionDialog(Ui_WindowSelectionDialog, QtWidgets.QDialog): def __init__(self, options=("Plot", "Numeric", "Tabular"), *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) for i, name in enumerate(options): radio = QtWidgets.QRadioButton(name) self.selection_layout.addWidget(radio) <|code_end|> , generate the next line using the imports in this file: from PyQt5 import QtWidgets from ..ui import resource_rc as resource_rc from ..ui.windows_selection_dialog import Ui_WindowSelectionDialog and context (functions, classes, or occasionally code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/windows_selection_dialog.py # class Ui_WindowSelectionDialog(object): # def setupUi(self, WindowSelectionDialog): # WindowSelectionDialog.setObjectName("WindowSelectionDialog") # WindowSelectionDialog.resize(306, 300) # self.verticalLayout_2 = QtWidgets.QVBoxLayout(WindowSelectionDialog) # self.verticalLayout_2.setObjectName("verticalLayout_2") # self.groupBox = QtWidgets.QGroupBox(WindowSelectionDialog) # self.groupBox.setFlat(True) # self.groupBox.setObjectName("groupBox") # self.lay = QtWidgets.QVBoxLayout(self.groupBox) # self.lay.setObjectName("lay") # self.scrollArea = QtWidgets.QScrollArea(self.groupBox) # self.scrollArea.setFrameShape(QtWidgets.QFrame.NoFrame) # self.scrollArea.setFrameShadow(QtWidgets.QFrame.Plain) # self.scrollArea.setWidgetResizable(True) # self.scrollArea.setObjectName("scrollArea") # self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() # self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 268, 220)) # self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") # self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents_2) # self.verticalLayout_3.setContentsMargins(1, 1, 1, 1) # self.verticalLayout_3.setObjectName("verticalLayout_3") # self.selection_layout = QtWidgets.QVBoxLayout() # self.selection_layout.setObjectName("selection_layout") # self.verticalLayout_3.addLayout(self.selection_layout) # self.scrollArea.setWidget(self.scrollAreaWidgetContents_2) # self.lay.addWidget(self.scrollArea) # self.verticalLayout_2.addWidget(self.groupBox) # self.buttonBox = QtWidgets.QDialogButtonBox(WindowSelectionDialog) # self.buttonBox.setOrientation(QtCore.Qt.Horizontal) # self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) # self.buttonBox.setObjectName("buttonBox") # self.verticalLayout_2.addWidget(self.buttonBox) # # self.retranslateUi(WindowSelectionDialog) # self.buttonBox.accepted.connect(WindowSelectionDialog.accept) # self.buttonBox.rejected.connect(WindowSelectionDialog.reject) # QtCore.QMetaObject.connectSlotsByName(WindowSelectionDialog) # # def retranslateUi(self, WindowSelectionDialog): # _translate = QtCore.QCoreApplication.translate # WindowSelectionDialog.setWindowTitle(_translate("WindowSelectionDialog", "Select window type")) # self.groupBox.setTitle(_translate("WindowSelectionDialog", "Available window types")) . Output only the next line.
if i == 0:
Using the snippet: <|code_start|> # # self.table.setCellWidget( # j, # 2 * i + 1, # label, # ) self.table.setItem( j, 2 * i, QtWidgets.QTableWidgetItem(str(sig.timestamps[j])) ) self.table.setItem( j, 2 * i + 1, QtWidgets.QTableWidgetItem(str(sig.samples[j])) ) layout.addWidget(self.table) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/info.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) self.setGeometry(240, 60, 1200, 600) screen = QtWidgets.QApplication.desktop().screenGeometry() self.move((screen.width() - 1200) // 2, (screen.height() - 600) // 2) def hover(self, row, column): print("hover", row, column) def show_name(self, index): <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc and context (class names, function names, or code) available: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): . Output only the next line.
name = self.header[index // 2]
Given snippet: <|code_start|> self.channels.setColumnCount(3) self.channels.setObjectName("channels") self.verticalLayout.addWidget(self.channels) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.timestamp = QtWidgets.QDoubleSpinBox(NumericDisplay) self.timestamp.setDecimals(9) self.timestamp.setSingleStep(0.001) self.timestamp.setObjectName("timestamp") self.horizontalLayout.addWidget(self.timestamp) self.min_t = QtWidgets.QLabel(NumericDisplay) self.min_t.setText("") self.min_t.setObjectName("min_t") self.horizontalLayout.addWidget(self.min_t) self.timestamp_slider = QtWidgets.QSlider(NumericDisplay) self.timestamp_slider.setMaximum(99999) self.timestamp_slider.setOrientation(QtCore.Qt.Horizontal) self.timestamp_slider.setInvertedAppearance(False) self.timestamp_slider.setInvertedControls(False) self.timestamp_slider.setTickPosition(QtWidgets.QSlider.NoTicks) self.timestamp_slider.setTickInterval(1) self.timestamp_slider.setObjectName("timestamp_slider") self.horizontalLayout.addWidget(self.timestamp_slider) self.max_t = QtWidgets.QLabel(NumericDisplay) self.max_t.setText("") self.max_t.setObjectName("max_t") self.horizontalLayout.addWidget(self.max_t) self.horizontalLayout.setStretch(2, 1) self.verticalLayout.addLayout(self.horizontalLayout) self.groupBox = QtWidgets.QGroupBox(NumericDisplay) <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt5 import QtCore, QtGui, QtWidgets from asammdf.gui.widgets.tree_numeric import NumericTreeWidget from . import resource_rc and context: # Path: asammdf/gui/widgets/tree_numeric.py # class NumericTreeWidget(QtWidgets.QTreeWidget): # add_channels_request = QtCore.pyqtSignal(list) # items_rearranged = QtCore.pyqtSignal() # items_deleted = QtCore.pyqtSignal(list) # # def __init__(self, *args, **kwargs): # # super().__init__(*args, **kwargs) # # self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) # self.setAcceptDrops(True) # self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove) # self.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked) # # self.header().sortIndicatorChanged.connect(self.handle_sorting_changed) # self.itemDoubleClicked.connect(self.handle_item_double_click) # # self._handles_double_click = True # self.set_double_clicked_enabled(True) # # def set_double_clicked_enabled(self, state): # self._handles_double_click = bool(state) # # def keyPressEvent(self, event): # key = event.key() # if ( # event.key() == QtCore.Qt.Key_Delete # and event.modifiers() == QtCore.Qt.NoModifier # ): # selected = reversed(self.selectedItems()) # names = [(item.mdf_uuid, item.text(0)) for item in selected] # for item in selected: # if item.parent() is None: # index = self.indexFromItem(item).row() # self.takeTopLevelItem(index) # else: # item.parent().removeChild(item) # self.items_deleted.emit(names) # else: # super().keyPressEvent(event) # # def startDrag(self, supportedActions): # selected_items = self.selectedItems() # # mimeData = QtCore.QMimeData() # # data = [] # # for item in selected_items: # # entry = item.entry # # if entry == (-1, -1): # info = { # "name": item.name, # "computation": item.computation, # } # else: # info = item.name # # ranges = [dict(e) for e in item.ranges] # # for range_info in ranges: # range_info["color"] = range_info["color"].color().name() # # data.append( # ( # info, # *item.entry, # str(item.mdf_uuid), # "channel", # ranges, # ) # ) # # data = json.dumps(data).encode("utf-8") # # mimeData.setData("application/octet-stream-asammdf", QtCore.QByteArray(data)) # # drag = QtGui.QDrag(self) # drag.setMimeData(mimeData) # drag.exec(QtCore.Qt.CopyAction) # # def dragEnterEvent(self, e): # e.accept() # # def dropEvent(self, e): # # if e.source() is self: # super().dropEvent(e) # self.items_rearranged.emit() # else: # data = e.mimeData() # if data.hasFormat("application/octet-stream-asammdf"): # names = extract_mime_names(data) # self.add_channels_request.emit(names) # else: # super().dropEvent(e) # # def handle_item_double_click(self, item, column): # if self._handles_double_click: # dlg = RangeEditor( # item.name, # ranges=item.ranges, # parent=self, # brush=True, # ) # dlg.exec_() # if dlg.pressed_button == "apply": # item.ranges = dlg.result # item.check_signal_range() # # def handle_sorting_changed(self, index, order): # iterator = QtWidgets.QTreeWidgetItemIterator(self) # while iterator.value(): # item = iterator.value() # iterator += 1 # # item._sorting_column = index which might include code, classes, or functions. Output only the next line.
self.groupBox.setObjectName("groupBox")
Given the following code snippet before the placeholder: <|code_start|> def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): if e.source() is self: super().dropEvent(e) self.items_rearranged.emit() else: data = e.mimeData() if data.hasFormat("application/octet-stream-asammdf"): names = extract_mime_names(data) self.add_channels_request.emit(names) else: super().dropEvent(e) def handle_item_double_click(self, item, column): if self._handles_double_click: dlg = RangeEditor( item.name, ranges=item.ranges, parent=self, brush=True, ) dlg.exec_() if dlg.pressed_button == "apply": item.ranges = dlg.result item.check_signal_range() def handle_sorting_changed(self, index, order): <|code_end|> , predict the next line using imports from the current file: import json from struct import pack from PyQt5 import QtCore, QtGui, QtWidgets from ..dialogs.range_editor import RangeEditor from ..utils import extract_mime_names and context including class names, function names, and sometimes code from other files: # Path: asammdf/gui/dialogs/range_editor.py # class RangeEditor(Ui_RangeDialog, QtWidgets.QDialog): # def __init__(self, name, unit="", ranges=None, brush=False, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # self.name = name # self.unit = unit # self.result = [] # self.pressed_button = None # self._brush = brush # # if ranges: # for range_info in ranges: # widget = RangeWidget( # parent=self, # name=self.name, # brush=brush, # **range_info, # ) # # item = QtWidgets.QListWidgetItem() # item.setSizeHint(widget.sizeHint()) # self.ranges.addItem(item) # self.ranges.setItemWidget(item, widget) # # self.ranges.setUniformItemSizes(True) # # self.apply_btn.clicked.connect(self.apply) # self.insert_btn.clicked.connect(self.insert) # self.cancel_btn.clicked.connect(self.cancel) # self.reset_btn.clicked.connect(self.reset) # # self.setWindowTitle(f"Edit {self.name} range colors") # # def apply(self, event): # ranges = [] # count = self.ranges.count() # for i in range(count): # item = self.ranges.item(i) # if item is None: # continue # # widget = self.ranges.itemWidget(item) # ranges.append(widget.to_dict(brush=self._brush)) # # self.result = ranges # self.pressed_button = "apply" # self.close() # # def insert(self, event): # widget = RangeWidget(self.name) # # item = QtWidgets.QListWidgetItem() # item.setSizeHint(widget.sizeHint()) # self.ranges.addItem(item) # self.ranges.setItemWidget(item, widget) # # def reset(self, event): # self.ranges.clear() # self.result = [] # # def cancel(self, event): # self.result = [] # self.pressed_button = "cancel" # self.close() # # Path: asammdf/gui/utils.py # def extract_mime_names(data): # def fix_comparison_name(data): # for i, ( # name, # group_index, # channel_index, # mdf_uuid, # item_type, # ranges, # ) in enumerate(data): # if item_type == "channel": # if (group_index, channel_index) != (-1, -1): # name = COMPARISON_NAME.match(name).group("name").strip() # data[i][0] = name # else: # fix_comparison_name(channel_index) # # names = [] # if data.hasFormat("application/octet-stream-asammdf"): # data = bytes(data.data("application/octet-stream-asammdf")).decode("utf-8") # data = json.loads(data) # fix_comparison_name(data) # names = data # # return names . Output only the next line.
iterator = QtWidgets.QTreeWidgetItemIterator(self)
Given the following code snippet before the placeholder: <|code_start|> if entry == (-1, -1): info = { "name": item.name, "computation": item.computation, } else: info = item.name ranges = [dict(e) for e in item.ranges] for range_info in ranges: range_info["color"] = range_info["color"].color().name() data.append( ( info, *item.entry, str(item.mdf_uuid), "channel", ranges, ) ) data = json.dumps(data).encode("utf-8") mimeData.setData("application/octet-stream-asammdf", QtCore.QByteArray(data)) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) <|code_end|> , predict the next line using imports from the current file: import json from struct import pack from PyQt5 import QtCore, QtGui, QtWidgets from ..dialogs.range_editor import RangeEditor from ..utils import extract_mime_names and context including class names, function names, and sometimes code from other files: # Path: asammdf/gui/dialogs/range_editor.py # class RangeEditor(Ui_RangeDialog, QtWidgets.QDialog): # def __init__(self, name, unit="", ranges=None, brush=False, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # self.name = name # self.unit = unit # self.result = [] # self.pressed_button = None # self._brush = brush # # if ranges: # for range_info in ranges: # widget = RangeWidget( # parent=self, # name=self.name, # brush=brush, # **range_info, # ) # # item = QtWidgets.QListWidgetItem() # item.setSizeHint(widget.sizeHint()) # self.ranges.addItem(item) # self.ranges.setItemWidget(item, widget) # # self.ranges.setUniformItemSizes(True) # # self.apply_btn.clicked.connect(self.apply) # self.insert_btn.clicked.connect(self.insert) # self.cancel_btn.clicked.connect(self.cancel) # self.reset_btn.clicked.connect(self.reset) # # self.setWindowTitle(f"Edit {self.name} range colors") # # def apply(self, event): # ranges = [] # count = self.ranges.count() # for i in range(count): # item = self.ranges.item(i) # if item is None: # continue # # widget = self.ranges.itemWidget(item) # ranges.append(widget.to_dict(brush=self._brush)) # # self.result = ranges # self.pressed_button = "apply" # self.close() # # def insert(self, event): # widget = RangeWidget(self.name) # # item = QtWidgets.QListWidgetItem() # item.setSizeHint(widget.sizeHint()) # self.ranges.addItem(item) # self.ranges.setItemWidget(item, widget) # # def reset(self, event): # self.ranges.clear() # self.result = [] # # def cancel(self, event): # self.result = [] # self.pressed_button = "cancel" # self.close() # # Path: asammdf/gui/utils.py # def extract_mime_names(data): # def fix_comparison_name(data): # for i, ( # name, # group_index, # channel_index, # mdf_uuid, # item_type, # ranges, # ) in enumerate(data): # if item_type == "channel": # if (group_index, channel_index) != (-1, -1): # name = COMPARISON_NAME.match(name).group("name").strip() # data[i][0] = name # else: # fix_comparison_name(channel_index) # # names = [] # if data.hasFormat("application/octet-stream-asammdf"): # data = bytes(data.data("application/octet-stream-asammdf")).decode("utf-8") # data = json.loads(data) # fix_comparison_name(data) # names = data # # return names . Output only the next line.
drag.exec(QtCore.Qt.CopyAction)
Given the following code snippet before the placeholder: <|code_start|> ) if len(timebase): line = L.polyline( np.column_stack( [self.latitude_signal.samples, self.longitude_signal.samples] ).tolist() ) line.addTo(self.map) self.map.setView([self.latitude, self.longitude], zoom) self.marker = L.marker([self.latitude, self.longitude]) self.map.addLayer(self.marker) else: self.marker = None self.timestamp.valueChanged.connect(self._timestamp_changed) self.timestamp_slider.valueChanged.connect(self._timestamp_slider_changed) self.set_timestamp() self.show() def _timestamp_changed(self, stamp): if not self._inhibit: self.set_timestamp(stamp) def _timestamp_slider_changed(self, stamp): if not self._inhibit: factor = stamp / 99999 stamp = (self._max - self._min) * factor + self._min <|code_end|> , predict the next line using imports from the current file: import io import numpy as np from PyQt5 import QtCore, QtWidgets from pyqtlet import L, MapWidget from ..ui import resource_rc as resource_rc from ..ui.gps import Ui_GPSDisplay and context including class names, function names, and sometimes code from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/gps.py # class Ui_GPSDisplay(object): # def setupUi(self, GPSDisplay): # GPSDisplay.setObjectName("GPSDisplay") # GPSDisplay.resize(674, 49) # self.map_layout = QtWidgets.QVBoxLayout(GPSDisplay) # self.map_layout.setObjectName("map_layout") # self.horizontalLayout_2 = QtWidgets.QHBoxLayout() # self.horizontalLayout_2.setObjectName("horizontalLayout_2") # self.timestamp = QtWidgets.QDoubleSpinBox(GPSDisplay) # self.timestamp.setDecimals(9) # self.timestamp.setSingleStep(0.001) # self.timestamp.setObjectName("timestamp") # self.horizontalLayout_2.addWidget(self.timestamp) # self.min_t = QtWidgets.QLabel(GPSDisplay) # self.min_t.setText("") # self.min_t.setObjectName("min_t") # self.horizontalLayout_2.addWidget(self.min_t) # self.timestamp_slider = QtWidgets.QSlider(GPSDisplay) # self.timestamp_slider.setMaximum(99999) # self.timestamp_slider.setOrientation(QtCore.Qt.Horizontal) # self.timestamp_slider.setInvertedAppearance(False) # self.timestamp_slider.setInvertedControls(False) # self.timestamp_slider.setTickPosition(QtWidgets.QSlider.NoTicks) # self.timestamp_slider.setTickInterval(1) # self.timestamp_slider.setObjectName("timestamp_slider") # self.horizontalLayout_2.addWidget(self.timestamp_slider) # self.max_t = QtWidgets.QLabel(GPSDisplay) # self.max_t.setText("") # self.max_t.setObjectName("max_t") # self.horizontalLayout_2.addWidget(self.max_t) # self.horizontalLayout_2.setStretch(2, 1) # self.map_layout.addLayout(self.horizontalLayout_2) # # self.retranslateUi(GPSDisplay) # QtCore.QMetaObject.connectSlotsByName(GPSDisplay) # # def retranslateUi(self, GPSDisplay): # _translate = QtCore.QCoreApplication.translate # GPSDisplay.setWindowTitle(_translate("GPSDisplay", "Form")) # self.timestamp.setSuffix(_translate("GPSDisplay", "s")) . Output only the next line.
self.set_timestamp(stamp)
Based on the snippet: <|code_start|> self.latitude = self.longitude = None self._min = self._max = 0 self._inhibit = False if len(timebase): self._min = timebase[0] self._max = timebase[-1] else: self._min = float("inf") self._max = -float("inf") if self._min == float("inf"): self._min = self._max = 0 self._timestamp = self._min self.timestamp.setRange(self._min, self._max) self.timestamp.setValue(self._min) self.min_t.setText(f"{self._min:.6f}s") self.max_t.setText(f"{self._max:.6f}s") self.mapWidget = MapWidget() self.map_layout.insertWidget(0, self.mapWidget) self.map_layout.setStretch(0, 1) self.map = L.map(self.mapWidget) self.map.setView([50.1364092, 8.5991296], zoom) L.tileLayer("https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png").addTo( <|code_end|> , predict the immediate next line with the help of imports: import io import numpy as np from PyQt5 import QtCore, QtWidgets from pyqtlet import L, MapWidget from ..ui import resource_rc as resource_rc from ..ui.gps import Ui_GPSDisplay and context (classes, functions, sometimes code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/gps.py # class Ui_GPSDisplay(object): # def setupUi(self, GPSDisplay): # GPSDisplay.setObjectName("GPSDisplay") # GPSDisplay.resize(674, 49) # self.map_layout = QtWidgets.QVBoxLayout(GPSDisplay) # self.map_layout.setObjectName("map_layout") # self.horizontalLayout_2 = QtWidgets.QHBoxLayout() # self.horizontalLayout_2.setObjectName("horizontalLayout_2") # self.timestamp = QtWidgets.QDoubleSpinBox(GPSDisplay) # self.timestamp.setDecimals(9) # self.timestamp.setSingleStep(0.001) # self.timestamp.setObjectName("timestamp") # self.horizontalLayout_2.addWidget(self.timestamp) # self.min_t = QtWidgets.QLabel(GPSDisplay) # self.min_t.setText("") # self.min_t.setObjectName("min_t") # self.horizontalLayout_2.addWidget(self.min_t) # self.timestamp_slider = QtWidgets.QSlider(GPSDisplay) # self.timestamp_slider.setMaximum(99999) # self.timestamp_slider.setOrientation(QtCore.Qt.Horizontal) # self.timestamp_slider.setInvertedAppearance(False) # self.timestamp_slider.setInvertedControls(False) # self.timestamp_slider.setTickPosition(QtWidgets.QSlider.NoTicks) # self.timestamp_slider.setTickInterval(1) # self.timestamp_slider.setObjectName("timestamp_slider") # self.horizontalLayout_2.addWidget(self.timestamp_slider) # self.max_t = QtWidgets.QLabel(GPSDisplay) # self.max_t.setText("") # self.max_t.setObjectName("max_t") # self.horizontalLayout_2.addWidget(self.max_t) # self.horizontalLayout_2.setStretch(2, 1) # self.map_layout.addLayout(self.horizontalLayout_2) # # self.retranslateUi(GPSDisplay) # QtCore.QMetaObject.connectSlotsByName(GPSDisplay) # # def retranslateUi(self, GPSDisplay): # _translate = QtCore.QCoreApplication.translate # GPSDisplay.setWindowTitle(_translate("GPSDisplay", "Form")) # self.timestamp.setSuffix(_translate("GPSDisplay", "s")) . Output only the next line.
self.map
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class SearchWidget(Ui_SearchWidget, QtWidgets.QWidget): selectionChanged = QtCore.pyqtSignal() def __init__(self, sorted_keys, channels_db, *args, **kwargs): <|code_end|> , predict the immediate next line with the help of imports: from PyQt5 import QtCore, QtWidgets from ..ui import resource_rc as resource_rc from ..ui.search_widget import Ui_SearchWidget and context (classes, functions, sometimes code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): . Output only the next line.
super().__init__(*args, **kwargs)
Predict the next line after this snippet: <|code_start|> ) elif self.int_format == "bin": try: self._target = int(target, 2) self.target.setText(f"0b{self._target:b}") except: QtWidgets.QMessageBox.warning( None, "Wrong target value", f"{column_name} requires a bin-format integer target value", ) else: try: self._target = int(target) except: try: self._target = int(target, 16) self.target.setText(f"0x{self._target:X}") except: QtWidgets.QMessageBox.warning( None, "Wrong target value", f"{column_name} requires an integer target value", ) elif kind == "f": try: self._target = float(target) except: QtWidgets.QMessageBox.warning( <|code_end|> using the current file's imports: import pandas as pd from PyQt5 import QtCore, QtWidgets from ..ui import resource_rc as resource_rc from ..ui.tabular_filter import Ui_TabularFilter and any relevant context from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/tabular_filter.py # class Ui_TabularFilter(object): # def setupUi(self, TabularFilter): # TabularFilter.setObjectName("TabularFilter") # TabularFilter.resize(813, 26) # TabularFilter.setMinimumSize(QtCore.QSize(0, 26)) # self.horizontalLayout = QtWidgets.QHBoxLayout(TabularFilter) # self.horizontalLayout.setContentsMargins(2, 2, 2, 2) # self.horizontalLayout.setSpacing(5) # self.horizontalLayout.setObjectName("horizontalLayout") # self.enabled = QtWidgets.QCheckBox(TabularFilter) # self.enabled.setText("") # self.enabled.setChecked(True) # self.enabled.setObjectName("enabled") # self.horizontalLayout.addWidget(self.enabled) # self.relation = QtWidgets.QComboBox(TabularFilter) # self.relation.setObjectName("relation") # self.horizontalLayout.addWidget(self.relation) # self.column = QtWidgets.QComboBox(TabularFilter) # self.column.setMinimumSize(QtCore.QSize(300, 0)) # self.column.setObjectName("column") # self.horizontalLayout.addWidget(self.column) # self.op = QtWidgets.QComboBox(TabularFilter) # self.op.setObjectName("op") # self.horizontalLayout.addWidget(self.op) # self.target = QtWidgets.QLineEdit(TabularFilter) # self.target.setClearButtonEnabled(False) # self.target.setObjectName("target") # self.horizontalLayout.addWidget(self.target) # # self.retranslateUi(TabularFilter) # QtCore.QMetaObject.connectSlotsByName(TabularFilter) # # def retranslateUi(self, TabularFilter): # _translate = QtCore.QCoreApplication.translate # TabularFilter.setWindowTitle(_translate("TabularFilter", "Form")) . Output only the next line.
None,
Predict the next line after this snippet: <|code_start|> f"{column_name} requires an integer target value", ) elif kind == "f": try: self._target = float(target) except: QtWidgets.QMessageBox.warning( None, "Wrong target value", f"{column_name} requires a float target value", ) elif kind == "O": is_bytearray = self.is_bytearray[idx] if is_bytearray: try: bytes.fromhex(target.replace(" ", "")) except: QtWidgets.QMessageBox.warning( None, "Wrong target value", f"{column_name} requires a correct hexstring", ) else: target = target.strip().replace(" ", "") target = [target[i : i + 2] for i in range(0, len(target), 2)] target = " ".join(target).upper() if self._target is None: self._target = f'"{target}"' self.target.setText(target) <|code_end|> using the current file's imports: import pandas as pd from PyQt5 import QtCore, QtWidgets from ..ui import resource_rc as resource_rc from ..ui.tabular_filter import Ui_TabularFilter and any relevant context from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/tabular_filter.py # class Ui_TabularFilter(object): # def setupUi(self, TabularFilter): # TabularFilter.setObjectName("TabularFilter") # TabularFilter.resize(813, 26) # TabularFilter.setMinimumSize(QtCore.QSize(0, 26)) # self.horizontalLayout = QtWidgets.QHBoxLayout(TabularFilter) # self.horizontalLayout.setContentsMargins(2, 2, 2, 2) # self.horizontalLayout.setSpacing(5) # self.horizontalLayout.setObjectName("horizontalLayout") # self.enabled = QtWidgets.QCheckBox(TabularFilter) # self.enabled.setText("") # self.enabled.setChecked(True) # self.enabled.setObjectName("enabled") # self.horizontalLayout.addWidget(self.enabled) # self.relation = QtWidgets.QComboBox(TabularFilter) # self.relation.setObjectName("relation") # self.horizontalLayout.addWidget(self.relation) # self.column = QtWidgets.QComboBox(TabularFilter) # self.column.setMinimumSize(QtCore.QSize(300, 0)) # self.column.setObjectName("column") # self.horizontalLayout.addWidget(self.column) # self.op = QtWidgets.QComboBox(TabularFilter) # self.op.setObjectName("op") # self.horizontalLayout.addWidget(self.op) # self.target = QtWidgets.QLineEdit(TabularFilter) # self.target.setClearButtonEnabled(False) # self.target.setObjectName("target") # self.horizontalLayout.addWidget(self.target) # # self.retranslateUi(TabularFilter) # QtCore.QMetaObject.connectSlotsByName(TabularFilter) # # def retranslateUi(self, TabularFilter): # _translate = QtCore.QCoreApplication.translate # TabularFilter.setWindowTitle(_translate("TabularFilter", "Form")) . Output only the next line.
elif self._target.strip('"') != target:
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class ChannelGroupInfoDialog(QtWidgets.QDialog): def __init__(self, mdf, group, index, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowFlags(QtCore.Qt.Window) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.setWindowTitle(f"Channel group {index}") layout.addWidget(ChannelGroupInfoWidget(mdf, group, self)) <|code_end|> , generate the next line using the imports in this file: from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..widgets.channel_group_info import ChannelGroupInfoWidget and context (functions, classes, or occasionally code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/widgets/channel_group_info.py # class ChannelGroupInfoWidget(Ui_ChannelGroupInfo, QtWidgets.QWidget): # def __init__(self, mdf, group, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # channel_group = group.channel_group # self.mdf = mdf # self.group = group # # self.channel_group_label.setText(channel_group.metadata()) # # if hasattr(channel_group, "acq_source") and channel_group.acq_source: # self.source_label.setText(channel_group.acq_source.metadata()) # # items = [] # for i, ch in enumerate(group.channels): # item = ListItem(entry=i, name=ch.name) # item.setText(item.name) # items.append(item) # # items.sort(key=lambda x: x.name) # # for item in items: # self.channels.addItem(item) # # self.scroll.valueChanged.connect(self._display) # self.channels.currentRowChanged.connect(self.select_channel) # # self.byte_count = 0 # self.byte_offset = 0 # self.position = 0 # # self.index_size = len(str(channel_group.cycles_nr)) # self.cycles = channel_group.cycles_nr # if self.mdf.version >= "4.00": # self.record_size = ( # channel_group.samples_byte_nr + channel_group.invalidation_bytes_nr # ) # else: # self.record_size = channel_group.samples_byte_nr # # self.wrap.stateChanged.connect(self.wrap_changed) # self._display(self.position) # # def wrap_changed(self): # if self.wrap.checkState() == QtCore.Qt.Checked: # self.display.setWordWrapMode(QtGui.QTextOption.WordWrap) # else: # self.display.setWordWrapMode(QtGui.QTextOption.NoWrap) # self._display(self.position) # # def select_channel(self, row): # item = self.channels.item(row) # channel = self.group.channels[item.entry] # self.byte_offset = channel.byte_offset # byte_count = channel.bit_count + channel.bit_offset # # if byte_count % 8: # byte_count += 8 - (byte_count % 8) # self.byte_count = byte_count // 8 # # self._display(self.position) # # def _display(self, position): # self.display.clear() # # self.position = position # # record_offset = max(0, position * self.cycles // self.scroll.maximum()) # record_end = max(0, position * self.cycles // self.scroll.maximum() + 100) # record_count = record_end - record_offset # # data = b"".join( # e[0] # for e in self.mdf._load_data( # self.group, record_offset=record_offset, record_count=record_count # ) # ) # # data = pd.Series(list(np.frombuffer(data, dtype=f"({self.record_size},)u1"))) # data = list(csv_bytearray2hex(data)) # # lines = [ # """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> # <html><head><meta name="qrichtext" content="1" /><style type="text/css"> # p, li { white-space: pre-wrap; } # </style></head><body style=" font-size:8pt; font-style:normal;">""" # ] # # if self.byte_count == 0: # template = f'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#61b2e2;">{{index: >{self.index_size}}}: </span>{{line}}</p>' # for i, l in enumerate(data, record_offset): # lines.append(template.format(index=i, line=l)) # else: # template = f'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#61b2e2;">{{index: >{self.index_size}}}: </span>{{start}}<span style=" font-weight:600; color:#ff5500;">{{middle}}</span>{{end}}</p>' # for i, l in enumerate(data, record_offset): # lines.append( # template.format( # index=i, # start=l[: self.byte_offset * 3], # middle=l[ # self.byte_offset * 3 : self.byte_offset * 3 # + self.byte_count * 3 # ], # end=l[self.byte_offset * 3 + self.byte_count * 3 :], # ) # ) # # self.display.appendHtml("\n".join(lines)) # # if position == 0: # self.display.verticalScrollBar().setSliderPosition(0) # elif position == self.scroll.maximum(): # self.display.verticalScrollBar().setSliderPosition( # self.display.verticalScrollBar().maximum() # ) . Output only the next line.
self.setStyleSheet('font: 8pt "Consolas";}')
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class ChannelGroupInfoDialog(QtWidgets.QDialog): def __init__(self, mdf, group, index, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowFlags(QtCore.Qt.Window) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.setWindowTitle(f"Channel group {index}") layout.addWidget(ChannelGroupInfoWidget(mdf, group, self)) <|code_end|> , predict the next line using imports from the current file: from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..widgets.channel_group_info import ChannelGroupInfoWidget and context including class names, function names, and sometimes code from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/widgets/channel_group_info.py # class ChannelGroupInfoWidget(Ui_ChannelGroupInfo, QtWidgets.QWidget): # def __init__(self, mdf, group, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # channel_group = group.channel_group # self.mdf = mdf # self.group = group # # self.channel_group_label.setText(channel_group.metadata()) # # if hasattr(channel_group, "acq_source") and channel_group.acq_source: # self.source_label.setText(channel_group.acq_source.metadata()) # # items = [] # for i, ch in enumerate(group.channels): # item = ListItem(entry=i, name=ch.name) # item.setText(item.name) # items.append(item) # # items.sort(key=lambda x: x.name) # # for item in items: # self.channels.addItem(item) # # self.scroll.valueChanged.connect(self._display) # self.channels.currentRowChanged.connect(self.select_channel) # # self.byte_count = 0 # self.byte_offset = 0 # self.position = 0 # # self.index_size = len(str(channel_group.cycles_nr)) # self.cycles = channel_group.cycles_nr # if self.mdf.version >= "4.00": # self.record_size = ( # channel_group.samples_byte_nr + channel_group.invalidation_bytes_nr # ) # else: # self.record_size = channel_group.samples_byte_nr # # self.wrap.stateChanged.connect(self.wrap_changed) # self._display(self.position) # # def wrap_changed(self): # if self.wrap.checkState() == QtCore.Qt.Checked: # self.display.setWordWrapMode(QtGui.QTextOption.WordWrap) # else: # self.display.setWordWrapMode(QtGui.QTextOption.NoWrap) # self._display(self.position) # # def select_channel(self, row): # item = self.channels.item(row) # channel = self.group.channels[item.entry] # self.byte_offset = channel.byte_offset # byte_count = channel.bit_count + channel.bit_offset # # if byte_count % 8: # byte_count += 8 - (byte_count % 8) # self.byte_count = byte_count // 8 # # self._display(self.position) # # def _display(self, position): # self.display.clear() # # self.position = position # # record_offset = max(0, position * self.cycles // self.scroll.maximum()) # record_end = max(0, position * self.cycles // self.scroll.maximum() + 100) # record_count = record_end - record_offset # # data = b"".join( # e[0] # for e in self.mdf._load_data( # self.group, record_offset=record_offset, record_count=record_count # ) # ) # # data = pd.Series(list(np.frombuffer(data, dtype=f"({self.record_size},)u1"))) # data = list(csv_bytearray2hex(data)) # # lines = [ # """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> # <html><head><meta name="qrichtext" content="1" /><style type="text/css"> # p, li { white-space: pre-wrap; } # </style></head><body style=" font-size:8pt; font-style:normal;">""" # ] # # if self.byte_count == 0: # template = f'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#61b2e2;">{{index: >{self.index_size}}}: </span>{{line}}</p>' # for i, l in enumerate(data, record_offset): # lines.append(template.format(index=i, line=l)) # else: # template = f'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; color:#61b2e2;">{{index: >{self.index_size}}}: </span>{{start}}<span style=" font-weight:600; color:#ff5500;">{{middle}}</span>{{end}}</p>' # for i, l in enumerate(data, record_offset): # lines.append( # template.format( # index=i, # start=l[: self.byte_offset * 3], # middle=l[ # self.byte_offset * 3 : self.byte_offset * 3 # + self.byte_count * 3 # ], # end=l[self.byte_offset * 3 + self.byte_count * 3 :], # ) # ) # # self.display.appendHtml("\n".join(lines)) # # if position == 0: # self.display.verticalScrollBar().setSliderPosition(0) # elif position == self.scroll.maximum(): # self.display.verticalScrollBar().setSliderPosition( # self.display.verticalScrollBar().maximum() # ) . Output only the next line.
self.setStyleSheet('font: 8pt "Consolas";}')
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class DatabaseItem(Ui_DatabaseItemUI, QtWidgets.QWidget): def __init__(self, database, bus_type="CAN"): super().__init__() self.setupUi(self) items = [f"Any {bus_type} bus"] + [ f"{bus_type} {i:>2} only" for i in range(1, 17) ] self.database.setText(database.strip()) <|code_end|> . Use current file imports: from PyQt5 import QtWidgets from ..ui.database_item import Ui_DatabaseItemUI and context (classes, functions, or code) from other files: # Path: asammdf/gui/ui/database_item.py # class Ui_DatabaseItemUI(object): # def setupUi(self, DatabaseItemUI): # DatabaseItemUI.setObjectName("DatabaseItemUI") # DatabaseItemUI.resize(291, 24) # self.horizontalLayout = QtWidgets.QHBoxLayout(DatabaseItemUI) # self.horizontalLayout.setContentsMargins(2, 2, 2, 2) # self.horizontalLayout.setSpacing(10) # self.horizontalLayout.setObjectName("horizontalLayout") # self.bus = QtWidgets.QComboBox(DatabaseItemUI) # self.bus.setObjectName("bus") # self.horizontalLayout.addWidget(self.bus) # self.database = QtWidgets.QLabel(DatabaseItemUI) # self.database.setObjectName("database") # self.horizontalLayout.addWidget(self.database) # self.horizontalLayout.setStretch(1, 1) # # self.retranslateUi(DatabaseItemUI) # QtCore.QMetaObject.connectSlotsByName(DatabaseItemUI) # # def retranslateUi(self, DatabaseItemUI): # _translate = QtCore.QCoreApplication.translate # DatabaseItemUI.setWindowTitle(_translate("DatabaseItemUI", "Form")) # self.database.setText(_translate("DatabaseItemUI", "TextLabel")) . Output only the next line.
self.bus.addItems(items)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- class ChannelInfoDialog(QtWidgets.QDialog): def __init__(self, channel, *args, **kwargs): super().__init__(*args, **kwargs) <|code_end|> , predict the immediate next line with the help of imports: from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..widgets.channel_info import ChannelInfoWidget and context (classes, functions, sometimes code) from other files: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/widgets/channel_info.py # class ChannelInfoWidget(Ui_ChannelInfo, QtWidgets.QWidget): # def __init__(self, channel, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # self.channel_label.setText(channel.metadata()) # # if channel.conversion: # self.conversion_label.setText(channel.conversion.metadata()) # # if channel.source: # self.source_label.setText(channel.source.metadata()) . Output only the next line.
self.setWindowFlags(QtCore.Qt.Window)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class ChannelInfoDialog(QtWidgets.QDialog): def __init__(self, channel, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowFlags(QtCore.Qt.Window) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.setWindowTitle(channel.name) layout.addWidget(ChannelInfoWidget(channel, self)) self.setStyleSheet('font: 8pt "Consolas";}') <|code_end|> , determine the next line of code. You have imports: from PyQt5 import QtCore, QtGui, QtWidgets from ..ui import resource_rc as resource_rc from ..widgets.channel_info import ChannelInfoWidget and context (class names, function names, or code) available: # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/widgets/channel_info.py # class ChannelInfoWidget(Ui_ChannelInfo, QtWidgets.QWidget): # def __init__(self, channel, *args, **kwargs): # super().__init__(*args, **kwargs) # self.setupUi(self) # # self.channel_label.setText(channel.metadata()) # # if channel.conversion: # self.conversion_label.setText(channel.conversion.metadata()) # # if channel.source: # self.source_label.setText(channel.source.metadata()) . Output only the next line.
icon = QtGui.QIcon()
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class Attachment(Ui_Attachment, QtWidgets.QWidget): def __init__(self, index, mdf, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.extract_btn.clicked.connect(self.extract) self.mdf = mdf self.index = index def extract(self, event=None): attachment = self.mdf.attachments[self.index] encryption_info = extract_encryption_information(attachment.comment) password = None if encryption_info.get("encrypted", False) and self.mdf._password is None: text, ok = QtWidgets.QInputDialog.getText( self, "Attachment password", "The attachment is encrypted. Please provide the password:", QtWidgets.QLineEdit.Password, ) if ok and text: password = text <|code_end|> using the current file's imports: from pathlib import Path from PyQt5 import QtWidgets from ...blocks.utils import extract_encryption_information from ..ui import resource_rc as resource_rc from ..ui.attachment import Ui_Attachment and any relevant context from other files: # Path: asammdf/blocks/utils.py # def extract_encryption_information(comment: str) -> dict[str, str]: # info = {} # if comment.startswith("<ATcomment") and "<encrypted>" in comment: # # try: # comment = ET.fromstring(comment) # for match in comment.findall(".//extensions/extension"): # encrypted = match.find("encrypted").text.strip().lower() == "true" # algorithm = match.find("algorithm").text.strip().lower() # original_md5_sum = match.find("original_md5_sum").text.strip().lower() # original_size = int(match.find("original_size").text) # # info["encrypted"] = encrypted # info["algorithm"] = algorithm # info["original_md5_sum"] = original_md5_sum # info["original_size"] = original_size # break # except: # pass # # return info # # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/attachment.py # class Ui_Attachment(object): # def setupUi(self, Attachment): # Attachment.setObjectName("Attachment") # Attachment.resize(717, 205) # self.horizontalLayout = QtWidgets.QHBoxLayout(Attachment) # self.horizontalLayout.setObjectName("horizontalLayout") # self.number = QtWidgets.QLabel(Attachment) # self.number.setObjectName("number") # self.horizontalLayout.addWidget(self.number) # self.fields = QtWidgets.QTreeWidget(Attachment) # self.fields.setMinimumSize(QtCore.QSize(0, 187)) # self.fields.setObjectName("fields") # self.fields.header().setVisible(True) # self.fields.header().setMinimumSectionSize(100) # self.horizontalLayout.addWidget(self.fields) # self.extract_btn = QtWidgets.QPushButton(Attachment) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(":/export.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.extract_btn.setIcon(icon) # self.extract_btn.setObjectName("extract_btn") # self.horizontalLayout.addWidget(self.extract_btn) # self.horizontalLayout.setStretch(1, 1) # # self.retranslateUi(Attachment) # QtCore.QMetaObject.connectSlotsByName(Attachment) # # def retranslateUi(self, Attachment): # _translate = QtCore.QCoreApplication.translate # Attachment.setWindowTitle(_translate("Attachment", "Form")) # self.number.setText(_translate("Attachment", "Number")) # self.fields.headerItem().setText(0, _translate("Attachment", "Item")) # self.fields.headerItem().setText(1, _translate("Attachment", "Value")) # self.extract_btn.setText(_translate("Attachment", "Extract")) . Output only the next line.
data, file_path, md5_sum = self.mdf.extract_attachment(
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class Attachment(Ui_Attachment, QtWidgets.QWidget): def __init__(self, index, mdf, *args, **kwargs): super().__init__(*args, **kwargs) <|code_end|> . Use current file imports: from pathlib import Path from PyQt5 import QtWidgets from ...blocks.utils import extract_encryption_information from ..ui import resource_rc as resource_rc from ..ui.attachment import Ui_Attachment and context (classes, functions, or code) from other files: # Path: asammdf/blocks/utils.py # def extract_encryption_information(comment: str) -> dict[str, str]: # info = {} # if comment.startswith("<ATcomment") and "<encrypted>" in comment: # # try: # comment = ET.fromstring(comment) # for match in comment.findall(".//extensions/extension"): # encrypted = match.find("encrypted").text.strip().lower() == "true" # algorithm = match.find("algorithm").text.strip().lower() # original_md5_sum = match.find("original_md5_sum").text.strip().lower() # original_size = int(match.find("original_size").text) # # info["encrypted"] = encrypted # info["algorithm"] = algorithm # info["original_md5_sum"] = original_md5_sum # info["original_size"] = original_size # break # except: # pass # # return info # # Path: asammdf/gui/ui/resource_rc.py # def qInitResources(): # def qCleanupResources(): # # Path: asammdf/gui/ui/attachment.py # class Ui_Attachment(object): # def setupUi(self, Attachment): # Attachment.setObjectName("Attachment") # Attachment.resize(717, 205) # self.horizontalLayout = QtWidgets.QHBoxLayout(Attachment) # self.horizontalLayout.setObjectName("horizontalLayout") # self.number = QtWidgets.QLabel(Attachment) # self.number.setObjectName("number") # self.horizontalLayout.addWidget(self.number) # self.fields = QtWidgets.QTreeWidget(Attachment) # self.fields.setMinimumSize(QtCore.QSize(0, 187)) # self.fields.setObjectName("fields") # self.fields.header().setVisible(True) # self.fields.header().setMinimumSectionSize(100) # self.horizontalLayout.addWidget(self.fields) # self.extract_btn = QtWidgets.QPushButton(Attachment) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(":/export.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) # self.extract_btn.setIcon(icon) # self.extract_btn.setObjectName("extract_btn") # self.horizontalLayout.addWidget(self.extract_btn) # self.horizontalLayout.setStretch(1, 1) # # self.retranslateUi(Attachment) # QtCore.QMetaObject.connectSlotsByName(Attachment) # # def retranslateUi(self, Attachment): # _translate = QtCore.QCoreApplication.translate # Attachment.setWindowTitle(_translate("Attachment", "Form")) # self.number.setText(_translate("Attachment", "Number")) # self.fields.headerItem().setText(0, _translate("Attachment", "Item")) # self.fields.headerItem().setText(1, _translate("Attachment", "Value")) # self.extract_btn.setText(_translate("Attachment", "Extract")) . Output only the next line.
self.setupUi(self)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python class TestATBLOCK(unittest.TestCase): @classmethod def setUpClass(cls): cls.plain_text = "sample text" cls.plain_bytes = b"##TX\x00\x00\x00\x00(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00sample text\x00\x00\x00\x00\x00" cls.plain_stream = BytesIO() cls.plain_stream.write(cls.plain_bytes) cls.meta_text = "<CN>sample text</CN>" cls.meta_bytes = b"##MD\x00\x00\x00\x000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00<CN>sample text</CN>\x00\x00\x00\x00" cls.meta_stream = BytesIO() cls.meta_stream.write(cls.meta_bytes) def test_read(self): self.plain_stream.seek(0) block = TextBlock(address=0, stream=self.plain_stream) <|code_end|> with the help of current file imports: from io import BytesIO from asammdf.blocks.utils import MdfException from asammdf.blocks.v4_blocks import TextBlock import unittest and context from other files: # Path: asammdf/blocks/utils.py # class MdfException(Exception): # """MDF Exception class""" # # pass # # Path: asammdf/blocks/v4_blocks.py # class TextBlock: # """common TXBLOCK and MDBLOCK class # # *TextBlock* has the following attributes, that are also available as # dict like key-value pairs # # TXBLOCK fields # # * ``id`` - bytes : block ID; b'##TX' for TXBLOCK and b'##MD' for MDBLOCK # * ``reserved0`` - int : reserved bytes # * ``block_len`` - int : block bytes size # * ``links_nr`` - int : number of links # * ``text`` - bytes : actual text content # # Other attributes # # * ``address`` - int : text block address # # Parameters # ---------- # address : int # block address # stream : handle # file handle # meta : bool # flag to set the block type to MDBLOCK for dynamically created objects; default *False* # text : bytes/str # text content for dynamically created objects # # # """ # # __slots__ = ("address", "id", "reserved0", "block_len", "links_nr", "text") # # def __init__(self, **kwargs) -> None: # # if "safe" in kwargs: # self.address = 0 # text = kwargs["text"] # size = len(text) # self.id = b"##MD" if kwargs["meta"] else b"##TX" # self.reserved0 = 0 # self.links_nr = 0 # self.text = text # # self.block_len = size + 32 - size % 8 # # elif "stream" in kwargs: # stream = kwargs["stream"] # mapped = kwargs.get("mapped", False) or not is_file_like(stream) # self.address = address = kwargs["address"] # # if mapped: # (self.id, self.reserved0, self.block_len, self.links_nr) = COMMON_uf( # stream, address # ) # # size = self.block_len - COMMON_SIZE # # if self.id not in (b"##TX", b"##MD"): # message = f'Expected "##TX" or "##MD" block @{hex(address)} but found "{self.id}"' # logger.exception(message) # raise MdfException(message) # # self.text = text = stream[ # address + COMMON_SIZE : address + self.block_len # ] # # else: # stream.seek(address) # (self.id, self.reserved0, self.block_len, self.links_nr) = COMMON_u( # stream.read(COMMON_SIZE) # ) # # size = self.block_len - COMMON_SIZE # # if self.id not in (b"##TX", b"##MD"): # message = f'Expected "##TX" or "##MD" block @{hex(address)} but found "{self.id}"' # logger.exception(message) # raise MdfException(message) # # self.text = text = stream.read(size) # # align = size % 8 # if align: # self.block_len = size + COMMON_SIZE + 8 - align # else: # if text: # if text[-1]: # self.block_len += 8 # else: # self.block_len += 8 # # else: # # text = kwargs["text"] # # try: # text = text.encode("utf-8", "replace") # except AttributeError: # pass # # size = len(text) # # self.id = b"##MD" if kwargs.get("meta", False) else b"##TX" # self.reserved0 = 0 # self.links_nr = 0 # self.text = text # # self.block_len = size + 32 - size % 8 # # def __getitem__(self, item: str) -> Any: # return self.__getattribute__(item) # # def __setitem__(self, item: str, value: Any) -> None: # self.__setattr__(item, value) # # def __bytes__(self) -> bytes: # return pack( # f"<4sI2Q{self.block_len - COMMON_SIZE}s", # self.id, # self.reserved0, # self.block_len, # self.links_nr, # self.text, # ) # # def __repr__(self) -> str: # return ( # f"TextBlock(id={self.id}," # f"reserved0={self.reserved0}, " # f"block_len={self.block_len}, " # f"links_nr={self.links_nr} " # f"text={self.text})" # ) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(block.id, b"##TX")
Continue the code snippet: <|code_start|>#!/usr/bin/env python class TestATBLOCK(unittest.TestCase): @classmethod def setUpClass(cls): cls.plain_text = "sample text" cls.plain_bytes = b"##TX\x00\x00\x00\x00(\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00sample text\x00\x00\x00\x00\x00" cls.plain_stream = BytesIO() cls.plain_stream.write(cls.plain_bytes) cls.meta_text = "<CN>sample text</CN>" cls.meta_bytes = b"##MD\x00\x00\x00\x000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00<CN>sample text</CN>\x00\x00\x00\x00" cls.meta_stream = BytesIO() cls.meta_stream.write(cls.meta_bytes) <|code_end|> . Use current file imports: from io import BytesIO from asammdf.blocks.utils import MdfException from asammdf.blocks.v4_blocks import TextBlock import unittest and context (classes, functions, or code) from other files: # Path: asammdf/blocks/utils.py # class MdfException(Exception): # """MDF Exception class""" # # pass # # Path: asammdf/blocks/v4_blocks.py # class TextBlock: # """common TXBLOCK and MDBLOCK class # # *TextBlock* has the following attributes, that are also available as # dict like key-value pairs # # TXBLOCK fields # # * ``id`` - bytes : block ID; b'##TX' for TXBLOCK and b'##MD' for MDBLOCK # * ``reserved0`` - int : reserved bytes # * ``block_len`` - int : block bytes size # * ``links_nr`` - int : number of links # * ``text`` - bytes : actual text content # # Other attributes # # * ``address`` - int : text block address # # Parameters # ---------- # address : int # block address # stream : handle # file handle # meta : bool # flag to set the block type to MDBLOCK for dynamically created objects; default *False* # text : bytes/str # text content for dynamically created objects # # # """ # # __slots__ = ("address", "id", "reserved0", "block_len", "links_nr", "text") # # def __init__(self, **kwargs) -> None: # # if "safe" in kwargs: # self.address = 0 # text = kwargs["text"] # size = len(text) # self.id = b"##MD" if kwargs["meta"] else b"##TX" # self.reserved0 = 0 # self.links_nr = 0 # self.text = text # # self.block_len = size + 32 - size % 8 # # elif "stream" in kwargs: # stream = kwargs["stream"] # mapped = kwargs.get("mapped", False) or not is_file_like(stream) # self.address = address = kwargs["address"] # # if mapped: # (self.id, self.reserved0, self.block_len, self.links_nr) = COMMON_uf( # stream, address # ) # # size = self.block_len - COMMON_SIZE # # if self.id not in (b"##TX", b"##MD"): # message = f'Expected "##TX" or "##MD" block @{hex(address)} but found "{self.id}"' # logger.exception(message) # raise MdfException(message) # # self.text = text = stream[ # address + COMMON_SIZE : address + self.block_len # ] # # else: # stream.seek(address) # (self.id, self.reserved0, self.block_len, self.links_nr) = COMMON_u( # stream.read(COMMON_SIZE) # ) # # size = self.block_len - COMMON_SIZE # # if self.id not in (b"##TX", b"##MD"): # message = f'Expected "##TX" or "##MD" block @{hex(address)} but found "{self.id}"' # logger.exception(message) # raise MdfException(message) # # self.text = text = stream.read(size) # # align = size % 8 # if align: # self.block_len = size + COMMON_SIZE + 8 - align # else: # if text: # if text[-1]: # self.block_len += 8 # else: # self.block_len += 8 # # else: # # text = kwargs["text"] # # try: # text = text.encode("utf-8", "replace") # except AttributeError: # pass # # size = len(text) # # self.id = b"##MD" if kwargs.get("meta", False) else b"##TX" # self.reserved0 = 0 # self.links_nr = 0 # self.text = text # # self.block_len = size + 32 - size % 8 # # def __getitem__(self, item: str) -> Any: # return self.__getattribute__(item) # # def __setitem__(self, item: str, value: Any) -> None: # self.__setattr__(item, value) # # def __bytes__(self) -> bytes: # return pack( # f"<4sI2Q{self.block_len - COMMON_SIZE}s", # self.id, # self.reserved0, # self.block_len, # self.links_nr, # self.text, # ) # # def __repr__(self) -> str: # return ( # f"TextBlock(id={self.id}," # f"reserved0={self.reserved0}, " # f"block_len={self.block_len}, " # f"links_nr={self.links_nr} " # f"text={self.text})" # ) . Output only the next line.
def test_read(self):
Given snippet: <|code_start|> menu.addSeparator() menu.addAction(self.tr("Relative time base shift")) menu.addAction(self.tr("Set time base start offset")) menu.addSeparator() menu.addAction(self.tr("Insert computation using this channel")) menu.addSeparator() menu.addAction(self.tr("Delete (Del)")) menu.addSeparator() menu.addAction(self.tr("Toggle details")) menu.addAction(self.tr("File/Computation properties")) action = menu.exec_(self.viewport().mapToGlobal(position)) if action is None: return if action.text() == "Copy name (Ctrl+C)": event = QtGui.QKeyEvent( QtCore.QEvent.KeyPress, QtCore.Qt.Key_C, QtCore.Qt.ControlModifier ) self.itemWidget(item).keyPressEvent(event) elif action.text() == "Copy display properties (Ctrl+Shift+C)": event = QtGui.QKeyEvent( QtCore.QEvent.KeyPress, QtCore.Qt.Key_C, QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier, ) self.itemWidget(item).keyPressEvent(event) <|code_end|> , continue by predicting the next line. Consider current file imports: import json from struct import pack from PyQt5 import QtCore, QtGui, QtWidgets from ..utils import extract_mime_names and context: # Path: asammdf/gui/utils.py # def extract_mime_names(data): # def fix_comparison_name(data): # for i, ( # name, # group_index, # channel_index, # mdf_uuid, # item_type, # ranges, # ) in enumerate(data): # if item_type == "channel": # if (group_index, channel_index) != (-1, -1): # name = COMPARISON_NAME.match(name).group("name").strip() # data[i][0] = name # else: # fix_comparison_name(channel_index) # # names = [] # if data.hasFormat("application/octet-stream-asammdf"): # data = bytes(data.data("application/octet-stream-asammdf")).decode("utf-8") # data = json.loads(data) # fix_comparison_name(data) # names = data # # return names which might include code, classes, or functions. Output only the next line.
elif action.text() == "Paste display properties (Ctrl+Shift+P)":
Continue the code snippet: <|code_start|> self.data_blocks.append(info) yield info except StopIteration: break def get_signal_data_blocks(self, index: int) -> Iterator[SignalDataBlockInfo]: signal_data = self.signal_data[index] if signal_data is not None: signal_data, signal_generator = signal_data for blk in signal_data: yield blk while True: try: info = next(signal_generator) signal_data.append(info) yield info except StopIteration: break class VirtualChannelGroup: """starting with MDF v4.20 it is possible to use remote masters and column oriented storage. This means we now have virtual channel groups that can span over multiple regular channel groups. This class facilitates the handling of this virtual groups""" __slots__ = ( "groups", "record_size", <|code_end|> . Use current file imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context (classes, functions, or code) from other files: # Path: asammdf/types.py . Output only the next line.
"cycles_nr",
Predict the next line for this snippet: <|code_start|> signal_data = self.signal_data[index] if signal_data is not None: signal_data, signal_generator = signal_data for blk in signal_data: yield blk while True: try: info = next(signal_generator) signal_data.append(info) yield info except StopIteration: break class VirtualChannelGroup: """starting with MDF v4.20 it is possible to use remote masters and column oriented storage. This means we now have virtual channel groups that can span over multiple regular channel groups. This class facilitates the handling of this virtual groups""" __slots__ = ( "groups", "record_size", "cycles_nr", ) def __init__(self) -> None: self.groups = [] self.record_size = 0 <|code_end|> with the help of current file imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context from other files: # Path: asammdf/types.py , which may contain function names, class names, or code. Output only the next line.
self.cycles_nr = 0
Based on the snippet: <|code_start|> __slots__ = ( "groups", "record_size", "cycles_nr", ) def __init__(self) -> None: self.groups = [] self.record_size = 0 self.cycles_nr = 0 def __repr__(self) -> None: return f"VirtualChannelGroup(groups={self.groups}, records_size={self.record_size}, cycles_nr={self.cycles_nr})" def block_fields(obj: object) -> list[str]: fields = [] for attr in dir(obj): if attr[:2] + attr[-2:] == "____": continue try: if callable(getattr(obj, attr)): continue fields.append(f"{attr}:{getattr(obj, attr)}") except AttributeError: continue return fields <|code_end|> , predict the immediate next line with the help of imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context (classes, functions, sometimes code) from other files: # Path: asammdf/types.py . Output only the next line.
def components(
Using the snippet: <|code_start|> while True: try: info = next(signal_generator) signal_data.append(info) yield info except StopIteration: break class VirtualChannelGroup: """starting with MDF v4.20 it is possible to use remote masters and column oriented storage. This means we now have virtual channel groups that can span over multiple regular channel groups. This class facilitates the handling of this virtual groups""" __slots__ = ( "groups", "record_size", "cycles_nr", ) def __init__(self) -> None: self.groups = [] self.record_size = 0 self.cycles_nr = 0 def __repr__(self) -> None: return f"VirtualChannelGroup(groups={self.groups}, records_size={self.record_size}, cycles_nr={self.cycles_nr})" <|code_end|> , determine the next line of code. You have imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context (class names, function names, or code) available: # Path: asammdf/types.py . Output only the next line.
def block_fields(obj: object) -> list[str]:
Here is a snippet: <|code_start|>class VirtualChannelGroup: """starting with MDF v4.20 it is possible to use remote masters and column oriented storage. This means we now have virtual channel groups that can span over multiple regular channel groups. This class facilitates the handling of this virtual groups""" __slots__ = ( "groups", "record_size", "cycles_nr", ) def __init__(self) -> None: self.groups = [] self.record_size = 0 self.cycles_nr = 0 def __repr__(self) -> None: return f"VirtualChannelGroup(groups={self.groups}, records_size={self.record_size}, cycles_nr={self.cycles_nr})" def block_fields(obj: object) -> list[str]: fields = [] for attr in dir(obj): if attr[:2] + attr[-2:] == "____": continue try: if callable(getattr(obj, attr)): continue fields.append(f"{attr}:{getattr(obj, attr)}") <|code_end|> . Write the next line using the current file imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context from other files: # Path: asammdf/types.py , which may include functions, classes, or code. Output only the next line.
except AttributeError:
Predict the next line for this snippet: <|code_start|> while True: try: info = next(signal_generator) signal_data.append(info) yield info except StopIteration: break class VirtualChannelGroup: """starting with MDF v4.20 it is possible to use remote masters and column oriented storage. This means we now have virtual channel groups that can span over multiple regular channel groups. This class facilitates the handling of this virtual groups""" __slots__ = ( "groups", "record_size", "cycles_nr", ) def __init__(self) -> None: self.groups = [] self.record_size = 0 self.cycles_nr = 0 def __repr__(self) -> None: return f"VirtualChannelGroup(groups={self.groups}, records_size={self.record_size}, cycles_nr={self.cycles_nr})" <|code_end|> with the help of current file imports: from collections.abc import Iterator from functools import lru_cache from io import StringIO from pathlib import Path from random import randint from struct import Struct from tempfile import TemporaryDirectory from typing import Any, Dict, overload, Tuple from typing_extensions import Literal, TypedDict from cchardet import detect from chardet import detect from canmatrix.canmatrix import CanMatrix from numpy import arange, bool_, dtype, interp, where from numpy.typing import NDArray from pandas import Series from . import v2_v3_constants as v3c from . import v4_constants as v4c from ..types import ( ChannelType, DataGroupType, MDF_v2_v3_v4, RasterType, ReadableBufferType, StrPathType, ) import logging import re import string import subprocess import sys import xml.etree.ElementTree as ET import canmatrix.formats import numpy as np and context from other files: # Path: asammdf/types.py , which may contain function names, class names, or code. Output only the next line.
def block_fields(obj: object) -> list[str]:
Here is a snippet: <|code_start|> HANDSHAKE_SIGNAL = b'HANDSHAKE' HANDSHAKE_ACK_SIGNAL = b'HANDSHAKE_ACK' async def connect_handshake(connection, local_identity, timeout=10): connection.send(b''.join([HANDSHAKE_SIGNAL, b';', local_identity.encode('utf-8')])) await connection.stream.drain() try: <|code_end|> . Write the next line using the current file imports: import asyncio from xwing.exceptions import HandshakeTimeoutError, HandshakeProtocolError and context from other files: # Path: xwing/exceptions.py # class HandshakeTimeoutError(HandshakeError): # pass # # class HandshakeProtocolError(HandshakeError): # pass , which may include functions, classes, or code. Output only the next line.
handshake_ack = await asyncio.wait_for(connection.recv(), timeout)
Here is a snippet: <|code_start|> class Connector: def __init__(self, loop, settings, client_factory): self.loop = loop self.settings = settings self.client_factory = client_factory self.clients = {} async def connect(self, pid): hub_frontend, identity = pid if hub_frontend not in self.clients: self.clients[hub_frontend] = self.create_client(hub_frontend) client = self.clients[hub_frontend] return await self.connect_client(client, identity) async def connect_client(self, client, remote_identity, max_retries=30, retry_sleep=0.1): log.info('Creating connection to %s' % remote_identity) connection = None number_of_retries = 0 while number_of_retries < max_retries: try: connection = await client.connect(remote_identity) except ConnectionError: log.info('Retrying connection to %s...' % remote_identity) number_of_retries += 1 await asyncio.sleep(retry_sleep) <|code_end|> . Write the next line using the current file imports: import asyncio import logging from xwing.exceptions import MaxRetriesExceededError and context from other files: # Path: xwing/exceptions.py # class MaxRetriesExceededError(Exception): # pass , which may include functions, classes, or code. Output only the next line.
continue
Next line prediction: <|code_start|> def send(self, data): self.stream.write(data + EOL) # TODO think more about this, not sure if should be the default case. # self.stream.writer.drain() return data async def recv(self): data = await self.stream.readline() if data is None: return data # TODO may be we can reduce this to one set, just time? self.liveness = INITIAL_HEARBEAT_LIVENESS self.start_time = time.time() while True: if not data.startswith(HEARTBEAT): break if data.startswith(HEARTBEAT_SIGNAL): log.debug('Sending heartbeat ack message.') self.send(HEARTBEAT_ACK) data = await self.stream.readline() if data and not data.endswith(EOL): log.warning('Received a partial message. ' 'This may indicate a broken pipe.') # TODO may be we need to raise an exception here # and only return None when connection is really closed? <|code_end|> . Use current file imports: (import asyncio import time import logging from xwing.exceptions import HeartbeatFailureError, ConnectionAlreadyExists) and context including class names, function names, or small code snippets from other files: # Path: xwing/exceptions.py # class HeartbeatFailureError(Exception): # pass # # class ConnectionAlreadyExists(Exception): # pass . Output only the next line.
return None
Next line prediction: <|code_start|> assert not get_access_token.called return {'oauth_token': alphabet, 'another': "cba"} async def oauth_verifier(oauth_token): assert oauth_token == alphabet assert get_oauth_token.called assert not get_access_token.called return "12345" async def access_token(consumer_key, consumer_secret, oauth_verifier, oauth_token, another): assert consumer_key == 'a' assert consumer_secret == 'b' assert oauth_verifier == "12345" assert oauth_token == alphabet assert another == "cba" assert get_access_token.called assert get_oauth_verifier.called return {'consumer_key': consumer_key, 'consumer_secret': consumer_secret, 'oauth_token': "abcdef", 'oauth_token_secret': "ghijkl", <|code_end|> . Use current file imports: (import io import pytest from contextlib import redirect_stdout from unittest.mock import patch from peony import oauth, oauth_dance, utils) and context including class names, function names, or small code snippets from other files: # Path: peony/oauth.py # def quote(s): # def __init__(self, compression=True, user_agent=None, headers=None): # def __setitem__(self, key, value): # async def prepare_request(self, method, url, # headers=None, # skip_params=False, # proxy=None, # **kwargs): # def _user_headers(self, headers=None): # def sign(self, *args, headers=None, **kwargs): # def __init__(self, consumer_key, consumer_secret, # access_token=None, access_token_secret=None, # compression=True, user_agent=None, headers=None): # def _default_content_type(skip_params): # def sign(self, method='GET', url=None, # data=None, # params=None, # skip_params=False, # headers=None, # **kwargs): # def gen_nonce(self): # def gen_signature(self, method, url, params, skip_params, oauth): # def __init__(self, consumer_key, consumer_secret, client, # bearer_token=None, compression=True, user_agent=None, # headers=None): # async def sign(self, url=None, *args, headers=None, **kwargs): # def get_basic_authorization(self): # def token(self): # def token(self, access_token): # def token(self): # def _invalidate_token(self): # async def invalidate_token(self): # async def refresh_token(self): # async def prepare_request(self, *args, oauth2_pass=False, **kwargs): # def _gen_form_urlencoded(self): # def key(item): # class PeonyHeaders(ABC, dict): # class OAuth1Headers(PeonyHeaders): # class OAuth2Headers(PeonyHeaders): # class RawFormData(aiohttp.FormData): # # Path: peony/oauth_dance.py # def oauth_dance(consumer_key, consumer_secret, # oauth_callback="oob", loop=None): # """ # OAuth dance to get the user's access token # # It calls async_oauth_dance and create event loop of not given # # Parameters # ---------- # consumer_key : str # Your consumer key # consumer_secret : str # Your consumer secret # oauth_callback : str # Callback uri, defaults to 'oob' # loop : event loop # asyncio event loop # # Returns # ------- # dict # Access tokens # """ # loop = asyncio.get_event_loop() if loop is None else loop # # coro = async_oauth_dance(consumer_key, consumer_secret, oauth_callback) # return loop.run_until_complete(coro) # # Path: peony/utils.py # class Handle: # class MetaErrorHandler(type): # class ErrorHandler(metaclass=MetaErrorHandler): # class DefaultErrorHandler(ErrorHandler): # class Entity: # def __init__(self, handler, *exceptions): # def __new__(cls, name, bases, attrs, **kwargs): # def __init__(self, request): # def handle(*exceptions): # def handler_decorator(handler): # async def _handle(self, exception_class, **kwargs): # async def __call__(self, future=None, **kwargs): # def __init__(self, request, tries=3): # async def handle_rate_limits(self, exception, url): # def handle_timeout_error(self, url): # async def handle_service_unavailable(self): # async def handle_client_error(self, exception=None): # def get_args(func, skip=0): # def log_error(msg=None, exc_info=None, logger=None, **kwargs): # async def get_media_metadata(data, path=None): # async def get_size(media): # async def get_type(media, path=None): # def get_category(media_type): # async def execute(coro): # def set_debug(): # def __init__(self, original: str, # entity_type: str, # data: Mapping[str, Any]): # def __getitem__(self, key: str) -> Any: # def start(self) -> int: # def end(self) -> int: # def text(self) -> str: # def url(self) -> str: # def get_twitter_entities( # text: str, # entities: Mapping[str, Mapping[str, Any]] # ) -> Iterable[Entity]: # RETRY = CONTINUE = OK = True # RAISE = STOP = False . Output only the next line.
'hello': "world"}
Given the code snippet: <|code_start|> assert get_oauth_verifier.called return {'consumer_key': consumer_key, 'consumer_secret': consumer_secret, 'oauth_token': "abcdef", 'oauth_token_secret': "ghijkl", 'hello': "world"} get_oauth_verifier.side_effect = oauth_verifier get_oauth_token.side_effect = oauth_token get_access_token.side_effect = access_token tokens = await oauth_dance.async_oauth_dance('a', 'b') assert tokens == {'consumer_key': 'a', 'consumer_secret': 'b', 'access_token': "abcdef", 'access_token_secret': "ghijkl"} def test_oauth_dance(event_loop): data = {'consumer_key': "abc", 'consumer_secret': "def", 'access_token': "ghi", 'access_token_secret': "jkl"} async def async_oauth_dance(consumer_key, consumer_secret, callback_uri): return data with patch.object(oauth_dance, 'async_oauth_dance', <|code_end|> , generate the next line using the imports in this file: import io import pytest from contextlib import redirect_stdout from unittest.mock import patch from peony import oauth, oauth_dance, utils and context (functions, classes, or occasionally code) from other files: # Path: peony/oauth.py # def quote(s): # def __init__(self, compression=True, user_agent=None, headers=None): # def __setitem__(self, key, value): # async def prepare_request(self, method, url, # headers=None, # skip_params=False, # proxy=None, # **kwargs): # def _user_headers(self, headers=None): # def sign(self, *args, headers=None, **kwargs): # def __init__(self, consumer_key, consumer_secret, # access_token=None, access_token_secret=None, # compression=True, user_agent=None, headers=None): # def _default_content_type(skip_params): # def sign(self, method='GET', url=None, # data=None, # params=None, # skip_params=False, # headers=None, # **kwargs): # def gen_nonce(self): # def gen_signature(self, method, url, params, skip_params, oauth): # def __init__(self, consumer_key, consumer_secret, client, # bearer_token=None, compression=True, user_agent=None, # headers=None): # async def sign(self, url=None, *args, headers=None, **kwargs): # def get_basic_authorization(self): # def token(self): # def token(self, access_token): # def token(self): # def _invalidate_token(self): # async def invalidate_token(self): # async def refresh_token(self): # async def prepare_request(self, *args, oauth2_pass=False, **kwargs): # def _gen_form_urlencoded(self): # def key(item): # class PeonyHeaders(ABC, dict): # class OAuth1Headers(PeonyHeaders): # class OAuth2Headers(PeonyHeaders): # class RawFormData(aiohttp.FormData): # # Path: peony/oauth_dance.py # def oauth_dance(consumer_key, consumer_secret, # oauth_callback="oob", loop=None): # """ # OAuth dance to get the user's access token # # It calls async_oauth_dance and create event loop of not given # # Parameters # ---------- # consumer_key : str # Your consumer key # consumer_secret : str # Your consumer secret # oauth_callback : str # Callback uri, defaults to 'oob' # loop : event loop # asyncio event loop # # Returns # ------- # dict # Access tokens # """ # loop = asyncio.get_event_loop() if loop is None else loop # # coro = async_oauth_dance(consumer_key, consumer_secret, oauth_callback) # return loop.run_until_complete(coro) # # Path: peony/utils.py # class Handle: # class MetaErrorHandler(type): # class ErrorHandler(metaclass=MetaErrorHandler): # class DefaultErrorHandler(ErrorHandler): # class Entity: # def __init__(self, handler, *exceptions): # def __new__(cls, name, bases, attrs, **kwargs): # def __init__(self, request): # def handle(*exceptions): # def handler_decorator(handler): # async def _handle(self, exception_class, **kwargs): # async def __call__(self, future=None, **kwargs): # def __init__(self, request, tries=3): # async def handle_rate_limits(self, exception, url): # def handle_timeout_error(self, url): # async def handle_service_unavailable(self): # async def handle_client_error(self, exception=None): # def get_args(func, skip=0): # def log_error(msg=None, exc_info=None, logger=None, **kwargs): # async def get_media_metadata(data, path=None): # async def get_size(media): # async def get_type(media, path=None): # def get_category(media_type): # async def execute(coro): # def set_debug(): # def __init__(self, original: str, # entity_type: str, # data: Mapping[str, Any]): # def __getitem__(self, key: str) -> Any: # def start(self) -> int: # def end(self) -> int: # def text(self) -> str: # def url(self) -> str: # def get_twitter_entities( # text: str, # entities: Mapping[str, Mapping[str, Any]] # ) -> Iterable[Entity]: # RETRY = CONTINUE = OK = True # RAISE = STOP = False . Output only the next line.
side_effect=async_oauth_dance) as async_dance:
Continue the code snippet: <|code_start|> async def sign(self, *args, **kwargs): self.token = alphabet return self.copy() def test_oauth2_dance(event_loop): with patch.object(oauth_dance.oauth, 'OAuth2Headers', side_effect=MockOAuth2Headers): args = 'consumer_key', 'consumer_secret' with patch.object(utils, 'get_args', return_value=args): assert alphabet == oauth_dance.oauth2_dance("a", "b", event_loop) @pytest.mark.asyncio async def test_get_oauth_token(): async def request(method, url, future, *args, **kwargs): assert method == 'post' assert url == "https://api.twitter.com/oauth/request_token" data = "oauth_token=abc&hello=world" future.set_result(data) return data with patch.object(oauth_dance.BasePeonyClient, 'request', side_effect=request): data = await oauth_dance.get_oauth_token("", "") assert data == {'oauth_token': "abc", 'hello': "world"} async def dummy(*args, **kwargs): <|code_end|> . Use current file imports: import io import pytest from contextlib import redirect_stdout from unittest.mock import patch from peony import oauth, oauth_dance, utils and context (classes, functions, or code) from other files: # Path: peony/oauth.py # def quote(s): # def __init__(self, compression=True, user_agent=None, headers=None): # def __setitem__(self, key, value): # async def prepare_request(self, method, url, # headers=None, # skip_params=False, # proxy=None, # **kwargs): # def _user_headers(self, headers=None): # def sign(self, *args, headers=None, **kwargs): # def __init__(self, consumer_key, consumer_secret, # access_token=None, access_token_secret=None, # compression=True, user_agent=None, headers=None): # def _default_content_type(skip_params): # def sign(self, method='GET', url=None, # data=None, # params=None, # skip_params=False, # headers=None, # **kwargs): # def gen_nonce(self): # def gen_signature(self, method, url, params, skip_params, oauth): # def __init__(self, consumer_key, consumer_secret, client, # bearer_token=None, compression=True, user_agent=None, # headers=None): # async def sign(self, url=None, *args, headers=None, **kwargs): # def get_basic_authorization(self): # def token(self): # def token(self, access_token): # def token(self): # def _invalidate_token(self): # async def invalidate_token(self): # async def refresh_token(self): # async def prepare_request(self, *args, oauth2_pass=False, **kwargs): # def _gen_form_urlencoded(self): # def key(item): # class PeonyHeaders(ABC, dict): # class OAuth1Headers(PeonyHeaders): # class OAuth2Headers(PeonyHeaders): # class RawFormData(aiohttp.FormData): # # Path: peony/oauth_dance.py # def oauth_dance(consumer_key, consumer_secret, # oauth_callback="oob", loop=None): # """ # OAuth dance to get the user's access token # # It calls async_oauth_dance and create event loop of not given # # Parameters # ---------- # consumer_key : str # Your consumer key # consumer_secret : str # Your consumer secret # oauth_callback : str # Callback uri, defaults to 'oob' # loop : event loop # asyncio event loop # # Returns # ------- # dict # Access tokens # """ # loop = asyncio.get_event_loop() if loop is None else loop # # coro = async_oauth_dance(consumer_key, consumer_secret, oauth_callback) # return loop.run_until_complete(coro) # # Path: peony/utils.py # class Handle: # class MetaErrorHandler(type): # class ErrorHandler(metaclass=MetaErrorHandler): # class DefaultErrorHandler(ErrorHandler): # class Entity: # def __init__(self, handler, *exceptions): # def __new__(cls, name, bases, attrs, **kwargs): # def __init__(self, request): # def handle(*exceptions): # def handler_decorator(handler): # async def _handle(self, exception_class, **kwargs): # async def __call__(self, future=None, **kwargs): # def __init__(self, request, tries=3): # async def handle_rate_limits(self, exception, url): # def handle_timeout_error(self, url): # async def handle_service_unavailable(self): # async def handle_client_error(self, exception=None): # def get_args(func, skip=0): # def log_error(msg=None, exc_info=None, logger=None, **kwargs): # async def get_media_metadata(data, path=None): # async def get_size(media): # async def get_type(media, path=None): # def get_category(media_type): # async def execute(coro): # def set_debug(): # def __init__(self, original: str, # entity_type: str, # data: Mapping[str, Any]): # def __getitem__(self, key: str) -> Any: # def start(self) -> int: # def end(self) -> int: # def text(self) -> str: # def url(self) -> str: # def get_twitter_entities( # text: str, # entities: Mapping[str, Mapping[str, Any]] # ) -> Iterable[Entity]: # RETRY = CONTINUE = OK = True # RAISE = STOP = False . Output only the next line.
pass
Continue the code snippet: <|code_start|> clsname=self.__class__.__name__, prefix=self.prefix, event=self.is_event ) @classmethod def event_handler(cls, event, prefix=None, **values): def decorator(func): event_handler = cls( func=func, event=event, prefix=prefix, **values ) return event_handler return decorator class EventStream(abc.ABC): def __init__(self, client): self._client = client self.functions = [getattr(self, func) for func in dir(self) if self._check(func)] self.functions.sort(key=lambda i: getattr(i.is_event, 'priority', 0)) <|code_end|> . Use current file imports: import abc import peony.utils from .commands import Commands from .tasks import task and context (classes, functions, or code) from other files: # Path: peony/commands/commands.py # class Commands(Functions): # # def __init__(self, prefix=None): # super().__init__(prefix=prefix) # # @self # def help(_self, data, *args, **kwargs): # """ show commands help """ # kdoc = [ # (key, utils.doc(value)) # for key, value in self.items() # if utils.permission_check( # data, # command_permissions=_self.permissions, # command=value # ) # ] # # kdoc.sort(key=self._key) # # msg = ["{key}: {doc}".format(key=key, doc=doc) # for key, doc in kdoc] # # return "\n".join(msg) # # def _key(self, item): # key, __ = item # if key == self.prefix + "help": # return '' # /help is the first in the message # else: # return key # sort other commands alphabeticaly # # def restricted(self, *permissions): # # def decorator(func): # # @wraps(func) # async def decorated(_self, *args, data): # permission = utils.permission_check( # data, # command_permissions=_self.permissions, # permissions=permissions # ) # # if permission: # argcount = func.__code__.co_argcount - 1 # args = (*args, data)[:argcount] # cmd = func(_self, *args) # # return await peony.utils.execute(cmd) # # decorated.permissions = permissions # # return self(decorated) # # return decorator # # Path: peony/commands/tasks.py # class Task: # def __init__(self, func): # def __call__(self, *args, **kwargs): # def __str__(self): # def __repr__(self): . Output only the next line.
def __getitem__(self, key):
Using the snippet: <|code_start|> args = args[:argcount] return super().__call__(*args) def __repr__(self): return "<{clsname}: event:{event} prefix:{prefix}>".format( clsname=self.__class__.__name__, prefix=self.prefix, event=self.is_event ) @classmethod def event_handler(cls, event, prefix=None, **values): def decorator(func): event_handler = cls( func=func, event=event, prefix=prefix, **values ) return event_handler return decorator class EventStream(abc.ABC): def __init__(self, client): self._client = client <|code_end|> , determine the next line of code. You have imports: import abc import peony.utils from .commands import Commands from .tasks import task and context (class names, function names, or code) available: # Path: peony/commands/commands.py # class Commands(Functions): # # def __init__(self, prefix=None): # super().__init__(prefix=prefix) # # @self # def help(_self, data, *args, **kwargs): # """ show commands help """ # kdoc = [ # (key, utils.doc(value)) # for key, value in self.items() # if utils.permission_check( # data, # command_permissions=_self.permissions, # command=value # ) # ] # # kdoc.sort(key=self._key) # # msg = ["{key}: {doc}".format(key=key, doc=doc) # for key, doc in kdoc] # # return "\n".join(msg) # # def _key(self, item): # key, __ = item # if key == self.prefix + "help": # return '' # /help is the first in the message # else: # return key # sort other commands alphabeticaly # # def restricted(self, *permissions): # # def decorator(func): # # @wraps(func) # async def decorated(_self, *args, data): # permission = utils.permission_check( # data, # command_permissions=_self.permissions, # permissions=permissions # ) # # if permission: # argcount = func.__code__.co_argcount - 1 # args = (*args, data)[:argcount] # cmd = func(_self, *args) # # return await peony.utils.execute(cmd) # # decorated.permissions = permissions # # return self(decorated) # # return decorator # # Path: peony/commands/tasks.py # class Task: # def __init__(self, func): # def __call__(self, *args, **kwargs): # def __str__(self): # def __repr__(self): . Output only the next line.
self.functions = [getattr(self, func)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- on = 'on_{name}' def _get_value(func): value = func() if value is None: <|code_end|> , predict the immediate next line with the help of imports: from functools import wraps from ..utils import get_args from .event_handlers import EventHandler and context (classes, functions, sometimes code) from other files: # Path: peony/utils.py # def get_args(func, skip=0): # """ # Hackish way to get the arguments of a function # # Parameters # ---------- # func : callable # Function to get the arguments from # skip : int, optional # Arguments to skip, defaults to 0 set it to 1 to skip the # ``self`` argument of a method. # # Returns # ------- # tuple # Function's arguments # """ # # code = getattr(func, '__code__', None) # if code is None: # code = func.__call__.__code__ # # return code.co_varnames[skip:code.co_argcount] # # Path: peony/commands/event_handlers.py # class EventHandler(task): # # def __init__(self, func, event, prefix=None, strict=False): # super().__init__(func) # # self.prefix = prefix # self.is_event = event # # if prefix is not None: # self.command = Commands(prefix=prefix, strict=strict) # # def __call__(self, *args): # argcount = self.__wrapped__.__code__.co_argcount # # if hasattr(self, 'command'): # args = (*args, self.command,) # # args = args[:argcount] # return super().__call__(*args) # # def __repr__(self): # return "<{clsname}: event:{event} prefix:{prefix}>".format( # clsname=self.__class__.__name__, # prefix=self.prefix, # event=self.is_event # ) # # @classmethod # def event_handler(cls, event, prefix=None, **values): # # def decorator(func): # event_handler = cls( # func=func, # event=event, # prefix=prefix, # **values # ) # # return event_handler # # return decorator . Output only the next line.
value = func.__name__
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- on = 'on_{name}' def _get_value(func): value = func() if value is None: value = func.__name__ <|code_end|> with the help of current file imports: from functools import wraps from ..utils import get_args from .event_handlers import EventHandler and context from other files: # Path: peony/utils.py # def get_args(func, skip=0): # """ # Hackish way to get the arguments of a function # # Parameters # ---------- # func : callable # Function to get the arguments from # skip : int, optional # Arguments to skip, defaults to 0 set it to 1 to skip the # ``self`` argument of a method. # # Returns # ------- # tuple # Function's arguments # """ # # code = getattr(func, '__code__', None) # if code is None: # code = func.__call__.__code__ # # return code.co_varnames[skip:code.co_argcount] # # Path: peony/commands/event_handlers.py # class EventHandler(task): # # def __init__(self, func, event, prefix=None, strict=False): # super().__init__(func) # # self.prefix = prefix # self.is_event = event # # if prefix is not None: # self.command = Commands(prefix=prefix, strict=strict) # # def __call__(self, *args): # argcount = self.__wrapped__.__code__.co_argcount # # if hasattr(self, 'command'): # args = (*args, self.command,) # # args = args[:argcount] # return super().__call__(*args) # # def __repr__(self): # return "<{clsname}: event:{event} prefix:{prefix}>".format( # clsname=self.__class__.__name__, # prefix=self.prefix, # event=self.is_event # ) # # @classmethod # def event_handler(cls, event, prefix=None, **values): # # def decorator(func): # event_handler = cls( # func=func, # event=event, # prefix=prefix, # **values # ) # # return event_handler # # return decorator , which may contain function names, class names, or code. Output only the next line.
return value
Continue the code snippet: <|code_start|> 'hariyama', 'infernape', 'jumpluff', 'kangaskhan', 'lucario', 'bisharp', 'lucariomega')] teams = [movesets[:6], movesets[6:12], [movesets[i] for i in (1, 12, 3, 4, 5, 6)], [movesets[i] for i in (3, 5, 6, 8, 9, 13)]] logs = [lg.generate_log(players[:2], teams[:2]), lg.generate_log(players[2:4], teams[2:]), lg.generate_log((players[1], players[4]), (teams[1], teams[0]))] tmpdir.mkdir('tj') for i, log in enumerate(logs): json.dump(log, open('{2}/tj/battle-{1}-{0}.log.json' .format(i + 1, log['p1rating']['formatid'], tmpdir.strpath), 'w+')) def check(self, processor, result): assert 3 == result assert 14 == len(processor.moveset_sink.sids) assert 5 == len(processor.battle_info_sink.pids) assert 4 == len(processor.battle_info_sink.tids) <|code_end|> . Use current file imports: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context (classes, functions, or code) from other files: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): . Output only the next line.
assert {'uu', 'ou'} == set(processor.battle_info_sink.battles.keys())