This will start listening for incoming sentences and will fetch labels from the server each time a speech was recognized. It will return a factory function which will generate an event handler for testing sentences against fetched labels
963340
function createLabelMatcher(speechEmitter) {
  if (speechEmitter == null) {
    throw TypeError('speech emitter must be provided');
  }

  if (!(speechEmitter instanceof SpeechEmitter)) {
    throw TypeError('first argument must be a speech emitter');
  }

  // This will be used to register events for fetched labels
  const labelEmitter = new SpeechEmitter();
  const sentencePattern = /.*/;

  // This will fetch labels and emit them whenever there is an incoming sentence
  const fetchHandler = (sentence) => {
    // e.g. ' ' (space) will be replaced with '%20'
    const encodedSentence = encodeURIComponent(sentence);
    const labelQueryUrl = `${settings.apiUrl}/label?sentence=${encodedSentence}`;
    const request = new Request(labelQueryUrl);

    fetch(request).then(response => response.json()).then(({ label }) => {
      labelEmitter.emit(label, sentence);

      // Re-register event listener after it (could have been) zeroed by the speech node.
      // Here we wait run the registration in the next event loop to ensure all promises
      // have been resolved
      setTimeout(() => {
        speechEmitter.once(sentencePattern, fetchHandler);
      });
    })
    .catch((error) => {
      console.error(error);
    });
  };

  // Here we use the once() method and not the on() method we re-register the event
  // listener once a fetch has been done
  speechEmitter.once(sentencePattern, fetchHandler);

  // A factory function which will generate an event handler for matching sentences
  // against fetched labels. Be sure to call the dispose() method once you don't need
  // the labels logic anymore! Otherwise requests will keep being made to the server
  // in the background
  const matchLabel = (label) => {
    if (label == null) {
      throw TypeError('label must be provided');
    }

    if (typeof label != 'string') {
      throw TypeError('label must be a string');
    }

    // An async event handler which returns a promise
    return () => new Promise((resolve) => {
      // The promise will resolve itself whenever an emitted label matches the
      // expected label
      const labelTest = (actualLabel, sentence) => {
        // This makes it a one-time test
        labelEmitter.off(labelTest);

        if (actualLabel == label) {
          // These are the arguments with whom the event handler will be invoked with
          return [sentence, label];
        }
      };

      labelEmitter.on(labelTest, resolve);
    });
  };

  // The disposal methods disposes all the registered label events and it stops the
  // auto-fetching to the server whenever there is an incoming sentence
  matchLabel.dispose = () => {
    speechEmitter.off(sentencePattern, fetchHandler);
    labelEmitter.off();
  };

  return matchLabel;
}
1211516
async def listener(self, channel):
        
        while True:
            message = await self.channel_layer.receive(channel)
            if not message.get("type", None):
                raise ValueError("Worker received message with no type.")
            # Make a scope and get an application instance for it
            scope = {"type": "channel", "channel": channel}
            instance_queue = self.get_or_create_application_instance(channel, scope)
            # Run the message into the app
            await instance_queue.put(message)
99687
def show_sentences():
    
    cursor = CONN.cursor()

    query = "select sen_id, sentence from sursentences where sen_is_valid = 'y' order by sen_id asc"
    cursor.execute(query)
    result = cursor.fetchall()

    response_dict = {}

    for row in result:
        response_dict[row[0]] = row[1]

    return response_dict
684163
def listen_init(self):
        """"""
        self.dispatcher = ObjectDispatch(self)
        self.factory = MsgPackProtocolFactory(self.dispatcher)
        self.server = UnixServer(self.loop, self.factory, self.path)
        self.server.start()
140952
def _create_sentence_objects(self):
        """"""
        sentence_objects = []
        sentences = sent_tokenize(self.raw, tokenizer=self.tokenizer)
        char_index = 0  # Keeps track of character index within the blob
        for sent in sentences:
            # Compute the start and end indices of the sentence
            # within the blob. This only works if the sentence splitter
            # does not perform any character replacements or changes to
            # white space.
            # Working: NLTKPunktTokenizer
            # Not working: PatternTokenizer
            try:
                start_index = self.raw.index(sent, char_index)
                char_index += len(sent)
                end_index = start_index + len(sent)
            except ValueError:
                start_index = None
                end_index = None
            # Sentences share the same models as their parent blob
            s = Sentence(
                sent,
                start_index=start_index,
                end_index=end_index,
                tokenizer=self.tokenizer,
                np_extractor=self.np_extractor,
                pos_tagger=self.pos_tagger,
                analyzer=self.analyzer,
                parser=self.parser,
                classifier=self.classifier)
            sentence_objects.append(s)
        return sentence_objects
1317600
function getNextResponse(){
    if (_waitingForInput !== null){
        throw new Error('concurreny error - receive listener already in-queue');
    }

    return new Promise(function(resolve){
        // data received ?
        if (_inputbuffer.length > 0){
            resolve(_inputbuffer.shift());
        }else{
            // add as waiting instance (no concurrent!)
            _waitingForInput = resolve;
        }
    });
}
488430
def __get_sentence(counts, sentence_id=None):
    

    # First of all we need a cursor and a query to retrieve our ID's
    cursor = CONN.cursor()
    check_query = "select sen_id from sursentences"

    # Now we fetch the result of the query and save it into check_result
    cursor.execute(check_query)
    check_result = cursor.fetchall()

    # declare an empty list to be populated below
    id_list = []
    id_to_fetch = None

    # Populate the id_list variable with all of the ID's we retrieved from the database query.
    for row in check_result:
        id_list.append(row[0])

    if sentence_id is not None:
        if type(sentence_id) is int:
            id_to_fetch = sentence_id
    else:
        id_to_fetch = random.randint(1, counts['max_sen'])

        while id_to_fetch not in id_list:
            id_to_fetch = random.randint(1, counts['max_sen'])

    query = ("select * from sursentences where sen_id = {0}".format(id_to_fetch))
    cursor.execute(query)
    result = cursor.fetchone()
    # cursor.close()

    return result
