Add a scenario to a specified network.
545938
def add_scenario(network_id, scenario,**kwargs):
    
    user_id = int(kwargs.get('user_id'))
    log.info("Adding scenarios to network")

    _check_network_ownership(network_id, user_id)

    existing_scen = db.DBSession.query(Scenario).filter(Scenario.name==scenario.name, Scenario.network_id==network_id).first()
    if existing_scen is not None:
        raise HydraError("Scenario with name %s already exists in network %s"%(scenario.name, network_id))

    scen = Scenario()
    scen.name                 = scenario.name
    scen.description          = scenario.description
    scen.layout               = scenario.get_layout()
    scen.network_id           = network_id
    scen.created_by           = user_id
    scen.start_time           = str(timestamp_to_ordinal(scenario.start_time)) if scenario.start_time else None
    scen.end_time             = str(timestamp_to_ordinal(scenario.end_time)) if scenario.end_time else None
    scen.time_step            = scenario.time_step
    scen.resourcescenarios    = []
    scen.resourcegroupitems   = []

    #Just in case someone puts in a negative ID for the scenario.
    if scenario.id < 0:
        scenario.id = None

    if scenario.resourcescenarios is not None:
        #extract the data from each resourcescenario so it can all be
        #inserted in one go, rather than one at a time
        all_data = [r.dataset for r in scenario.resourcescenarios]

        datasets = data._bulk_insert_data(all_data, user_id=user_id)

        #record all the resource attribute ids
        resource_attr_ids = [r.resource_attr_id for r in scenario.resourcescenarios]

        #get all the resource scenarios into a list and bulk insert them
        for i, ra_id in enumerate(resource_attr_ids):
            rs_i = ResourceScenario()
            rs_i.resource_attr_id = ra_id
            rs_i.dataset_id       = datasets[i].id
            rs_i.scenario_id      = scen.id
            rs_i.dataset = datasets[i]
            scen.resourcescenarios.append(rs_i)

    if scenario.resourcegroupitems is not None:
        #Again doing bulk insert.
        for group_item in scenario.resourcegroupitems:
            group_item_i = ResourceGroupItem()
            group_item_i.scenario_id = scen.id
            group_item_i.group_id    = group_item.group_id
            group_item_i.ref_key     = group_item.ref_key
            if group_item.ref_key == 'NODE':
                group_item_i.node_id      = group_item.ref_id
            elif group_item.ref_key == 'LINK':
                group_item_i.link_id      = group_item.ref_id
            elif group_item.ref_key == 'GROUP':
                group_item_i.subgroup_id  = group_item.ref_id
            scen.resourcegroupitems.append(group_item_i)
    db.DBSession.add(scen)
    db.DBSession.flush()
    return scen
322440
public Observable<LifecycleState> addNode(final NetworkAddress hostname, final NetworkAddress alternate) {
        Node node = nodeBy(hostname);
        if (node != null) {
            LOGGER.debug("Node {} already registered, skipping.", hostname);
            return Observable.just(node.state());
        }
        return addNode(new CouchbaseNode(hostname, ctx, alternate));
    }
59623
def create_network_postcommit(self, context):
        """"""
        network = context.current

        log_context("create_network_postcommit: network", network)

        segments = context.network_segments
        tenant_id = network['project_id']
        self.create_tenant(tenant_id)
        self.create_network(network)
        self.create_segments(segments)
1225803
def add(setname=None, entry=None, family='ipv4', **kwargs):
    '''
    

    '''
    if not setname:
        return 'Error: Set needs to be specified'
    if not entry:
        return 'Error: Entry needs to be specified'

    setinfo = _find_set_info(setname)
    if not setinfo:
        return 'Error: Set {0} does not exist'.format(setname)

    settype = setinfo['Type']

    cmd = '{0}'.format(entry)

    if 'timeout' in kwargs:
        if 'timeout' not in setinfo['Header']:
            return 'Error: Set {0} not created with timeout support'.format(setname)

    if 'packets' in kwargs or 'bytes' in kwargs:
        if 'counters' not in setinfo['Header']:
            return 'Error: Set {0} not created with counters support'.format(setname)

    if 'comment' in kwargs:
        if 'comment' not in setinfo['Header']:
            return 'Error: Set {0} not created with comment support'.format(setname)
        if 'comment' not in entry:
            cmd = '{0} comment "{1}"'.format(cmd, kwargs['comment'])

    if set(['skbmark', 'skbprio', 'skbqueue']) & set(kwargs):
        if 'skbinfo' not in setinfo['Header']:
            return 'Error: Set {0} not created with skbinfo support'.format(setname)

    for item in _ADD_OPTIONS[settype]:
        if item in kwargs:
            cmd = '{0} {1} {2}'.format(cmd, item, kwargs[item])

    current_members = _find_set_members(setname)
    if cmd in current_members:
        return 'Warn: Entry {0} already exists in set {1}'.format(cmd, setname)

    # Using -exist to ensure entries are updated if the comment changes
    cmd = '{0} add -exist {1} {2}'.format(_ipset_cmd(), setname, cmd)
    out = __salt__['cmd.run'](cmd, python_shell=False)

    if not out:
        return 'Success'
    return 'Error: {0}'.format(out)
