Return node_participation_settings record
    or create it if it does not exist

    usage:
    node = Node.objects.get(pk=1)
    node.participation_settings
322252
def _node_participation_settings(self):
    
    try:
        return self.node_participation_settings
    except ObjectDoesNotExist:
        node_participation_settings = NodeParticipationSettings(node=self)
        node_participation_settings.save()
        return node_participation_settings
1081035
def getNodeBeingMade(self, buid):
        '''
        
        '''
        nodeevnt = self.allbldgbuids.get(buid)
        if nodeevnt is None:
            return None
        if buid not in self.mybldgbuids:
            self.otherbldgbuids.add(buid)
        return nodeevnt[0]
1173371
def publish_participation_to_thread(sender, instance, created, **kwargs):
    
    if kwargs.get('created_and_add_participants') is True:
        request_participant_id = kwargs.get('request_participant_id')
        if request_participant_id is not None:
            client = Client("{0}api/".format(getattr(settings, "CENTRIFUGE_ADDRESS")), getattr(settings, "CENTRIFUGE_SECRET"))
            active_participants = [participation.participant for participation in Participation.objects.filter(thread=instance, date_left__isnull=True).select_related('participant')]
            for participant in active_participants:
                client.publish(
                    build_channel(settings.CENTRIFUGO_THREAD_NAMESPACE, participant.id, [participant.id]),
                    {
                        "message_channel_to_connect_to": build_channel(settings.CENTRIFUGO_MESSAGE_NAMESPACE, instance.id, [p.id for p in active_participants])
                    }
                )
854299
def get_record(self, zone_name, record_id):
        
        return self._client.get(
            '/domain/zone/{}/record/{}'.format(zone_name, record_id))
