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_Ex...
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 #----------------------------------------- #...
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 co...
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...
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 ...
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.mo...
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: ...
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( ...
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...
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 ...
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...
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 re...
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, me...
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 langua...
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.Fake...
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 dist...
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 permissi...
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_...
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 ...
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....
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(...
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/licens...
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 ag...
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/licens...
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...
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: {}, ...
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/...
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...
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 ...
_("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: ...
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() su...
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 permissi...
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(se...
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...
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 permissio...
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 applicabl...
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/li...
@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]) ...
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 distrib...
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/li...
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 CONDITIO...
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=phy...
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 # distrib...
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/li...
@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. IGNO...
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 th...
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 # # h...
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.o...
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 actu...
(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.se...
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 lang...
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....
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 # # Unl...
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 bas...
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/...
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 # # Unle...
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 ...
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 # # ...
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 se...
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_handle...
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(ba...
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....
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 'featur...
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: LO...
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 permis...
@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 ...
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 ...
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', ...
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. ...
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.o...
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 TestLegacyPortBind...
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 ...
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: """ Co...
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 l...
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]) st...
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]) star...
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:e...
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...
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: Val...
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...
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]...
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) :retu...
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: l...
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 im...
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_e...
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.AssertSp...
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 concurre...
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 v...
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( ...
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)...
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)...
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 ...
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 """ ...
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: i...
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), ...
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_i...
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...
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): """Di...
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_t...
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_temp...
api.init_app(app)