592873
def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs):

    
    user_id = int(kwargs.get('user_id'))

    if scenario is None:
        scenario = _get_scenario(scenario_id, user_id)

    _check_network_ownership(scenario.network_id, user_id)

    newitems = []
    for group_item in items:
        group_item_i = _add_resourcegroupitem(group_item, scenario.id)
        newitems.append(group_item_i)

    db.DBSession.flush()

    return newitems
632227
def append(self, network):
        
        arr = network.to_array(self.hg.mappings)
        if len(self.__matrix):
            self.__matrix = np.append(self.__matrix, [arr], axis=0)
            self.__networks = np.append(self.__networks, network.networks)
        else:
            self.__matrix = np.array([arr])
            self.__networks = np.array([network.networks])
331599
def add_node(self, node):
        """"""
        nodes = [n for n in self.nodes() if not isinstance(n, Source)]
        num_agents = len(nodes)
        curr_generation = int((num_agents - 1) / float(self.generation_size))
        node.generation = curr_generation

        if curr_generation == 0:
            if self.initial_source:
                source = min(
                    self.nodes(type=Source),
                    key=attrgetter('creation_time'))
                source.connect(whom=node)
                source.transmit(to_whom=node)
        else:
            prev_agents = Node.query\
                .filter_by(failed=False,
                           network_id=self.id,
                           generation=(curr_generation - 1))\
                .all()
            prev_fits = [p.fitness for p in prev_agents]
            prev_probs = [(f / (1.0 * sum(prev_fits))) for f in prev_fits]

            rnd = random.random()
            temp = 0.0
            for i, probability in enumerate(prev_probs):
                temp += probability
                if temp > rnd:
                    parent = prev_agents[i]
                    break

            parent.connect(whom=node)
            parent.transmit(to_whom=node)
1191230
def network(name, options = {}, provider = nil)
    plugin(:CORL, :network, provider, Config.ensure(options).import({ :name => name }))
  end
319372
public void addScenario(Class<? extends Scenario> scenarioClass,
            String scenarioID, String initialState, Properties properties,
            String gatewayDeviceID, String externalLinkID)
            throws ShanksException {
        // throws NonGatewayDeviceException, TooManyConnectionException,
        // DuplicatedIDException, AlreadyConnectedScenarioException,
        // SecurityException, NoSuchMethodException, IllegalArgumentException,
        // InstantiationException, IllegalAccessException,
        // InvocationTargetException {
        Constructor<? extends Scenario> c;
        Scenario scenario;
        try {
            c = scenarioClass.getConstructor(new Class[] { String.class,
                    String.class, Properties.class, Logger.class });
            scenario = c.newInstance(scenarioID, initialState, properties, this.getLogger());
        } catch (SecurityException e) {
            throw new ShanksException(e);
        } catch (NoSuchMethodException e) {
            throw new ShanksException(e);
        } catch (IllegalArgumentException e) {
            throw new ShanksException(e);
        } catch (InstantiationException e) {
            throw new ShanksException(e);
        } catch (IllegalAccessException e) {
            throw new ShanksException(e);
        } catch (InvocationTargetException e) {
            throw new ShanksException(e);
        }

        Device gateway = (Device) scenario.getNetworkElement(gatewayDeviceID);
        Link externalLink = (Link) this.getNetworkElement(externalLinkID);
        if (!scenario.getCurrentElements().containsKey(gatewayDeviceID)) {
            throw new NonGatewayDeviceException(scenario, gateway, externalLink);
        } else {
            gateway.connectToLink(externalLink);
            if (!this.getCurrentElements().containsKey(externalLink.getID())) {
                this.addNetworkElement(externalLink);
            }
            if (!this.scenarios.containsKey(scenario)) {
                this.scenarios.put(scenario, new ArrayList<Link>());
            } else {
                List<Link> externalLinks = this.scenarios.get(scenario);
                if (!externalLinks.contains(externalLink)) {
                    externalLinks.add(externalLink);
                } else if (externalLink.getLinkedDevices().contains(gateway)) {
                    throw new AlreadyConnectedScenarioException(scenario,
                            gateway, externalLink);
                }
            }
        }
    }
731615
def after_scenario(ctx, scenario):
    

    if hasattr(ctx, 'container') and hasattr(ctx, 'client'):
        try:
            ctx.client.remove_container(ctx.container, force=True)
        except:
            pass
