Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> self.f = self.build_layered_var( self.f) self.C = self.build_layered_var( self.C) # initialize_computed_vars() #------------------------------------------------------------------- def update_infil_rate(self): Beven_Exp_K_Infil_Rate_v1(self) # update_infil_rate() #------------------------------------------------------------------- def open_input_files(self): #------------------------------------------------------- # NB! Beven, Green-Ampt & Smith-Parlange currently only # support ONE layer (n_layers == 1). #------------------------------------------------------- self.Ks_unit = [] # (empty lists to hold file objects) self.qs_unit = [] self.qi_unit = [] self.f_unit = [] self.C_unit = [] for k in xrange(self.n_layers): self.Ks_file[k] = self.in_directory + self.Ks_file[k] self.qs_file[k] = self.in_directory + self.qs_file[k] self.qi_file[k] = self.in_directory + self.qi_file[k] self.f_file[k] = self.in_directory + self.f_file[k] self.C_file[k] = self.in_directory + self.C_file[k] <|code_end|> with the help of current file imports: import numpy as np from topoflow.components import infil_base from topoflow.utils import model_input from topoflow.utils.tf_utils import TF_Print, TF_String and context from other files: # Path: topoflow/components/infil_base.py # class infil_component( BMI_base.BMI_component): # def set_constants(self): # def initialize(self, cfg_file=None, mode="nondriver", # SILENT=False): # def update(self, dt=-1.0): # def finalize(self): # def build_layer_z_vector(self): # def build_layered_var(self, var_list_for_layers): # def set_computed_input_vars(self): # def check_input_types(self): # def update_surface_influx(self): # def update_infil_rate(self): # def adjust_infil_rate(self): # def update_IN_integral(self): # def update_Rg(self): # def update_Rg_integral(self): # def update_I(self): # def update_q0(self): # def check_infiltration(self): # def check_low_rainrate(self): # def open_input_files(self): # def read_input_files(self): # def close_input_files(self): # def update_outfile_names(self): # def open_output_files(self): # def write_output_files(self, time_seconds=None): # def close_output_files(self): # def save_grids(self): # def save_pixel_values(self): # def save_profiles(self): # def save_cubes(self): # ALL_SCALARS = (nmax == 1) # SM = self.SM # (2/3/13, new framework) # CHECK_LOW_RAIN = not(self.RICHARDS) # SM = self.SM # (2/3/13, new framework) # OK = np.isfinite( self.IN ) # OK = (nbad == 0) # G = model_input.read_next(self.G_unit[k], self.G_type[k], rti) # # Path: topoflow/utils/model_input.py # def open_file(var_type, input_file): # def read_next2(self, var_name, rti, dtype='Float32', factor=1.0): # def read_next(file_unit, var_type, rti, \ # dtype='Float32', factor=1.0): # def read_scalar(file_unit, dtype='Float32'): # def read_grid(file_unit, rti, dtype='Float32'): # def close_file(file_unit): # END_OF_FILE = (file_pos == file_size) # # Path: topoflow/utils/tf_utils.py # def TF_Print(string): # """Print a string to the TopoFlow output log window.""" # # #------------------------------------------ # # For now, just print to terminal window. # # Later, this will be method in tf_gui.py. # #------------------------------------------ # print string # # def TF_String(number, FORMAT=None): # # return idl_func.string(number, format=FORMAT).strip() , which may contain function names, class names, or code. Output only the next line.
self.Ks_unit.append( model_input.open_file(self.Ks_type[k], self.Ks_file[k]) )
Here is a snippet: <|code_start|>## Copyright (c) 2001-2013, Scott D. Peckham #----------------------------------------------------------------------- def test_instantiate(): g = evap_energy_balance.evap_component() g.CCA = False g.DEBUG = False #----------------------------------------- # This function adjusts for the platform # and can be changed in "tf_utils.py". #----------------------------------------- <|code_end|> . Write the next line using the current file imports: from topoflow.components import evap_energy_balance from topoflow.utils import tf_utils and context from other files: # Path: topoflow/components/evap_energy_balance.py # class evap_component(evap_base.evap_component): # def get_component_name(self): # def get_attribute(self, att_name): # def get_input_var_names(self): # def get_output_var_names(self): # def get_var_name(self, long_var_name): # def get_var_units(self, long_var_name): # def check_input_types(self): # def update_ET_rate(self): # def open_input_files(self): # def read_input_files(self): # def close_input_files(self): # ET = (Qet / np.float64(2.5E+9)) # [m/s] # # Path: topoflow/utils/tf_utils.py # def TF_Use_CCA(): # def TF_Set_Test_Info(self): # def TF_Test_Directory(): # def TF_Test_Site_Prefix(): # def TF_Test_Case_Prefix(): # def TF_Build_Date(): # def TF_Version_Number(): # def TF_Version(): # def TF_Print(string): # def TF_String(number, FORMAT=None): # def file_exists(filename): # def Count_Lines(filename, SILENT=False): # def Current_Directory(): # def Resize(array, factor, REDUCE, new_ncols, new_nrows, SAMP_TYPE=None): # def Make_Savefile(): # def Get_Site_Prefix(filepath): # def Get_Case_Prefix(): # def Not_Same_Byte_Order(byte_order): # def Courant_Condition_OK(dx, dt, vmax): # def Stable_Timestep(dx, vmax): # def TF_Tan(angle): # def Convert_Flow_Grid(infile, outfile, itype, otype, byte_order, \ # icodes=None, ocodes=None, REPORT=False): # SAMP_TYPE = int16(0) # NOT_SAME = (machine_byte_order != byte_order) # OK = ((vmax * dt * factor) <= dx) # SWAP_ENDIAN = Not_Same_Byte_Order(byte_order) , which may include functions, classes, or code. Output only the next line.
cfg_directory = tf_utils.TF_Test_Directory()
Using the snippet: <|code_start|> # So (rho_w * Lf) = 3.34e+8 [J/m^3] #------------------------------------------ M = (Qm / np.float64(3.34E+8)) #[m/s] self.SM = np.maximum(M, np.float64(0)) #-------------------------------------------------- # Update the cold content of the snowpack [J m-2] # If this is positive, there was no melt so far. #-------------------------------------------------- # (9/13/14) Bug fix: Ecc wasn't stored into self. #-------------------------------------------------- self.Ecc = np.maximum((self.Ecc - E_in), np.float64(0)) #------------------------------------------------------- # Note: enforce_max_meltrate() method is always called # by the base class to make sure that meltrate # does not exceed the max possible. #------------------------------------------------------- # self.enforce_max_meltrate() # update_meltrate() #--------------------------------------------------------------------- def open_input_files(self): self.Cp_snow_file = self.in_directory + self.Cp_snow_file self.rho_snow_file = self.in_directory + self.rho_snow_file self.T0_file = self.in_directory + self.T0_file self.h0_snow_file = self.in_directory + self.h0_snow_file self.h0_swe_file = self.in_directory + self.h0_swe_file <|code_end|> , determine the next line of code. You have imports: import numpy as np from topoflow.utils import model_input from topoflow.components import snow_base and context (class names, function names, or code) available: # Path: topoflow/utils/model_input.py # def open_file(var_type, input_file): # def read_next2(self, var_name, rti, dtype='Float32', factor=1.0): # def read_next(file_unit, var_type, rti, \ # dtype='Float32', factor=1.0): # def read_scalar(file_unit, dtype='Float32'): # def read_grid(file_unit, rti, dtype='Float32'): # def close_file(file_unit): # END_OF_FILE = (file_pos == file_size) # # Path: topoflow/components/snow_base.py # class snow_component( BMI_base.BMI_component ): # def set_constants(self): # def latent_heat_of_sublimation(self): # def initialize(self, cfg_file=None, mode="nondriver", # SILENT=False): # def update(self, dt=-1.0): # def finalize(self): # def set_computed_input_vars(self): # def check_input_types(self): # def initialize_computed_vars(self): # def update_meltrate(self): # def enforce_max_meltrate(self): # def update_SM_integral(self): # def update_swe(self): # def update_depth(self): # def open_input_files(self): # def read_input_files(self): # def close_input_files(self): # def update_outfile_names(self): # def open_output_files(self): # def write_output_files(self, time_seconds=None): # def close_output_files(self): # def save_grids(self): # def save_pixel_values(self): # T = self.T_air # T_IS_GRID = self.is_grid('T_air') # P_IS_GRID = self.is_grid('P_snow') # H0_SNOW_IS_SCALAR = self.is_scalar('h0_snow') # H0_SWE_IS_SCALAR = self.is_scalar('h0_swe') . Output only the next line.
self.Cp_snow_unit = model_input.open_file(self.Cp_snow_type, self.Cp_snow_file)
Next line prediction: <|code_start|>""" Tests for OEShape color utilities. """ class TestColorForceField(unittest.TestCase): """ Tests for ColorForceField. """ def setUp(self): """ Set up tests. """ <|code_end|> . Use current file imports: (import numpy as np import unittest from openeye.oechem import * from openeye.oeshape import * from ..color import ColorForceField) and context including class names, function names, or small code snippets from other files: # Path: oe_utils/shape/color.py # class ColorForceField(OEColorForceField): # """ # Color force field wrapper with additional utility methods. # """ # def get_interactions(self): # """ # Extract color-color interactions from INTERACTION lines. # # Returns # ------- # interactions : array_like # Array containing tuples of (a_type, b_type, decay, weight, radius). # # Notes # ----- # * Negative weights indicate attractive interactions. # * Interaction list is sorted. # """ # interactions = [] # for line in self.get_string().split('\n'): # fields = line.split() # if not len(fields) or str.lower(fields[0]) != 'interaction': # continue # assert len(fields) == 7 # # # get color atom types # a_type = self.GetType(fields[1]) # b_type = self.GetType(fields[2]) # assert a_type and b_type # # # get decay # decay = fields[4] # # # get weight and direction (negative weights are attractive) # weight_name, weight = fields[5].split('=') # assert str.lower(weight_name) == 'weight' # weight = float(weight) # if str.lower(fields[3]) == 'attractive': # weight *= -1 # else: # assert str.lower(fields[3]) == 'repulsive' # # # get radius # radius_name, radius = fields[6].split('=') # assert str.lower(radius_name) == 'radius' # radius = float(radius) # # # construct an interaction tuple matching the order required by # # OEColorForceField.AddInteraction # interactions.append((a_type, b_type, decay, weight, radius)) # return sorted(interactions) # sort interaction list # # def get_string(self): # """ # Return the color force field as a string. # """ # ostream = oeosstream() # self.Write(ostream) # return ostream.str() # # def isolate_interactions(self): # """ # Yield color force fields that each have only a single interaction. # """ # for interaction in self.get_interactions(): # color_ff = ColorForceField(self) # create a copy # color_ff.ClearInteractions() # color_ff.AddInteraction(*interaction) # yield color_ff . Output only the next line.
self.color_ff = ColorForceField()
Continue the code snippet: <|code_start|> result = OEColorResults() self.ColorScore(fit_mol, result) return ColorOverlapResult(result) def get_color_components(self, fit_mol): """ Get overlap scores for each color type. The color overlap is repeated with a series of different color force fields that each have a single color type defined. Parameters ---------- fit_mol : OEMol Fit molecule. """ if self.color_component_engines is None: self.color_component_engines = self.get_color_component_engines() results = collections.defaultdict(list) for color_type, color_type_name, engine in self.color_component_engines: results['overlaps'].append(engine.overlap(fit_mol)) results['color_types'].append(color_type) results['color_type_names'].append(color_type_name) return results def get_color_component_engines(self): """ Create a separate ColorOverlap engine for each interaction. """ color_component_engines = [] <|code_end|> . Use current file imports: import collections import numpy as np from openeye.oechem import * from openeye.oeshape import * from oe_utils.shape.color import ColorForceField and context (classes, functions, or code) from other files: # Path: oe_utils/shape/color.py # class ColorForceField(OEColorForceField): # """ # Color force field wrapper with additional utility methods. # """ # def get_interactions(self): # """ # Extract color-color interactions from INTERACTION lines. # # Returns # ------- # interactions : array_like # Array containing tuples of (a_type, b_type, decay, weight, radius). # # Notes # ----- # * Negative weights indicate attractive interactions. # * Interaction list is sorted. # """ # interactions = [] # for line in self.get_string().split('\n'): # fields = line.split() # if not len(fields) or str.lower(fields[0]) != 'interaction': # continue # assert len(fields) == 7 # # # get color atom types # a_type = self.GetType(fields[1]) # b_type = self.GetType(fields[2]) # assert a_type and b_type # # # get decay # decay = fields[4] # # # get weight and direction (negative weights are attractive) # weight_name, weight = fields[5].split('=') # assert str.lower(weight_name) == 'weight' # weight = float(weight) # if str.lower(fields[3]) == 'attractive': # weight *= -1 # else: # assert str.lower(fields[3]) == 'repulsive' # # # get radius # radius_name, radius = fields[6].split('=') # assert str.lower(radius_name) == 'radius' # radius = float(radius) # # # construct an interaction tuple matching the order required by # # OEColorForceField.AddInteraction # interactions.append((a_type, b_type, decay, weight, radius)) # return sorted(interactions) # sort interaction list # # def get_string(self): # """ # Return the color force field as a string. # """ # ostream = oeosstream() # self.Write(ostream) # return ostream.str() # # def isolate_interactions(self): # """ # Yield color force fields that each have only a single interaction. # """ # for interaction in self.get_interactions(): # color_ff = ColorForceField(self) # create a copy # color_ff.ClearInteractions() # color_ff.AddInteraction(*interaction) # yield color_ff . Output only the next line.
color_ff = ColorForceField(self.color_ff)
Predict the next line for this snippet: <|code_start|>""" Test scaffold utilities. """ class TestScaffold(unittest.TestCase): """ Test Scaffold. """ def setUp(self): """ Set up tests. """ smiles = 'C[C@@]1(C(=O)NC(=O)N(C1=O)C)C2=CCCCC2 (S)-Hexobarbital' self.mol = OEMol() OESmilesToMol(self.mol, smiles) <|code_end|> with the help of current file imports: import unittest from oe_utils.chem.scaffold import Scaffold from openeye.oechem import * and context from other files: # Path: oe_utils/chem/scaffold.py # class Scaffold(object): # """ # Extract the scaffold of a molecule. The default parameters give the # Murcko scaffold as defined in J. Med. Chem. 1996, 39, 2887-289. # # To be part of the scaffold, an atom must be in a ring or in a linker # between two rings. # # Parameters # ---------- # stereo : bool, optional (default False) # Whether to retain stereochemistry in the scaffold. # """ # def __init__(self, stereo=False): # self.stereo = stereo # # def __call__(self, mol): # """ # Extract the scaffold of a molecule. # # Parameters # ---------- # mol : OEMol # Molecule. # """ # return self.get_scaffold(mol) # # def get_scaffold(self, mol): # """ # Extract the scaffold of a molecule. # # Parameters # ---------- # mol : OEMol # Molecule. # """ # mol = mol.CreateCopy() # pred = IsInScaffold() # OEFindRingAtomsAndBonds(mol) # prepare molecule # scaffold = OEMol() # adjust_h_count = True # OESubsetMol(scaffold, mol, pred, adjust_h_count) # # # acyclic molecules: return the original molecule # if not scaffold.IsValid(): # scaffold = mol # # # handle stereochemistry # if not self.stereo: # flat = OECreateCanSmiString(scaffold) # scaffold = OEMol() # OESmilesToMol(scaffold, flat) # else: # OEPerceiveChiral(scaffold) # return scaffold # # def get_scaffold_smiles(self, mol): # """ # Extract the scaffold of a molecule as a SMILES string. # # Parameters # ---------- # mol : OEMol # Molecule. # """ # return OECreateIsoSmiString(self.get_scaffold(mol)) , which may contain function names, class names, or code. Output only the next line.
self.engine = Scaffold()
Here is a snippet: <|code_start|> 'kif11', 'rxra', 'sahh', 'urok', ] def load_datasets(): datasets = [] if FLAGS.dataset is not None: datasets.append(FLAGS.dataset) elif FLAGS.dataset_file is not None: with open(FLAGS.datasets) as f: for line in f: datasets.append(line.strip()) else: raise ValueError('No dataset(s) specified.') return datasets def load_features_and_labels(dataset): """Load features from ROCS overlays. Returns: features: Dict mapping feature names to numpy arrays. labels: Numpy array containing labels for molecules. """ features = {} # ROCS. <|code_end|> . Write the next line using the current file imports: import collections import cPickle as pickle import gflags as flags import gzip import logging import numpy as np import pandas as pd import sys from oe_utils.utils import h5_utils from sklearn import cross_validation from sklearn import ensemble from sklearn import grid_search from sklearn import linear_model from sklearn import metrics from sklearn import preprocessing from sklearn import svm and context from other files: # Path: oe_utils/utils/h5_utils.py # def load(filename, load_all=True): # def dump(data, filename, attrs=None, options=None): , which may include functions, classes, or code. Output only the next line.
rocs_actives = h5_utils.load(FLAGS.rocs_actives % dataset)
Here is a snippet: <|code_start|> # for now we only support transition from DOWN->ACTIVE # https://bugs.launchpad.net/networking-odl/+bug/1686023 if status == n_const.PORT_STATUS_ACTIVE: provisioning_blocks.provisioning_complete( context.get_admin_context(), port_id, resources.PORT, provisioning_blocks.L2_AGENT_ENTITY) if operation == event.OPERATION_DELETE: LOG.debug("PortStatus: Ignoring delete operation") def _process_websocket_reconnect(self, status): if status == odl_ws_client.ODL_WEBSOCKET_CONNECTED: # Get port data using restconf LOG.debug("Websocket notification on reconnection") reconn_thread = threading.Thread( name='websocket', target=self._pull_missed_statuses) reconn_thread.start() def _pull_missed_statuses(self): LOG.debug("starting to pull pending statuses...") plugin = directory.get_plugin() filter = {"status": [n_const.PORT_STATUS_DOWN], "vif_type": ["unbound"]} ports = plugin.get_ports(context.get_admin_context(), filter) if not ports: LOG.debug("no down ports found, done") return port_fetch_url = utils.get_odl_url(self.PORT_PATH) <|code_end|> . Write the next line using the current file imports: import threading from neutron_lib.callbacks import resources from neutron_lib import constants as n_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib import worker from oslo_log import log from neutron.db import provisioning_blocks from networking_odl.common import client as odl_client from networking_odl.common import odl_features from networking_odl.common import utils from networking_odl.common import websocket_client as odl_ws_client and context from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): # # Path: networking_odl/common/websocket_client.py # LOG = log.getLogger(__name__) # ODL_OPERATIONAL_DATASTORE = "OPERATIONAL" # ODL_CONFIGURATION_DATASTORE = "CONFIGURATION" # ODL_NOTIFICATION_SCOPE_BASE = "BASE" # ODL_NOTIFICATION_SCOPE_ONE = "ONE" # ODL_NOTIFICATION_SCOPE_SUBTREE = "SUBTREE" # ODL_WEBSOCKET_DISCONNECTED = "ODL_WEBSOCKET_DISCONNECTED" # ODL_WEBSOCKET_CONNECTING = "ODL_WEBSOCKET_CONNECTING" # ODL_WEBSOCKET_CONNECTED = "ODL_WEBSOCKET_CONNECTED" # NOTIFICATION_TAG = 'notification' # DC_NOTIFICATION_TAG = 'data-changed-notification' # DC_EVENT_TAG = 'data-change-event' # OPERATION_DELETE = 'deleted' # OPERATION_CREATE = 'created' # OPERATION_UPDATE = 'updated' # class OpenDaylightWebsocketClient(object): # class EventDataParser(object): # def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, # packet_handler, timeout, status_cb=None): # def odl_create_websocket(cls, odl_url, path, datastore, scope, # packet_handler, status_cb=None, # leaf_node_only=False): # def start_odl_websocket_thread(self): # def set_exit_flag(self, value=True): # def run_websocket_thread(self, exit_after_run=False): # def _set_websocket_status(self, status): # def _subscribe_websocket(self): # def _socket_create_connection(self, stream_url): # def _connect_ws(self): # def _close_ws(self, ws): # def __init__(self, item): # def get_item(cls, payload): # def get_fields(self): # def get_path(self): # def get_data(self): # def get_operation(self): # def extract_field(text, key): , which may include functions, classes, or code. Output only the next line.
client = odl_client.OpenDaylightRestClient.create_client(
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. LOG = log.getLogger(__name__) class OdlPortStatusUpdate(worker.BaseWorker): """Class to register and handle port status update""" PORT_PATH = "restconf/operational/neutron:neutron/ports/port" def __init__(self): super(OdlPortStatusUpdate, self).__init__() self.odl_websocket_client = None def start(self): super(OdlPortStatusUpdate, self).start() LOG.debug('OdlPortStatusUpdate worker running') <|code_end|> . Use current file imports: import threading from neutron_lib.callbacks import resources from neutron_lib import constants as n_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib import worker from oslo_log import log from neutron.db import provisioning_blocks from networking_odl.common import client as odl_client from networking_odl.common import odl_features from networking_odl.common import utils from networking_odl.common import websocket_client as odl_ws_client and context (classes, functions, or code) from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): # # Path: networking_odl/common/websocket_client.py # LOG = log.getLogger(__name__) # ODL_OPERATIONAL_DATASTORE = "OPERATIONAL" # ODL_CONFIGURATION_DATASTORE = "CONFIGURATION" # ODL_NOTIFICATION_SCOPE_BASE = "BASE" # ODL_NOTIFICATION_SCOPE_ONE = "ONE" # ODL_NOTIFICATION_SCOPE_SUBTREE = "SUBTREE" # ODL_WEBSOCKET_DISCONNECTED = "ODL_WEBSOCKET_DISCONNECTED" # ODL_WEBSOCKET_CONNECTING = "ODL_WEBSOCKET_CONNECTING" # ODL_WEBSOCKET_CONNECTED = "ODL_WEBSOCKET_CONNECTED" # NOTIFICATION_TAG = 'notification' # DC_NOTIFICATION_TAG = 'data-changed-notification' # DC_EVENT_TAG = 'data-change-event' # OPERATION_DELETE = 'deleted' # OPERATION_CREATE = 'created' # OPERATION_UPDATE = 'updated' # class OpenDaylightWebsocketClient(object): # class EventDataParser(object): # def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, # packet_handler, timeout, status_cb=None): # def odl_create_websocket(cls, odl_url, path, datastore, scope, # packet_handler, status_cb=None, # leaf_node_only=False): # def start_odl_websocket_thread(self): # def set_exit_flag(self, value=True): # def run_websocket_thread(self, exit_after_run=False): # def _set_websocket_status(self, status): # def _subscribe_websocket(self): # def _socket_create_connection(self, stream_url): # def _connect_ws(self): # def _close_ws(self, ws): # def __init__(self, item): # def get_item(cls, payload): # def get_fields(self): # def get_path(self): # def get_data(self): # def get_operation(self): # def extract_field(text, key): . Output only the next line.
if odl_features.has(odl_features.OPERATIONAL_PORT_STATUS):
Given the code snippet: <|code_start|> class OdlPortStatusUpdate(worker.BaseWorker): """Class to register and handle port status update""" PORT_PATH = "restconf/operational/neutron:neutron/ports/port" def __init__(self): super(OdlPortStatusUpdate, self).__init__() self.odl_websocket_client = None def start(self): super(OdlPortStatusUpdate, self).start() LOG.debug('OdlPortStatusUpdate worker running') if odl_features.has(odl_features.OPERATIONAL_PORT_STATUS): self.run_websocket() def stop(self): if self.odl_websocket_client: self.odl_websocket_client.set_exit_flag() def wait(self): """Wait for service to complete.""" @staticmethod def reset(): pass def run_websocket(self): # OpenDaylight path to recieve websocket notifications on neutron_ports_path = "/neutron:neutron/neutron:ports" <|code_end|> , generate the next line using the imports in this file: import threading from neutron_lib.callbacks import resources from neutron_lib import constants as n_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib import worker from oslo_log import log from neutron.db import provisioning_blocks from networking_odl.common import client as odl_client from networking_odl.common import odl_features from networking_odl.common import utils from networking_odl.common import websocket_client as odl_ws_client and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): # # Path: networking_odl/common/websocket_client.py # LOG = log.getLogger(__name__) # ODL_OPERATIONAL_DATASTORE = "OPERATIONAL" # ODL_CONFIGURATION_DATASTORE = "CONFIGURATION" # ODL_NOTIFICATION_SCOPE_BASE = "BASE" # ODL_NOTIFICATION_SCOPE_ONE = "ONE" # ODL_NOTIFICATION_SCOPE_SUBTREE = "SUBTREE" # ODL_WEBSOCKET_DISCONNECTED = "ODL_WEBSOCKET_DISCONNECTED" # ODL_WEBSOCKET_CONNECTING = "ODL_WEBSOCKET_CONNECTING" # ODL_WEBSOCKET_CONNECTED = "ODL_WEBSOCKET_CONNECTED" # NOTIFICATION_TAG = 'notification' # DC_NOTIFICATION_TAG = 'data-changed-notification' # DC_EVENT_TAG = 'data-change-event' # OPERATION_DELETE = 'deleted' # OPERATION_CREATE = 'created' # OPERATION_UPDATE = 'updated' # class OpenDaylightWebsocketClient(object): # class EventDataParser(object): # def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, # packet_handler, timeout, status_cb=None): # def odl_create_websocket(cls, odl_url, path, datastore, scope, # packet_handler, status_cb=None, # leaf_node_only=False): # def start_odl_websocket_thread(self): # def set_exit_flag(self, value=True): # def run_websocket_thread(self, exit_after_run=False): # def _set_websocket_status(self, status): # def _subscribe_websocket(self): # def _socket_create_connection(self, stream_url): # def _connect_ws(self): # def _close_ws(self, ws): # def __init__(self, item): # def get_item(cls, payload): # def get_fields(self): # def get_path(self): # def get_data(self): # def get_operation(self): # def extract_field(text, key): . Output only the next line.
self.path_uri = utils.get_odl_url()
Predict the next line for this snippet: <|code_start|> PORT_PATH = "restconf/operational/neutron:neutron/ports/port" def __init__(self): super(OdlPortStatusUpdate, self).__init__() self.odl_websocket_client = None def start(self): super(OdlPortStatusUpdate, self).start() LOG.debug('OdlPortStatusUpdate worker running') if odl_features.has(odl_features.OPERATIONAL_PORT_STATUS): self.run_websocket() def stop(self): if self.odl_websocket_client: self.odl_websocket_client.set_exit_flag() def wait(self): """Wait for service to complete.""" @staticmethod def reset(): pass def run_websocket(self): # OpenDaylight path to recieve websocket notifications on neutron_ports_path = "/neutron:neutron/neutron:ports" self.path_uri = utils.get_odl_url() self.odl_websocket_client = ( <|code_end|> with the help of current file imports: import threading from neutron_lib.callbacks import resources from neutron_lib import constants as n_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib import worker from oslo_log import log from neutron.db import provisioning_blocks from networking_odl.common import client as odl_client from networking_odl.common import odl_features from networking_odl.common import utils from networking_odl.common import websocket_client as odl_ws_client and context from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): # # Path: networking_odl/common/websocket_client.py # LOG = log.getLogger(__name__) # ODL_OPERATIONAL_DATASTORE = "OPERATIONAL" # ODL_CONFIGURATION_DATASTORE = "CONFIGURATION" # ODL_NOTIFICATION_SCOPE_BASE = "BASE" # ODL_NOTIFICATION_SCOPE_ONE = "ONE" # ODL_NOTIFICATION_SCOPE_SUBTREE = "SUBTREE" # ODL_WEBSOCKET_DISCONNECTED = "ODL_WEBSOCKET_DISCONNECTED" # ODL_WEBSOCKET_CONNECTING = "ODL_WEBSOCKET_CONNECTING" # ODL_WEBSOCKET_CONNECTED = "ODL_WEBSOCKET_CONNECTED" # NOTIFICATION_TAG = 'notification' # DC_NOTIFICATION_TAG = 'data-changed-notification' # DC_EVENT_TAG = 'data-change-event' # OPERATION_DELETE = 'deleted' # OPERATION_CREATE = 'created' # OPERATION_UPDATE = 'updated' # class OpenDaylightWebsocketClient(object): # class EventDataParser(object): # def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, # packet_handler, timeout, status_cb=None): # def odl_create_websocket(cls, odl_url, path, datastore, scope, # packet_handler, status_cb=None, # leaf_node_only=False): # def start_odl_websocket_thread(self): # def set_exit_flag(self, value=True): # def run_websocket_thread(self, exit_after_run=False): # def _set_websocket_status(self, status): # def _subscribe_websocket(self): # def _socket_create_connection(self, stream_url): # def _connect_ws(self): # def _close_ws(self, ws): # def __init__(self, item): # def get_item(cls, payload): # def get_fields(self): # def get_path(self): # def get_data(self): # def get_operation(self): # def extract_field(text, key): , which may contain function names, class names, or code. Output only the next line.
odl_ws_client.OpenDaylightWebsocketClient.odl_create_websocket(
Next line prediction: <|code_start|># # Copyright (C) 2016 Red Hat, Inc. # # 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 _DriverTest(base.OdlTestsBase): def test_network_create(self): with self.network() as network: <|code_end|> . Use current file imports: (import functools from neutron.tests.unit.extensions import test_securitygroup from neutron.tests.unit.plugins.ml2 import test_plugin from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base) and context including class names, function names, or small code snippets from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
self.assert_resource_created(odl_const.ODL_NETWORK, network)
Predict the next line for this snippet: <|code_start|> ADMIN_ID = str(uuidutils.generate_uuid()) PORT_1_TENANT_ID = str(uuidutils.generate_uuid()) PORT_2_TENANT_ID = str(uuidutils.generate_uuid()) PORT_1_ID = str(uuidutils.generate_uuid()) PORT_2_ID = str(uuidutils.generate_uuid()) class _Base(base.BaseTestCase, metaclass=abc.ABCMeta): @abc.abstractmethod def switch_data(self): pass fake_odl_url = urllib.parse.ParseResult('opendaylight.v2', 'localhost:8080', 'controller/statistics', None, None, None) fake_params = urllib.parse.parse_qs( 'user=admin&password=admin&scheme=http&auth=basic') def setUp(self): super(_Base, self).setUp() self.addCleanup(mock.patch.stopall) conf = service.prepare_service([], []) <|code_end|> with the help of current file imports: import abc import urllib from unittest import mock from oslotest import base from ceilometer import service from networking_odl.ceilometer.network.statistics.opendaylight_v2 import driver from oslo_utils import uuidutils and context from other files: # Path: networking_odl/ceilometer/network/statistics/opendaylight_v2/driver.py # LOG = log.getLogger(__name__) # INT64_MAX_VALUE = (2 ** 64 / 2 - 1) # class OpenDaylightDriver(driver.Driver): # def _get_int_sample(key, statistic, resource_id, # resource_meta, tenant_id): # def _prepare_cache(self, endpoint, params, cache): # def get_sample_data(self, meter_name, parse_url, params, cache): # def _get_iter(self, meter_name): # def _get_extractor(self, meter_name): # def _iter_switch(extractor, data): # def _switch(statistic, resource_id, # resource_meta, tenant_id): # def _switch_ports(statistic, resource_id, # resource_meta, tenant_id): # def _iter_switch_port(extractor, data): # def _iter_port(extractor, data): # def _port(statistic, resource_id, resource_meta, tenant_id): # def _port_uptime(statistic, resource_id, # resource_meta, tenant_id): # def _port_receive_packets(statistic, resource_id, # resource_meta, tenant_id): # def _port_transmit_packets(statistic, resource_id, # resource_meta, tenant_id): # def _port_receive_bytes(statistic, resource_id, # resource_meta, tenant_id): # def _port_transmit_bytes(statistic, resource_id, # resource_meta, tenant_id): # def _port_receive_drops(statistic, resource_id, # resource_meta, tenant_id): # def _port_receive_errors(statistic, resource_id, # resource_meta, tenant_id): # def _iter_table(extractor, data): # def _switch_table_active_entries(statistic, resource_id, # resource_meta, tenant_id): , which may contain function names, class names, or code. Output only the next line.
self.driver = driver.OpenDaylightDriver(conf)
Predict the next line for 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. IdType = sa.BigInteger().with_variant(sa.Integer(), 'sqlite') journal_dependencies = sa.Table( 'opendaylight_journal_deps', model_base.BASEV2.metadata, sa.Column('depends_on', IdType, sa.ForeignKey('opendaylightjournal.seqnum', ondelete='CASCADE'), primary_key=True), sa.Column('dependent', IdType, sa.ForeignKey('opendaylightjournal.seqnum', ondelete='CASCADE'), primary_key=True)) class OpenDaylightJournal(model_base.BASEV2): __tablename__ = 'opendaylightjournal' seqnum = sa.Column(IdType, primary_key=True, autoincrement=True) object_type = sa.Column(sa.String(36), nullable=False) object_uuid = sa.Column(sa.String(36), nullable=False) operation = sa.Column(sa.String(36), nullable=False) data = sa.Column(sa.PickleType, nullable=True) <|code_end|> with the help of current file imports: import sqlalchemy as sa from neutron_lib.db import model_base from networking_odl.common import constants as odl_const and context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } , which may contain function names, class names, or code. Output only the next line.
state = sa.Column(sa.Enum(odl_const.PENDING, odl_const.PROCESSING,
Given snippet: <|code_start|> def _generate_log_entry(log_type=None, entry_id=None): entry = mock.Mock() entry.seqnum = entry_id if entry_id else _random_string() entry.operation = _random_string() entry.object_type = _random_string() entry.object_uuid = _random_string() logger = fixtures.FakeLogger() with logger: journal._log_entry(log_type if log_type else _random_string(), entry) return entry, "noise %s noise" % logger.output class TestAnalyzeJournal(base.DietTestCase): def setUp(self): super(TestAnalyzeJournal, self).setUp() self.output = io.StringIO() def _assert_nothing_printed(self): self.assertEqual('', self.output.getvalue()) def _assert_something_printed(self, expected=None): self.assertNotEqual('', self.output.getvalue()) if expected: self.assertIn(str(expected), self.output.getvalue()) def test_setup_conf_no_args(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import contextlib import io import random import string import fixtures from unittest import mock from networking_odl.cmd import analyze_journal from networking_odl.journal import journal from networking_odl.tests import base and context: # Path: networking_odl/cmd/analyze_journal.py # COMMAND_LINE_OPTIONS = [ # cfg.StrOpt('file', default=None, # help=_("Log file to analyze.")), # cfg.IntOpt('slowest', min=1, default=10, # help=_("Prints the N slowest entries (10 by default).")), # ] # KEY_MATCHER = re.compile(r'\%\((\S+)\)s') # LOG_KEYS = KEY_MATCHER.findall(journal.LOG_ENTRY_TEMPLATE) # KEY_TEMP_PATTERN = 'KEYPATTERN' # LOG_MATCHER = re.compile( # re.sub(KEY_TEMP_PATTERN, r'(\\S+)', re.escape( # KEY_MATCHER.sub(KEY_TEMP_PATTERN, journal.LOG_ENTRY_TEMPLATE)))) # ENTRY_LOG_TEMPLATE = ' * Entry id: %s, processing time: %.3fs; %s %s %s' # def setup_conf(output, args): # def parse_log(content): # def analyze_entries(entries): # def _percentile(timings, percent): # def print_stats(output, slowest, entries_stats): # def get_content(file_name): # def main(output=sys.stdout): # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): which might include code, classes, or functions. Output only the next line.
conf = analyze_journal.setup_conf(self.output, [])
Continue 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 _random_string(): letters = string.ascii_lowercase return ''.join(random.choice(letters) for _ in range(random.randint(1, 10))) def _generate_log_entry(log_type=None, entry_id=None): entry = mock.Mock() entry.seqnum = entry_id if entry_id else _random_string() entry.operation = _random_string() entry.object_type = _random_string() entry.object_uuid = _random_string() logger = fixtures.FakeLogger() with logger: <|code_end|> . Use current file imports: import contextlib import io import random import string import fixtures from unittest import mock from networking_odl.cmd import analyze_journal from networking_odl.journal import journal from networking_odl.tests import base and context (classes, functions, or code) from other files: # Path: networking_odl/cmd/analyze_journal.py # COMMAND_LINE_OPTIONS = [ # cfg.StrOpt('file', default=None, # help=_("Log file to analyze.")), # cfg.IntOpt('slowest', min=1, default=10, # help=_("Prints the N slowest entries (10 by default).")), # ] # KEY_MATCHER = re.compile(r'\%\((\S+)\)s') # LOG_KEYS = KEY_MATCHER.findall(journal.LOG_ENTRY_TEMPLATE) # KEY_TEMP_PATTERN = 'KEYPATTERN' # LOG_MATCHER = re.compile( # re.sub(KEY_TEMP_PATTERN, r'(\\S+)', re.escape( # KEY_MATCHER.sub(KEY_TEMP_PATTERN, journal.LOG_ENTRY_TEMPLATE)))) # ENTRY_LOG_TEMPLATE = ' * Entry id: %s, processing time: %.3fs; %s %s %s' # def setup_conf(output, args): # def parse_log(content): # def analyze_entries(entries): # def _percentile(timings, percent): # def print_stats(output, slowest, entries_stats): # def get_content(file_name): # def main(output=sys.stdout): # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): . Output only the next line.
journal._log_entry(log_type if log_type else _random_string(), entry)
Using the 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 _random_string(): letters = string.ascii_lowercase return ''.join(random.choice(letters) for _ in range(random.randint(1, 10))) def _generate_log_entry(log_type=None, entry_id=None): entry = mock.Mock() entry.seqnum = entry_id if entry_id else _random_string() entry.operation = _random_string() entry.object_type = _random_string() entry.object_uuid = _random_string() logger = fixtures.FakeLogger() with logger: journal._log_entry(log_type if log_type else _random_string(), entry) return entry, "noise %s noise" % logger.output <|code_end|> , determine the next line of code. You have imports: import contextlib import io import random import string import fixtures from unittest import mock from networking_odl.cmd import analyze_journal from networking_odl.journal import journal from networking_odl.tests import base and context (class names, function names, or code) available: # Path: networking_odl/cmd/analyze_journal.py # COMMAND_LINE_OPTIONS = [ # cfg.StrOpt('file', default=None, # help=_("Log file to analyze.")), # cfg.IntOpt('slowest', min=1, default=10, # help=_("Prints the N slowest entries (10 by default).")), # ] # KEY_MATCHER = re.compile(r'\%\((\S+)\)s') # LOG_KEYS = KEY_MATCHER.findall(journal.LOG_ENTRY_TEMPLATE) # KEY_TEMP_PATTERN = 'KEYPATTERN' # LOG_MATCHER = re.compile( # re.sub(KEY_TEMP_PATTERN, r'(\\S+)', re.escape( # KEY_MATCHER.sub(KEY_TEMP_PATTERN, journal.LOG_ENTRY_TEMPLATE)))) # ENTRY_LOG_TEMPLATE = ' * Entry id: %s, processing time: %.3fs; %s %s %s' # def setup_conf(output, args): # def parse_log(content): # def analyze_entries(entries): # def _percentile(timings, percent): # def print_stats(output, slowest, entries_stats): # def get_content(file_name): # def main(output=sys.stdout): # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): . Output only the next line.
class TestAnalyzeJournal(base.DietTestCase):
Continue the code snippet: <|code_start|> class _TestBGPVPNBase(base.OdlTestsBase): rds = ['100:1'] def setUp(self, plugin=None, service_plugins=None, ext_mgr=None): provider = { 'service_type': 'BGPVPN', 'name': 'OpenDaylight', 'driver': 'networking_odl.bgpvpn.odl_v2.OpenDaylightBgpvpnDriver', 'default': True } self.service_providers.return_value = [provider] self.plugin_arg = plugin self.service_plugin_arg = service_plugins self.ext_mgr_arg = ext_mgr super(_TestBGPVPNBase, self).setUp() def get_ext_managers(self): return self.ext_mgr_arg def get_plugins(self): return self.plugin_arg def get_additional_service_plugins(self): return self.service_plugin_arg def _assert_networks_associated(self, net_ids, bgpvpn): <|code_end|> . Use current file imports: import webob.exc from neutron.tests.unit.plugins.ml2 import test_plugin from neutron.tests.unit import testlib_api from networking_bgpvpn.neutron.db import bgpvpn_db # noqa from networking_bgpvpn.tests.unit.services import test_plugin as bgpvpn_plugin from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base and context (classes, functions, or code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
response = self.get_odl_resource(odl_const.ODL_BGPVPN, bgpvpn)
Using the 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. RETRIABLE_EXCEPTIONS = (db_exc.DBDeadlock, exc.StaleDataError, db_exc.DBConnectionError, db_exc.DBDuplicateEntry, db_exc.RetryRequest) RETRY_INTERVAL = 0.001 RETRY_MAX = 2 class _InnerException(Exception): pass class ODLBaseDbTestCase(SqlTestCaseLight): <|code_end|> , determine the next line of code. You have imports: import logging import sqlalchemy from unittest import mock from pecan import util as p_util from neutron.tests.unit.testlib_api import SqlTestCaseLight from neutron_lib import context as neutron_context from neutron_lib.db import api as db_api from neutron_lib import fixture as lib_fixtures from oslo_config import fixture as config_fixture from oslo_db import exception as db_exc from sqlalchemy.orm import exc from networking_odl.common import constants from networking_odl.db import models and context (class names, function names, or code) available: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/db/models.py # class OpenDaylightJournal(model_base.BASEV2): # class OpenDaylightPeriodicTask(model_base.BASEV2): . Output only the next line.
UPDATE_ROW = [constants.ODL_NETWORK, 'id', constants.ODL_UPDATE,
Given the following code snippet before the placeholder: <|code_start|> UPDATE_ROW = [constants.ODL_NETWORK, 'id', constants.ODL_UPDATE, {'test': 'data'}] def setUp(self): super(ODLBaseDbTestCase, self).setUp() self.db_context = neutron_context.get_admin_context() self.cfg = self.useFixture(config_fixture.Config()) self.cfg.config(completed_rows_retention=-1, group='ml2_odl') self._setup_retry_tracker_table() def _setup_retry_tracker_table(self): metadata = sqlalchemy.MetaData() self.retry_table = sqlalchemy.Table( 'retry_tracker', metadata, sqlalchemy.Column( 'id', sqlalchemy.Integer, autoincrement=True, primary_key=True, ), ) metadata.create_all(self.engine) self.addCleanup(metadata.drop_all, self.engine) class RetryTracker(object): pass sqlalchemy.orm.mapper(RetryTracker, self.retry_table) self.retry_tracker = RetryTracker def _db_cleanup(self): <|code_end|> , predict the next line using imports from the current file: import logging import sqlalchemy from unittest import mock from pecan import util as p_util from neutron.tests.unit.testlib_api import SqlTestCaseLight from neutron_lib import context as neutron_context from neutron_lib.db import api as db_api from neutron_lib import fixture as lib_fixtures from oslo_config import fixture as config_fixture from oslo_db import exception as db_exc from sqlalchemy.orm import exc from networking_odl.common import constants from networking_odl.db import models and context including class names, function names, and sometimes code from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/db/models.py # class OpenDaylightJournal(model_base.BASEV2): # class OpenDaylightPeriodicTask(model_base.BASEV2): . Output only the next line.
self.db_context.session.query(models.OpenDaylightJournal).delete()
Given the code snippet: <|code_start|> LOG = logging.getLogger(__name__) class PeriodicTask(object): def __init__(self, task, interval): self.task = task self.phases = [] self.timer = loopingcall.FixedIntervalLoopingCall(self.execute_ops) self.interval = interval def start(self): self.timer.start(self.interval, stop_on_exception=False) def cleanup(self): # this method is used for unit test to tear down self.timer.stop() try: self.timer.wait() except AttributeError: # NOTE(yamahata): workaround # some tests call this cleanup without calling start pass @db_api.retry_if_session_inactive() @db_api.CONTEXT_WRITER.savepoint def _set_operation(self, context, operation): <|code_end|> , generate the next line using the imports in this file: from neutron_lib import context as neutron_context from neutron_lib.db import api as db_api from oslo_log import log as logging from oslo_service import loopingcall from networking_odl.db import db and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/db/db.py # LOG = logging.getLogger(__name__) # def get_pending_or_processing_ops(context, object_uuid, operation=None): # def get_pending_delete_ops_with_parent(context, object_type, parent_id): # def get_all_db_rows(context): # def get_all_db_rows_by_state(context, state): # def get_oldest_pending_db_row_with_lock(context): # def delete_dependency(context, entry): # def update_db_row_state(context, row, state, flush=True): # def update_pending_db_row_retry(context, row, retry_count): # def delete_row(context, row=None, row_id=None, flush=True): # def create_pending_row(context, object_type, object_uuid, # operation, data, depending_on=None): # def delete_pending_rows(context, operations_to_delete): # def _update_periodic_task_state(context, expected_state, state, task): # def was_periodic_task_executed_recently(context, task, interval): # def lock_periodic_task(context, task): # def unlock_periodic_task(context, task): # def update_periodic_task(context, task, operation=None): # def delete_rows_by_state_and_time(context, state, time_delta): # def reset_processing_rows(context, max_timedelta): . Output only the next line.
db.update_periodic_task(context, task=self.task,
Given snippet: <|code_start|># Copyright (c) 2016 OpenStack Foundation # 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. class TestPortBindingManager(base.DietTestCase): def test_create(self): mgr = port_binding.PortBindingManager.create( name="legacy-port-binding") self.assertEqual("legacy-port-binding", mgr.name) self.assertIsInstance(mgr.controller, <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import mock from networking_odl.ml2 import legacy_port_binding from networking_odl.ml2 import port_binding from networking_odl.tests import base and context: # Path: networking_odl/ml2/legacy_port_binding.py # LOG = log.getLogger(__name__) # class LegacyPortBindingManager(port_binding.PortBindingController): # def __init__(self): # def bind_port(self, port_context): # def _check_segment(self, segment): # def _get_vif_type(self, port_context): # # Path: networking_odl/ml2/port_binding.py # LOG = log.getLogger(__name__) # class PortBindingController(object, metaclass=abc.ABCMeta): # class PortBindingManager(PortBindingController): # def get_workers(self): # def bind_port(self, port_context): # def __init__(self, name, controller): # def create( # cls, namespace='networking_odl.ml2.port_binding_controllers', # name=None): # def get_workers(self): # def bind_port(self, port_context): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): which might include code, classes, or functions. Output only the next line.
legacy_port_binding.LegacyPortBindingManager)
Here is a snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class LightweightTestingTestCase(base.DietTestCase): def setUp(self): self.useFixture(odl_base.OpenDaylightRestClientFixture()) self.cfg = self.useFixture(config_fixture.Config()) super(LightweightTestingTestCase, self).setUp() def test_create_client_with_lwt_enabled(self): """Have to do the importation here, otherwise there will be a loop""" self.cfg.config(enable_lightweight_testing=True, group='ml2_odl') # DietTestCase does not automatically cleans configuration overrides self.addCleanup(odl_client.cfg.CONF.reset) client = odl_client.OpenDaylightRestClient.create_client() <|code_end|> . Write the next line using the current file imports: from unittest import mock from neutron.tests import base from oslo_config import fixture as config_fixture from networking_odl.common import lightweight_testing as lwt from networking_odl.tests import base as odl_base from networking_odl.common import client as odl_client from networking_odl.common import client as odl_client and context from other files: # Path: networking_odl/common/lightweight_testing.py # LOG = logging.getLogger(__name__) # OK = requests.codes.ok # NO_CONTENT = requests.codes.no_content # NOT_ALLOWED = requests.codes.not_allowed # NOT_FOUND = requests.codes.not_found # BAD_REQUEST = requests.codes.bad_request # class OpenDaylightLwtClient(client.OpenDaylightRestClient): # def _make_response(cls, status_code=OK, content=None): # def _get_resource_id(cls, urlpath): # def post(cls, resource_type, resource_dict, urlpath, resource_list): # def put(cls, resource_type, resource_dict, urlpath, resource_list): # def delete(cls, resource_type, resource_dict, urlpath, resource_list): # def get(cls, resource_type, resource_dict, urlpath, resource_list=None): # def sendjson(self, method, urlpath, obj=None): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): , which may include functions, classes, or code. Output only the next line.
self.assertIsInstance(client, lwt.OpenDaylightLwtClient)
Given snippet: <|code_start|># Copyright (c) 2017 OpenStack Foundation # 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. class TestOdlDhcpDriver(base.V2DriverAdjustment, base.OdlTestsBase, test_plugin.Ml2PluginV2TestCase): _mechanism_drivers = ['opendaylight_v2'] def setUp(self): self.cfg = self.useFixture(config_fixture.Config()) self.cfg.config(enable_dhcp_service=True, group='ml2_odl') super(TestOdlDhcpDriver, self).setUp() def get_port_data(self, network, subnet): plugin = self.get_plugin() <|code_end|> , continue by predicting the next line. Consider current file imports: from neutron.tests.unit.plugins.ml2 import test_plugin from neutron_lib import constants as n_const from neutron_lib.plugins import directory from oslo_config import fixture as config_fixture from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base and context: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): which might include code, classes, or functions. Output only the next line.
device_id = odl_const.ODL_DEVICE_ID_START + \
Based on 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 ClientTestCase(base.DietTestCase): def setUp(self): self.cfg = self.useFixture(config_fixture.Config()) self.cfg.config(mechanism_drivers=[ 'logger', 'opendaylight_v2'], group='ml2') super(ClientTestCase, self).setUp() def _set_config(self, url='http://127.0.0.1:9999', username='someuser', password='somepass'): self.cfg.config(url=url, group='ml2_odl') self.cfg.config(username=username, group='ml2_odl') self.cfg.config(password=password, group='ml2_odl') def _test_missing_config(self, **kwargs): self._set_config(**kwargs) self.assertRaisesRegex(cfg.RequiredOptError, r'value required for option \w+ in group ' r'\[ml2_odl\]', <|code_end|> , predict the immediate next line with the help of imports: from oslo_config import cfg from oslo_config import fixture as config_fixture from networking_odl.common import client from neutron.tests import base and context (classes, functions, sometimes code) from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): . Output only the next line.
client.OpenDaylightRestClient._check_opt,
Given the code snippet: <|code_start|> class OpenDaylightLwtClient(client.OpenDaylightRestClient): """Lightweight testing client""" lwt_dict = {odl_const.ODL_NETWORKS: {}, odl_const.ODL_SUBNETS: {}, odl_const.ODL_PORTS: {}, odl_const.ODL_SGS: {}, odl_const.ODL_SG_RULES: {}} @classmethod def _make_response(cls, status_code=OK, content=None): """Only supports 'content-type': 'application/json'""" response = requests.models.Response() response.status_code = status_code if content: response.raw = io.BytesIO(jsonutils.dumps(content).encode('utf-8')) return response @classmethod def _get_resource_id(cls, urlpath): # resource ID is the last element of urlpath return str(urlpath).rsplit('/', 1)[-1] @classmethod def post(cls, resource_type, resource_dict, urlpath, resource_list): """No ID in URL, elements in resource_list must have ID""" if resource_list is None: <|code_end|> , generate the next line using the imports in this file: from copy import deepcopy from oslo_log import log as logging from oslo_serialization import jsonutils from networking_odl._i18n import _ from networking_odl.common import client from networking_odl.common import constants as odl_const import io import requests and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } . Output only the next line.
raise ValueError(_("resource_list can not be None"))
Based on the snippet: <|code_start|># Copyright (c) 2015 Intel Inc. # 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. LOG = logging.getLogger(__name__) OK = requests.codes.ok NO_CONTENT = requests.codes.no_content NOT_ALLOWED = requests.codes.not_allowed NOT_FOUND = requests.codes.not_found BAD_REQUEST = requests.codes.bad_request <|code_end|> , predict the immediate next line with the help of imports: from copy import deepcopy from oslo_log import log as logging from oslo_serialization import jsonutils from networking_odl._i18n import _ from networking_odl.common import client from networking_odl.common import constants as odl_const import io import requests and context (classes, functions, sometimes code) from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } . Output only the next line.
class OpenDaylightLwtClient(client.OpenDaylightRestClient):
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. LOG = logging.getLogger(__name__) OK = requests.codes.ok NO_CONTENT = requests.codes.no_content NOT_ALLOWED = requests.codes.not_allowed NOT_FOUND = requests.codes.not_found BAD_REQUEST = requests.codes.bad_request class OpenDaylightLwtClient(client.OpenDaylightRestClient): """Lightweight testing client""" <|code_end|> with the help of current file imports: from copy import deepcopy from oslo_log import log as logging from oslo_serialization import jsonutils from networking_odl._i18n import _ from networking_odl.common import client from networking_odl.common import constants as odl_const import io import requests and context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } , which may contain function names, class names, or code. Output only the next line.
lwt_dict = {odl_const.ODL_NETWORKS: {},
Here is a snippet: <|code_start|> super(JournalPeriodicProcessor, self).__init__() self._journal = journal.OpenDaylightJournalThread(start_thread=False) self._interval = cfg.CONF.ml2_odl.sync_timeout self._timer = None self._maintenance_task = None self._running = None self.pidfile = None def _create_pidfile(self): pidfile = os.path.join(cfg.CONF.state_path, type(self).__name__.lower() + '.pid') self.pidfile = daemon.Pidfile(pidfile, 'python') # NOTE(mpeterson): We want self._running to be None before the first # run so atexit is only registered once and not several times. if self._running is None: atexit.unregister(self._delete_pidfile) atexit.register(self._delete_pidfile) self.pidfile.write(os.getpid()) def _delete_pidfile(self): if self.pidfile is not None: self.pidfile.unlock() os.remove(str(self.pidfile)) self.pidfile = None def start(self): if self._running: raise RuntimeError( <|code_end|> . Write the next line using the current file imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): , which may include functions, classes, or code. Output only the next line.
_("Thread has to be stopped before started again")
Predict the next line after this snippet: <|code_start|> self.pidfile.write(os.getpid()) def _delete_pidfile(self): if self.pidfile is not None: self.pidfile.unlock() os.remove(str(self.pidfile)) self.pidfile = None def start(self): if self._running: raise RuntimeError( _("Thread has to be stopped before started again") ) super(JournalPeriodicProcessor, self).start() LOG.debug('JournalPeriodicProcessor starting') self._journal.start() self._timer = loopingcall.FixedIntervalLoopingCall(self._call_journal) self._timer.start(self._interval) self._start_maintenance_task() self._create_pidfile() self._running = True def stop(self): if not self._running: return LOG.debug('JournalPeriodicProcessor stopping') self._journal.stop() self._timer.stop() <|code_end|> using the current file's imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and any relevant context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): . Output only the next line.
self._maintenance_task.cleanup()
Predict the next line after this snippet: <|code_start|> def stop(self): if not self._running: return LOG.debug('JournalPeriodicProcessor stopping') self._journal.stop() self._timer.stop() self._maintenance_task.cleanup() self._delete_pidfile() super(JournalPeriodicProcessor, self).stop() self._running = False def wait(self): pass def reset(self): if self._maintenance_task is not None: self._maintenance_task.execute_ops(forced=True) def _call_journal(self): self._journal.set_sync_event() def _start_maintenance_task(self): self._maintenance_task = periodic_task.PeriodicTask( 'maintenance', cfg.CONF.ml2_odl.maintenance_interval) for phase in ( cleanup.delete_completed_rows, cleanup.cleanup_processing_rows, <|code_end|> using the current file's imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and any relevant context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): . Output only the next line.
full_sync.full_sync,
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. # TODO(mpeterson): this should go back to the previous block once the problems # with flake8-import-order are fixed. LOG = logging.getLogger(__name__) class JournalPeriodicProcessor(worker.BaseWorker): """Responsible for running the periodic processing of the journal. This is a separate worker as the regular journal thread is called when an operation finishes and that run will take care of any and all entries that might be present in the journal, including the one relating to that operation. A periodic run over the journal is thus necessary for cases when journal entries in the aforementioned run didn't process correctly due to some error (usually a connection problem) and need to be retried. """ def __init__(self): super(JournalPeriodicProcessor, self).__init__() <|code_end|> . Write the next line using the current file imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): , which may include functions, classes, or code. Output only the next line.
self._journal = journal.OpenDaylightJournalThread(start_thread=False)
Predict the next line for this snippet: <|code_start|> self._journal.start() self._timer = loopingcall.FixedIntervalLoopingCall(self._call_journal) self._timer.start(self._interval) self._start_maintenance_task() self._create_pidfile() self._running = True def stop(self): if not self._running: return LOG.debug('JournalPeriodicProcessor stopping') self._journal.stop() self._timer.stop() self._maintenance_task.cleanup() self._delete_pidfile() super(JournalPeriodicProcessor, self).stop() self._running = False def wait(self): pass def reset(self): if self._maintenance_task is not None: self._maintenance_task.execute_ops(forced=True) def _call_journal(self): self._journal.set_sync_event() def _start_maintenance_task(self): <|code_end|> with the help of current file imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): , which may contain function names, class names, or code. Output only the next line.
self._maintenance_task = periodic_task.PeriodicTask(
Given snippet: <|code_start|> def stop(self): if not self._running: return LOG.debug('JournalPeriodicProcessor stopping') self._journal.stop() self._timer.stop() self._maintenance_task.cleanup() self._delete_pidfile() super(JournalPeriodicProcessor, self).stop() self._running = False def wait(self): pass def reset(self): if self._maintenance_task is not None: self._maintenance_task.execute_ops(forced=True) def _call_journal(self): self._journal.set_sync_event() def _start_maintenance_task(self): self._maintenance_task = periodic_task.PeriodicTask( 'maintenance', cfg.CONF.ml2_odl.maintenance_interval) for phase in ( cleanup.delete_completed_rows, cleanup.cleanup_processing_rows, full_sync.full_sync, <|code_end|> , continue by predicting the next line. Consider current file imports: import atexit import os from neutron_lib import worker from oslo_config import cfg from oslo_log import log as logging from oslo_service import loopingcall from neutron.agent.linux import daemon from networking_odl._i18n import _ from networking_odl.journal import cleanup from networking_odl.journal import full_sync from networking_odl.journal import journal from networking_odl.journal import periodic_task from networking_odl.journal import recovery and context: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/journal/full_sync.py # @db_api.retry_if_session_inactive() # @db_api.CONTEXT_WRITER.savepoint # def full_sync(context): # if not _full_sync_needed(context): # return # # db.delete_pending_rows(context, _OPS_TO_DELETE_ON_SYNC) # # for resource_type in _ORDERED_ODL_RESOURCES: # handler = FULL_SYNC_RESOURCES.get(resource_type) # if handler: # _sync_resources(context, resource_type, handler) # # journal.record(context, odl_const.ODL_NETWORK, _CANARY_NETWORK_ID, # odl_const.ODL_CREATE, _CANARY_NETWORK_DATA) # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/journal/recovery.py # _CLIENT = client.OpenDaylightRestClientGlobal() # LOG = logging.getLogger(__name__) # def journal_recovery(context): # def get_latest_resource(context, row): # def _get_latest_resource(context, row): # def _sync_resource_to_odl(context, row, operation_type, exists_on_odl): # def _handle_existing_resource(context, row): # def _handle_non_existing_resource(context, row): which might include code, classes, or functions. Output only the next line.
recovery.journal_recovery,
Given the code 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. # class QoSTestExtensionManager(object): def get_resources(self): return qos_ext.Qos.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class _QoSDriverTestCase(base.OdlTestsBase): def test_policy_create(self): with self.qos_policy() as policy: self.assert_resource_created( <|code_end|> , generate the next line using the imports in this file: import contextlib from oslo_utils import uuidutils from neutron.extensions import qos as qos_ext from neutron.services.qos import qos_plugin from neutron.tests.unit.api import test_extensions from neutron.tests.unit.plugins.ml2 import test_plugin from neutron_lib import fixture as nlib_fixture from neutron_lib.plugins import directory from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
odl_const.ODL_QOS_POLICY, policy)
Predict the next line after 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. # class QoSTestExtensionManager(object): def get_resources(self): return qos_ext.Qos.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] <|code_end|> using the current file's imports: import contextlib from oslo_utils import uuidutils from neutron.extensions import qos as qos_ext from neutron.services.qos import qos_plugin from neutron.tests.unit.api import test_extensions from neutron.tests.unit.plugins.ml2 import test_plugin from neutron_lib import fixture as nlib_fixture from neutron_lib.plugins import directory from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base and any relevant context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
class _QoSDriverTestCase(base.OdlTestsBase):
Here is a snippet: <|code_start|># Copyright (c) 2017 OpenStack Foundation # 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. class BaseTest(object): def create_resource1_postcommit(self): pass update_resource1_postcommit = create_resource1_postcommit delete_resource1_postcommit = create_resource1_postcommit update_resource2_postcommit = create_resource1_postcommit delete_resource2_postcommit = create_resource1_postcommit create_resource2_postcommit = create_resource1_postcommit class TestPostCommit(base.DietTestCase): def _get_class(self, *args): <|code_end|> . Write the next line using the current file imports: from networking_odl.common import postcommit from neutron.tests import base and context from other files: # Path: networking_odl/common/postcommit.py # def postcommit(cls): # _build_methods(cls, *args) # return cls , which may include functions, classes, or code. Output only the next line.
@postcommit.add_postcommit(*args)
Predict the next line after this snippet: <|code_start|> } """ admin_project_id = None @staticmethod def _get_int_sample(key, statistic, resource_id, resource_meta, tenant_id): if key not in statistic: return None value = int(statistic[key]) if not (0 <= value <= INT64_MAX_VALUE): value = 0 return value, resource_id, resource_meta, tenant_id def _prepare_cache(self, endpoint, params, cache): if 'network.statistics.opendaylight_v2' in cache: return cache['network.statistics.opendaylight_v2'] data = {} odl_params = {} if 'auth' in params: odl_params['auth'] = params['auth'][0] if 'user' in params: odl_params['user'] = params['user'][0] if 'password' in params: odl_params['password'] = params['password'][0] <|code_end|> using the current file's imports: import urllib from debtcollector import removals from oslo_log import log from ceilometer import keystone_client from ceilometer.network.statistics import driver from networking_odl.ceilometer.network.statistics.opendaylight_v2 import client and any relevant context from other files: # Path: networking_odl/ceilometer/network/statistics/opendaylight_v2/client.py # LOG = log.getLogger(__name__) # class _Base(object, metaclass=abc.ABCMeta): # class OpenDaylightRESTAPIFailed(Exception): # class SwitchStatisticsAPIClient(_Base): # class Client(object): # def base_url(self): # def __init__(self, client): # def get_statistics(self): # def __init__(self, conf, endpoint, params): # def _get_req_params(self, params): # def _log_req(self, url): # def _log_res(resp): # def _http_request(self, url): # def request(self, path): . Output only the next line.
cs = client.Client(self.conf, endpoint, odl_params)
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. class TestUtils(base.DietTestCase): def setUp(self): self.cfg = self.useFixture(config_fixture.Config()) super(TestUtils, self).setUp() # TODO(manjeets) remove this test once neutronify is # consolidated with make_plural def test_neutronify(self): self.assertEqual('a-b-c', utils.neutronify('a_b_c')) def test_neutronify_empty(self): self.assertEqual('', utils.neutronify('')) @staticmethod def _get_resources(): <|code_end|> , generate the next line using the imports in this file: from neutron.tests import base from oslo_config import fixture as config_fixture from networking_odl.common import constants as odl_const from networking_odl.common import utils and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): . Output only the next line.
return {odl_const.ODL_SG: 'security-groups',
Using the snippet: <|code_start|># Copyright (c) 2015 OpenStack Foundation # 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. class TestUtils(base.DietTestCase): def setUp(self): self.cfg = self.useFixture(config_fixture.Config()) super(TestUtils, self).setUp() # TODO(manjeets) remove this test once neutronify is # consolidated with make_plural def test_neutronify(self): <|code_end|> , determine the next line of code. You have imports: from neutron.tests import base from oslo_config import fixture as config_fixture from networking_odl.common import constants as odl_const from networking_odl.common import utils and context (class names, function names, or code) available: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): . Output only the next line.
self.assertEqual('a-b-c', utils.neutronify('a_b_c'))
Predict the next line for this snippet: <|code_start|># 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. # """Add journal maintenance table Revision ID: 703dbf02afde Revises: 37e242787ae5 Create Date: 2016-04-12 10:49:31.802663 """ # revision identifiers, used by Alembic. revision = '703dbf02afde' down_revision = '37e242787ae5' def upgrade(): maint_table = op.create_table( 'opendaylight_maintenance', sa.Column('id', sa.String(36), primary_key=True), <|code_end|> with the help of current file imports: from alembic import op from oslo_utils import uuidutils from networking_odl.common import constants as odl_const import sqlalchemy as sa and context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } , which may contain function names, class names, or code. Output only the next line.
sa.Column('state', sa.Enum(odl_const.PENDING, odl_const.PROCESSING,
Given snippet: <|code_start|> }' To make sure to use system data path (Kernel) python set_ovs_hostconfigs.py --noovs_dpdk To make sure to use user space data path (vhostuser) python set_ovs_hostconfigs.py --ovs_dpdk To give bridge mappings python --bridge_mapping=physnet1:br-ex,physnet2:br-eth0 """ LOG = logging.getLogger(__name__) USERSPACE_DATAPATH_TYPES = ['netdev', 'dpdkvhostuser'] COMMAND_LINE_OPTIONS = [ cfg.ListOpt( 'allowed_network_types', default=['local', 'flat', 'vlan', 'vxlan', 'gre'], <|code_end|> , continue by predicting the next line. Consider current file imports: import os import socket import subprocess # nosec import sys from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from networking_odl._i18n import _ and context: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): which might include code, classes, or functions. Output only the next line.
help=_("""
Given the following code snippet before the placeholder: <|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. # """create opendaylight_preiodic_task table Revision ID: 6f7dfb241354 Revises: 0472f56ff2fb Create Date: 2017-05-24 03:01:00.755796 """ # revision identifiers, used by Alembic. revision = '6f7dfb241354' down_revision = '0472f56ff2fb' def upgrade(): periodic_table = op.create_table( 'opendaylight_periodic_task', <|code_end|> , predict the next line using imports from the current file: from alembic import op from networking_odl.common import constants as odl_const import sqlalchemy as sa and context including class names, function names, and sometimes code from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } . Output only the next line.
sa.Column('state', sa.Enum(odl_const.PENDING, odl_const.PROCESSING,
Using the snippet: <|code_start|># Copyright (c) 2017 OpenStack Foundation # 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. LOG = logging.getLogger(__name__) @registry.has_registry_receivers class OdlDhcpDriver(driver_base.OdlDhcpDriverBase): <|code_end|> , determine the next line of code. You have imports: from neutron_lib.callbacks import registry from neutron_lib import constants as n_const from neutron_lib.plugins import directory from oslo_log import log as logging from neutron.plugins.ml2 import driver_context from networking_odl.common import constants from networking_odl.dhcp import odl_dhcp_driver_base as driver_base and context (class names, function names, or code) available: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/dhcp/odl_dhcp_driver_base.py # LOG = logging.getLogger(__name__) # class OdlDhcpDriverBase(object): # def create_or_delete_dhcp_port(self, subnet_context): # def _delete_port(self, plugin, context, port_id): # def _make_dhcp_port_dict(self, subnet_context): # def get_dhcp_port_if_exists(self, subnet_context): . Output only the next line.
@registry.receives(constants.ODL_SUBNET, [constants.BEFORE_COMPLETE])
Continue the code snippet: <|code_start|>BGPVPN_TABLES = ( 'bgpvpns', 'bgpvpn_network_associations', 'bgpvpn_router_associations', 'ml2_route_target_allocations', 'sfc_bagpipe_ppg_rtnn_associations', 'sfc_bagpipe_chain_hops', ) # Tables from other repos that we depend on but do not manage. IGNORED_TABLES_MATCH = set( FWAAS_TABLES + L2GW_TABLES + BGPVPN_TABLES ) # EXTERNAL_TABLES should contain all names of tables that are not related to # current repo. EXTERNAL_TABLES = set(external.TABLES) VERSION_TABLE = 'odl_alembic_version' class _TestModelsMigrationsODL(test_migrations._TestModelsMigrations): def db_sync(self, engine): self.cfg.config(connection=engine.url, group='database') for conf in migration.get_alembic_configs(): self.alembic_config = conf self.alembic_config.neutron_config = cfg.CONF migration.do_alembic_command(conf, 'upgrade', 'heads') def get_metadata(self): <|code_end|> . Use current file imports: from oslo_config import cfg from sqlalchemy import sql from sqlalchemy.sql import schema from neutron.db.migration.alembic_migrations import external from neutron.db.migration import cli as migration from neutron.tests.functional.db import test_migrations from neutron.tests.unit import testlib_api from networking_odl.db import head and context (classes, functions, or code) from other files: # Path: networking_odl/db/head.py # def get_metadata(): . Output only the next line.
return head.get_metadata()
Based on the 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. # class _TestL3Base(test_l3.L3NatTestCaseMixin, base.OdlTestsBase): # Override default behavior so that extension manager is used, otherwise # we can't test security groups. def setup_parent(self): """Perform parent setup with the common plugin configuration class.""" ext_mgr = test_l3.L3TestExtensionManager() # Ensure that the parent setup can be called without arguments # by the common configuration setUp. parent_setup = functools.partial( super(test_plugin.Ml2PluginV2TestCase, self).setUp, plugin=test_plugin.PLUGIN_NAME, ext_mgr=ext_mgr, service_plugins={'l3_plugin_name': self.l3_plugin}, ) self.useFixture(test_plugin.Ml2ConfFixture(parent_setup)) def test_router_create(self): with self.router() as router: <|code_end|> , predict the immediate next line with the help of imports: import functools from neutron.tests.unit.extensions import test_l3 from neutron.tests.unit.plugins.ml2 import test_plugin from neutron_lib import constants as q_const from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base and context (classes, functions, sometimes code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
self.assert_resource_created(odl_const.ODL_ROUTER, router)
Predict the next line after this snippet: <|code_start|># Copyright (c) 2015 OpenStack Foundation # 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. LOG = logging.getLogger(__name__) bakery = baked.bakery() def get_pending_or_processing_ops(context, object_uuid, operation=None): # NOTE (sai): For performance reasons, we expect this method to use baked # query (http://docs.sqlalchemy.org/en/latest/orm/extensions/baked.html) baked_query = bakery(lambda s: s.query( models.OpenDaylightJournal)) baked_query += lambda q: q.filter( <|code_end|> using the current file's imports: import datetime from neutron_lib.db import api as db_api from oslo_log import log as logging from sqlalchemy import asc from sqlalchemy import bindparam from sqlalchemy.ext import baked from sqlalchemy import func from sqlalchemy import or_ from sqlalchemy.orm import aliased from networking_odl.common import constants as odl_const from networking_odl.db import models and any relevant context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/db/models.py # class OpenDaylightJournal(model_base.BASEV2): # class OpenDaylightPeriodicTask(model_base.BASEV2): . Output only the next line.
or_(models.OpenDaylightJournal.state == odl_const.PENDING,
Given the code snippet: <|code_start|># Copyright (c) 2015 OpenStack Foundation # 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. LOG = logging.getLogger(__name__) bakery = baked.bakery() def get_pending_or_processing_ops(context, object_uuid, operation=None): # NOTE (sai): For performance reasons, we expect this method to use baked # query (http://docs.sqlalchemy.org/en/latest/orm/extensions/baked.html) baked_query = bakery(lambda s: s.query( <|code_end|> , generate the next line using the imports in this file: import datetime from neutron_lib.db import api as db_api from oslo_log import log as logging from sqlalchemy import asc from sqlalchemy import bindparam from sqlalchemy.ext import baked from sqlalchemy import func from sqlalchemy import or_ from sqlalchemy.orm import aliased from networking_odl.common import constants as odl_const from networking_odl.db import models and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/db/models.py # class OpenDaylightJournal(model_base.BASEV2): # class OpenDaylightPeriodicTask(model_base.BASEV2): . Output only the next line.
models.OpenDaylightJournal))
Here is a snippet: <|code_start|># It's safe to pass those names _ODL_KNOWN_PROTOCOL_NAMES = ( n_const.PROTO_NAME_TCP, n_const.PROTO_NAME_UDP, n_const.PROTO_NAME_ICMP, n_const.PROTO_NAME_IPV6_ICMP_LEGACY, ) def _sgrule_scrub_unknown_protocol_name(protocol): """Convert unknown protocol name to actual interger. OpenDaylight does't want to keep catching up list of protocol names. So networking-odl converts unknown protcol name into integer """ if protocol in _ODL_KNOWN_PROTOCOL_NAMES: return protocol if protocol in n_const.IP_PROTOCOL_MAP: return n_const.IP_PROTOCOL_MAP[protocol] return protocol def _filter_security_group_rule(sg_rule): _sgrule_scrub_icmpv6_name(sg_rule) if sg_rule.get('protocol'): sg_rule['protocol'] = _sgrule_scrub_unknown_protocol_name( sg_rule['protocol']) _FILTER_MAP = { <|code_end|> . Write the next line using the current file imports: from neutron_lib import constants as n_const from oslo_log import log from oslo_serialization import jsonutils from networking_odl.common import constants as odl_const from networking_odl.common import utils as odl_utils and context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): , which may include functions, classes, or code. Output only the next line.
(odl_const.ODL_NETWORK, odl_const.ODL_CREATE): _filter_network_create,
Given snippet: <|code_start|> project_id = resource_dict.get('project_id', resource_dict.get('tenant_id')) if project_id is not None: # NOTE(yamahata): project_id can be ""(empty string) resource_dict.setdefault('project_id', project_id) resource_dict.setdefault('tenant_id', project_id) def _filter_unmapped_null(resource_dict, unmapped_keys): # NOTE(yamahata): bug work around # https://bugs.eclipse.org/bugs/show_bug.cgi?id=475475 # Null-value for an unmapped element causes next mapped # collection to contain a null value # JSON: { "unmappedField": null, "mappedCollection": [ "a" ] } # # Java Object: # class Root { # Collection<String> mappedCollection = new ArrayList<String>; # } # # Result: # Field B contains one element; null # # TODO(yamahata): update along side with neutron and ODL # add when neutron adds more extensions # delete when ODL neutron northbound supports it # TODO(yamahata): do same thing for other resources keys_to_del = [key for key in unmapped_keys if resource_dict.get(key) is None] if keys_to_del: <|code_end|> , continue by predicting the next line. Consider current file imports: from neutron_lib import constants as n_const from oslo_log import log from oslo_serialization import jsonutils from networking_odl.common import constants as odl_const from networking_odl.common import utils as odl_utils and context: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): which might include code, classes, or functions. Output only the next line.
odl_utils.try_del(resource_dict, keys_to_del)
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. TEST_UUID = 'bd8db3a8-2b30-4083-a8b3-b3fd46401142' TEST_PLUGIN = 'test_plugin' TEST_RESOURCE1 = 'test_resource1' TEST_RESOURCE2 = 'test_resource2' TEST_RESOURCE1_SUFFIX = 'test_resource1s' TEST_RESOURCE2_SUFFIX = 'test_resource2s' INVALID_RESOURCE = 'invalid_resource' INVALID_PLUGIN = 'invalid_plugin' INVALID_METHOD = 'invalid_method_name' class TestPlugin(object): def get_test_resource1s(self, context): return [{'id': 'test_id1'}, {'id': 'test_id2'}] def get_test_resource2s(self, context): return [{'id': 'test_id3'}, {'id': 'test_id4'}] def get_test_resource1(self, context, id_): return {'id': id_} <|code_end|> using the current file's imports: from networking_odl.journal import base_driver and any relevant context from other files: # Path: networking_odl/journal/base_driver.py # LOG = logging.getLogger(__name__) # ALL_RESOURCES = {} # RESOURCES = {} # def get_driver(resource_type): # def __init__(self, *args, **kwargs): # def _get_resource_getter(self, method_suffix): # def get_resources_for_full_sync(self, context, resource_type): # def plugin(self): # def get_resource_for_recovery(self, context, obj): # class ResourceBaseDriver(object): . Output only the next line.
class TestDriver(base_driver.ResourceBaseDriver):
Next line prediction: <|code_start|># Copyright (c) 2017 Ericsson India Global Service Pvt Ltd. # 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. class _TrunkDriverTest(base.OdlTestsBase): def test_trunk_create(self): with self.trunk() as trunk: <|code_end|> . Use current file imports: (import contextlib from networking_odl.common import constants as odl_const from networking_odl.tests.functional import base from neutron.services.trunk import plugin as trunk_plugin from neutron.tests.unit.plugins.ml2 import test_plugin from neutron_lib.plugins import utils from neutron_lib.services.trunk import constants from oslo_utils import uuidutils) and context including class names, function names, or small code snippets from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } # # Path: networking_odl/tests/functional/base.py # class OdlTestsBase(object): # class V2DriverAdjustment(test_base_db.ODLBaseDbTestCase): # DEFAULT_LOG_DIR = os.path.join(helpers.get_test_log_path(), # 'functional-logs') # def setUp(self): # def setup_parent(self): # def get_plugins(self): # def get_ext_managers(self): # def get_odl_resource(self, resource_type, resource): # def assert_resource_created(self, resource_type, resource): # def resource_update_test(self, resource_type, resource): # def resource_delete_test(self, resource_type, resource): # def setUp(self): # def get_odl_resource(self, resource_type, resource): # def no_journal_rows(): . Output only the next line.
self.assert_resource_created(odl_const.ODL_TRUNK, trunk)
Given the following code snippet before the placeholder: <|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. """ Command line script to analyze journal entry processing time based on logs. By default the input is read through pipe, unless a log file is specified. Examples: Analyzing devstack's Neutron log: journalctl -u devstack@neutron-api | python analyze_journal.py Analyzing an arbitrary log file: python analyze_journal.py --file /path/to/file.log """ COMMAND_LINE_OPTIONS = [ cfg.StrOpt('file', default=None, <|code_end|> , predict the next line using imports from the current file: import collections import re import sys from oslo_config import cfg from networking_odl._i18n import _ from networking_odl.journal import journal and context including class names, function names, and sometimes code from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): . Output only the next line.
help=_("Log file to analyze.")),
Given the following code snippet before the placeholder: <|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. """ Command line script to analyze journal entry processing time based on logs. By default the input is read through pipe, unless a log file is specified. Examples: Analyzing devstack's Neutron log: journalctl -u devstack@neutron-api | python analyze_journal.py Analyzing an arbitrary log file: python analyze_journal.py --file /path/to/file.log """ COMMAND_LINE_OPTIONS = [ cfg.StrOpt('file', default=None, help=_("Log file to analyze.")), cfg.IntOpt('slowest', min=1, default=10, help=_("Prints the N slowest entries (10 by default).")), ] # This regex will match any replacement key in the log message and extract # the key name. KEY_MATCHER = re.compile(r'\%\((\S+)\)s') <|code_end|> , predict the next line using imports from the current file: import collections import re import sys from oslo_config import cfg from networking_odl._i18n import _ from networking_odl.journal import journal and context including class names, function names, and sometimes code from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/journal/journal.py # LOG = logging.getLogger(__name__) # MAKE_URL = {} # LOG_ENTRY_TEMPLATE = ("%(log_type)s (Entry ID: %(entry_id)s) - %(op)s " # "%(obj_type)s %(obj_id)s (Time stamp: %(timestamp)s)") # LOG_RECORDED = 'Recorded' # LOG_PROCESSING = 'Processing' # LOG_COMPLETED = 'Completed' # LOG_ERROR_PROCESSING = 'Error while processing' # _RETRY_SLEEP_MIN = 0.1 # _RETRY_SLEEP_MAX = 60 # def call_thread_on_end(func): # def new_func(obj, *args, **kwargs): # def _enrich_port(plugin_context, ml2_context, object_type, operation, data): # def _log_entry(log_type, entry, log_level=logging.INFO, **kwargs): # def record(plugin_context, object_type, object_uuid, operation, data, # ml2_context=None): # def entry_complete(context, entry): # def entry_reset(context, entry): # def entry_update_state_by_retry_count(context, entry, retry_count): # def _make_url(row): # def register_url_builder(object_type, method): # def _build_url(row): # def __init__(self, start_thread=True): # def _create_odl_sync_thread(self): # def start(self): # def stop(self, timeout=None): # def set_sync_event(self): # def _json_data(row): # def run_sync_thread(self): # def sync_pending_entries(self): # def _retry_sleep(self): # def _retry_reset(self): # def _sync_entry(self, context, entry): # class OpenDaylightJournalThread(object): . Output only the next line.
LOG_KEYS = KEY_MATCHER.findall(journal.LOG_ENTRY_TEMPLATE)
Given the code snippet: <|code_start|># Copyright (c) 2017 NEC Corp # 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. LOG = logging.getLogger(__name__) ALL_RESOURCES = {} def get_driver(resource_type): try: return ALL_RESOURCES[resource_type] except KeyError: <|code_end|> , generate the next line using the imports in this file: from neutron_lib.plugins import directory from oslo_log import log as logging from networking_odl.common import exceptions and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/exceptions.py # class NetworkingODLException(exceptions.NeutronException): # class FullSyncError(NetworkingODLException): # class UnsupportedResourceType(NetworkingODLException): # class PluginMethodNotFound(NetworkingODLException, AttributeError): # class ResourceNotRegistered(FullSyncError): . Output only the next line.
raise exceptions.ResourceNotRegistered(resource_type=resource_type)
Continue the code snippet: <|code_start|># # Copyright (C) 2017 Red Hat, Inc. # # 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 JournalCleanupTestCase(test_base_db.ODLBaseDbTestCase): def test_delete_completed_rows_retries_exceptions(self): self.cfg.config(completed_rows_retention=1, group='ml2_odl') <|code_end|> . Use current file imports: from unittest import mock from networking_odl.db import db from networking_odl.journal import cleanup from networking_odl.tests.unit import test_base_db and context (classes, functions, or code) from other files: # Path: networking_odl/db/db.py # LOG = logging.getLogger(__name__) # def get_pending_or_processing_ops(context, object_uuid, operation=None): # def get_pending_delete_ops_with_parent(context, object_type, parent_id): # def get_all_db_rows(context): # def get_all_db_rows_by_state(context, state): # def get_oldest_pending_db_row_with_lock(context): # def delete_dependency(context, entry): # def update_db_row_state(context, row, state, flush=True): # def update_pending_db_row_retry(context, row, retry_count): # def delete_row(context, row=None, row_id=None, flush=True): # def create_pending_row(context, object_type, object_uuid, # operation, data, depending_on=None): # def delete_pending_rows(context, operations_to_delete): # def _update_periodic_task_state(context, expected_state, state, task): # def was_periodic_task_executed_recently(context, task, interval): # def lock_periodic_task(context, task): # def unlock_periodic_task(context, task): # def update_periodic_task(context, task, operation=None): # def delete_rows_by_state_and_time(context, state, time_delta): # def reset_processing_rows(context, max_timedelta): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/tests/unit/test_base_db.py # RETRIABLE_EXCEPTIONS = (db_exc.DBDeadlock, exc.StaleDataError, # db_exc.DBConnectionError, db_exc.DBDuplicateEntry, # db_exc.RetryRequest) # RETRY_INTERVAL = 0.001 # RETRY_MAX = 2 # UPDATE_ROW = [constants.ODL_NETWORK, 'id', constants.ODL_UPDATE, # {'test': 'data'}] # class _InnerException(Exception): # class ODLBaseDbTestCase(SqlTestCaseLight): # class RetryTracker(object): # def setUp(self): # def _setup_retry_tracker_table(self): # def _db_cleanup(self): # def _test_db_exceptions_handled(self, method, mock_object, expect_retries): # def _assertRaises(exceptions, method, context, *args, **kwargs): # def increase_retry_counter_and_except(*args, **kwargs): # def _assertRetryCount(self, expected_count): # def _test_retry_exceptions(self, method, mock_object, # assert_transaction=True): . Output only the next line.
with mock.patch.object(db, 'delete_rows_by_state_and_time') as m:
Given snippet: <|code_start|># # Copyright (C) 2017 Red Hat, Inc. # # 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 JournalCleanupTestCase(test_base_db.ODLBaseDbTestCase): def test_delete_completed_rows_retries_exceptions(self): self.cfg.config(completed_rows_retention=1, group='ml2_odl') with mock.patch.object(db, 'delete_rows_by_state_and_time') as m: self._test_retry_exceptions( <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import mock from networking_odl.db import db from networking_odl.journal import cleanup from networking_odl.tests.unit import test_base_db and context: # Path: networking_odl/db/db.py # LOG = logging.getLogger(__name__) # def get_pending_or_processing_ops(context, object_uuid, operation=None): # def get_pending_delete_ops_with_parent(context, object_type, parent_id): # def get_all_db_rows(context): # def get_all_db_rows_by_state(context, state): # def get_oldest_pending_db_row_with_lock(context): # def delete_dependency(context, entry): # def update_db_row_state(context, row, state, flush=True): # def update_pending_db_row_retry(context, row, retry_count): # def delete_row(context, row=None, row_id=None, flush=True): # def create_pending_row(context, object_type, object_uuid, # operation, data, depending_on=None): # def delete_pending_rows(context, operations_to_delete): # def _update_periodic_task_state(context, expected_state, state, task): # def was_periodic_task_executed_recently(context, task, interval): # def lock_periodic_task(context, task): # def unlock_periodic_task(context, task): # def update_periodic_task(context, task, operation=None): # def delete_rows_by_state_and_time(context, state, time_delta): # def reset_processing_rows(context, max_timedelta): # # Path: networking_odl/journal/cleanup.py # LOG = logging.getLogger(__name__) # def delete_completed_rows(context): # def cleanup_processing_rows(context): # # Path: networking_odl/tests/unit/test_base_db.py # RETRIABLE_EXCEPTIONS = (db_exc.DBDeadlock, exc.StaleDataError, # db_exc.DBConnectionError, db_exc.DBDuplicateEntry, # db_exc.RetryRequest) # RETRY_INTERVAL = 0.001 # RETRY_MAX = 2 # UPDATE_ROW = [constants.ODL_NETWORK, 'id', constants.ODL_UPDATE, # {'test': 'data'}] # class _InnerException(Exception): # class ODLBaseDbTestCase(SqlTestCaseLight): # class RetryTracker(object): # def setUp(self): # def _setup_retry_tracker_table(self): # def _db_cleanup(self): # def _test_db_exceptions_handled(self, method, mock_object, expect_retries): # def _assertRaises(exceptions, method, context, *args, **kwargs): # def increase_retry_counter_and_except(*args, **kwargs): # def _assertRetryCount(self, expected_count): # def _test_retry_exceptions(self, method, mock_object, # assert_transaction=True): which might include code, classes, or functions. Output only the next line.
cleanup.delete_completed_rows, m)
Based on the snippet: <|code_start|># Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # 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. LOG = logging.getLogger(__name__) ODLResource = collections.namedtuple('ODLResource', ('singular', 'plural')) _RESOURCE_MAPPING = { <|code_end|> , predict the immediate next line with the help of imports: import collections from neutron_lib.callbacks import events from neutron_lib.callbacks import registry from neutron_lib.callbacks import resources from neutron_lib.db import api as db_api from oslo_log import log as logging from oslo_utils import excutils from networking_odl.common import constants as odl_const and context (classes, functions, sometimes code) from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } . Output only the next line.
resources.SECURITY_GROUP: ODLResource(odl_const.ODL_SG, odl_const.ODL_SGS),
Next line prediction: <|code_start|> def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, packet_handler, timeout, status_cb=None): self.odl_rest_client = odl_rest_client self.path = path self.datastore = datastore self.scope = scope self.leaf_node_only = leaf_node_only self.packet_handler = packet_handler self.timeout = timeout self.exit_websocket_thread = False self.status_cb = status_cb self.current_status = ODL_WEBSOCKET_DISCONNECTED self._odl_sync_thread = self.start_odl_websocket_thread() @classmethod def odl_create_websocket(cls, odl_url, path, datastore, scope, packet_handler, status_cb=None, leaf_node_only=False): """Create a websocket connection with ODL. This method will create a websocket client based on path, datastore and scope params. On data recv from websocket packet_handler callback is called. status_cb callback can be provided if notifications are requried for socket status changes """ if odl_url is None: LOG.error("invalid odl url", exc_info=True) <|code_end|> . Use current file imports: (import re import ssl import threading import time import websocket from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from oslo_utils import excutils from requests import codes from requests import exceptions from networking_odl._i18n import _ from networking_odl.common import client as odl_client) and context including class names, function names, or small code snippets from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): . Output only the next line.
raise ValueError(_("Invalid ODL URL"))
Predict the next line after this snippet: <|code_start|> packet_handler, timeout, status_cb=None): self.odl_rest_client = odl_rest_client self.path = path self.datastore = datastore self.scope = scope self.leaf_node_only = leaf_node_only self.packet_handler = packet_handler self.timeout = timeout self.exit_websocket_thread = False self.status_cb = status_cb self.current_status = ODL_WEBSOCKET_DISCONNECTED self._odl_sync_thread = self.start_odl_websocket_thread() @classmethod def odl_create_websocket(cls, odl_url, path, datastore, scope, packet_handler, status_cb=None, leaf_node_only=False): """Create a websocket connection with ODL. This method will create a websocket client based on path, datastore and scope params. On data recv from websocket packet_handler callback is called. status_cb callback can be provided if notifications are requried for socket status changes """ if odl_url is None: LOG.error("invalid odl url", exc_info=True) raise ValueError(_("Invalid ODL URL")) <|code_end|> using the current file's imports: import re import ssl import threading import time import websocket from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from oslo_utils import excutils from requests import codes from requests import exceptions from networking_odl._i18n import _ from networking_odl.common import client as odl_client and any relevant context from other files: # Path: networking_odl/_i18n.py # DOMAIN = "networking_odl" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): . Output only the next line.
odl_rest_client = odl_client.OpenDaylightRestClient.create_client(
Given the code snippet: <|code_start|># 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 TestClientHTTPBasicAuth(base.BaseTestCase): auth_way = 'basic' scheme = 'http' def setUp(self): super(TestClientHTTPBasicAuth, self).setUp() conf = ceilometer_service.prepare_service(argv=[], config_files=[]) self.CONF = self.useFixture(config_fixture.Config(conf)).conf self.parsed_url = urllib.parse.urlparse( 'http://127.0.0.1:8080/controller/statistics?' 'auth=%s&user=admin&password=admin_pass&' 'scheme=%s' % (self.auth_way, self.scheme)) self.params = urllib.parse.parse_qs(self.parsed_url.query) self.endpoint = urllib.parse.urlunparse( urllib.parse.ParseResult(self.scheme, self.parsed_url.netloc, self.parsed_url.path, None, None, None)) odl_params = {'auth': self.params.get('auth')[0], 'user': self.params.get('user')[0], 'password': self.params.get('password')[0]} <|code_end|> , generate the next line using the imports in this file: from unittest import mock from oslo_config import fixture as config_fixture from oslotest import base from requests import auth as req_auth from ceilometer.i18n import _ from ceilometer import service as ceilometer_service from networking_odl.ceilometer.network.statistics.opendaylight_v2 import client import urllib and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/ceilometer/network/statistics/opendaylight_v2/client.py # LOG = log.getLogger(__name__) # class _Base(object, metaclass=abc.ABCMeta): # class OpenDaylightRESTAPIFailed(Exception): # class SwitchStatisticsAPIClient(_Base): # class Client(object): # def base_url(self): # def __init__(self, client): # def get_statistics(self): # def __init__(self, conf, endpoint, params): # def _get_req_params(self, params): # def _log_req(self, url): # def _log_res(resp): # def _http_request(self, url): # def request(self, path): . Output only the next line.
self.client = client.Client(self.CONF, self.endpoint, odl_params)
Given snippet: <|code_start|> '''Set odl_features back to it's pre-initlialized ''' global feature_configs feature_configs = copy.copy(EMPTY_FEATURES) def _load_features(json): """parse and save features from json""" features = json['features'] if 'feature' not in features: return copy.copy(EMPTY_FEATURES) # documentation on the JSON received can be found at: # https://github.com/opendaylight/neutron/blob/master/model/src/main/yang/neutron-extensions.yang LOG.info('Retrieved ODL features %s', features) response = {} for feature in features['feature']: cfg = feature.get('configuration', '') response[feature['service-provider-feature'].split(':')[1]] = cfg return response def _fetch_features(): '''Fetch the list of features declared by ODL. This function should be called once during initialization ''' path = 'restconf/operational/neutron:neutron/neutron:features' features_url = utils.get_odl_url(path) <|code_end|> , continue by predicting the next line. Consider current file imports: import copy import itertools import time from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from requests import exceptions from networking_odl.common import client as odl_client from networking_odl.common import utils and context: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): which might include code, classes, or functions. Output only the next line.
client = odl_client.OpenDaylightRestClient.create_client(features_url)
Predict the next line for this snippet: <|code_start|> def deinit(): '''Set odl_features back to it's pre-initlialized ''' global feature_configs feature_configs = copy.copy(EMPTY_FEATURES) def _load_features(json): """parse and save features from json""" features = json['features'] if 'feature' not in features: return copy.copy(EMPTY_FEATURES) # documentation on the JSON received can be found at: # https://github.com/opendaylight/neutron/blob/master/model/src/main/yang/neutron-extensions.yang LOG.info('Retrieved ODL features %s', features) response = {} for feature in features['feature']: cfg = feature.get('configuration', '') response[feature['service-provider-feature'].split(':')[1]] = cfg return response def _fetch_features(): '''Fetch the list of features declared by ODL. This function should be called once during initialization ''' path = 'restconf/operational/neutron:neutron/neutron:features' <|code_end|> with the help of current file imports: import copy import itertools import time from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from requests import exceptions from networking_odl.common import client as odl_client from networking_odl.common import utils and context from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): , which may contain function names, class names, or code. Output only the next line.
features_url = utils.get_odl_url(path)
Based on the snippet: <|code_start|> for opt in required_opts: if not getattr(cfg.CONF.ml2_odl, opt): raise cfg.RequiredOptError(opt, cfg.OptGroup('ml2_odl')) @classmethod def create_client(cls, url=None): if cfg.CONF.ml2_odl.enable_lightweight_testing: LOG.debug("ODL lightweight testing is enabled, " "returning a OpenDaylightLwtClient instance") # Have to import at here, otherwise we create a dependency loop # pylint: disable=import-outside-toplevel cls = lwt.OpenDaylightLwtClient url = url or cfg.CONF.ml2_odl.url cls._check_opt(url) return cls( url, cfg.CONF.ml2_odl.username, cfg.CONF.ml2_odl.password, cfg.CONF.ml2_odl.timeout) def __init__(self, url, username, password, timeout): super(OpenDaylightRestClient, self).__init__() self.url = url self.timeout = timeout self.session = sessions.Session() self.session.auth = (username, password) def get_resource(self, resource_type, resource_id): <|code_end|> , predict the immediate next line with the help of imports: import threading import requests from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from oslo_utils import excutils from requests import sessions from networking_odl.common import utils from networking_odl.common import lightweight_testing as lwt and context (classes, functions, sometimes code) from other files: # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): . Output only the next line.
response = self.get(utils.make_url_object(resource_type) + '/' +
Using the 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. class TestOdlFeatures(base.DietTestCase): """Basic tests for odl_features""" feature_json = """{"features": {"feature": [{"service-provider-feature": "neutron-extensions:operational-port-status"}, {"service-provider-feature": "neutron-extensions:feature-with-config", "configuration": "steal-your-face"}]}}""" feature_list = 'thing1, thing2' def setUp(self): self.features_fixture = base.OpenDaylightFeaturesFixture() self.useFixture(self.features_fixture) self.cfg = self.useFixture(config_fixture.Config()) super(TestOdlFeatures, self).setUp() self.addCleanup(odl_features.deinit) <|code_end|> , determine the next line of code. You have imports: from unittest import mock from oslo_config import fixture as config_fixture from oslo_serialization import jsonutils from requests import exceptions from networking_odl.common.client import OpenDaylightRestClient from networking_odl.common import odl_features from networking_odl.tests import base and context (class names, function names, or code) available: # Path: networking_odl/common/client.py # class OpenDaylightRestClient(object): # @staticmethod # def _check_opt(url): # if not url: # raise cfg.RequiredOptError('url', cfg.OptGroup('ml2_odl')) # required_opts = ('url', 'username', 'password') # for opt in required_opts: # if not getattr(cfg.CONF.ml2_odl, opt): # raise cfg.RequiredOptError(opt, cfg.OptGroup('ml2_odl')) # # @classmethod # def create_client(cls, url=None): # if cfg.CONF.ml2_odl.enable_lightweight_testing: # LOG.debug("ODL lightweight testing is enabled, " # "returning a OpenDaylightLwtClient instance") # # # Have to import at here, otherwise we create a dependency loop # # pylint: disable=import-outside-toplevel # from networking_odl.common import lightweight_testing as lwt # cls = lwt.OpenDaylightLwtClient # # url = url or cfg.CONF.ml2_odl.url # cls._check_opt(url) # return cls( # url, # cfg.CONF.ml2_odl.username, # cfg.CONF.ml2_odl.password, # cfg.CONF.ml2_odl.timeout) # # def __init__(self, url, username, password, timeout): # super(OpenDaylightRestClient, self).__init__() # self.url = url # self.timeout = timeout # self.session = sessions.Session() # self.session.auth = (username, password) # # def get_resource(self, resource_type, resource_id): # response = self.get(utils.make_url_object(resource_type) + '/' + # resource_id) # if response.status_code == requests.codes.not_found: # return None # # return self._check_response(response).json() # # def get(self, urlpath='', data=None): # return self.request('get', urlpath, data) # # def request(self, method, urlpath='', data=None): # headers = {'Content-Type': 'application/json'} # url = '/'.join([self.url, urlpath]) # LOG.debug( # "Sending METHOD (%(method)s) URL (%(url)s) JSON (%(data)s)", # {'method': method, 'url': url, 'data': data}) # return self.session.request( # method, url=url, headers=headers, data=data, timeout=self.timeout) # # def sendjson(self, method, urlpath, obj): # """Send json to the OpenDaylight controller.""" # data = jsonutils.dumps(obj, indent=2) if obj else None # try: # return self._check_response( # self.request(method, urlpath, data)) # except Exception: # with excutils.save_and_reraise_exception(): # LOG.error("REST request ( %(method)s ) to " # "url ( %(urlpath)s ) is failed. " # "Request body : [%(body)s] service", # {'method': method, # 'urlpath': urlpath, # 'body': obj}) # # def _check_response(self, response): # try: # response.raise_for_status() # except requests.HTTPError as error: # with excutils.save_and_reraise_exception(): # LOG.debug("Exception from ODL: %(e)s %(text)s", # {'e': error, 'text': response.text}, exc_info=1) # else: # LOG.debug("Got response:\n" # "(%(response)s)", {'response': response.text}) # return response # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): . Output only the next line.
@mock.patch.object(OpenDaylightRestClient, 'request')
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 TestOdlFeatures(base.DietTestCase): """Basic tests for odl_features""" feature_json = """{"features": {"feature": [{"service-provider-feature": "neutron-extensions:operational-port-status"}, {"service-provider-feature": "neutron-extensions:feature-with-config", "configuration": "steal-your-face"}]}}""" feature_list = 'thing1, thing2' def setUp(self): self.features_fixture = base.OpenDaylightFeaturesFixture() self.useFixture(self.features_fixture) self.cfg = self.useFixture(config_fixture.Config()) super(TestOdlFeatures, self).setUp() <|code_end|> , determine the next line of code. You have imports: from unittest import mock from oslo_config import fixture as config_fixture from oslo_serialization import jsonutils from requests import exceptions from networking_odl.common.client import OpenDaylightRestClient from networking_odl.common import odl_features from networking_odl.tests import base and context (class names, function names, or code) available: # Path: networking_odl/common/client.py # class OpenDaylightRestClient(object): # @staticmethod # def _check_opt(url): # if not url: # raise cfg.RequiredOptError('url', cfg.OptGroup('ml2_odl')) # required_opts = ('url', 'username', 'password') # for opt in required_opts: # if not getattr(cfg.CONF.ml2_odl, opt): # raise cfg.RequiredOptError(opt, cfg.OptGroup('ml2_odl')) # # @classmethod # def create_client(cls, url=None): # if cfg.CONF.ml2_odl.enable_lightweight_testing: # LOG.debug("ODL lightweight testing is enabled, " # "returning a OpenDaylightLwtClient instance") # # # Have to import at here, otherwise we create a dependency loop # # pylint: disable=import-outside-toplevel # from networking_odl.common import lightweight_testing as lwt # cls = lwt.OpenDaylightLwtClient # # url = url or cfg.CONF.ml2_odl.url # cls._check_opt(url) # return cls( # url, # cfg.CONF.ml2_odl.username, # cfg.CONF.ml2_odl.password, # cfg.CONF.ml2_odl.timeout) # # def __init__(self, url, username, password, timeout): # super(OpenDaylightRestClient, self).__init__() # self.url = url # self.timeout = timeout # self.session = sessions.Session() # self.session.auth = (username, password) # # def get_resource(self, resource_type, resource_id): # response = self.get(utils.make_url_object(resource_type) + '/' + # resource_id) # if response.status_code == requests.codes.not_found: # return None # # return self._check_response(response).json() # # def get(self, urlpath='', data=None): # return self.request('get', urlpath, data) # # def request(self, method, urlpath='', data=None): # headers = {'Content-Type': 'application/json'} # url = '/'.join([self.url, urlpath]) # LOG.debug( # "Sending METHOD (%(method)s) URL (%(url)s) JSON (%(data)s)", # {'method': method, 'url': url, 'data': data}) # return self.session.request( # method, url=url, headers=headers, data=data, timeout=self.timeout) # # def sendjson(self, method, urlpath, obj): # """Send json to the OpenDaylight controller.""" # data = jsonutils.dumps(obj, indent=2) if obj else None # try: # return self._check_response( # self.request(method, urlpath, data)) # except Exception: # with excutils.save_and_reraise_exception(): # LOG.error("REST request ( %(method)s ) to " # "url ( %(urlpath)s ) is failed. " # "Request body : [%(body)s] service", # {'method': method, # 'urlpath': urlpath, # 'body': obj}) # # def _check_response(self, response): # try: # response.raise_for_status() # except requests.HTTPError as error: # with excutils.save_and_reraise_exception(): # LOG.debug("Exception from ODL: %(e)s %(text)s", # {'e': error, 'text': response.text}, exc_info=1) # else: # LOG.debug("Got response:\n" # "(%(response)s)", {'response': response.text}) # return response # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): . Output only the next line.
self.addCleanup(odl_features.deinit)
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. cfg.CONF.import_group('ml2_odl', 'networking_odl.common.config') def try_del(d, keys): """Ignore key errors when deleting from a dictionary.""" for key in keys: try: del d[key] except KeyError: pass def make_url_object(object_type): <|code_end|> using the current file's imports: import urllib from oslo_config import cfg from networking_odl.common import constants as odl_const and any relevant context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } . Output only the next line.
obj_pl = odl_const.RESOURCE_URL_MAPPINGS.get(object_type, None)
Based on the snippet: <|code_start|># under the License. PROFILE = {"capabilities": ["switchdev"]} PROFILE_STR = '{"capabilities": ["switchdev"]}' FAKE_PORT = {'status': 'DOWN', 'binding:host_id': '', 'allowed_address_pairs': [], 'device_owner': 'fake_owner', 'binding:profile': {"capabilities": ["switchdev"]}, 'fixed_ips': [], 'id': '72c56c48-e9b8-4dcf-b3a7-0813bb3bd839', 'security_groups': [], 'device_id': 'fake_device', 'name': '', 'admin_state_up': True, 'network_id': 'c13bba05-eb07-45ba-ace2-765706b2d701', 'tenant_id': 'bad_tenant_id', 'binding:vif_details': {}, 'binding:vnic_type': 'normal', 'binding:vif_type': 'unbound', 'mac_address': '12:34:56:78:21:b6'} class TestFilters(base.DietTestCase): def _check_id(self, resource, project_id): <|code_end|> , predict the immediate next line with the help of imports: import copy from unittest import mock from neutron.tests import base from neutron_lib import constants as n_const from networking_odl.common import filters and context (classes, functions, sometimes code) from other files: # Path: networking_odl/common/filters.py # LOG = log.getLogger(__name__) # _NETWORK_UNMAPPED_KEYS = ['qos_policy_id'] # _SUBNET_UNMAPPED_KEYS = ['segment_id', 'subnetpool_id'] # _PORT_UNMAPPED_KEYS = ['binding:profile', 'dns_name', # 'port_security_enabled', 'qos_policy_id'] # _FIP_UNMAPPED_KEYS = ['port_id', 'fixed_ip_address', 'router_id'] # _ODL_KNOWN_PROTOCOL_NAMES = ( # n_const.PROTO_NAME_TCP, # n_const.PROTO_NAME_UDP, # n_const.PROTO_NAME_ICMP, # n_const.PROTO_NAME_IPV6_ICMP_LEGACY, # ) # _FILTER_MAP = { # (odl_const.ODL_NETWORK, odl_const.ODL_CREATE): _filter_network_create, # (odl_const.ODL_NETWORK, odl_const.ODL_UPDATE): _filter_network_update, # (odl_const.ODL_SUBNET, odl_const.ODL_CREATE): _filter_subnet_create, # (odl_const.ODL_SUBNET, odl_const.ODL_UPDATE): _filter_subnet_update, # (odl_const.ODL_PORT, odl_const.ODL_CREATE): _filter_port_create, # (odl_const.ODL_PORT, odl_const.ODL_UPDATE): _filter_port_update, # (odl_const.ODL_ROUTER, odl_const.ODL_UPDATE): _filter_router_update, # (odl_const.ODL_SG_RULE, odl_const.ODL_CREATE): _filter_security_group_rule, # (odl_const.ODL_SG_RULE, odl_const.ODL_UPDATE): _filter_security_group_rule, # (odl_const.ODL_FLOATINGIP, odl_const.ODL_UPDATE): _filter_floatingip, # } # def _populate_project_id_and_tenant_id(resource_dict): # def _filter_unmapped_null(resource_dict, unmapped_keys): # def _filter_network_create(network): # def _filter_network_update(network): # def _filter_floatingip(fip): # def _filter_subnet_create(subnet): # def _filter_subnet_update(subnet): # def _convert_value_to_str(dictionary, key): # def _filter_port(port, attributes): # def _filter_port_create(port): # def _filter_port_update(port): # def _filter_router_update(router): # def _sgrule_scrub_icmpv6_name(sgrule): # def _sgrule_scrub_unknown_protocol_name(protocol): # def _filter_security_group_rule(sg_rule): # def filter_for_odl(object_type, operation, data): . Output only the next line.
filters._populate_project_id_and_tenant_id(resource)
Predict the next line for this snippet: <|code_start|> # NOTE:(Achuth) Fixes bug 1746715 # DHCP port to be created for IPv4 subnets only, since ODL doesn't # support IPv6 neutron port ARP responses. This prevents validations # in ODL and avoids processing these ports incorrectly. if subnet_context.current['ip_version'] != 4: LOG.warning("ODL DHCP port is supported only for IPv4 subnet %s", subnet_context.current['id']) return port_id = self.get_dhcp_port_if_exists(subnet_context) plugin = subnet_context._plugin if not port_id and subnet_context.current['enable_dhcp']: LOG.debug("Creating ODL DHCP port for subnet %s of network %s", subnet_context.current['id'], subnet_context.current['network_id']) port = self._make_dhcp_port_dict(subnet_context) # TODO(boden): rehome and consume from neutron-lib p_utils.create_port(plugin, subnet_context._plugin_context, port) if port_id and not subnet_context.current['enable_dhcp']: self._delete_port(plugin, subnet_context._plugin_context, port_id) def _delete_port(self, plugin, context, port_id): LOG.debug("Deleting ODL DHCP port with id %s", port_id) plugin.delete_port(context, port_id) def _make_dhcp_port_dict(self, subnet_context): subnet_id = subnet_context.current['id'] port_dict = dict( name='', admin_state_up=True, <|code_end|> with the help of current file imports: from neutron_lib import constants as n_const from neutron_lib.plugins import utils as p_utils from oslo_log import log as logging from networking_odl.common import constants and context from other files: # Path: networking_odl/common/constants.py # ODL_NETWORK = 'network' # ODL_NETWORKS = 'networks' # ODL_SUBNET = 'subnet' # ODL_SUBNETS = 'subnets' # ODL_PORT = 'port' # ODL_PORTS = 'ports' # ODL_SG = 'security_group' # ODL_SGS = 'security_groups' # ODL_SG_RULE = 'security_group_rule' # ODL_SG_RULES = 'security_group_rules' # ODL_ROUTER = 'router' # ODL_ROUTERS = 'routers' # ODL_FLOATINGIP = 'floatingip' # ODL_FLOATINGIPS = 'floatingips' # ODL_QOS = 'qos' # ODL_QOS_POLICY = 'policy' # ODL_QOS_POLICIES = 'policies' # ODL_SFC = 'sfc' # ODL_SFC_FLOW_CLASSIFIER = 'flowclassifier' # ODL_SFC_FLOW_CLASSIFIERS = 'flowclassifiers' # ODL_SFC_PORT_PAIR = 'portpair' # ODL_SFC_PORT_PAIRS = 'portpairs' # ODL_SFC_PORT_PAIR_GROUP = 'portpairgroup' # ODL_SFC_PORT_PAIR_GROUPS = 'portpairgroups' # ODL_SFC_PORT_CHAIN = 'portchain' # ODL_SFC_PORT_CHAINS = 'portchains' # NETWORKING_SFC_FLOW_CLASSIFIER = 'flow_classifier' # NETWORKING_SFC_FLOW_CLASSIFIERS = 'flow_classifiers' # NETWORKING_SFC_PORT_PAIR = 'port_pair' # NETWORKING_SFC_PORT_PAIRS = 'port_pairs' # NETWORKING_SFC_PORT_PAIR_GROUP = 'port_pair_group' # NETWORKING_SFC_PORT_PAIR_GROUPS = 'port_pair_groups' # NETWORKING_SFC_PORT_CHAIN = 'port_chain' # NETWORKING_SFC_PORT_CHAINS = 'port_chains' # ODL_TRUNK = 'trunk' # ODL_TRUNKS = 'trunks' # ODL_L2GATEWAY = 'l2_gateway' # ODL_L2GATEWAYS = 'l2_gateways' # ODL_L2GATEWAY_CONNECTION = 'l2gateway_connection' # ODL_L2GATEWAY_CONNECTIONS = 'l2_gateway_connections' # ODL_BGPVPN = 'bgpvpn' # ODL_BGPVPNS = 'bgpvpns' # ODL_BGPVPN_NETWORK_ASSOCIATION = 'bgpvpn_network_association' # ODL_BGPVPN_NETWORK_ASSOCIATIONS = 'bgpvpn_network_associations' # ODL_BGPVPN_ROUTER_ASSOCIATION = 'bgpvpn_router_association' # ODL_BGPVPN_ROUTER_ASSOCIATIONS = 'bgpvpn_router_associations' # ODL_ML2_MECH_DRIVER_V2 = "opendaylight_v2" # ODL_DEVICE_ID_START = 'OpenDaylight' # ODL_CREATE = 'create' # ODL_UPDATE = 'update' # ODL_DELETE = 'delete' # PENDING = 'pending' # PROCESSING = 'processing' # FAILED = 'failed' # COMPLETED = 'completed' # BEFORE_COMPLETE = 'before_complete' # AFTER_DELETE = 'after_delete' # RESOURCE_URL_MAPPINGS = { # ODL_QOS_POLICY: "%s/%s" % (ODL_QOS, ODL_QOS_POLICIES), # ODL_SFC_FLOW_CLASSIFIER: "%s/%s" % (ODL_SFC, ODL_SFC_FLOW_CLASSIFIERS), # ODL_SFC_PORT_CHAIN: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_CHAINS), # ODL_SFC_PORT_PAIR: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIRS), # ODL_SFC_PORT_PAIR_GROUP: "%s/%s" % (ODL_SFC, ODL_SFC_PORT_PAIR_GROUPS) # } , which may contain function names, class names, or code. Output only the next line.
device_id=constants.ODL_DEVICE_ID_START + '-' + subnet_id,
Given the code snippet: <|code_start|># Copyright (c) 2016 OpenStack Foundation # 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. cfg.CONF.import_group('ml2_odl', 'networking_odl.common.config') LOG = log.getLogger(__name__) class PseudoAgentDBBindingTaskBase(object): def __init__(self, worker): super(PseudoAgentDBBindingTaskBase, self).__init__() self._worker = worker # extract host/port from ODL URL and append hostconf_uri path <|code_end|> , generate the next line using the imports in this file: import logging from string import Template from neutron_lib.api.definitions import portbindings from neutron_lib.callbacks import events from neutron_lib.callbacks import registry from neutron_lib.callbacks import resources from neutron_lib import constants as nl_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib.plugins.ml2 import api from neutron_lib import worker from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from requests import codes from requests import exceptions from neutron.db import provisioning_blocks from networking_odl.common import client as odl_client from networking_odl.common import odl_features from networking_odl.common import utils from networking_odl.common import websocket_client as odl_ws_client from networking_odl.journal import periodic_task from networking_odl.ml2 import port_binding and context (functions, classes, or occasionally code) from other files: # Path: networking_odl/common/client.py # LOG = log.getLogger(__name__) # class OpenDaylightRestClient(object): # class OpenDaylightRestClientGlobal(object): # def _check_opt(url): # def create_client(cls, url=None): # def __init__(self, url, username, password, timeout): # def get_resource(self, resource_type, resource_id): # def get(self, urlpath='', data=None): # def request(self, method, urlpath='', data=None): # def sendjson(self, method, urlpath, obj): # def _check_response(self, response): # def __init__(self): # def get_client(self): # # Path: networking_odl/common/odl_features.py # LOG = log.getLogger(__name__) # OPERATIONAL_PORT_STATUS = 'operational-port-status' # EMPTY_FEATURES = {} # def init(): # def has(feature): # def get_config(feature): # def deinit(): # def _load_features(json): # def _fetch_features(): # # Path: networking_odl/common/utils.py # def try_del(d, keys): # def make_url_object(object_type): # def neutronify(name): # def get_odl_url(path=''): # # Path: networking_odl/common/websocket_client.py # LOG = log.getLogger(__name__) # ODL_OPERATIONAL_DATASTORE = "OPERATIONAL" # ODL_CONFIGURATION_DATASTORE = "CONFIGURATION" # ODL_NOTIFICATION_SCOPE_BASE = "BASE" # ODL_NOTIFICATION_SCOPE_ONE = "ONE" # ODL_NOTIFICATION_SCOPE_SUBTREE = "SUBTREE" # ODL_WEBSOCKET_DISCONNECTED = "ODL_WEBSOCKET_DISCONNECTED" # ODL_WEBSOCKET_CONNECTING = "ODL_WEBSOCKET_CONNECTING" # ODL_WEBSOCKET_CONNECTED = "ODL_WEBSOCKET_CONNECTED" # NOTIFICATION_TAG = 'notification' # DC_NOTIFICATION_TAG = 'data-changed-notification' # DC_EVENT_TAG = 'data-change-event' # OPERATION_DELETE = 'deleted' # OPERATION_CREATE = 'created' # OPERATION_UPDATE = 'updated' # class OpenDaylightWebsocketClient(object): # class EventDataParser(object): # def __init__(self, odl_rest_client, path, datastore, scope, leaf_node_only, # packet_handler, timeout, status_cb=None): # def odl_create_websocket(cls, odl_url, path, datastore, scope, # packet_handler, status_cb=None, # leaf_node_only=False): # def start_odl_websocket_thread(self): # def set_exit_flag(self, value=True): # def run_websocket_thread(self, exit_after_run=False): # def _set_websocket_status(self, status): # def _subscribe_websocket(self): # def _socket_create_connection(self, stream_url): # def _connect_ws(self): # def _close_ws(self, ws): # def __init__(self, item): # def get_item(cls, payload): # def get_fields(self): # def get_path(self): # def get_data(self): # def get_operation(self): # def extract_field(text, key): # # Path: networking_odl/journal/periodic_task.py # LOG = logging.getLogger(__name__) # class PeriodicTask(object): # def __init__(self, task, interval): # def start(self): # def cleanup(self): # def _set_operation(self, context, operation): # def _execute_op(self, operation, context): # def task_already_executed_recently(self, context): # def _clear_and_unlock_task(self, context): # def _lock_task(self, context): # def execute_ops(self, forced=False): # def register_operation(self, phase): # # Path: networking_odl/ml2/port_binding.py # LOG = log.getLogger(__name__) # class PortBindingController(object, metaclass=abc.ABCMeta): # class PortBindingManager(PortBindingController): # def get_workers(self): # def bind_port(self, port_context): # def __init__(self, name, controller): # def create( # cls, namespace='networking_odl.ml2.port_binding_controllers', # name=None): # def get_workers(self): # def bind_port(self, port_context): . Output only the next line.
hostconf_uri = utils.get_odl_url(cfg.CONF.ml2_odl.odl_hostconf_uri)
Using the snippet: <|code_start|># 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 TestLegacyPortBindingManager(base.DietTestCase): # valid and invalid segments valid_segment = { api.ID: 'API_ID', api.NETWORK_TYPE: n_constants.TYPE_LOCAL, api.SEGMENTATION_ID: 'API_SEGMENTATION_ID', api.PHYSICAL_NETWORK: 'API_PHYSICAL_NETWORK'} invalid_segment = { api.ID: 'API_ID', api.NETWORK_TYPE: n_constants.TYPE_NONE, api.SEGMENTATION_ID: 'API_SEGMENTATION_ID', api.PHYSICAL_NETWORK: 'API_PHYSICAL_NETWORK'} def test_check_segment(self): """Validate the _check_segment method.""" all_network_types = [n_constants.TYPE_FLAT, n_constants.TYPE_GRE, n_constants.TYPE_LOCAL, n_constants.TYPE_VXLAN, n_constants.TYPE_VLAN, n_constants.TYPE_NONE] <|code_end|> , determine the next line of code. You have imports: from unittest import mock from neutron.plugins.ml2 import driver_context as ctx from neutron_lib.api.definitions import portbindings from neutron_lib import constants as n_constants from neutron_lib.plugins.ml2 import api from networking_odl.ml2 import legacy_port_binding from networking_odl.tests import base and context (class names, function names, or code) available: # Path: networking_odl/ml2/legacy_port_binding.py # LOG = log.getLogger(__name__) # class LegacyPortBindingManager(port_binding.PortBindingController): # def __init__(self): # def bind_port(self, port_context): # def _check_segment(self, segment): # def _get_vif_type(self, port_context): # # Path: networking_odl/tests/base.py # class DietTestCase(base.DietTestCase): # class OpenDaylightRestClientFixture(fixtures.Fixture): # class OpenDaylightRestClientGlobalFixture(fixtures.Fixture): # class OpenDaylightFeaturesFixture(fixtures.Fixture): # class OpenDaylightJournalThreadFixture(fixtures.Fixture): # class JournalWorkerPidFileFixture(fixtures.Fixture): # class OpenDaylightPeriodicTaskFixture(fixtures.Fixture): # class OpenDaylightPseudoAgentPrePopulateFixture( # nl_fixture.CallbackRegistryFixture): # class OpenDaylightFullSyncFixture(fixtures.Fixture): # def patch(self, target, name, *args, **kwargs): # def _setUp(self): # def __init__(self, global_client): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def remock_atexit(self): # def _setUp(self): # def _setUp(self): # def _setUp(self): # def _restore(self): # def _setUp(self): . Output only the next line.
mgr = legacy_port_binding.LegacyPortBindingManager()
Continue the code snippet: <|code_start|> class Env: """ An interface for reinforcement learning environments. :param ob_space: ValType representing the valid observations generated by the environment :param ac_space: ValType representing the valid actions that an agent can take in the environment :param num: number of simultaneous episodes """ <|code_end|> . Use current file imports: from typing import Any, Dict, List, Sequence, Tuple from gym3.types import ValType and context (classes, functions, or code) from other files: # Path: gym3/types.py # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals . Output only the next line.
def __init__(self, ob_space: ValType, ac_space: ValType, num: int):
Using the snippet: <|code_start|> keepalives.append(c_data) keepalives.append(c_option_array) c_options.items = c_option_array c_options.count = len(options) return c_options, keepalives def _maybe_copy_ndarray(self, obj: np.ndarray) -> np.ndarray: """ Copy a single numpy array if reuse_arrays is False, otherwise just return the object """ if self._reuse_arrays: return obj else: return obj.copy() def _maybe_copy_dict(self, obj: Dict[str, Any]) -> Dict[str, Any]: """ Copy a list of dicts of numpy arrays if reuse_arrays is False, otherwise just return the object """ if self._reuse_arrays: return obj else: result = {} for name, arr in obj.items(): result[name] = arr.copy() return result <|code_end|> , determine the next line of code. You have imports: import collections import copy import os import platform import threading import numpy as np from typing import Any, Dict, List, Optional, Sequence, Tuple from cffi import FFI from gym3 import types from gym3.env import Env and context (class names, function names, or code) available: # Path: gym3/types.py # INTEGER_DTYPE_NAMES = set( # ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"] # ) # FLOAT_DTYPE_NAMES = set(["float32", "float64"]) # DTYPE_NAME_TO_MAX_VALUE = {} # DTYPE_NAME_TO_BIT_WIDTH = {} # def pod_equals(x, y): # def __init__(self): # def __init__(self, dtype_name: str = "float32"): # def __repr__(self): # def __str__(self): # def __init__(self, n: int, dtype_name: str = "int64") -> None: # def __repr__(self): # def __str__(self): # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # def ndim(self): # def size(self): # def __repr__(self): # def __str__(self): # def discrete_scalar(n: int) -> TensorType: # def __init__(self, **name2type: ValType) -> None: # def __repr__(self): # def __str__(self): # def __len__(self): # def keys(self): # def values(self): # def items(self): # def __getitem__(self, key): # def __contains__(self, key): # def multimap(f: Callable, *xs: Any) -> Any: # class ScalarType: # class Real(ScalarType): # class Discrete(ScalarType): # class ValType: # class TensorType(ValType): # class DictType(ValType): # # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) . Output only the next line.
def _get_space(self, c_name: Any) -> Tuple[types.DictType, List[Spec]]:
Given the following code snippet before the placeholder: <|code_start|> FFI_CACHE_LOCK = threading.Lock() FFI_CACHE = {} def get_header_dir(): return SCRIPT_DIR def _load_libenv_cdef(): libenv_cdef = "" with open(os.path.join(get_header_dir(), "libenv.h")) as f: inside_cdef = False for line in f: if line.startswith("// BEGIN_CDEF"): inside_cdef = True elif line.startswith("// END_CDEF"): inside_cdef = False elif line.startswith("#if") or line.startswith("#endif"): continue if inside_cdef: line = line.replace("LIBENV_API", "") libenv_cdef += line return libenv_cdef Spec = collections.namedtuple("Spec", ["name", "shape", "dtype"]) <|code_end|> , predict the next line using imports from the current file: import collections import copy import os import platform import threading import numpy as np from typing import Any, Dict, List, Optional, Sequence, Tuple from cffi import FFI from gym3 import types from gym3.env import Env and context including class names, function names, and sometimes code from other files: # Path: gym3/types.py # INTEGER_DTYPE_NAMES = set( # ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"] # ) # FLOAT_DTYPE_NAMES = set(["float32", "float64"]) # DTYPE_NAME_TO_MAX_VALUE = {} # DTYPE_NAME_TO_BIT_WIDTH = {} # def pod_equals(x, y): # def __init__(self): # def __init__(self, dtype_name: str = "float32"): # def __repr__(self): # def __str__(self): # def __init__(self, n: int, dtype_name: str = "int64") -> None: # def __repr__(self): # def __str__(self): # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # def ndim(self): # def size(self): # def __repr__(self): # def __str__(self): # def discrete_scalar(n: int) -> TensorType: # def __init__(self, **name2type: ValType) -> None: # def __repr__(self): # def __str__(self): # def __len__(self): # def keys(self): # def values(self): # def items(self): # def __getitem__(self, key): # def __contains__(self, key): # def multimap(f: Callable, *xs: Any) -> Any: # class ScalarType: # class Real(ScalarType): # class Discrete(ScalarType): # class ValType: # class TensorType(ValType): # class DictType(ValType): # # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) . Output only the next line.
class CEnv(Env):
Given the code snippet: <|code_start|> def _chunk_seq(x: Sequence, sizes: Sequence[int]) -> Sequence[Any]: result = [] assert len(x) == sum(sizes), f"x has incorrect length {len(x)} != {sum(sizes)}" start = 0 for size in sizes: end = start + size result.append(x[start:end]) start = end return result <|code_end|> , generate the next line using the imports in this file: from typing import Any, Dict, List, Sequence, Tuple from gym3.env import Env from gym3.internal import misc from gym3.types_np import concat, split import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) # # Path: gym3/internal/misc.py # def intprod(xs): # def allsame(xs): # # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # """ # Concatenate the (leaf) arrays from xs # # :param xs: list of trees with the same shape, where the leaf values are numpy arrays # :param axis: axis to concatenate along # """ # return multimap(lambda *xs: np.concatenate(xs, axis=axis), *xs) # # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # """ # Split the (leaf) arrays from the tree x # # Examples: # # split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] # split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] # # :param x: a tree where the leaf values are numpy arrays # :param sections: list of indices to split at (not sizes of each split) # # :returns: list of trees with length `len(sections)` with the same shape as x # where each leaf is the corresponding section of the leaf in x # """ # result = [] # start = 0 # for end in sections: # select_tree = multimap(lambda arr: arr[start:end], x) # start = end # result.append(select_tree) # return result . Output only the next line.
class ConcatEnv(Env):
Based on the snippet: <|code_start|> def _chunk_seq(x: Sequence, sizes: Sequence[int]) -> Sequence[Any]: result = [] assert len(x) == sum(sizes), f"x has incorrect length {len(x)} != {sum(sizes)}" start = 0 for size in sizes: end = start + size result.append(x[start:end]) start = end return result class ConcatEnv(Env): """ Concatenate multiple environments into a single environment. :param envs: list of environments to concatenate, must all have the same ac_space and ob_space """ def __init__(self, envs: Sequence[Env]): total_num = sum(env.num for env in envs) super().__init__(envs[0].ob_space, envs[0].ac_space, total_num) <|code_end|> , predict the immediate next line with the help of imports: from typing import Any, Dict, List, Sequence, Tuple from gym3.env import Env from gym3.internal import misc from gym3.types_np import concat, split import numpy as np and context (classes, functions, sometimes code) from other files: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) # # Path: gym3/internal/misc.py # def intprod(xs): # def allsame(xs): # # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # """ # Concatenate the (leaf) arrays from xs # # :param xs: list of trees with the same shape, where the leaf values are numpy arrays # :param axis: axis to concatenate along # """ # return multimap(lambda *xs: np.concatenate(xs, axis=axis), *xs) # # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # """ # Split the (leaf) arrays from the tree x # # Examples: # # split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] # split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] # # :param x: a tree where the leaf values are numpy arrays # :param sections: list of indices to split at (not sizes of each split) # # :returns: list of trees with length `len(sections)` with the same shape as x # where each leaf is the corresponding section of the leaf in x # """ # result = [] # start = 0 # for end in sections: # select_tree = multimap(lambda arr: arr[start:end], x) # start = end # result.append(select_tree) # return result . Output only the next line.
assert misc.allsame([env.ac_space for env in envs])
Predict the next line for this snippet: <|code_start|> def _chunk_seq(x: Sequence, sizes: Sequence[int]) -> Sequence[Any]: result = [] assert len(x) == sum(sizes), f"x has incorrect length {len(x)} != {sum(sizes)}" start = 0 for size in sizes: end = start + size result.append(x[start:end]) start = end return result class ConcatEnv(Env): """ Concatenate multiple environments into a single environment. :param envs: list of environments to concatenate, must all have the same ac_space and ob_space """ def __init__(self, envs: Sequence[Env]): total_num = sum(env.num for env in envs) super().__init__(envs[0].ob_space, envs[0].ac_space, total_num) assert misc.allsame([env.ac_space for env in envs]) assert misc.allsame([env.ob_space for env in envs]) self.envs = envs def observe(self) -> Tuple[Any, Any, Any]: rews, obs, firsts = zip(*[env.observe() for env in self.envs]) <|code_end|> with the help of current file imports: from typing import Any, Dict, List, Sequence, Tuple from gym3.env import Env from gym3.internal import misc from gym3.types_np import concat, split import numpy as np and context from other files: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) # # Path: gym3/internal/misc.py # def intprod(xs): # def allsame(xs): # # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # """ # Concatenate the (leaf) arrays from xs # # :param xs: list of trees with the same shape, where the leaf values are numpy arrays # :param axis: axis to concatenate along # """ # return multimap(lambda *xs: np.concatenate(xs, axis=axis), *xs) # # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # """ # Split the (leaf) arrays from the tree x # # Examples: # # split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] # split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] # # :param x: a tree where the leaf values are numpy arrays # :param sections: list of indices to split at (not sizes of each split) # # :returns: list of trees with length `len(sections)` with the same shape as x # where each leaf is the corresponding section of the leaf in x # """ # result = [] # start = 0 # for end in sections: # select_tree = multimap(lambda arr: arr[start:end], x) # start = end # result.append(select_tree) # return result , which may contain function names, class names, or code. Output only the next line.
return np.concatenate(rews), concat(obs), np.concatenate(firsts)
Using the snippet: <|code_start|> result.append(x[start:end]) start = end return result class ConcatEnv(Env): """ Concatenate multiple environments into a single environment. :param envs: list of environments to concatenate, must all have the same ac_space and ob_space """ def __init__(self, envs: Sequence[Env]): total_num = sum(env.num for env in envs) super().__init__(envs[0].ob_space, envs[0].ac_space, total_num) assert misc.allsame([env.ac_space for env in envs]) assert misc.allsame([env.ob_space for env in envs]) self.envs = envs def observe(self) -> Tuple[Any, Any, Any]: rews, obs, firsts = zip(*[env.observe() for env in self.envs]) return np.concatenate(rews), concat(obs), np.concatenate(firsts) def get_info(self) -> List[Dict]: result = [] for env in self.envs: result.extend(env.get_info()) return result def act(self, ac: Any) -> None: <|code_end|> , determine the next line of code. You have imports: from typing import Any, Dict, List, Sequence, Tuple from gym3.env import Env from gym3.internal import misc from gym3.types_np import concat, split import numpy as np and context (class names, function names, or code) available: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) # # Path: gym3/internal/misc.py # def intprod(xs): # def allsame(xs): # # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # """ # Concatenate the (leaf) arrays from xs # # :param xs: list of trees with the same shape, where the leaf values are numpy arrays # :param axis: axis to concatenate along # """ # return multimap(lambda *xs: np.concatenate(xs, axis=axis), *xs) # # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # """ # Split the (leaf) arrays from the tree x # # Examples: # # split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] # split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] # # :param x: a tree where the leaf values are numpy arrays # :param sections: list of indices to split at (not sizes of each split) # # :returns: list of trees with length `len(sections)` with the same shape as x # where each leaf is the corresponding section of the leaf in x # """ # result = [] # start = 0 # for end in sections: # select_tree = multimap(lambda arr: arr[start:end], x) # start = end # result.append(select_tree) # return result . Output only the next line.
split_ac = split(ac, sections=np.cumsum([env.num for env in self.envs]))
Given the following code snippet before the placeholder: <|code_start|> :param tt: TensorType to get dtype for :returns: torch.dtype to use for tt """ assert isinstance(tt, TensorType) return getattr(th, tt.eltype.dtype_name) def zeros(vt: ValType, bshape: Tuple) -> Any: """ :param vt: ValType to create zeros for :param bshape: batch shape to prepend to the shape of each tensor created by this function :returns: tree of torch tensors matching vt """ return multimap( lambda subdt: th.zeros(bshape + subdt.shape, dtype=dtype(subdt)), vt ) def _sample_tensor(tt: TensorType, bshape: Tuple) -> Any: """ :param tt: TensorType to create sample for :param bshape: batch shape to prepend to the shape of each torch tensor created by this function :returns: torch tensor matching tt """ assert isinstance(tt, TensorType) eltype = tt.eltype shape = bshape + tt.shape <|code_end|> , predict the next line using imports from the current file: from functools import partial from typing import Any, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import torch as th and context including class names, function names, and sometimes code from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
if isinstance(eltype, Discrete):
Based on the snippet: <|code_start|> :returns: torch.dtype to use for tt """ assert isinstance(tt, TensorType) return getattr(th, tt.eltype.dtype_name) def zeros(vt: ValType, bshape: Tuple) -> Any: """ :param vt: ValType to create zeros for :param bshape: batch shape to prepend to the shape of each tensor created by this function :returns: tree of torch tensors matching vt """ return multimap( lambda subdt: th.zeros(bshape + subdt.shape, dtype=dtype(subdt)), vt ) def _sample_tensor(tt: TensorType, bshape: Tuple) -> Any: """ :param tt: TensorType to create sample for :param bshape: batch shape to prepend to the shape of each torch tensor created by this function :returns: torch tensor matching tt """ assert isinstance(tt, TensorType) eltype = tt.eltype shape = bshape + tt.shape if isinstance(eltype, Discrete): return th.randint(0, eltype.n, size=shape, dtype=dtype(tt)) <|code_end|> , predict the immediate next line with the help of imports: from functools import partial from typing import Any, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import torch as th and context (classes, functions, sometimes code) from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
elif isinstance(eltype, Real):
Based on the snippet: <|code_start|> :param dim: dimension to stack along """ return multimap(lambda *xs: th.stack(xs, dim=dim), *xs) def split(x: Any, sections: Sequence[int]) -> Any: """ Split the (leaf) tensors from the tree x Examples: split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] :param x: a tree where the leaf values are torch tensors :param sections: list of indices to split at (not sizes of each split) :returns: list of trees with length `len(sections)` with the same shape as x where each leaf is the corresponding section of the leaf in x """ # split each leaf and select the correct component result = [] start = 0 for end in sections: select_tree = multimap(lambda t: t[start:end], x) start = end result.append(select_tree) return result <|code_end|> , predict the immediate next line with the help of imports: from functools import partial from typing import Any, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import torch as th and context (classes, functions, sometimes code) from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
def dtype(tt: TensorType) -> th.dtype:
Predict the next line after this snippet: <|code_start|> split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] :param x: a tree where the leaf values are torch tensors :param sections: list of indices to split at (not sizes of each split) :returns: list of trees with length `len(sections)` with the same shape as x where each leaf is the corresponding section of the leaf in x """ # split each leaf and select the correct component result = [] start = 0 for end in sections: select_tree = multimap(lambda t: t[start:end], x) start = end result.append(select_tree) return result def dtype(tt: TensorType) -> th.dtype: """ :param tt: TensorType to get dtype for :returns: torch.dtype to use for tt """ assert isinstance(tt, TensorType) return getattr(th, tt.eltype.dtype_name) <|code_end|> using the current file's imports: from functools import partial from typing import Any, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import torch as th and any relevant context from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
def zeros(vt: ValType, bshape: Tuple) -> Any:
Given the code snippet: <|code_start|>""" This is the torch equivalent of the numpy types_np.py This can be used to perform the same operations but on torch tensors instead of numpy arrays. """ def concat(xs: Sequence[Any], dim: int = 0) -> Any: """ Concatenate the (leaf) tensors from xs :param xs: list of trees with the same shape, where the leaf values are torch tensors :param dim: dimension to concatenate along """ <|code_end|> , generate the next line using the imports in this file: from functools import partial from typing import Any, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import torch as th and context (functions, classes, or occasionally code) from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
return multimap(lambda *xs: th.cat(xs, dim=dim), *xs)
Based on the snippet: <|code_start|> def gym3_rollout(e): for _ in range(10): rew, ob, done = e.observe() <|code_end|> , predict the immediate next line with the help of imports: import gym import numpy as np import pytest import gym3 from baselines.common.vec_env import DummyVecEnv from gym3.types_np import multimap, sample, zeros and context (classes, functions, sometimes code) from other files: # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # def stack(xs: Sequence[Any], axis: int = 0) -> Any: # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # def dtype(tt: TensorType) -> np.dtype: # def zeros(vt: ValType, bshape: Tuple) -> Any: # def _sample_tensor( # tt: TensorType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> np.ndarray: # def sample( # vt: ValType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> Any: . Output only the next line.
print(multimap(lambda x: x.shape, ob), rew.shape, done.shape)
Continue the code snippet: <|code_start|> def gym3_rollout(e): for _ in range(10): rew, ob, done = e.observe() print(multimap(lambda x: x.shape, ob), rew.shape, done.shape) <|code_end|> . Use current file imports: import gym import numpy as np import pytest import gym3 from baselines.common.vec_env import DummyVecEnv from gym3.types_np import multimap, sample, zeros and context (classes, functions, or code) from other files: # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # def stack(xs: Sequence[Any], axis: int = 0) -> Any: # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # def dtype(tt: TensorType) -> np.dtype: # def zeros(vt: ValType, bshape: Tuple) -> Any: # def _sample_tensor( # tt: TensorType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> np.ndarray: # def sample( # vt: ValType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> Any: . Output only the next line.
e.act(sample(e.ac_space, (e.num,)))
Given the code snippet: <|code_start|> assert len(obs) == 1 @pytest.mark.parametrize("env_id", ENV_IDS) def test_from_baselines_env(env_id): env_fn = lambda: gym.make(env_id) e = gym3.FromBaselinesVecEnv(DummyVecEnv([env_fn])) gym3_rollout(e) def test_from_procgen_env(): e = gym3.testing.AssertSpacesWrapper(gym3.testing.FixedSequenceEnv(num=3)) gym3_rollout(e) @pytest.mark.parametrize("env_id", ENV_IDS) def test_to_gym_env(env_id): e = gym3.ToGymEnv(gym3.FromGymEnv(gym.make(env_id))) gym_rollout(e) @pytest.mark.parametrize("env_id", ENV_IDS) def test_to_baselines_env(env_id): e = gym3.ToBaselinesVecEnv(gym3.FromGymEnv(gym.make(env_id))) vecenv_rollout(e) def test_vectorize_gym(): env = gym3.vectorize_gym(num=2, env_fn=gym.make, env_kwargs={"id": "Pendulum-v0"}) env.observe() <|code_end|> , generate the next line using the imports in this file: import gym import numpy as np import pytest import gym3 from baselines.common.vec_env import DummyVecEnv from gym3.types_np import multimap, sample, zeros and context (functions, classes, or occasionally code) from other files: # Path: gym3/types_np.py # def concat(xs: Sequence[Any], axis: int = 0) -> Any: # def stack(xs: Sequence[Any], axis: int = 0) -> Any: # def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: # def dtype(tt: TensorType) -> np.dtype: # def zeros(vt: ValType, bshape: Tuple) -> Any: # def _sample_tensor( # tt: TensorType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> np.ndarray: # def sample( # vt: ValType, bshape: Tuple, rng: Optional[np.random.RandomState] = None # ) -> Any: . Output only the next line.
env.act(zeros(env.ac_space, bshape=(env.num,)))
Predict the next line after this snippet: <|code_start|> class AsynchronousWrapper(Wrapper): """ For environments with a synchronous act() function, run act() asynchronously on a separate thread. :param env: environment to wrap """ <|code_end|> using the current file's imports: import concurrent.futures from typing import Any, Dict, List, Tuple from gym3.env import Env from gym3.wrapper import Wrapper and any relevant context from other files: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) # # Path: gym3/wrapper.py # class Wrapper(Env): # """ # An interface for reinforcement learning environments. # # :param env: gym3 environment to wrap # :param ob_space: observation space to use (overrides env's observation space) # :param ac_space: action space to use (overrides env's action space) # """ # # def __init__(self, env, ob_space=None, ac_space=None): # super().__init__(ob_space or env.ob_space, ac_space or env.ac_space, env.num) # self.env = env # # def observe(self) -> Tuple[Any, Any, Any]: # return self.env.observe() # # def get_info(self) -> List[Dict]: # return self.env.get_info() # # def act(self, ac: Any) -> None: # return self.env.act(ac) # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # return self.env.callmethod(method, *args, **kwargs) . Output only the next line.
def __init__(self, env: Env) -> None:
Here is a snippet: <|code_start|> return np.dtype(tt.eltype.dtype_name) def zeros(vt: ValType, bshape: Tuple) -> Any: """ :param vt: ValType to create zeros for :param bshape: batch shape to prepend to the shape of each numpy array created by this function :returns: tree of numpy arrays matching vt """ return multimap( lambda subdt: np.zeros(bshape + subdt.shape, dtype=dtype(subdt)), vt ) def _sample_tensor( tt: TensorType, bshape: Tuple, rng: Optional[np.random.RandomState] = None ) -> np.ndarray: """ :param tt: TensorType to create sample for :param bshape: batch shape to prepend to the shape of each numpy array created by this function :param rng: np.random.RandomState to use for sampling :returns: numpy array matching tt """ if rng is None: rng = np.random assert isinstance(tt, TensorType) eltype = tt.eltype shape = bshape + tt.shape <|code_end|> . Write the next line using the current file imports: from functools import partial from typing import Any, Optional, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import numpy as np and context from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) , which may include functions, classes, or code. Output only the next line.
if isinstance(eltype, Discrete):
Given the code snippet: <|code_start|> def zeros(vt: ValType, bshape: Tuple) -> Any: """ :param vt: ValType to create zeros for :param bshape: batch shape to prepend to the shape of each numpy array created by this function :returns: tree of numpy arrays matching vt """ return multimap( lambda subdt: np.zeros(bshape + subdt.shape, dtype=dtype(subdt)), vt ) def _sample_tensor( tt: TensorType, bshape: Tuple, rng: Optional[np.random.RandomState] = None ) -> np.ndarray: """ :param tt: TensorType to create sample for :param bshape: batch shape to prepend to the shape of each numpy array created by this function :param rng: np.random.RandomState to use for sampling :returns: numpy array matching tt """ if rng is None: rng = np.random assert isinstance(tt, TensorType) eltype = tt.eltype shape = bshape + tt.shape if isinstance(eltype, Discrete): return rng.randint(eltype.n, size=shape, dtype=dtype(tt)) <|code_end|> , generate the next line using the imports in this file: from functools import partial from typing import Any, Optional, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
elif isinstance(eltype, Real):
Using the snippet: <|code_start|> :param xs: list of trees with the same shape, where the leaf values are numpy arrays :param axis: axis to stack along """ return multimap(lambda *xs: np.stack(xs, axis=axis), *xs) def split(x: Any, sections: Sequence[int]) -> Sequence[Any]: """ Split the (leaf) arrays from the tree x Examples: split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] :param x: a tree where the leaf values are numpy arrays :param sections: list of indices to split at (not sizes of each split) :returns: list of trees with length `len(sections)` with the same shape as x where each leaf is the corresponding section of the leaf in x """ result = [] start = 0 for end in sections: select_tree = multimap(lambda arr: arr[start:end], x) start = end result.append(select_tree) return result <|code_end|> , determine the next line of code. You have imports: from functools import partial from typing import Any, Optional, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import numpy as np and context (class names, function names, or code) available: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
def dtype(tt: TensorType) -> np.dtype:
Predict the next line for this snippet: <|code_start|> Examples: split([1,2,3,4], [1,2,3,4]) => [[1], [2], [3], [4]] split([1,2,3,4], [1,3,4]) => [[1], [2, 3], [4]] :param x: a tree where the leaf values are numpy arrays :param sections: list of indices to split at (not sizes of each split) :returns: list of trees with length `len(sections)` with the same shape as x where each leaf is the corresponding section of the leaf in x """ result = [] start = 0 for end in sections: select_tree = multimap(lambda arr: arr[start:end], x) start = end result.append(select_tree) return result def dtype(tt: TensorType) -> np.dtype: """ :param tt: TensorType to get dtype for :returns: numpy.dtype to use for tt """ assert isinstance(tt, TensorType) return np.dtype(tt.eltype.dtype_name) <|code_end|> with the help of current file imports: from functools import partial from typing import Any, Optional, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import numpy as np and context from other files: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) , which may contain function names, class names, or code. Output only the next line.
def zeros(vt: ValType, bshape: Tuple) -> Any:
Using the snippet: <|code_start|> def concat(xs: Sequence[Any], axis: int = 0) -> Any: """ Concatenate the (leaf) arrays from xs :param xs: list of trees with the same shape, where the leaf values are numpy arrays :param axis: axis to concatenate along """ <|code_end|> , determine the next line of code. You have imports: from functools import partial from typing import Any, Optional, Sequence, Tuple from gym3.types import Discrete, Real, TensorType, ValType, multimap import numpy as np and context (class names, function names, or code) available: # Path: gym3/types.py # class Discrete(ScalarType): # """ # A scalar that can represent discrete (integer) values # # :param n: number of discrete values that this scalar can assume, which are required to be in the range [0, n) # :param bit_width: number of bits for the integer dtype that will be used to store values # :param signed: Set to False to use an unsigned integer type # """ # # def __init__(self, n: int, dtype_name: str = "int64") -> None: # self.n = int(n) # self.dtype_name = dtype_name # assert self.dtype_name in INTEGER_DTYPE_NAMES # max_value = DTYPE_NAME_TO_MAX_VALUE[self.dtype_name] # assert ( # n <= max_value + 1 # ), f"{n} cannot be greater than {max_value + 1} for dtype_name={dtype_name}" # # def __repr__(self): # return f"<Discrete: {self}>" # # def __str__(self): # return f"D{self.n}" # # class Real(ScalarType): # """ # A scalar that can represent continuous values # """ # # def __init__(self, dtype_name: str = "float32"): # self.dtype_name = dtype_name # # def __repr__(self): # return "<Real>" # # def __str__(self): # return "R" # # class TensorType(ValType): # """ # A tensor value type # # :param eltype: instance of ScalarType subclass that represents the types of values in this tensor # :param shape: shape of the tensor as a tuple of ints # """ # # def __init__(self, eltype: ScalarType, shape: Tuple) -> None: # assert isinstance(shape, tuple) # self.eltype = eltype # self.shape = shape # # @property # def ndim(self): # """ # Number of dimensions of the tensor # """ # return len(self.shape) # # @property # def size(self): # """ # Number of elements of the tensor # """ # return int(misc.intprod(self.shape)) # # def __repr__(self): # return f"<TensorType: {self}>" # # def __str__(self): # shape_str = ",".join(map(str, self.shape)) # return f"{self.eltype}[{shape_str}]" # # class ValType: # """ # Tensor or combination of tensors # """ # # __eq__ = pod_equals # # def multimap(f: Callable, *xs: Any) -> Any: # """ # Apply f at each leaf of the list of trees # # A tree is: # * a (possibly nested) dict # * a (possibly nested) DictType # * any other object (a leaf value) # # `{"a": 1}`, `{"a": {"b": 2}}`, and `3` are all valid trees, where the leaf values # are the integers # # :param f: function to call at each leaf, must take len(xs) arguments # :param xs: a list of trees, all with the same structure # # :returns: A tree of the same structure, where each leaf contains f's return value. # """ # first = xs[0] # if isinstance(first, dict) or isinstance(first, DictType): # assert all(isinstance(x, dict) or isinstance(x, DictType) for x in xs) # assert all(sorted(x.keys()) == sorted(first.keys()) for x in xs) # return {k: multimap(f, *(x[k] for x in xs)) for k in sorted(first.keys())} # else: # return f(*xs) . Output only the next line.
return multimap(lambda *xs: np.concatenate(xs, axis=axis), *xs)
Predict the next line for this snippet: <|code_start|> """ __eq__ = pod_equals class TensorType(ValType): """ A tensor value type :param eltype: instance of ScalarType subclass that represents the types of values in this tensor :param shape: shape of the tensor as a tuple of ints """ def __init__(self, eltype: ScalarType, shape: Tuple) -> None: assert isinstance(shape, tuple) self.eltype = eltype self.shape = shape @property def ndim(self): """ Number of dimensions of the tensor """ return len(self.shape) @property def size(self): """ Number of elements of the tensor """ <|code_end|> with the help of current file imports: from typing import Any, Callable, Tuple from gym3.internal import misc and context from other files: # Path: gym3/internal/misc.py # def intprod(xs): # def allsame(xs): , which may contain function names, class names, or code. Output only the next line.
return int(misc.intprod(self.shape))
Continue the code snippet: <|code_start|> _clear_lock = threading.Lock() CODECS = {"pickle": (pickle.dumps, pickle.loads)} try: except ImportError: pass else: CODECS["cloudpickle"] = (cloudpickle.dumps, cloudpickle.loads) class SubprocError(Exception): pass <|code_end|> . Use current file imports: import contextlib import multiprocessing as mp import os import pickle import threading import traceback import cloudpickle from typing import Any, Dict, List, Sequence, Tuple from gym3.env import Env and context (classes, functions, or code) from other files: # Path: gym3/env.py # class Env: # """ # An interface for reinforcement learning environments. # # :param ob_space: ValType representing the valid observations generated by the environment # :param ac_space: ValType representing the valid actions that an agent can take in the environment # :param num: number of simultaneous episodes # """ # # def __init__(self, ob_space: ValType, ac_space: ValType, num: int): # self.ob_space = ob_space # self.ac_space = ac_space # self.num = num # # def observe(self) -> Tuple[Any, Any, Any]: # """ # Structured data that's accessible to the agent # # Can be called zero or more times per act() call; it is idempotent and does # not affect the environment. Returns the observation after the last act() # call has affected the environment or the initial state if no act() # call has been made. # # The following snippet shows what the start of a rollout looks like, and # the usual convention for indexing the values: # # env = Env() # # initial reward is ignored; didn't depend on actions # _reward, ob_0, first_0 = env.observe() # env.act(ac_0) # reward_0, ob_1, first_1 = env.observe() # env.act(ac_1) # # Note that the initial reward `_reward` is ignored by algorithms, since it # didn't depend on the actions. And that first_0 is always True since the # environment was just created. # # :returns: # reward: (float array) last reward, shaped (num,) # ob: observation matching ob_space, with (num,) prepended to the shape of each leaf # first: (bool array) whether new episode just started, shaped (num,) # """ # raise NotImplementedError # # def get_info(self) -> List[Dict]: # """ # Return unstructured diagnostics that aren't accessible to the agent # Per-episode stats, rendered images, etc. # Corresponds to same timestep as the observation from observe(). # # :returns: a list of dictionaries with length `self.num` # """ # return [{} for _ in range(self.num)] # # def act(self, ac: Any) -> None: # """ # Apply an action # # :param ac: action matching ac_space, with (num,) prepended to the shape of each leaf # """ # raise NotImplementedError # # def callmethod( # self, method: str, *args: Sequence[Any], **kwargs: Sequence[Any] # ) -> List[Any]: # """ # Call a method on the underlying python object that offers the Gym3 interface. # By default, this is the Env instance (self), but this can be overridden if you are # encapsulating another object or if your wrapper wishes to handle the method call. # # :param method: name of method to call on the base object # :param *args, **kwargs: the value of each argument must be a list with length equal to `self.num` # # :returns: A list of objects, with length equal to `self.num` # """ # return getattr(self, method)(*args, **kwargs) . Output only the next line.
class SubprocEnv(Env):
Based on the snippet: <|code_start|> def run_test_with_mpi(fn_path, kwargs=None, nproc=2, timeout=30): if kwargs is None: kwargs = {} serialized_fn = base64.b64encode(pickle.dumps((fn_path, kwargs))) subprocess.check_call( [ "mpiexec", "-n", str(nproc), sys.executable, "-m", "gym3.internal.test_with_mpi", serialized_fn, ], env=os.environ, timeout=timeout, ) if __name__ == "__main__": fn_path, kwargs = pickle.loads(base64.b64decode(sys.argv[1])) <|code_end|> , predict the immediate next line with the help of imports: import base64 import os import pickle import subprocess import sys from gym3.util import call_func and context (classes, functions, sometimes code) from other files: # Path: gym3/util.py # def call_func(fn_path, **kwargs): # """ # Look up a function for a function path, e.g. fn_path='gym3:call_func' will # return this function, then call it with the specified kwargs. # """ # assert isinstance(fn_path, str) # module_path, fn_name = fn_path.split(":") # module = importlib.import_module(module_path) # return getattr(module, fn_name)(**kwargs) . Output only the next line.
call_func(fn_path, **kwargs)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- logger = logging.getLogger(__name__) report_bp = Blueprint('report', __name__, template_folder='templates', static_folder='static', static_url_path='/static/report') @report_bp.route('/genes/<gene_id>') def gene(gene_id): """Display coverage information on a gene.""" sample_ids = request.args.getlist('sample_id') sample_dict = map_samples(sample_ids=sample_ids) matching_tx = Transcript.filter_by(gene_id=gene_id).first() if matching_tx is None: return abort(404, "gene not found: {}".format(gene_id)) gene_name = matching_tx.gene_name <|code_end|> , predict the next line using imports from the current file: import logging from chanjo.store.models import Transcript, TranscriptStat, Sample from flask import abort, Blueprint, render_template, request, url_for from flask_weasyprint import render_pdf from chanjo_report.server.extensions import api from chanjo_report.server.constants import LEVELS from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples, transcript_coverage) and context including class names, function names, and sometimes code from other files: # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) # # Path: chanjo_report/server/blueprints/report/utils.py # def samplesex_rows(sample_ids): # """Generate sex prediction info rows.""" # sex_query = (api.query( # TranscriptStat.sample_id, # Transcript.chromosome, # func.avg(TranscriptStat.mean_coverage) # ).join( # TranscriptStat.transcript # ).filter( # Transcript.chromosome.in_(['X', 'Y']), # TranscriptStat.sample_id.in_(sample_ids) # ).group_by( # TranscriptStat.sample_id, # Transcript.chromosome # )) # # samples = itertools.groupby(sex_query, lambda row: row[0]) # for sample_id, chromosomes in samples: # chr_coverage = [coverage for _, _, coverage in chromosomes] # LOG.debug('predicting sex') # predicted_sex = predict_sex(*chr_coverage) # sample_obj = Sample.query.get(sample_id) # sample_row = { # 'sample': sample_obj.name or sample_obj.id, # 'group': sample_obj.group_name, # 'analysis_date': sample_obj.created_at, # 'sex': predicted_sex, # 'x_coverage': chr_coverage[0], # 'y_coverage': chr_coverage[1], # } # yield sample_row # # def keymetrics_rows(samples_ids, genes=None): # """Generate key metrics rows.""" # query = ( # api.query( # TranscriptStat, # func.avg(TranscriptStat.mean_coverage).label('mean_coverage'), # func.avg(TranscriptStat.completeness_10).label('completeness_10'), # func.avg(TranscriptStat.completeness_15).label('completeness_15'), # func.avg(TranscriptStat.completeness_20).label('completeness_20'), # func.avg(TranscriptStat.completeness_50).label('completeness_50'), # func.avg(TranscriptStat.completeness_100).label('completeness_100'), # ) # .filter(TranscriptStat.sample_id.in_(samples_ids)) # .group_by(TranscriptStat.sample_id) # ) # # if genes: # query = (query.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # return query # # def transcripts_rows(sample_ids, genes=None, level=10): # """Generate metrics rows for transcripts.""" # for sample_id in sample_ids: # sample_obj = Sample.query.get(sample_id) # all_tx = TranscriptStat.query.filter_by(sample_id=sample_id) # if genes: # all_tx = (all_tx.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # tx_count = all_tx.count() # stat_field = getattr(TranscriptStat, LEVELS[level]) # missed_tx = all_tx.filter(stat_field < 100) # missed_count = missed_tx.count() # if tx_count == 0: # tx_yield = 0 # flash("no matching transcripts found!") # else: # tx_yield = 100 - (missed_count / tx_count * 100) # yield { # 'sample': sample_obj, # 'yield': tx_yield, # 'missed': missed_tx, # 'missed_count': missed_count, # 'total': tx_count, # } # # def map_samples(group_id=None, sample_ids=None): # if group_id: # query = Sample.query.filter(Sample.group_id == group_id) # elif sample_ids: # query = Sample.query.filter(Sample.id.in_(sample_ids)) # else: # query = Sample.query # try: # samples = {sample_obj.id: sample_obj for sample_obj in query} # return samples # except OperationalError as error: # LOG.exception(error) # api.session.rollback() # return abort(500, 'MySQL error, try again') # # def transcript_coverage(api, gene_id, *sample_ids): # """Return coverage metrics per transcript for a given gene.""" # query = (api.query(TranscriptStat) # .join(TranscriptStat.transcript) # .filter(Transcript.gene_id == gene_id) # .order_by(TranscriptStat.transcript_id, # TranscriptStat.sample_id)) # if sample_ids: # query = query.filter(TranscriptStat.sample_id.in_(sample_ids)) # # tx_groups = itertools.groupby(query, key=lambda tx: tx.transcript_id) # return tx_groups . Output only the next line.
tx_groups = transcript_coverage(api, gene_id, *sample_ids)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- logger = logging.getLogger(__name__) report_bp = Blueprint('report', __name__, template_folder='templates', static_folder='static', static_url_path='/static/report') @report_bp.route('/genes/<gene_id>') def gene(gene_id): """Display coverage information on a gene.""" sample_ids = request.args.getlist('sample_id') <|code_end|> . Write the next line using the current file imports: import logging from chanjo.store.models import Transcript, TranscriptStat, Sample from flask import abort, Blueprint, render_template, request, url_for from flask_weasyprint import render_pdf from chanjo_report.server.extensions import api from chanjo_report.server.constants import LEVELS from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples, transcript_coverage) and context from other files: # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) # # Path: chanjo_report/server/blueprints/report/utils.py # def samplesex_rows(sample_ids): # """Generate sex prediction info rows.""" # sex_query = (api.query( # TranscriptStat.sample_id, # Transcript.chromosome, # func.avg(TranscriptStat.mean_coverage) # ).join( # TranscriptStat.transcript # ).filter( # Transcript.chromosome.in_(['X', 'Y']), # TranscriptStat.sample_id.in_(sample_ids) # ).group_by( # TranscriptStat.sample_id, # Transcript.chromosome # )) # # samples = itertools.groupby(sex_query, lambda row: row[0]) # for sample_id, chromosomes in samples: # chr_coverage = [coverage for _, _, coverage in chromosomes] # LOG.debug('predicting sex') # predicted_sex = predict_sex(*chr_coverage) # sample_obj = Sample.query.get(sample_id) # sample_row = { # 'sample': sample_obj.name or sample_obj.id, # 'group': sample_obj.group_name, # 'analysis_date': sample_obj.created_at, # 'sex': predicted_sex, # 'x_coverage': chr_coverage[0], # 'y_coverage': chr_coverage[1], # } # yield sample_row # # def keymetrics_rows(samples_ids, genes=None): # """Generate key metrics rows.""" # query = ( # api.query( # TranscriptStat, # func.avg(TranscriptStat.mean_coverage).label('mean_coverage'), # func.avg(TranscriptStat.completeness_10).label('completeness_10'), # func.avg(TranscriptStat.completeness_15).label('completeness_15'), # func.avg(TranscriptStat.completeness_20).label('completeness_20'), # func.avg(TranscriptStat.completeness_50).label('completeness_50'), # func.avg(TranscriptStat.completeness_100).label('completeness_100'), # ) # .filter(TranscriptStat.sample_id.in_(samples_ids)) # .group_by(TranscriptStat.sample_id) # ) # # if genes: # query = (query.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # return query # # def transcripts_rows(sample_ids, genes=None, level=10): # """Generate metrics rows for transcripts.""" # for sample_id in sample_ids: # sample_obj = Sample.query.get(sample_id) # all_tx = TranscriptStat.query.filter_by(sample_id=sample_id) # if genes: # all_tx = (all_tx.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # tx_count = all_tx.count() # stat_field = getattr(TranscriptStat, LEVELS[level]) # missed_tx = all_tx.filter(stat_field < 100) # missed_count = missed_tx.count() # if tx_count == 0: # tx_yield = 0 # flash("no matching transcripts found!") # else: # tx_yield = 100 - (missed_count / tx_count * 100) # yield { # 'sample': sample_obj, # 'yield': tx_yield, # 'missed': missed_tx, # 'missed_count': missed_count, # 'total': tx_count, # } # # def map_samples(group_id=None, sample_ids=None): # if group_id: # query = Sample.query.filter(Sample.group_id == group_id) # elif sample_ids: # query = Sample.query.filter(Sample.id.in_(sample_ids)) # else: # query = Sample.query # try: # samples = {sample_obj.id: sample_obj for sample_obj in query} # return samples # except OperationalError as error: # LOG.exception(error) # api.session.rollback() # return abort(500, 'MySQL error, try again') # # def transcript_coverage(api, gene_id, *sample_ids): # """Return coverage metrics per transcript for a given gene.""" # query = (api.query(TranscriptStat) # .join(TranscriptStat.transcript) # .filter(Transcript.gene_id == gene_id) # .order_by(TranscriptStat.transcript_id, # TranscriptStat.sample_id)) # if sample_ids: # query = query.filter(TranscriptStat.sample_id.in_(sample_ids)) # # tx_groups = itertools.groupby(query, key=lambda tx: tx.transcript_id) # return tx_groups , which may include functions, classes, or code. Output only the next line.
sample_dict = map_samples(sample_ids=sample_ids)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- logger = logging.getLogger(__name__) report_bp = Blueprint('report', __name__, template_folder='templates', static_folder='static', static_url_path='/static/report') @report_bp.route('/genes/<gene_id>') def gene(gene_id): """Display coverage information on a gene.""" sample_ids = request.args.getlist('sample_id') sample_dict = map_samples(sample_ids=sample_ids) matching_tx = Transcript.filter_by(gene_id=gene_id).first() if matching_tx is None: return abort(404, "gene not found: {}".format(gene_id)) gene_name = matching_tx.gene_name <|code_end|> , generate the next line using the imports in this file: import logging from chanjo.store.models import Transcript, TranscriptStat, Sample from flask import abort, Blueprint, render_template, request, url_for from flask_weasyprint import render_pdf from chanjo_report.server.extensions import api from chanjo_report.server.constants import LEVELS from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples, transcript_coverage) and context (functions, classes, or occasionally code) from other files: # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) # # Path: chanjo_report/server/blueprints/report/utils.py # def samplesex_rows(sample_ids): # """Generate sex prediction info rows.""" # sex_query = (api.query( # TranscriptStat.sample_id, # Transcript.chromosome, # func.avg(TranscriptStat.mean_coverage) # ).join( # TranscriptStat.transcript # ).filter( # Transcript.chromosome.in_(['X', 'Y']), # TranscriptStat.sample_id.in_(sample_ids) # ).group_by( # TranscriptStat.sample_id, # Transcript.chromosome # )) # # samples = itertools.groupby(sex_query, lambda row: row[0]) # for sample_id, chromosomes in samples: # chr_coverage = [coverage for _, _, coverage in chromosomes] # LOG.debug('predicting sex') # predicted_sex = predict_sex(*chr_coverage) # sample_obj = Sample.query.get(sample_id) # sample_row = { # 'sample': sample_obj.name or sample_obj.id, # 'group': sample_obj.group_name, # 'analysis_date': sample_obj.created_at, # 'sex': predicted_sex, # 'x_coverage': chr_coverage[0], # 'y_coverage': chr_coverage[1], # } # yield sample_row # # def keymetrics_rows(samples_ids, genes=None): # """Generate key metrics rows.""" # query = ( # api.query( # TranscriptStat, # func.avg(TranscriptStat.mean_coverage).label('mean_coverage'), # func.avg(TranscriptStat.completeness_10).label('completeness_10'), # func.avg(TranscriptStat.completeness_15).label('completeness_15'), # func.avg(TranscriptStat.completeness_20).label('completeness_20'), # func.avg(TranscriptStat.completeness_50).label('completeness_50'), # func.avg(TranscriptStat.completeness_100).label('completeness_100'), # ) # .filter(TranscriptStat.sample_id.in_(samples_ids)) # .group_by(TranscriptStat.sample_id) # ) # # if genes: # query = (query.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # return query # # def transcripts_rows(sample_ids, genes=None, level=10): # """Generate metrics rows for transcripts.""" # for sample_id in sample_ids: # sample_obj = Sample.query.get(sample_id) # all_tx = TranscriptStat.query.filter_by(sample_id=sample_id) # if genes: # all_tx = (all_tx.join(TranscriptStat.transcript) # .filter(Transcript.gene_id.in_(genes))) # tx_count = all_tx.count() # stat_field = getattr(TranscriptStat, LEVELS[level]) # missed_tx = all_tx.filter(stat_field < 100) # missed_count = missed_tx.count() # if tx_count == 0: # tx_yield = 0 # flash("no matching transcripts found!") # else: # tx_yield = 100 - (missed_count / tx_count * 100) # yield { # 'sample': sample_obj, # 'yield': tx_yield, # 'missed': missed_tx, # 'missed_count': missed_count, # 'total': tx_count, # } # # def map_samples(group_id=None, sample_ids=None): # if group_id: # query = Sample.query.filter(Sample.group_id == group_id) # elif sample_ids: # query = Sample.query.filter(Sample.id.in_(sample_ids)) # else: # query = Sample.query # try: # samples = {sample_obj.id: sample_obj for sample_obj in query} # return samples # except OperationalError as error: # LOG.exception(error) # api.session.rollback() # return abort(500, 'MySQL error, try again') # # def transcript_coverage(api, gene_id, *sample_ids): # """Return coverage metrics per transcript for a given gene.""" # query = (api.query(TranscriptStat) # .join(TranscriptStat.transcript) # .filter(Transcript.gene_id == gene_id) # .order_by(TranscriptStat.transcript_id, # TranscriptStat.sample_id)) # if sample_ids: # query = query.filter(TranscriptStat.sample_id.in_(sample_ids)) # # tx_groups = itertools.groupby(query, key=lambda tx: tx.transcript_id) # return tx_groups . Output only the next line.
tx_groups = transcript_coverage(api, gene_id, *sample_ids)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- def create_app(config=None): """Create a Flask app (Flask Application Factory).""" app = Flask(__name__, instance_relative_config=True) configure_app(app, config=config) configure_extensions(app) configure_blueprints(app) configure_template_filters(app) return app def configure_app(app, config=None, config_file=None): """Configure app in different ways.""" # http://flask.pocoo.org/docs/api/#configuration <|code_end|> , predict the immediate next line with the help of imports: from flask import current_app, Flask, request from flask_babel import Babel from .config import DefaultConfig from .extensions import api from .utils import pretty_date from .constants import LEVELS and context (classes, functions, sometimes code) from other files: # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} # # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/utils.py # def pretty_date(date, default=None): # """Return string representing "time since": 3 days ago, 5 hours ago. # # Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/ # """ # if default is None: # default = 'just now' # # now = datetime.utcnow() # diff = now - date # # periods = ((diff.days / 365, 'year', 'years'), # (diff.days / 30, 'month', 'months'), # (diff.days / 7, 'week', 'weeks'), # (diff.days, 'day', 'days'), # (diff.seconds / 3600, 'hour', 'hours'), # (diff.seconds / 60, 'minute', 'minutes'), # (diff.seconds, 'second', 'seconds')) # # for period, singular, plural in periods: # if not period: # continue # if period == 1: # return "%d %s ago" % (period, singular) # else: # return "%d %s ago" % (period, plural) # return default # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) . Output only the next line.
app.config.from_object(DefaultConfig)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- def create_app(config=None): """Create a Flask app (Flask Application Factory).""" app = Flask(__name__, instance_relative_config=True) configure_app(app, config=config) configure_extensions(app) configure_blueprints(app) configure_template_filters(app) return app def configure_app(app, config=None, config_file=None): """Configure app in different ways.""" # http://flask.pocoo.org/docs/api/#configuration app.config.from_object(DefaultConfig) if config: app.config.from_object(config) def configure_extensions(app): """Initialize Flask extensions.""" <|code_end|> , determine the next line of code. You have imports: from flask import current_app, Flask, request from flask_babel import Babel from .config import DefaultConfig from .extensions import api from .utils import pretty_date from .constants import LEVELS and context (class names, function names, or code) available: # Path: chanjo_report/server/config.py # class DefaultConfig(BaseConfig): # # """Default config values during development.""" # # DEBUG = True # ACCEPT_LANGUAGES = {'en': 'English', 'sv': 'Svenska'} # # Path: chanjo_report/server/extensions.py # # Path: chanjo_report/server/utils.py # def pretty_date(date, default=None): # """Return string representing "time since": 3 days ago, 5 hours ago. # # Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/ # """ # if default is None: # default = 'just now' # # now = datetime.utcnow() # diff = now - date # # periods = ((diff.days / 365, 'year', 'years'), # (diff.days / 30, 'month', 'months'), # (diff.days / 7, 'week', 'weeks'), # (diff.days, 'day', 'days'), # (diff.seconds / 3600, 'hour', 'hours'), # (diff.seconds / 60, 'minute', 'minutes'), # (diff.seconds, 'second', 'seconds')) # # for period, singular, plural in periods: # if not period: # continue # if period == 1: # return "%d %s ago" % (period, singular) # else: # return "%d %s ago" % (period, plural) # return default # # Path: chanjo_report/server/constants.py # LEVELS = OrderedDict([ # (10, 'completeness_10'), # (15, 'completeness_15'), # (20, 'completeness_20'), # (50, 'completeness_50'), # (100, 'completeness_100'), # ]) . Output only the next line.
api.init_app(app)