1230050
function Node (host, customSettings) {
  let node = new EventEmitter()

  let _settings = {...defaultSettings, ...customSettings, host}
  _validateSettings(_settings)

  let _id = getNodeId(_settings)
  let _name = nodeIdToName(_id)
  let _active = false
  let _deactivating = false
  let _canPublish = false
  let _receiving = false
  let _master = null

  let { external } = _settings

  //  Debug
  const _debugStr = `dnsmq-messagebus:${external ? 'externalnode' : 'dnsnode'}`
  const _debug = D(_debugStr)
  const debug = (...args) => _debug(_name, ...args)

  /**
   * starts a master node resolution;
   * if a master node is found starts a connection to it
   */
  const _seekForMaster = () => {
    if (!_active || _masterResolver.isResolving) return
    _masterResolver
    .resolve()
    .then(_connectToMaster)
    .catch(() => {
      _seekForMaster()
    })
  }
  /**
   * starts a connection of the PUB and SUB interfaces
   * to a given master
   * @param  {string} id
   * @param  {string} name
   * @param  {object} endpoints
   */
  const _connectToMaster = ({id, name, endpoints}) => {
    if (!_active) return
    _master = {id, name, endpoints}
    _subConnection.connect({name, endpoint: endpoints.pub})
    _pubConnection.connect({name, endpoint: endpoints.sub})
    if (!external) {
      name === _name ? _masterBroker.startHeartbeats() : _masterBroker.stoptHeartbeats()
    }
  }

  /**
   * publish interface
   * @type {object}
   */
  let _pubConnection = PubConnection(node)
  _pubConnection.on('connect', () => {
    _canPublish = true
    node.emit('can:publish')
    if (_receiving) node.emit('ready')
  })
  _pubConnection.on('disconnect', () => {
    _canPublish = false
    node.emit('cannot:publish')
    if (_receiving) node.emit('not:ready')
  })

  /**
   * subscribe interface
   * @type {object}
   */
  let _subConnection = SubConnection(node)
  _subConnection.on('missingmaster', () => {
    _pubConnection.disconnect()
    _seekForMaster()
  })
  _subConnection.on('newmaster', _connectToMaster)
  _subConnection.on('connect', () => {
    _receiving = true
    node.emit('receiving')
    if (_canPublish) node.emit('ready')
  })
  _subConnection.on('disconnect', () => {
    _receiving = false
    _master = null
    node.emit('not:receiving')
    if (_canPublish) node.emit('not:ready')
  })

  /**
   * master resolution component
   * @type {object}
   */
  let _masterResolver

  /**
   * master broker component
   * The external nodes dont have this component
   * @type {object}
   */
  let _masterBroker

  if (!external) {
    _masterBroker = MasterBroker(node)
    _masterResolver = MasterElector(node, _masterBroker)
    _masterResolver.on('newmaster', _connectToMaster)
  } else {
    _masterResolver = MasterFinder(node)
  }

  /**
   * Activates the node
   * @return {object} node instance
   */
  function activate () {
    if (_active) return node
    _active = true
    debug('activated')

    if (!external) {
      _masterBroker.bind()
      _masterResolver.bind()
    }
    if (!node.isReady) _seekForMaster()
    return node
  }
  /**
   * Starts the node's deactivation routine
   * @return {object} node instance
   */
  function deactivate () {
    if (!_active || _deactivating) return node
    debug('deactivating')

    if (external) {
      _active = false
      _subConnection.disconnect()
      _pubConnection.disconnect()
      node.emit('deactivated')
    } else {
      _deactivating = true
      let ensuredMaster = Promise.resolve()

      const isMaster = _subConnection.master && _subConnection.master.name === _name

      if (isMaster) {
        debug(`I'm the master node. I will try to elect another master before disconnecting.`)

        let advertiseId = `zz-zzzzzzzz-${_id}`
        ensuredMaster = _masterResolver
                        .resolve(advertiseId)
                        .then(master => {
                          debug(`successfully elected a new master: ${master.name}`)
                          try {
                            _masterBroker.signalNewMaster(master)
                          } catch (e) {
                            console.log(e)
                          }
                        })
                        .catch(() => {
                          debug(`failed to elect a new master. Disconnecting anyway.`)
                        })
      }

      ensuredMaster
      .then(() => {
        _subConnection.disconnect()
        _pubConnection.disconnect()
        _masterResolver.unbind()
        let timeout = isMaster ? 1000 : 1
        setTimeout(() => {
          debug('deactivated')
          node.emit('deactivated')
          _masterBroker.unbind()
        }, timeout)
      })
    }

    return node
  }
  /**
   * Sends a message through the bus, published on a particular channel
   * @param  {string} channel
   * @param  {array} args
   * @return {object} node instance
   */
  function publish (channel, ...args) {
    if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`)
    if (~internalChannels.indexOf(channel)) {
      console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`)
      return node
    }
    if (!_pubConnection.connected) {
      console.warn(`${_debugStr} cannot publish on bus.`)
      return node
    }
    _pubConnection.publish(channel, ...args)
    return node
  }
  /**
   * Subscribes the node to the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .subscribe([...channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot subscribe to it.`)
        return
      }
      _subConnection.subscribe([channel])
    })
    return node
  }
  /**
   * Unsubscribes the node from the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`)
        return
      }
      _subConnection.unsubscribe([channel])
    })
    return node
  }

  return Object.defineProperties(node, {
    id: {get: () => _id},
    name: {get: () => _name},
    settings: {get: () => ({..._settings})},
    type: {get: () => external ? EXTERNAL_NODE : DNS_NODE},
    canPublish: {get: () => _pubConnection.connected},
    isReceiving: {get: () => _subConnection.connected},
    isReady: {get: () => _pubConnection.connected && _subConnection.connected},
    subscribedChannels: {get: () => _subConnection.subscribedChannels},
    isMaster: {get: () => _master && _master.name === _name || false},
    master: {get: () => _master && {..._master, endpoints: {..._master.endpoints}}},
    activate: {value: activate},
    deactivate: {value: deactivate},
    publish: {value: publish},
    subscribe: {value: subscribe},
    unsubscribe: {value: unsubscribe}
  })
}
1052636
def get_node(self, node_id, project_id=None):
        

        if project_id:
            # check the project_id exists
            project = ProjectManager.instance().get_project(project_id)

        try:
            UUID(node_id, version=4)
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(text="Node ID {} is not a valid UUID".format(node_id))

        if node_id not in self._nodes:
            raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))

        node = self._nodes[node_id]
        if project_id:
            if node.project.id != project.id:
                raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't belong to node {}".format(project_id, node.name))

        return node
68598
def refresh_token(self, subid):
    ''''''
    from expfactory.database.models import Participant
    p = Participant.query.filter(Participant.id == subid).first()
    if p is not None:
        p.token = str(uuid.uuid4())
    self.session.commit()
    return p
52896
def generate_subid(self, token=None, return_user=False):
    '''
    '''    
    from expfactory.database.models import Participant
    if not token:
        p = Participant()
    else:
        p = Participant(token=token)
    self.session.add(p)
    self.session.commit()
    if return_user is True:
        return p
    return p.id
71735
def save(self, **kwargs):
        
        is_active = True
        try:
            user = get_user_model().objects.get(email=self.cleaned_data["email"])
        except get_user_model().DoesNotExist:
            user = invitation_backend().invite_by_email(
                self.cleaned_data["email"],
                **{
                    "domain": get_current_site(self.request),
                    "organization": self.cleaned_data["name"],
                    "sender": self.request.user,
                    "created": True,
                }
            )
            is_active = False
        return create_organization(
            user,
            self.cleaned_data["name"],
            self.cleaned_data["slug"],
            is_active=is_active,
        )
373794
def accept_record(self, record):
        
        with db.session.begin_nested():
            req = InclusionRequest.get(self.id, record.id)
            if req is None:
                raise InclusionRequestMissingError(community=self,
                                                   record=record)
            req.delete()
            self.add_record(record)
            self.last_record_accepted = datetime.utcnow()
318034
def get_settings(self, *args, **kwargs):
        
        url = self.reddit_session.config['wiki_page_settings']
        url = url.format(subreddit=six.text_type(self.subreddit),
                         page=self.page)
        return self.reddit_session.request_json(url, *args, **kwargs)['data']
976558
def visit(self, node):
        
        if isinstance(node, Placeholder):
            return self.placeholders[node.id]
        else:
            return super(PlaceholderReplace, self).visit(node)
648224
def connect(node_id, other_node_id):
    
    exp = experiment(session)

    # get the parameters
    direction = request_parameter(parameter="direction", default="to")
    if type(direction == Response):
        return direction

    # check the nodes exist
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(error_type="/node/connect, node does not exist")

    other_node = models.Node.query.get(other_node_id)
    if other_node is None:
        return error_response(
            error_type="/node/connect, other node does not exist",
            participant=node.participant)

    # execute the request
    try:
        vectors = node.connect(whom=other_node, direction=direction)
        for v in vectors:
            assign_properties(v)

        # ping the experiment
        exp.vector_post_request(
            node=node,
            vectors=vectors)

        session.commit()
    except:
        return error_response(error_type="/vector POST server error",
                              status=403,
                              participant=node.participant)

    return success_response(field="vectors",
                            data=[v.__json__() for v in vectors],
                            request_type="vector post")
201143
public static Key<ConfigRecord> getKey (String node, String object, String field)
    {
        return newKey(_R, node, object, field);
    }
229099
def create_node(self, network, participant):
        """"""
        if network.role == "practice" or network.role == "catch":
            return RogersAgentFounder(network=network, participant=participant)
        elif network.size(type=Agent) < network.generation_size:
            return RogersAgentFounder(network=network, participant=participant)
        else:
            return RogersAgent(network=network, participant=participant)
514927
def initial(self, request, *args, **kwargs):
        
        super(NodeDeviceList, self).initial(request, *args, **kwargs)

        # ensure node exists
        try:
            self.node = Node.objects.published()\
                        .accessible_to(request.user)\
                        .get(slug=self.kwargs.get('slug', None))
        except Node.DoesNotExist:
            raise Http404(_('Node not found.'))

        # check permissions on node (for device creation)
        self.check_object_permissions(request, self.node)

        # return only devices of current node
        self.queryset = Device.objects.filter(node_id=self.node.id)\
                        .accessible_to(self.request.user)\
                        .select_related('node')
957086
def create_node(self, network, participant):
        """"""
        return self.models.MCMCPAgent(network=network, participant=participant)