56177
def add_node_to_network(self, node, network):
        """"""
        network.add_node(node)
        parents = node.neighbors(direction="from")
        if len(parents):
            parent = parents[0]
            parent.transmit()
        node.receive()
458313
public OperationFuture<Network> update(Network network, UpdateNetworkConfig config) {
        NetworkMetadata networkMetadata = findByRef(network);

        networkClient.update(
            networkMetadata.getDataCenterId(),
            networkMetadata.getId(),
            new UpdateNetworkRequest()
                .name(config.getName())
                .description(config.getDescription())
        );

        return new OperationFuture<>(network, new NoWaitingJobFuture());
    }
1340842
public static ns_detail_vlan add(nitro_service client, ns_detail_vlan resource) throws Exception
	{
		resource.validate("add");
		return ((ns_detail_vlan[]) resource.perform_operation(client, "add"))[0];
	}
158528
function createScenario(def) {
  const finalScenario = Object.assign({}, scenarioDefaults, def);
  scenariosArr.push(finalScenario);
}
660037
def bdd_common_before_scenario(context_or_world, scenario, no_driver=False):
    
    # Initialize and connect driver wrapper
    start_driver(context_or_world, no_driver)

    # Add assert screenshot methods with scenario configuration
    add_assert_screenshot_methods(context_or_world, scenario)

    # Configure Jira properties
    save_jira_conf()

    context_or_world.logger.info("Running new scenario: %s", scenario.name)
283782
def add_netreg_api(mock):
    ''''''

    # also add an emergency number which is not a real one, in case one runs a
    # test case against a production ofono :-)
    mock.AddProperties('org.ofono.NetworkRegistration', {
        'Mode': 'auto',
        'Status': 'registered',
        'LocationAreaCode': _parameters.get('LocationAreaCode', 987),
        'CellId': _parameters.get('CellId', 10203),
        'MobileCountryCode': _parameters.get('MobileCountryCode', '777'),
        'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'),
        'Technology': _parameters.get('Technology', 'gsm'),
        'Name': _parameters.get('Name', 'fake.tel'),
        'Strength': _parameters.get('Strength', dbus.Byte(80)),
        'BaseStation': _parameters.get('BaseStation', ''),
    })

    mock.AddObject('/%s/operator/op1' % mock.name,
                   'org.ofono.NetworkOperator',
                   {
                       'Name': _parameters.get('Name', 'fake.tel'),
                       'Status': 'current',
                       'MobileCountryCode': _parameters.get('MobileCountryCode', '777'),
                       'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'),
                       'Technologies': [_parameters.get('Technology', 'gsm')],
                   },
                   [
                       ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkOperator")'),
                       ('Register', '', '', ''),
                   ]  # noqa: silly pep8 error here about hanging indent
                  )

    mock.AddMethods('org.ofono.NetworkRegistration', [
        ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkRegistration")'),
        ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); '
         'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': 'org.ofono.NetworkRegistration'}),
        ('Register', '', '', ''),
        ('GetOperators', '', 'a(oa{sv})', get_all_operators(mock)),
        ('Scan', '', 'a(oa{sv})', get_all_operators(mock)),
    ])
540850
def add_network_profile(self, obj, params):
        """"""

        network_id = self._send_cmd_to_wpas(obj['name'], 'ADD_NETWORK', True)
        network_id = network_id.strip()

        params.process_akm()

        self._send_cmd_to_wpas(
                obj['name'],
                'SET_NETWORK {} ssid \"{}\"'.format(network_id, params.ssid))

        key_mgmt = ''
        if params.akm[-1] in [AKM_TYPE_WPAPSK, AKM_TYPE_WPA2PSK]:
            key_mgmt = 'WPA-PSK'
        elif params.akm[-1] in [AKM_TYPE_WPA, AKM_TYPE_WPA2]:
            key_mgmt = 'WPA-EAP'
        else:
            key_mgmt = 'NONE'

        if key_mgmt:
            self._send_cmd_to_wpas(
                    obj['name'],
                    'SET_NETWORK {} key_mgmt {}'.format(
                        network_id,
                        key_mgmt))

        proto = ''
        if params.akm[-1] in [AKM_TYPE_WPAPSK, AKM_TYPE_WPA]:
            proto = 'WPA'
        elif params.akm[-1] in [AKM_TYPE_WPA2PSK, AKM_TYPE_WPA2]:
            proto = 'RSN'

        if proto:
            self._send_cmd_to_wpas(
                    obj['name'],
                    'SET_NETWORK {} proto {}'.format(
                        network_id,
                        proto))

        if params.akm[-1] in [AKM_TYPE_WPAPSK, AKM_TYPE_WPA2PSK]:
            self._send_cmd_to_wpas(
                    obj['name'],
                    'SET_NETWORK {} psk \"{}\"'.format(network_id, params.key))

        return params