521100
def listen(url, prefix=None, **kwargs):
    
    return listener(url, prefix=get_prefix(prefix), **kwargs)
881298
def create_single_dialog_train_example(context_dialog_path, candidate_dialog_paths, rng, positive_probability,
                                       minimum_context_length=2, max_context_length=20):
    

    dialog = translate_dialog_to_lists(context_dialog_path)

    context_str, next_utterance_ix = create_random_context(dialog, rng,
                                                           minimum_context_length=minimum_context_length,
                                                           max_context_length=max_context_length)

    if positive_probability > rng.random():
        # use the next utterance as positive example
        response = singe_user_utterances_to_string(dialog[next_utterance_ix])
        label = 1.0
    else:
        response = get_random_utterances_from_corpus(candidate_dialog_paths, rng, 1,
                                                     min_turn=minimum_context_length + 1,
                                                     max_turn=max_context_length)[0]
        label = 0.0
    return context_str, response, label
55953
function speechTreeApi(options) {
  if (!options.speechClassifier) {
    throw TypeError('speech classifier must be specified');
  }

  if (typeof options.speechClassifier != 'function') {
    throw TypeError('speech classifier must be a function');
  }

  const router = express.Router();
  const apiUrl = '/' + settings.apiUrl.split('/').pop();

  router.get(`${apiUrl}/label`, async (req, res) => {
    const sentence = req.query.sentence;

    if (!sentence) {
      res.status(400);
      return res.send('sentence must be provided');
    }

    let label = options.speechClassifier(sentence);

    if (!label) {
      res.status(404);
      return res.send('label not found');
    }

    if (typeof label.then == 'function' &&
        typeof label.catch == 'function') {
      label = await label;
    }

    if (typeof label != 'string') {
      throw TypeError('label must be a string');
    }

    res.status(200);
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ label }));
  });

  return router;
}
939394
protected void triggerEpochListeners(boolean epochStart, Model model, int epochNum){
        Collection<TrainingListener> listeners;
        if(model instanceof MultiLayerNetwork){
            MultiLayerNetwork n = ((MultiLayerNetwork) model);
            listeners = n.getListeners();
            n.setEpochCount(epochNum);
        } else if(model instanceof ComputationGraph){
            ComputationGraph cg = ((ComputationGraph) model);
            listeners = cg.getListeners();
            cg.getConfiguration().setEpochCount(epochNum);
        } else {
            return;
        }

        if(listeners != null && !listeners.isEmpty()){
            for (TrainingListener l : listeners) {
                if (epochStart) {
                    l.onEpochStart(model);
                } else {
                    l.onEpochEnd(model);
                }
            }
        }
    }
725834
function(obj, name, callback, context, listening) {
    obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
      context: context,
      ctx: obj,
      listening: listening
    });

    if (listening) {
      var listeners = obj._listeners || (obj._listeners = {});
      listeners[listening.id] = listening;
    }

    return obj;
  }
810247
function bindFromStrings(target, entity, evt, methods){
    var methodNames = methods.split(/\s+/);

    _.each(methodNames,function(methodName) {

      var method = target[methodName];
      if(!method) {
        throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
      }

      target.listenTo(entity, evt, method, target);
    });
  }
577977
def listen(self):
        ''''''
        try:
            self._pubsub.subscribe(self._channels)
            for message in self._pubsub.listen():
                if message['type'] == 'message':
                    yield message
        finally:
            self._channels = []
462340
Word2VecModel train(Log log, TrainingProgressListener listener, Iterable<List<String>> sentences) throws InterruptedException {
		try (ProfilingTimer timer = ProfilingTimer.createLoggingSubtasks(log, "Training word2vec")) {
			final Multiset<String> counts;
			
			try (AC ac = timer.start("Acquiring word frequencies")) {
				listener.update(Stage.ACQUIRE_VOCAB, 0.0);
				counts = (vocab.isPresent())
							? vocab.get()
							: count(Iterables.concat(sentences));
			}
			
			final ImmutableMultiset<String> vocab;
			try (AC ac = timer.start("Filtering and sorting vocabulary")) {
				listener.update(Stage.FILTER_SORT_VOCAB, 0.0);
				vocab = filterAndSort(counts);
			}
			
			final Map<String, HuffmanNode> huffmanNodes;
			try (AC task = timer.start("Create Huffman encoding")) {
				huffmanNodes = new HuffmanCoding(vocab, listener).encode();
			}
			
			final NeuralNetworkModel model;
			try (AC task = timer.start("Training model %s", neuralNetworkConfig)) {
				model = neuralNetworkConfig.createTrainer(vocab, huffmanNodes, listener).train(sentences);
			}
			
			return new Word2VecModel(vocab.elementSet(), model.layerSize(), Doubles.concat(model.vectors()));
		}
	}
773149
function listenFor (event, listener, context, duration) {
    setTimeout(function () {
        this.off(event, listener, context);
    }.bind(this), duration);
    this.on(event, listener, context);
}
45867
function Parser() {
  if (!(this instanceof Parser))
    return new Parser();

  EventEmitter.call(this);

  this.waiting = 9;
  this.header = null;
  this.pending = [];
  this.total = 0;
}