text:
# Copyright 2017 Google 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.

require 'fluent/input'
require 'fluent/plugin_helper/timer'

require_relative 'log_directives'
require_relative 'log_state'
require_relative 'position'

module Fluent
  # A fluentd input plugin for reading W3C IIS logs.
  class IISInput < Input
    Fluent::Plugin.register_input('iis', self)

    helpers :timer

    desc 'The path(s) to read from.  Accepts comma separated paths and wild cards \'*\'.'
    config_param :path, :string, default: 'C:/inetpub/logs/LogFiles/W3SVC*/**/*.log'

    desc 'The tag to emit the entries as.'
    config_param :tag, :string, default: 'iis'

    desc 'A file to keep track of the read positions in logs.'
    config_param :pos_file, :string, default: nil

    desc 'How often the list of watched logs is refreshed in seconds.'
    config_param :refresh_logs_list, :integer, default: 60

    desc 'How often the position file is written to in seconds.'
    config_param :write_position_file, :integer, default: 60

    desc 'How often log entries should be read for each file in seconds.'
    config_param :read_log_entires, :integer, default: 60

    desc 'The maximum number of lines to read from one file at a time.'
    config_param :read_line_limit, :integer, default: 1000

    desc 'If log entries should be processed. Associating each directive with its entry in each log.'
    config_param :process_logs, :bool, default: false

    def initialize()
      super
      # A map from string file path to LogState containing all the currently watched files.
      @watched_files = {}
      # The event timer to refresh the list of watched files.
      @watcher_refresh_timer = nil
      # The event timer to write out the position file.
      @write_pos_file_timer = nil
      # The position file object.
      @pos = nil
    end

    def configure(conf)
      super
      @pos = PositionFile.new(@pos_file) if @pos_file != nil
    end

    def start()
      super
      # Start the timers to watch files and update the position file.
      @watcher_refresh_timer = timer_execute(:iis_refresh_watchers, @refresh_logs_list, &method(:refresh_watchers))
      @write_pos_file_timer = timer_execute(:iis_write_pos_file, @write_position_file, &method(:write_pos_file)) if @pos != nil
    end

    def shutdown()
      super
      # Stop all active watches.
      stop_watches(@watched_files.keys)

      # Stop the timers if they are running.
      @watcher_refresh_timer.detach if @watcher_refresh_timer.attached?
      @write_pos_file_timer.detach if @write_pos_file_timer != nil && @write_pos_file_timer.attached?

      # Write out the final position file.
      @pos.write_to_file() if @pos != nil
    end

  private
    # Refresh the list of currently watched files. Adding unwatched files and removing files
    # that no longer exist.
    def refresh_watchers()
      paths = []

      # A list of all file paths the user passed in.
      unresolved_paths = @path.split(',')
      unresolved_paths = unresolved_paths.size == 0 ? @path : unresolved_paths

      # Glob all file paths and keep all readable files.
      for unresolved_path in unresolved_paths
        paths += Dir.glob(unresolved_path.strip).select do |resource|
          File.file?(resource) && File.readable?(resource)
        end
      end

      watched = @watched_files.keys

      # Files we are not yet watching.
      new_files = paths - watched

      # Files we are watching that no longer exist.
      dead_files = watched - paths

      start_watches(new_files)
      stop_watches(dead_files, true)
    end

    # Write an updated position file if any positions have changed.
    def write_pos_file()
      last_update = File.exist?(@pos.pos_file) ? File.mtime(@pos.pos_file) : Time.at(0)
      for state in @watched_files.values
        if last_update < state.last_emit
          @pos.write_to_file()
          break
        end
      end
    end

    # Start watching file paths.
    # Params:
    # +paths+:: An array of string paths.
    def start_watches(paths)
      for path in paths
        # Get or create a Position object for the file path.
        pos_file = @pos != nil ? @pos.get_position(path) : Position.new(path)
        # Create a LogState to track the log.
        log_state = LogState.new(pos_file, method(:emit_lines))
        # Start a timer to check for changes in the log and emit new lines.
        log_state.timer = timer_execute(:iis_file_watchers, @read_log_entires, repeat: false, &log_state.method(:emit_lines))
        @watched_files[path] = log_state
      end
    end

    # Stop watching file paths.
    # Params:
    # +paths+:: An array of string paths.
    # +delete_pos+:: If the associated position in the position file should be deleted.
    #   Defaults to false.
    def stop_watches(paths, delete_pos = false)
      for path in paths
        log_state = @watched_files.delete(path)
        log_state.timer.detach if log_state.timer.attached?
        @pos.remove_position(path) if delete_pos && @pos != nil
      end
    end

    # Emit records (lines) for a given LogState.
    # Params:
    # +log_state+:: The LogState to emit records for.
    def emit_lines(log_state)
      begin
        # If the file doesn't exist do not emit lines.  The watch will be cleaned up on the next refresh.
        if !File.exist?(log_state.pos_file.path)
          return
        end

        # If there are no unread lines from the last read and the file has not been modified
        # do not emit lines.
        if !log_state.unread_lines && File.mtime(log_state.pos_file.path) < log_state.last_emit
          return
        end

        file = File.open(log_state.pos_file.path)

        # Read in the last directives if they exist.
        if log_state.pos_file.last_directives_pos >= 0
          update_directives(file, log_state)
        end

        # Seek to the last read position.
        if log_state.pos_file.last_read_pos >= 0
          file.seek(log_state.pos_file.last_read_pos)
        end

        # Create an event stream to write records to.
        event_stream = MultiEventStream.new()

        # The last start position of directives.
        last_directives_pos = nil

        # Keep track of log directives as they are read in.
        # We cannot emit them as we read them as we need the date
        # from the Date directive to properly date all the directives.
        log_directives = []

        for _ in 0...@read_line_limit
          starting_pos = file.pos
          begin
            line = file.readline.strip
          rescue EOFError
            log_state.unread_lines = false
            break
          end

          if LogDirectives.is_directive(line)
            # If this is a new set of directives record needed info.
            if log_directives.empty?
              # Save the directive start position to record later.
              last_directives_pos = starting_pos
              # Clear out any old directives to ensure no stale data.
              log_state.log_directives = LogDirectives.new()
            end
            log_state.log_directives.process_info(line)
            log_directives.push(line)
          else
            # If we have finished reading directives write out the info.
            if !log_directives.empty?
              for directive in log_directives
                record = create_record(directive, path, log_state, false)
                event_stream.add(Engine.now, record)
              end
            end

            log_directives = []
            record = create_record(line, file.path, log_state, @process_logs)
            event_stream.add(Engine.now, record)
          end
        end

        # Update info in the LogState, close the file and emit the stream.
        log_state.pos_file.last_read_pos = file.pos
        log_state.pos_file.last_directives_pos = last_directives_pos if last_directives_pos != nil
        file.close()
        log_state.last_emit = Time.now
        router.emit_stream(@tag, event_stream)
      ensure
        log_state.timer = timer_execute(:iis_file_watchers, @read_log_entires, repeat: false, &log_state.method(:emit_lines))
      end
    end

    # Update a LogState's LogDirectives from a file.
    # Params:
    # +file+:: A file open for reading.
    # +log_state+:: The LogState associated with the file.
    def update_directives(file, log_state)
      # Clear out any old directives to ensure no stale data.
      log_state.log_directives = LogDirectives.new()
      file.seek(log_state.pos_file.last_directives_pos)

      # There should not be more than 8-10 directives but allow more to be safe.
      for _ in 1..20
        begin
          line = file.readline
          if LogDirectives.is_directive(line)
            log_state.log_directives.process_info(line)
          else
            return
          end
        rescue EOFError
          break
        end
      end
    end

    # Create a recored to be emitted.
    # Params:
    # +line+:: The line of text to emit.
    # +path+:: The path of the file the line was from.
    # +log_state+:: The LogState associated with the file path.
    # +process_fields+:: True if the fields should be processed.
    def create_record(line, path, log_state, process_fields)
      directives = {}

      # If we have directive information about fields in the logs parse it.
      if log_state.log_directives.fields != nil
        directives = Hash[log_state.log_directives.fields.zip(line.split(" "))]
      end

      if process_fields && log_state.log_directives.fields != nil
        record = directives
      elsif
        record = {'message' => line }
      end

      # Add information about where the log entry came from.
      record['log-path'] = path
      # Attempt to get a timestamp from the fields and/or directives.
      timestamp = get_timestamp(directives['date'], directives['time'], log_state.log_directives.date)
      record['timestamp'] = timestamp if timestamp != nil
      return record
    end

    # Get a timestamp in the format:
    #  {'seconds' => int, 'nanos' => int}
    # Will attempt to create the timestamp with the date and time but will fall back to
    # the date_time if needed.
    # Params:
    # +date+:: A date as a string.  Can be nil.
    # +time+:: A date as a string.  Can be nil.
    # +date_time+:: A date and time as a string.  Can be nil.
    def get_timestamp(date, time, date_time)
      timestamep_str = nil
      if date != nil && time != nil
        timestamep_str = "#{date} #{time}"
      elsif time != nil && date_time != nil
        parts = date_time.split(" ")
        date = parts.size == 0 ? date : parts.first
        timestamep_str = "#{date} #{time}"
      elsif date_time != nil
        timestamep_str = date_time
      else
        return nil
      end

      begin
        time = Time.parse(timestamep_str)
        return {'seconds' => time.tv_sec, 'nanos' => time.tv_nsec}
      rescue
        return nil
      end
    end

  end
end


text:
<?php

namespace App\Controller;

use Cake\Controller\Controller;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);

        $this->Auth->allow(['display']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/host_port.h>
#include <grpc/support/string_util.h>
#include <grpc/support/subprocess.h>
#include "src/core/lib/support/string.h"
#include "test/core/util/port.h"

int main(int argc, char **argv) {
  char *me = argv[0];
  char *lslash = strrchr(me, '/');
  char root[1024];
  int port = grpc_pick_unused_port_or_die();
  char *args[10];
  int status;
  gpr_subprocess *svr, *cli;
  /* figure out where we are */
  if (lslash) {
    memcpy(root, me, (size_t)(lslash - me));
    root[lslash - me] = 0;
  } else {
    strcpy(root, ".");
  }
  /* start the server */
  gpr_asprintf(&args[0], "%s/memory_profile_server%s", root,
               gpr_subprocess_binary_extension());
  args[1] = "--bind";
  gpr_join_host_port(&args[2], "::", port);
  args[3] = "--no-secure";
  svr = gpr_subprocess_create(4, (const char **)args);
  gpr_free(args[0]);
  gpr_free(args[2]);

  /* start the client */
  gpr_asprintf(&args[0], "%s/memory_profile_client%s", root,
               gpr_subprocess_binary_extension());
  args[1] = "--target";
  gpr_join_host_port(&args[2], "127.0.0.1", port);
  args[3] = "--warmup=1000";
  args[4] = "--benchmark=9000";
  cli = gpr_subprocess_create(5, (const char **)args);
  gpr_free(args[0]);
  gpr_free(args[2]);

  /* wait for completion */
  printf("waiting for client\n");
  if ((status = gpr_subprocess_join(cli))) {
    gpr_subprocess_destroy(cli);
    gpr_subprocess_destroy(svr);
    return status;
  }
  gpr_subprocess_destroy(cli);

  gpr_subprocess_interrupt(svr);
  status = gpr_subprocess_join(svr);
  gpr_subprocess_destroy(svr);
  return status;
}


text:
/**
 *
 * Thanks Tritonus.org for handling byte float buffer array complexities
 * Thanks Minim (http://code.compartmental.net/tools/minim/) for an example of
 * root mean squared example of getLevel() an of course
 * Thanks Google !
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * The working part of this was eventually traced back to:
 * http://www.developer.com/java/other/article.php/1565671/Java-Sound-An-Introduction.htm
 * And I would like to give all well deserved credit to
 * Richard G. Baldwin's excellent and comprehensive tutorial regarding the many
 * details of sound and Java
 *
 * References :
 *  http://www.jsresources.org/faq_audio.html#calculate_power
 *  http://stackoverflow.com/questions/1026761/how-to-convert-a-byte-array-to-its-numeric-value-java
 *  http://www.daniweb.com/software-development/java/code/216874
 *  http://code.google.com/apis/language/translate/v2/using_rest.html
 *
 * */

package org.myrobotlab.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javaFlacEncoder.FLAC_FileEncoder;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;

import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.speech.TranscriptionThread;
import org.slf4j.Logger;
import org.tritonus.share.sampled.FloatSampleBuffer;

public class GoogleSTT extends Service implements SpeechRecognizer {

	/**
	 * @author grog Does the audio capturing, rms, and data copying. Should
	 *         probably be refactored into an AudioCaptureThread which could be
	 *         shared with other Services.
	 */
	class CaptureThread extends Thread {
		private Service myService = null;

		CaptureThread(Service s) {
			this(s, s.getName() + "_capture");
		}

		CaptureThread(Service s, String n) {
			super(n);
			myService = s;
		}

		@Override
		public void run() {
			boolean x = true;

			int transcriptionIndex = 0;

			while (x) {
				synchronized (isListening) {
					try {
						// if we are told not to listen - we will
						// wait without pulling data off the targetDataLine
						while (!isListening) {
							isListening.wait();
						}
					} catch (InterruptedException ex) {
						log.debug("capture thread interrupted");
						return;
					}
				}

				int byteBufferSize = buffer.getByteArrayBufferSize(targetDataLine.getFormat());
				rawBytes = new byte[byteBufferSize];// TODO - create buffer here
													// ?
				log.info("starting capture with " + bufferSize + " buffer size and " + byteBufferSize + " byte buffer length");
				byteArrayOutputStream = new ByteArrayOutputStream();
				stopCapture = false; // FIXME - remove

				try {
					while (!stopCapture) {

						// read from the line
						int cnt = targetDataLine.read(rawBytes, 0, rawBytes.length);
						// convert to float samples
						buffer.setSamplesFromBytes(rawBytes, 0, targetDataLine.getFormat(), 0, buffer.getSampleCount());

						rms = level(buffer.getChannel(0)); // cheezy
						if (rms > rmsThreshold) {
							log.info("rms " + rms + " will begin recording ");
							isCapturing = true;
							captureStartTimeMS = System.currentTimeMillis();
						}

						// && isListening && thresholdReached && (listenTime <
						// minListenTime)
						if (cnt > 0 && isCapturing) {
							byteArrayOutputStream.write(rawBytes, 0, cnt);
						}// end if

						captureTimeMS = System.currentTimeMillis() - captureStartTimeMS;

						if (isCapturing == true && captureTimeMS > captureTimeMinimumMS && rms < rmsThreshold) {
							isCapturing = false;
							stopCapture = true;
						}

					}// end while capture

					byteArrayOutputStream.flush();
					byteArrayOutputStream.close();

					++transcriptionIndex;
					saveWavAsFile(byteArrayOutputStream.toByteArray(), audioFormat, "googletts_" + transcriptionIndex + ".wav");
					encoder.encode(new File("googletts_" + transcriptionIndex + ".wav"), new File("googletts_" + transcriptionIndex + ".flac"));
					transcribe("googletts_" + transcriptionIndex + ".flac");
					stopCapture = false;

				} catch (Exception e) {
					log.error(Service.stackToString(e));
				}

			}// while (isRunning)
		} // run
	} // CaptureThread

	public final static Logger log = LoggerFactory.getLogger(GoogleSTT.class.getCanonicalName());

	private static final long serialVersionUID = 1L;

	// microphone capture
	boolean stopCapture = false;

	transient ByteArrayOutputStream byteArrayOutputStream;

	transient AudioFormat audioFormat;

	transient TargetDataLine targetDataLine;
	transient AudioInputStream audioInputStream;
	transient SourceDataLine sourceDataLine;

	transient CaptureThread captureThread = null;

	String language = "en";

	private Boolean isListening = true;
	// audio format
	float sampleRate = 8000.0F; // 8000,11025,16000,22050,44100
	int sampleSizeInBits = 16; // 8,16
	int channels = 1; // 1,2 TODO - check for 2 & triangulation
	boolean signed = true; // true,false

	boolean bigEndian = false;
	// transcribing
	public final static int SUCCESS = 1;
	public final static int ERROR = 2;
	public final static int TRANSCRIBING = 3;

	transient TranscriptionThread transcription = null;

	// encoding
	transient FLAC_FileEncoder encoder; // TODO - memory encoder
	// root mean square level detection and capture management
	// TODO - auto-gain adjustment
	float rms;
	float rmsThreshold = 0.0050f;
	transient public byte[] rawBytes;
	boolean isCapturing = false;
	long captureStartTimeMS;
	long captureTimeMinimumMS = 1200;
	long captureTimeMS;
	transient private FloatSampleBuffer buffer;

	private int bufferSize = 512; // TODO - experiment with sampling size

	public static void main(String[] args) {
		LoggingFactory.getInstance().configure();
		LoggingFactory.getInstance().setLevel(Level.DEBUG);

		GoogleSTT stt = new GoogleSTT("stt");
		// stt.startService();
		stt.captureAudio();
		stt.stopAudioCapture();
	}

	public static void saveWavAsFile(byte[] byte_array, AudioFormat audioFormat, String file) {
		try {
			long length = byte_array.length / audioFormat.getFrameSize();
			ByteArrayInputStream bais = new ByteArrayInputStream(byte_array);
			AudioInputStream audioInputStreamTemp = new AudioInputStream(bais, audioFormat, length);
			File fileOut = new File(file);
			AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

			if (AudioSystem.isFileTypeSupported(fileType, audioInputStreamTemp)) {
				AudioSystem.write(audioInputStreamTemp, fileType, fileOut);
			}
		} catch (Exception e) {
		}
	}

	/*
	 * public double volumeRMS(double[] raw) { double sum = 0d; if
	 * (raw.length==0) { return sum; } else { for (int ii=0; ii<raw.length;
	 * ii++) { sum += raw[ii]; } } double average = sum/raw.length;
	 *
	 * double[] meanSquare = new double[raw.length]; double sumMeanSquare = 0d;
	 * for (int ii=0; ii<raw.length; ii++) { sumMeanSquare +=
	 * Math.pow(raw[ii]-average,2d); meanSquare[ii] = sumMeanSquare; } double
	 * averageMeanSquare = sumMeanSquare/raw.length; double rootMeanSquare =
	 * Math.pow(averageMeanSquare,0.5d);
	 *
	 * return rootMeanSquare; }
	 */
	public static double toDouble(byte[] data) {
		if (data == null || data.length != 8)
			return 0x0;
		return Double.longBitsToDouble(toLong(data));
	}

	public static int toInt(byte[] bytes) {
		int result = 0;
		for (int i = 0; i < 4; i++) {
			result = (result << 8) - Byte.MIN_VALUE + bytes[i];
		}
		return result;
	}

	public static long toLong(byte[] data) {
		if (data == null || data.length != 8)
			return 0x0;
		return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32
				| (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0;
	}

	public GoogleSTT(String n) {
		super(n);
		encoder = new FLAC_FileEncoder();
	}

	public void captureAudio() {
		try {
			audioFormat = getAudioFormat();
			log.info("sample rate         " + sampleRate);
			log.info("channels            " + channels);
			log.info("sample size in bits " + sampleSizeInBits);
			log.info("signed              " + signed);
			log.info("bigEndian           " + bigEndian);
			log.info("data rate is " + sampleRate * sampleSizeInBits / 8 + " bytes per second");
			// create a data line with parameters
			DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
			// attempt to find & get an input data line with those parameters
			targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
			targetDataLine.open(audioFormat);
			targetDataLine.start();

			// create buffer for root mean square level detection
			buffer = new FloatSampleBuffer(targetDataLine.getFormat().getChannels(), bufferSize, targetDataLine.getFormat().getSampleRate());

			// capture from microphone
			captureThread = new CaptureThread(this);
			captureThread.start();
		} catch (Exception e) {
			log.error(Service.stackToString(e));
		}
	}

	private AudioFormat getAudioFormat() {
		return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
	}

	@Override
	public String[] getCategories() {
		return new String[] { "speech recognition" };
	}

	/*
	 * public synchronized float level() { float level = 0; for (int i = 0; i <
	 * samples.length; i++) { level += (samples[i] * samples[i]); } level /=
	 * samples.length; level = (float) Math.sqrt(level); return level; }
	 */
	@Override
	public String getDescription() {
		return "Uses the Google Speech To Text service";
	}

	public float level(float[] samples) {
		float level = 0;
		for (int i = 0; i < samples.length; i++) {
			level += (samples[i] * samples[i]);
		}
		level /= samples.length;
		level = (float) Math.sqrt(level);
		return level;
	}

	/**
	 * Event is sent when the listening Service is actually listening. There is
	 * some delay when it initially loads.
	 */
	@Override
	public void listeningEvent() {
		return;
	}

	@Override
	public void pauseListening() {
		// TODO Auto-generated method stub

	}

	public void publishRecognized(String recognizedText) {
		invoke("recognized", recognizedText);
	}

	@Override
	public String recognized(String word) {
		return word;
	}

	@Override
	public void releaseService() {
		super.releaseService();
		stopAudioCapture();
	}

	@Override
	public void resumeListening() {
		// TODO Auto-generated method stub

	}

	public synchronized boolean setListening(boolean b) {
		isListening = b;
		isListening.notifyAll();
		return b;
	}

	@Override
	public void startListening() {

	}

	public void stopAudioCapture() {
		stopCapture = true;
	}

	@Override
	public void stopListening() {

	}

	private void transcribe(String path) {
		// only interrupt if available
		// transcription.interrupt();

		Logging.logTime("start");
		Logging.logTime("pre new transcription " + path);
		TranscriptionThread transcription = new TranscriptionThread(this, this.getName() + "_transcriber", language);
		transcription.debug = true;
		Logging.logTime("pre new thread start");
		transcription.start();
		Logging.logTime("pre transcription");
		transcription.startTranscription(path);
		Logging.logTime("post transcription");

		// threads.add(transcription);
	}

}


text:
const WebpackCLITestPlugin = require("../../utils/webpack-cli-test-plugin");

module.exports = {
  plugins: [new WebpackCLITestPlugin()],
};


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
  <meta http-equiv="Content-Language" content="nl">
<link rel="alternate" hreflang="en" href="https://polyglot.untra.io/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="es" href="https://polyglot.untra.io/es/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="de" href="https://polyglot.untra.io/de/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="fr" href="https://polyglot.untra.io/fr/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="ru" href="https://polyglot.untra.io/ru/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="nl" href="https://polyglot.untra.io/nl/2015/09/19/presenting-polyglot/"/>
<link rel="alternate" hreflang="he" href="https://polyglot.untra.io/he/2015/09/19/presenting-polyglot/"/>

  <title>

      Aankondiging Polyglot · Polyglot

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="/public/css/custom.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/nl/atom.xml">

Hallo!

          Polyglot

Een plug-in voor internationlisering van Jekyll die meertalige ondersteuning snel en intuïtief maakt, voor blogs groot en klein. Gemaakt door @untra.

      Home

            About

            Een werkelijk lange permalink

            Sample rich text data

            SEO Recipes

      Ruby Gem
      GitHub project
      view this page source on github
      Currently v1.5.1

© 2022 Samuel Volin
MIT Licensed

en |

es |

de |

fr |

ru |

nl |

he |

Aankondiging Polyglot

  19 Sep 2015

Na maanden van werk en verbeteringen kondig ik met trots aan Polyglot: een i18n-plug-in voor Jekyll-websites, die een noodzaak hebben hun content in meerdere talen aan hun publike aan te bieden.

Features

Zowaar er andere meertalige plugin-ins voor Jekyll zijn, Polyglot is anders. Polyglot bekommert zich om de typische zaken die normaal door ontwikkelaars worden beheerd (zoals het vermangelen van URL's en verzekeren van consistente sitemaps) en tegelijkertijd efficiënte en eenvoudige tools aanbieden die Jekyll-ontwikkelaars kunnen gebruiken in SEO en snelle contentaggregatie.

Gerelativeerde URL's

Een meertalige statische site of blog moest in het verleden delicaat bijhouden welke taal werd aangeboden door elke relatieve link op de website. Hierdoor struikelde een ontwikkelaar snel en buitenlandse bezoekers met een andere taal verloren zichzelf snel in onvertaalde content.

Polyglot relativeert automatisch de URL's voor elke taal waar je je website voor wil bouwen. Dit maakt het mogelijk dat bezoekers geïsoleerd blijven in een taal terwijl ze je website bekijken.

Fallback-ondersteuning

Als je geen vertaalde or meertalige content hebt, zal Jekyll nog steeds de site bouwen met de content die je hebt. Als je wel vertaalde of meertalige content hebt, zal Jekyll de site bouwen met die conent. Zo eenvoudig is het.

Sitemaps blijven consistent over alle talen, en de vertaling blijft in de website waarvoor het gebouwd was.

Rich content vertalen

Vertalen van rich content is normaal moeilijk te implementeren. Korte strings of taalafhankelijke banners zijn typisch lastig voor een Jekyll-website om consistent te houden.

Behalve, wanneer het makkelijk is. In je config.yml, sla je string op deze manier op:

hello:
  en: Hello!
  es: ¡hola!
  fr: Bonjour!
  de: Guten Tag!

en in je liquid, roep alleen maar aan

{{ site.hello[site.active_lang]}}

dat produceert:

Hallo!

Snel, asynchroon en zonder overhead bouwen

Polyglot bouwt je meertalige website net zo snel als het je website voor je standaardtaal bouwt. Polyglot runt met een minimale overhead door simultaan alle talen van je website in een apart proces te bouwen. Dit betekent dat je website wordt gebouwd in een tijd die onafhankelijk is van de hoeveelheid talen die je wil ondersteunen.

Download

Polyglot is beschikbaar als een ruby gem of als een Jekyll-plug-in. Het kan worden geïnstalleerd met:

  gem install 'jekyll-polyglot'

Related Posts

            Polyglot 1.5.1
            01 Oct 2022

            Dutch Site Support
            15 Jan 2022

            Polyglot 1.5.0
            17 Jul 2021


text:
<?xml version="1.0" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.txtr</groupId>
    <artifactId>hibernate-delta</artifactId>
    <version>0.37-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>com.txtr.hibernate-delta</name>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <preparationGoals>clean install</preparationGoals>
                    <arguments>-DskipTests</arguments>
                    <useReleaseProfile>false</useReleaseProfile>
                    <goals>clean deploy</goals>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.1</version>
            <exclusions>
                <exclusion>
                    <groupId>xmlpull</groupId>
                    <artifactId>xmlpull</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
       	    <groupId>com.github.storecast.liquibase</groupId>
       	    <artifactId>liquibase-core</artifactId>
       	    <version>11cedf9247bf5a4221b4e7a0702e040791e01641</version>
       	</dependency>

        <!--It's tested with this oracle driver-->
        <!--<dependency>-->
            <!--<groupId>com.oracle</groupId>-->
            <!--<artifactId>ojdbc6</artifactId>-->
            <!--<version>11.2.0.2</version>-->
        <!--</dependency>-->

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
            <version>3.6.2</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>

    <distributionManagement>
        <snapshotRepository>
            <id>ci</id>
            <name>ci-snapshots</name>
            <url>http://artifactory-backend.int.my-storecast.com/artifactory/ext-snapshots-local</url>
        </snapshotRepository>
        <repository>
            <id>ci-releases</id>
            <name>ci-releases</name>
            <url>http://artifactory-backend.int.my-storecast.com/artifactory/ext-releases-local</url>
        </repository>
    </distributionManagement>

    <scm>
        <connection>scm:git:git@github.com:storecast/hibernate-delta.git</connection>
        <developerConnection>scm:git:git@github.com:storecast/hibernate-delta.git</developerConnection>
      <tag>HEAD</tag>
  </scm>

</project>


text:
(function( jQuery ) {

var rclass = /[\n\t]/g,
	rspaces = /\s+/,
	rreturn = /\r/g,
	rspecialurl = /^(?:href|src|style)$/,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea)?$/i,
	rradiocheck = /^(?:radio|checkbox)$/i;

jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.attr );
	},

	removeAttr: function( name, fn ) {
		return this.each(function(){
			jQuery.attr( this, name, "" );
			if ( this.nodeType === 1 ) {
				this.removeAttribute( name );
			}
		});
	},

	addClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.addClass( value.call(this, i, self.attr("class")) );
			});
		}

		if ( value && typeof value === "string" ) {
			var classNames = (value || "").split( rspaces );

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 ) {
					if ( !elem.className ) {
						elem.className = value;

					} else {
						var className = " " + elem.className + " ", setClass = elem.className;
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
								setClass += " " + classNames[c];
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.removeClass( value.call(this, i, self.attr("class")) );
			});
		}

		if ( (value && typeof value === "string") || value === undefined ) {
			var classNames = (value || "").split( rspaces );

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						var className = (" " + elem.className + " ").replace(rclass, " ");
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[c] + " ", " ");
						}
						elem.className = jQuery.trim( className );

					} else {
						elem.className = "";
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value, isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className, i = 0, self = jQuery(this),
					state = stateVal,
					classNames = value.split( rspaces );

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space seperated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery.data( this, "__className__", this.className );
				}

				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ";
		for ( var i = 0, l = this.length; i < l; i++ ) {
			if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	},

	val: function( value ) {
		if ( !arguments.length ) {
			var elem = this[0];

			if ( elem ) {
				if ( jQuery.nodeName( elem, "option" ) ) {
					// attributes.value is undefined in Blackberry 4.7 but
					// uses .value. See #6932
					var val = elem.attributes.value;
					return !val || val.specified ? elem.value : elem.text;
				}

				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type === "select-one";

					// Nothing was selected
					if ( index < 0 ) {
						return null;
					}

					// Loop through all the selected options
					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
						var option = options[ i ];

						// Don't return options that are disabled or in a disabled optgroup
						if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
								(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {

							// Get the specific value for the option
							value = jQuery(option).val();

							// We don't need an array for one selects
							if ( one ) {
								return value;
							}

							// Multi-Selects return an array
							values.push( value );
						}
					}

					return values;
				}

				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
					return elem.getAttribute("value") === null ? "on" : elem.value;
				}

				// Everything else, we just grab the value
				return (elem.value || "").replace(rreturn, "");

			}

			return undefined;
		}

		var isFunction = jQuery.isFunction(value);

		return this.each(function(i) {
			var self = jQuery(this), val = value;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call(this, i, self.val());
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			}

			if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
				this.checked = jQuery.inArray( self.val(), val ) >= 0;

			} else if ( jQuery.nodeName( this, "select" ) ) {
				var values = jQuery.makeArray(val);

				jQuery( "option", this ).each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});

				if ( !values.length ) {
					this.selectedIndex = -1;
				}

			} else {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	attrFn: {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true
	},

	attr: function( elem, name, value, pass ) {
		// don't set attributes on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
			return undefined;
		}

		if ( pass && name in jQuery.attrFn ) {
			return jQuery(elem)[name](value);
		}

		var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
			// Whether we are setting (or getting)
			set = value !== undefined;

		// Try to normalize/fix the name
		name = notxml && jQuery.props[ name ] || name;

		// Only do all the following if this is a node (faster for style)
		if ( elem.nodeType === 1 ) {
			// These attributes require special treatment
			var special = rspecialurl.test( name );

			// Safari mis-reports the default selected property of an option
			// Accessing the parent's selectedIndex property fixes it
			if ( name === "selected" && !jQuery.support.optSelected ) {
				var parent = elem.parentNode;
				if ( parent ) {
					parent.selectedIndex;

					// Make sure that it also works with optgroups, see #5701
					if ( parent.parentNode ) {
						parent.parentNode.selectedIndex;
					}
				}
			}

			// If applicable, access the attribute via the DOM 0 way
			// 'in' checks fail in Blackberry 4.7 #6931
			if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
				if ( set ) {
					// We can't allow the type property to be changed (since it causes problems in IE)
					if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
						jQuery.error( "type property can't be changed" );
					}

					if ( value === null ) {
						if ( elem.nodeType === 1 ) {
							elem.removeAttribute( name );
						}

					} else {
						elem[ name ] = value;
					}
				}

				// browsers index elements by id/name on forms, give priority to attributes.
				if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
					return elem.getAttributeNode( name ).nodeValue;
				}

				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				if ( name === "tabIndex" ) {
					var attributeNode = elem.getAttributeNode( "tabIndex" );

					return attributeNode && attributeNode.specified ?
						attributeNode.value :
						rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
							0 :
							undefined;
				}

				return elem[ name ];
			}

			if ( !jQuery.support.style && notxml && name === "style" ) {
				if ( set ) {
					elem.style.cssText = "" + value;
				}

				return elem.style.cssText;
			}

			if ( set ) {
				// convert the value to a string (all browsers do this but IE) see #1070
				elem.setAttribute( name, "" + value );
			}

			// Ensure that missing attributes return undefined
			// Blackberry 4.7 returns "" from getAttribute #6938
			if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
				return undefined;
			}

			var attr = !jQuery.support.hrefNormalized && notxml && special ?
					// Some attributes require a special call on IE
					elem.getAttribute( name, 2 ) :
					elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return attr === null ? undefined : attr;
		}
	}
});

})( jQuery );


text:
#ifndef CAPABILITIESSTORAGE_H
#define CAPABILITIESSTORAGE_H

#include <string>
#include <vector>

#include <boost/mpl/push_front.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/optional.hpp>

#include <muesli/Traits.h>

#include "joynr/serializer/Serializer.h"
#include "joynr/types/DiscoveryEntry.h"

namespace joynr
{

namespace capabilities
{

using joynr::types::DiscoveryEntry;

namespace tags
{
struct DomainAndInterface;
struct ParticipantId;
struct ExpiryDate;
struct Timestamp;
} // namespace tags

using InterfaceNameKey = BOOST_MULTI_INDEX_CONST_MEM_FUN(DiscoveryEntry,
                                                         const std::string&,
                                                         getInterfaceName);
using DomainKey = BOOST_MULTI_INDEX_CONST_MEM_FUN(DiscoveryEntry, const std::string&, getDomain);
using ParticipantIdKey = BOOST_MULTI_INDEX_CONST_MEM_FUN(DiscoveryEntry,
                                                         const std::string&,
                                                         getParticipantId);

using ExpiryDateKey = BOOST_MULTI_INDEX_CONST_MEM_FUN(DiscoveryEntry,
                                                      const std::int64_t&,
                                                      getExpiryDateMs);

namespace bmi = boost::multi_index;

struct LocalDiscoveryEntry : public DiscoveryEntry {
    LocalDiscoveryEntry() : DiscoveryEntry(), gbids()
    {
    }
    LocalDiscoveryEntry(const DiscoveryEntry& entry,
                        const std::vector<std::string>& gbidsParam = {})
            : DiscoveryEntry(entry), gbids(gbidsParam)
    {
    }
    std::vector<std::string> gbids;

    template <typename Archive>
    void serialize(Archive& archive)
    {
        archive(muesli::BaseClass<joynr::types::DiscoveryEntry>(this), MUESLI_NVP(gbids));
    }
};

using Container = bmi::multi_index_container<
        LocalDiscoveryEntry,
        bmi::indexed_by<
                bmi::hashed_non_unique<
                        bmi::tag<tags::DomainAndInterface>,
                        bmi::composite_key<LocalDiscoveryEntry, DomainKey, InterfaceNameKey>>,
                bmi::hashed_unique<bmi::tag<tags::ParticipantId>, ParticipantIdKey>,
                bmi::ordered_non_unique<bmi::tag<tags::ExpiryDate>, ExpiryDateKey>>>;

using Timestamp = std::chrono::time_point<std::chrono::system_clock>;

struct CachedDiscoveryEntry : public DiscoveryEntry {
    CachedDiscoveryEntry(const DiscoveryEntry& entry, Timestamp timestamp)
            : DiscoveryEntry(entry), _timestamp(timestamp)
    {
    }
    Timestamp _timestamp;
};

using ContainerIndices = Container::index_specifier_type_list;
using SequencedContainerIndices = boost::mpl::push_front<ContainerIndices, bmi::sequenced<>>::type;
using TimestampKey = BOOST_MULTI_INDEX_MEMBER(CachedDiscoveryEntry, Timestamp, _timestamp);
using TimestampIndex = bmi::ordered_non_unique<bmi::tag<tags::Timestamp>, TimestampKey>;
using CacheContainerIndices =
        boost::mpl::push_back<SequencedContainerIndices, TimestampIndex>::type;

using CachingContainer = bmi::multi_index_container<CachedDiscoveryEntry, CacheContainerIndices>;

template <typename C>
class BaseStorage
{
public:
    virtual ~BaseStorage() = default;
    virtual std::vector<DiscoveryEntry> lookupByDomainAndInterface(
            const std::string& domain,
            const std::string& interface) const
    {
        return lookupByDomainAndInterfaceFiltered(domain, interface, NoFilter());
    }

    virtual boost::optional<DiscoveryEntry> lookupByParticipantId(
            const std::string& participantId) const
    {
        return lookupByParticipantIdFiltered(participantId, NoFilter());
    }

    virtual void removeByParticipantId(const std::string& participantId)
    {
        auto& index = _container.template get<tags::ParticipantId>();
        auto it = index.find(participantId);
        if (it != index.end()) {
            index.erase(it);
        }
    }

    virtual void clear()
    {
        _container.clear();
    }

    template <typename Archive>
    void serialize(Archive& archive)
    {
        archive(_container);
    }

    auto begin()
    {
        return _container.begin();
    }

    auto begin() const
    {
        return _container.begin();
    }

    auto cbegin() const
    {
        return _container.cbegin();
    }

    auto end()
    {
        return _container.end();
    }

    auto end() const
    {
        return _container.end();
    }

    auto cend() const
    {
        return _container.cend();
    }

    virtual std::size_t size() const
    {
        return _container.size();
    }

    /**
     * @brief removes expired entries based on expiryDate
     * @return expired/removed entries
     */
    virtual std::vector<DiscoveryEntry> removeExpired()
    {
        auto& index = _container.template get<tags::ExpiryDate>();
        auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
                           std::chrono::system_clock::now().time_since_epoch())
                           .count();
        auto last = index.lower_bound(now);
        std::vector<DiscoveryEntry> removedEntries(index.begin(), last);
        index.erase(index.begin(), last);
        return removedEntries;
    }

    std::vector<std::string> touchAndReturnGlobalParticipantIds(
            const std::int64_t newLastSeenDateMs,
            const std::int64_t newExpiryDateMs)
    {
        std::vector<std::string> result;
        auto modifier = [&result, newLastSeenDateMs, newExpiryDateMs](DiscoveryEntry& entry) {
            bool refresh_entry = false;
            if (newLastSeenDateMs > entry.getLastSeenDateMs()) {
                entry.setLastSeenDateMs(newLastSeenDateMs);
                refresh_entry = true;
            }
            if (newExpiryDateMs > entry.getExpiryDateMs()) {
                entry.setExpiryDateMs(newExpiryDateMs);
                refresh_entry = true;
            }
            if (refresh_entry && entry.getQos().getScope() == types::ProviderScope::GLOBAL) {
                result.push_back(entry.getParticipantId());
            }
        };
        auto& index = _container.template get<tags::ParticipantId>();
        for (auto it = index.begin(); it != index.end(); it++) {
            index.modify(it, modifier);
        }
        return result;
    }

    void touchSelected(const std::vector<std::string> participantIds,
                       const std::int64_t newLastSeenDateMs,
                       const std::int64_t newExpiryDateMs)
    {
        auto modifier = [newLastSeenDateMs, newExpiryDateMs](DiscoveryEntry& entry) {
            if (newLastSeenDateMs > entry.getLastSeenDateMs()) {
                entry.setLastSeenDateMs(newLastSeenDateMs);
            }
            if (newExpiryDateMs > entry.getExpiryDateMs()) {
                entry.setExpiryDateMs(newExpiryDateMs);
            }
        };
        auto& index = _container.template get<tags::ParticipantId>();
        for (const auto& participantId : participantIds) {
            auto it = index.find(participantId);
            if (it != index.end()) {
                index.modify(it, modifier);
            }
        }
    }

protected:
    template <typename FilterFun>
    std::vector<DiscoveryEntry> lookupByDomainAndInterfaceFiltered(const std::string& domain,
                                                                   const std::string& interface,
                                                                   FilterFun filterFun) const
    {
        std::vector<DiscoveryEntry> result;

        auto& index = _container.template get<tags::DomainAndInterface>();
        auto range = index.equal_range(std::tie(domain, interface));
        std::copy_if(range.first, range.second, std::back_inserter(result), filterFun);

        return result;
    }

    template <typename FilterFun>
    boost::optional<DiscoveryEntry> lookupByParticipantIdFiltered(const std::string& participantId,
                                                                  FilterFun filterFun) const
    {
        boost::optional<DiscoveryEntry> result;

        auto& index = _container.template get<tags::ParticipantId>();
        auto it = index.find(participantId);
        if (it != index.end()) {
            if (filterFun(*it)) {
                result = *it;
            }
        }
        return result;
    }

    struct NoFilter {
        template <typename T>
        bool operator()(T&&) const
        {
            return true;
        }
    };

    C _container;
};

class Storage : public BaseStorage<Container>
{
public:
    virtual ~Storage() = default;
    virtual void insert(const DiscoveryEntry& entry, const std::vector<std::string>& gbids = {})
    {
        auto& index = _container.get<tags::ParticipantId>();
        LocalDiscoveryEntry entryWithGbids(entry, gbids);
        auto insertResult = index.insert(entryWithGbids);

        // entry already existed
        if (!insertResult.second) {

            auto existingIt = insertResult.first;

            // replace
            bool replaceResult = index.replace(existingIt, entryWithGbids);
            assert(replaceResult);
            std::ignore = replaceResult;
        }
    }
};

class CachingStorage : public BaseStorage<CachingContainer>
{
private:
    static auto filterByAge(std::chrono::milliseconds maxAge)
    {
        auto now = std::chrono::system_clock::now();
        return [maxAge, now](const CachedDiscoveryEntry& cachedEntry) {
            auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
                    now - cachedEntry._timestamp);
            return elapsed <= maxAge;
        };
    }

public:
    CachingStorage(std::size_t maxElementCount = 1000) : _maxElementCount(maxElementCount)
    {
    }

    virtual ~CachingStorage() = default;
    virtual void insert(const DiscoveryEntry& entry)
    {
        auto& index = _container.get<tags::ParticipantId>();

        auto now = std::chrono::system_clock::now();
        CachedDiscoveryEntry cachedEntry(entry, now);
        auto insertResult = index.insert(cachedEntry);

        // entry already existed
        if (!insertResult.second) {

            auto existingIt = insertResult.first;

            // replace
            bool replaceResult = index.replace(existingIt, cachedEntry);
            assert(replaceResult);
            std::ignore = replaceResult;

            // rank to top
            auto sequencedIt = _container.project<0>(existingIt);
            _container.relocate(_container.begin(), sequencedIt);
        } else if (_container.size() > _maxElementCount) {
            _container.pop_back();
        }
    }

    virtual boost::optional<DiscoveryEntry> lookupCacheByParticipantId(
            const std::string& participantId,
            std::chrono::milliseconds maxAge) const
    {
        return lookupByParticipantIdFiltered(participantId, filterByAge(maxAge));
    }

    virtual std::vector<DiscoveryEntry> lookupCacheByDomainAndInterface(
            const std::string& domain,
            const std::string& interface,
            std::chrono::milliseconds maxAge) const
    {
        return lookupByDomainAndInterfaceFiltered(domain, interface, filterByAge(maxAge));
    }

private:
    std::size_t _maxElementCount;
};

} // namespace capabilities

} // namespace joynr

MUESLI_REGISTER_TYPE(joynr::capabilities::BaseStorage<joynr::capabilities::Container>,
                     "joynr.capabilities.BaseStorage")
MUESLI_REGISTER_POLYMORPHIC_TYPE(joynr::capabilities::Storage,
                                 joynr::capabilities::BaseStorage<joynr::capabilities::Container>,
                                 "joynr::capabilities::Storage")

namespace muesli
{
template <>
struct SkipIntroOutroTraits<joynr::capabilities::Storage> : std::true_type {
};
} // namespace muesli

#endif // CAPABILITIESSTORAGE_H


text:
set(files
    debugger.cpp
    get_gles_proc_address.cpp
    get_vulkan_proc_address.cpp
    mutex.cpp
    thread.cpp
    thread_local.cpp
)
set(dirs

)


text:
using System;

namespace Hangfire.MemoryStorage.Dto
{
    public interface IExpirable
    {
        DateTime? ExpireAt { get; }
    }
}


text:
local REL = (...):gsub('[^.]*$', '')

local sdl = require(REL .. 'sdl')

local SpriteBatch = setmetatable({}, { __call = function (self, ...)
    local object = setmetatable({}, { __index = self })
    return object, self.constructor(object, ...)
end })

--[[
spriteBatch = SpriteBatch( image, size )

Arguments

Image image
    The Image to use for the sprites.
number size (1000)
    The max number of sprites.

Returns

SpriteBatch spriteBatch
    The new SpriteBatch.
--]]
function SpriteBatch:constructor (image)
    self.image = image
    self.sprites = {}
end

function SpriteBatch:clear ()
    self.sprites = {}
end

--[[
id = SpriteBatch:add( quad, x, y, r, sx, sy )

Arguments

Quad quad
    The Quad to add.
number x
    The position to draw the object (x-axis).
number y
    The position to draw the object (y-axis).
number r (0)
    Orientation (radians). (not implemented)
number sx (1)
    Scale factor (x-axis).
number sy (sx)
    Scale factor (y-axis).

Returns

number id
    An identifier for the added sprite.
--]]
function SpriteBatch:add (quad, x, y, r, sx, sy)
    local sprites = self.sprites

    sprites[#sprites + 1] = { quad = quad, x = x, y = y,
        sx = sx or 1, sy = sy or 1 }
end

function SpriteBatch:draw ()
    local image = self.image
    local renderer = image.sdlRenderer
    local texture = image.sdlTexture

    for _, sprite in ipairs(self.sprites) do
        local quad = sprite.quad
        local w = math.ceil(quad[3] * sprite.sx)
        local h = math.ceil(quad[4] * sprite.sy)
        local src = sdl.Rect(quad)
        local dst = sdl.Rect(sprite.x, sprite.y, w, h)
        sdl.renderCopy(renderer, texture, src, dst)
    end
end

return SpriteBatch


text:
<sqx-title message="i18n:rules.ruleEvents.listPageTitle"></sqx-title>

<sqx-layout layout="main" titleText="i18n:common.events" titleIcon="events" [width]="50" [hideSidebar]="true">
    <ng-container menu>
        <button type="button" class="btn btn-text-secondary" (click)="reload()" title="i18n:rules.refreshEventsTooltip" shortcut="CTRL + B">
             {{ 'common.refresh' | sqxTranslate }}
        </button>

        <ng-container *ngIf="ruleEventsState.canCancelAll | async">
            <button type="button" class="btn btn-danger ms-2"
                (sqxConfirmClick)="cancelAll()"
                confirmTitle="i18n:rules.ruleEvents.cancelAllConfirmTitle"
                confirmText="i18n:rules.ruleEvents.cancelAllConfirmText"
                confirmRememberKey="cancelAllRuleEvents">
                {{ 'common.cancelAll' | sqxTranslate }}
            </button>
        </ng-container>
    </ng-container>

    <ng-container>
        <sqx-list-view [isLoading]="ruleEventsState.isLoading | async" [table]="true">

                            {{ 'common.status' | sqxTranslate }}

                            {{ 'common.event' | sqxTranslate }}

                            {{ 'common.description' | sqxTranslate }}

                            {{ 'common.created' | sqxTranslate }}

            <sqx-pager [autoHide]="true" [paging]="ruleEventsState.paging | async" (pagingChange)="ruleEventsState.page($event)"></sqx-pager>
        </sqx-list-view>
    </ng-container>
</sqx-layout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia elongata var. elongata Hillmann

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_displaynotif"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Display Notification" />
</LinearLayout>


text:
module Sorts
  module Comparison
    module Bubble
      def bubble_sort!
        each_index do |index|
          (size.pred).downto(index) do |i|
            self[i.pred], self[i] = self[i], self[i.pred] if self[i.pred] > self[i]
          end
        end

        self
      end

      def bubble_sort
        dup.bubble_sort!
      end
    end
  end
end


text:
TableFunctionStandart TBFunction;

#if defined ORI_WINDOWS
unsigned __stdcall _RunStart(void* param)
#endif
#if defined ORI_LINUX
void *_RunStart(void* param)
#endif
{
	int ID = *((int*)(&param));
	((*TBFunction.TBNull[ID].Function)());
	return 0;
}

bool NewThread(void* Param) {

#if defined ORI_WINDOWS

	unsigned threadID;
	if (_beginthreadex(NULL, 800, _RunStart, Param, 0, &threadID) == 0)
		return false;

#endif

#if defined ORI_LINUX

	pthread_t th;
	if (pthread_create(&th, NULL, _RunStart, Param) != 0)
		return false;
	pthread_detach(th);

#endif
	return true;
}

void OriThread::Run()  {
	for (int i = 0; i < TBFunction.CountTBNull; i++)
	NewThread((void *)i);
}

OriThread& OriThread::operator << (FunctionNull FuncStart) {
	TBFunction.AddFunction(FuncStart);
	return *this;
}

OriThread::OriThread(int CountThread) {
	TBFunction.ReCreateTB(CountThread);
}

bool OriCreateThread(FUNCTION_RUN, void* Param)
{
#if defined ORI_WINDOWS

	if (_beginthread(_StartAddress, 8, Param) == 0)
		return false;

#endif

#if defined ORI_LINUX

	pthread_t th;
	if (pthread_create(&th, NULL, _StartAddress, Param) != 0)
		return false;
	pthread_detach(th);

#endif
	return true;
}


text:
#ifndef PPAPI_TESTS_PP_THREAD_H_
#define PPAPI_TESTS_PP_THREAD_H_

#include "ppapi/c/pp_macros.h"
#include "ppapi/tests/test_utils.h"

#if defined(PPAPI_POSIX)
#include <pthread.h>
#elif defined(PPAPI_OS_WIN)
#include <process.h>
#include <windows.h>
#else
#error No thread library detected.
#endif

/**
 * @file
 * This file provides platform-independent wrappers around threads. This is for
 * use by PPAPI wrappers and tests which need to run on multiple platforms to
 * support both trusted platforms (Windows, Mac, Linux) and untrusted (Native
 * Client). Apps that use PPAPI only with Native Client should generally use the
 * Native Client POSIX implementation instead.
 *
 * TODO(dmichael): Move this file to ppapi/c and delete this comment, if we end
 * up needing platform independent threads in PPAPI C or C++. This file was
 * written using inline functions and PPAPI naming conventions with the intent
 * of making it possible to put it in to ppapi/c. Currently, however, it's only
 * used in ppapi/tests, so is not part of the published API.
 */

typedef void (PP_ThreadFunction)(void* data);

#if defined(PPAPI_POSIX)
typedef pthread_t PP_Thread;
#elif defined(PPAPI_OS_WIN)
struct PP_Thread {
  HANDLE handle;
  PP_ThreadFunction* thread_func;
  void* thread_arg;
};
#endif

PP_INLINE bool PP_CreateThread(PP_Thread* thread,
                               PP_ThreadFunction function,
                               void* thread_arg);
PP_INLINE void PP_JoinThread(PP_Thread thread);

#if defined(PPAPI_POSIX)
/* Because POSIX thread functions return void* and Windows thread functions do
 * not, we make PPAPI thread functions have the least capability (no returns).
 * This struct wraps the user data & function so that we can use the correct
 * function type on POSIX platforms.
 */
struct PP_ThreadFunctionArgWrapper {
  void* user_data;
  PP_ThreadFunction* user_function;
};

PP_INLINE void* PP_POSIXThreadFunctionThunk(void* posix_thread_arg) {
  PP_ThreadFunctionArgWrapper* arg_wrapper =
      (PP_ThreadFunctionArgWrapper*)posix_thread_arg;
  arg_wrapper->user_function(arg_wrapper->user_data);
  free(posix_thread_arg);
  return NULL;
}

PP_INLINE bool PP_CreateThread(PP_Thread* thread,
                               PP_ThreadFunction function,
                               void* thread_arg) {
  PP_ThreadFunctionArgWrapper* arg_wrapper =
      (PP_ThreadFunctionArgWrapper*)malloc(sizeof(PP_ThreadFunctionArgWrapper));
  arg_wrapper->user_function = function;
  arg_wrapper->user_data = thread_arg;
  return (pthread_create(thread,
                         NULL,
                         PP_POSIXThreadFunctionThunk,
                         arg_wrapper) == 0);
}

PP_INLINE void PP_JoinThread(PP_Thread thread) {
  void* exit_status;
  pthread_join(thread, &exit_status);
}

#elif defined(PPAPI_OS_WIN)

PP_INLINE unsigned __stdcall PP_WindowsThreadFunction(void* param) {
  PP_Thread* thread = reinterpret_cast<PP_Thread*>(param);
  thread->thread_func(thread->thread_arg);
  return 0;
}

PP_INLINE bool PP_CreateThread(PP_Thread* thread,
                               PP_ThreadFunction function,
                               void* thread_arg) {
  if (!thread)
    return false;
  thread->thread_func = function;
  thread->thread_arg = thread_arg;
  uintptr_t raw_handle = ::_beginthreadex(NULL,
                                          0,  /* Use default stack size. */
                                          &PP_WindowsThreadFunction,
                                          thread,
                                          0,
                                          NULL);
  thread->handle = reinterpret_cast<HANDLE>(raw_handle);
  return (thread->handle != NULL);
}

PP_INLINE void PP_JoinThread(PP_Thread thread) {
  ::WaitForSingleObject(thread.handle, INFINITE);
  ::CloseHandle(thread.handle);
}

#endif

/**
 * @}
 */

#endif  /* PPAPI_TESTS_PP_THREAD_H_ */


text:
using System;
using System.Diagnostics;

namespace Miracle.FileZilla.Api.Samples
{
    internal class Stopwatch2 : Stopwatch
    {
        private TimeSpan? _lastSplit;

        public new static Stopwatch2 StartNew()
        {
            var stopwatch2 = new Stopwatch2();
            stopwatch2.Start();
            return stopwatch2;
        }

        public TimeSpan GetDelta()
        {
            var elapsed = this.Elapsed;
            var delta = elapsed - _lastSplit.GetValueOrDefault();
            _lastSplit = elapsed;
            return delta;
        }
    }
}


text:
ScalaJS.impls.scala_collection_SortedMapLike$class__firstKey__Lscala_collection_SortedMapLike__O = (function($$this) {
  return ScalaJS.as.scala_Tuple2($$this.head__O()).$$und1__O()
});
ScalaJS.impls.scala_collection_SortedMapLike$class__lastKey__Lscala_collection_SortedMapLike__O = (function($$this) {
  return ScalaJS.as.scala_Tuple2($$this.last__O()).$$und1__O()
});
ScalaJS.impls.scala_collection_SortedMapLike$class__keySet__Lscala_collection_SortedMapLike__Lscala_collection_SortedSet = (function($$this) {
  return new ScalaJS.c.scala_collection_SortedMapLike$DefaultKeySortedSet().init___Lscala_collection_SortedMapLike($$this)
});
ScalaJS.impls.scala_collection_SortedMapLike$class__updated__Lscala_collection_SortedMapLike__O__O__Lscala_collection_SortedMap = (function($$this, key, value) {
  return $$this.$$plus__Lscala_Tuple2__Lscala_collection_SortedMap(new ScalaJS.c.scala_Tuple2().init___O__O(key, value))
});
ScalaJS.impls.scala_collection_SortedMapLike$class__$plus__Lscala_collection_SortedMapLike__Lscala_Tuple2__Lscala_Tuple2__Lscala_collection_Seq__Lscala_collection_SortedMap = (function($$this, elem1, elem2, elems) {
  var m = new ScalaJS.c.scala_runtime_ObjectRef().init___O($$this.$$plus__Lscala_Tuple2__Lscala_collection_SortedMap(elem1).$$plus__Lscala_Tuple2__Lscala_collection_SortedMap(elem2));
  elems.foreach__Lscala_Function1__V(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(m$1) {
    return (function(e) {
      m$1.elem$1 = ScalaJS.as.scala_collection_SortedMap(m$1.elem$1).$$plus__Lscala_Tuple2__Lscala_collection_SortedMap(e);
      return ScalaJS.bV(undefined)
    })
  })(m)));
  return ScalaJS.as.scala_collection_SortedMap(m.elem$1)
});
ScalaJS.impls.scala_collection_SortedMapLike$class__filterKeys__Lscala_collection_SortedMapLike__Lscala_Function1__Lscala_collection_SortedMap = (function($$this, p) {
  return new ScalaJS.c.scala_collection_SortedMapLike$$anon$1().init___Lscala_collection_SortedMapLike__Lscala_Function1($$this, p)
});
ScalaJS.impls.scala_collection_SortedMapLike$class__mapValues__Lscala_collection_SortedMapLike__Lscala_Function1__Lscala_collection_SortedMap = (function($$this, f) {
  return new ScalaJS.c.scala_collection_SortedMapLike$$anon$2().init___Lscala_collection_SortedMapLike__Lscala_Function1($$this, f)
});
ScalaJS.impls.scala_collection_SortedMapLike$class__$plus$plus__Lscala_collection_SortedMapLike__Lscala_collection_GenTraversableOnce__Lscala_collection_SortedMap = (function($$this, xs) {
  var x$1 = ScalaJS.as.scala_collection_SortedMap($$this.repr__O());
  return ScalaJS.as.scala_collection_SortedMap(xs.seq__Lscala_collection_TraversableOnce().$$div$colon__O__Lscala_Function2__O(x$1, new ScalaJS.c.scala_scalajs_runtime_AnonFunction2().init___Lscala_scalajs_js_Function2((function() {
    return (function(x$2, x$3) {
      return x$2.$$plus__Lscala_Tuple2__Lscala_collection_SortedMap(x$3)
    })
  })())))
});
ScalaJS.impls.scala_collection_SortedMapLike$class__$init$__Lscala_collection_SortedMapLike__V = (function($$this) {
  /*<skip>*/
});
//@ sourceMappingURL=SortedMapLike$class.js.map


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="author" content="Subil" />
<meta name="description" content="Subil's programming and tech blog" />
<meta name="keywords" content="blog, tech, programming" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

<link rel="canonical" href="/tags/privacy/">
<base href="/" />
<meta property="og:title" content="Privacy" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="/tags/privacy/" />
<meta property="og:updated_time" content="2017-02-25T00:00:00+00:00"/>

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Privacy"/>
<meta name="twitter:description" content=""/>

<meta itemprop="name" content="Privacy">
<meta itemprop="description" content="">

<link rel="stylesheet" href="css/layout.css" />

<title>

     Privacy

</title>

      S.P.A.M.

  Subil's Public Archive of the Mundane

Posts

Tags

About

    Privacy

2017

 Do They Have Control?

        #privacy

 Feb 25, 2017

GitHub

Twitter

  RSS

 Copyright (c) 2016 - 2020. Licensed under CC BY-NC-SA 4.0

 Send any corrections/opinions to subil [the symbol] secondspass [the dot] org


text:
var should = require('should');

var testconfig = require('../etc/test-config-qa.js');

var marklogic = require('../');
var q = marklogic.queryBuilder;

var db = marklogic.createDatabaseClient(testconfig.restReaderConnection);
var dbWriter = marklogic.createDatabaseClient(testconfig.restWriterConnection);
var dbAdmin = marklogic.createDatabaseClient(testconfig.restAdminConnection);

describe('Document geo query test', function(){
  before(function(done){
    this.timeout(10000);
    dbWriter.documents.write({
      uri: '/test/query/geo/doc1.json',
      collections: ['geoCollection'],
      contentType: 'application/json',
      content: {
        title: 'karl_kara',
        gElemPoint: '12,5',
        gElemChildParent: {
          gElemChildPoint: '12,5'
        },
        gElemPair: {
          latitude: 12,
          longitude: 5
        }
      }
    },
    {
      uri: '/test/query/geo/doc2.json',
      collections: ['geoCollection'],
      contentType: 'application/json',
      content: {
        title: 'bob_long',
        gElemPoint: '34,88',
        gElemChildParent: {
          gElemChildPoint: '34,88'
        },
        gElemPair: {
          latitude: 34,
          longitude: 88
        }
      }
    },
    {
      uri: '/test/query/geo/doc3.json',
      collections: ['geoCollection'],
      contentType: 'application/json',
      content: {
        title: 'sam_sung',
        gElemPoint: '101,4',
        gElemChildParent: {
          gElemChildPoint: '101,4'
        },
        gElemPair: {
          latitude: 101,
          longitude: 4
        }
      }
    },
    {
      uri: '/test/query/geo/doc4.xml',
      collections: ['geoCollection'],
      contentType: 'application/xml',
      content:
        '<root>' +
        '  <title>ben_red</title>' +
        '  <gElemPoint>50,44</gElemPoint>' +
        '  <gElemChildParent>' +
        '    <gElemChildPoint>50,44</gElemChildPoint>' +
        '  </gElemChildParent>' +
        '  <gElemPair>' +
        '    <latitude>50</latitude>' +
        '    <longitude>44</longitude>' +
        '  </gElemPair>' +
        '</root>'
    },
    {
      uri: '/test/query/geo/doc5.xml',
      collections: ['geoCollection'],
      contentType: 'application/xml',
      content:
        '<root>' +
        '  <title>george_blue</title>' +
        '  <gElemPoint>250,144</gElemPoint>' +
        '  <gElemChildParent>' +
        '    <gElemChildPoint>250,144</gElemChildPoint>' +
        '  </gElemChildParent>' +
        '  <gElemPair>' +
        '    <latitude>250</latitude>' +
        '    <longitude>144</longitude>' +
        '  </gElemPair>' +
        '  <gAttrPair latitude="250" longitude="144"/>' +
        '</root>'
    },
    {
      uri: '/test/query/geo/doc6.json',
      collections: ['geoCollection'],
      contentType: 'application/json',
      content: {
        title: 'cross_pole',
        gElemPoint: '37.2768,-77.4008',
        gElemChildParent: {
          gElemChildPoint: '37.2768,-77.4008'
        },
        gElemPair: {
          latitude: 37.2768,
          longitude: -77.4008
        }
      }
    }
    ).
    result(function(response){done();}, done);
  });

  it('should do geo property pair query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
            q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
            q.latlon(12, 5)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo property pair query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.latlon(12, 5),
          q.geoOptions('boundaries-latitude-excluded')
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo property point query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoProperty('gElemPoint'),
          q.point(34, 88)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('bob_long');
      done();
    }, done);
  });

  it('should do geo property child point query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoProperty(
            q.property('gElemChildParent'),
            q.property('gElemChildPoint')
          ),
          q.latlon(34, 88)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('bob_long');
      done();
    }, done);
  });

  it('should do combination geo and word query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.or(
          q.geospatial(
            q.geoProperty(
              q.property('gElemChildParent'),
              q.property('gElemChildPoint')
            ),
            q.latlon(34, 88)
          ),
          q.word('title', 'karl_kara')
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(2);
      //response[0].content.title.should.equal('bob_long');
      done();
    }, done);
  });

  it('should do geo property pair query with circle in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.circle(100, 11, 5)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo property pair query with circle in crossed pole', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.circle(2000, 32.2768, -62.4008)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('cross_pole');
      done();
    }, done);
  });

  it('should do geo property pair query with box in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.box(11, 4, 20, 10),
          q.geoOptions('boundaries-included')
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo property pair query with box boundaries included in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.box(12, 5, 20, 10),
          q.geoOptions('boundaries-included')
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo property pair query with box boundaries excluded in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.box(12, 5, 20, 10),
          q.geoOptions('boundaries-excluded')
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(0);
      done();
    }, done);
  });

  it('should do geo property pair query with polygon in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPropertyPair('gElemPair', 'latitude', 'longitude'),
          q.polygon([12, 5], [20, 10], [34, 22])
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo path query in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPath('gElemChildParent/gElemChildPoint'),
          q.latlon(12, 5)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo path query with pathIndex in json doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoPath(q.pathIndex('gElemChildParent/gElemChildPoint')),
          q.point(12, 5)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].content.title.should.equal('karl_kara');
      done();
    }, done);
  });

  it('should do geo element pair query in xml doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoElementPair('gElemPair', 'latitude', 'longitude'),
          q.latlon(50, 44)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].uri.should.equal('/test/query/geo/doc4.xml');
      done();
    }, done);
  });

  it('should do geo element query in xml doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoElement('gElemPoint'),
          q.latlon(50, 44)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].uri.should.equal('/test/query/geo/doc4.xml');
      done();
    }, done);
  });

  it('should do geo attribute pair query in xml doc', function(done){
    dbWriter.documents.query(
      q.where(
        q.geospatial(
          q.geoAttributePair('gAttrPair', 'latitude', 'longitude'),
          q.circle(100, 240, 144)
        )
      )
    ).
    result(function(response) {
      //console.log(JSON.stringify(response, null, 2));
      response.length.should.equal(1);
      response[0].uri.should.equal('/test/query/geo/doc5.xml');
      done();
    }, done);
  });

  it('should delete all documents', function(done){
    dbAdmin.documents.removeAll({
      all: true
    }).
    result(function(response) {
      done();
    }, done);
  });

});


text:
package org.oscm.billing.external.context;

import java.io.Serializable;

/**
 * Specifies values for the keys in the context that defines the element for
 * which a price model is to be returned.
 */
public abstract class ContextValue<T> implements Serializable {

    private static final long serialVersionUID = 4738410026389162268L;

    /**
     * The value for a context key.
     */
    protected T value;

    /**
     * Constructs a context value object with the given value.
     *
     * @param value
     *            the value
     */
    public ContextValue(T value) {
        this.value = value;
    }

    /**
     * Returns the context value.
     *
     * @return the value
     */
    public abstract T getValue();

    /**
     * Sets the context value.
     *
     * @param value
     *            the value
     */
    public abstract void setValue(T value);

}


text:
import os
import time
import shutil

import autoqm.utils
import autoqm.connector

def select_push_target(registration_table,
						results_table,
						success_data_path):
	"""
	This method is to inform job pusher which targets
	to push, which need meet three requirements:
	1. status is job_success
	2. job files (.log and .inp) located as expected
	3. results table doesn't have this job at
	   that level of theory

	Returns a list of targets with necessary meta data
	"""
	reg_query = {"status":"job_success"}
	targets = list(registration_table.find(reg_query))

	selected_targets = []
	for target in targets:
		aug_inchi = str(target['aug_inchi'])
		spec_name = aug_inchi.replace('/', '_slash_')
		spec_path = os.path.join(success_data_path, spec_name)
		log_path = os.path.join(spec_path, 'input.log')
		inp_path = os.path.join(spec_path, 'input.inp')
		if os.path.exists(log_path) and os.path.exists(inp_path):
			level_of_theory = autoqm.utils.get_level_of_theory(inp_path)

			# query results table
			res_query = {"aug_inchi":aug_inchi,
						"level_of_theory":level_of_theory}
			res_entries = list(results_table.find(res_query))
			if len(res_entries) == 0:
				# means no records of this target
				# in results table
				selected_targets.append(target)
	return selected_targets

def push_jobs(registration_table, results_table, success_data_path):

	# select push targets
	targets = select_push_target(registration_table,
								results_table,
								success_data_path)

	for target in targets:
		aug_inchi = str(target['aug_inchi'])
		spec_name = aug_inchi.replace('/', '_slash_')
		spec_path = os.path.join(success_data_path, spec_name)

		inp_path = os.path.join(spec_path, 'input.inp')
		model_chemistry = autoqm.utils.get_level_of_theory(inp_path)

		smiles = str(target['SMILES_input'])

		# run cantherm
		thermo = autoqm.utils.run_cantherm(spec_path, model_chemistry, smiles)

		# push to results table
		Hf298 = thermo.H298.value_si/1000/4.184  # kcal/mol
		S298 = thermo.S298.value_si/4.184		 # cal/mol/K
		Cp300 = thermo.Cpdata.value_si[0]/4.184  # cal/mol/K
		Cp400 = thermo.Cpdata.value_si[1]/4.184  # cal/mol/K
		Cp500 = thermo.Cpdata.value_si[2]/4.184  # cal/mol/K
		Cp600 = thermo.Cpdata.value_si[3]/4.184  # cal/mol/K
		Cp800 = thermo.Cpdata.value_si[4]/4.184  # cal/mol/K
		Cp1000 = thermo.Cpdata.value_si[5]/4.184 # cal/mol/K
		Cp1500 = thermo.Cpdata.value_si[6]/4.184 # cal/mol/K

		# check results table again there's no
		# same entry
		res_query = {"aug_inchi":aug_inchi,
					"level_of_theory":model_chemistry}
		res_entries = list(results_table.find(res_query))

		if len(res_entries) > 0:
			continue

		# do the insertion
		insert_entry = {"aug_inchi" : aug_inchi,
						"Hf298(kcal/mol)" : Hf298,
						"S298(cal/mol/K)" : S298,
						"Cp300(cal/mol/K)" : Cp300,
						"Cp400(cal/mol/K)" : Cp400,
						"Cp500(cal/mol/K)" : Cp500,
						"Cp600(cal/mol/K)" : Cp600,
						"Cp800(cal/mol/K)" : Cp800,
						"Cp1000(cal/mol/K)" : Cp1000,
						"Cp1500(cal/mol/K)" : Cp1500,
						"timestamp" : time.time(),
						"SMILES_input" : smiles,
						"level_of_theory" : model_chemistry}

		results_table.insert_one(insert_entry)

def run():
	# get config info
	config = autoqm.utils.read_config()

	# connect to thermo central db
	auth_info = autoqm.utils.get_TCD_authentication_info()
	tcdi = autoqm.connector.ThermoCentralDatabaseInterface(*auth_info)
	tcd =  getattr(tcdi.client, 'thermoCentralDB')

	# get registration table and result table
	# and specify success job data path
	pusher_reg_table = getattr(tcd, 'saturated_ringcore_table')
	pusher_res_table = getattr(tcd, 'saturated_ringcore_res_table')
	success_data_path = os.path.join(config['QuantumMechanicJob']['scratch_data_path'],
									'success')

	push_jobs(pusher_reg_table, pusher_res_table, success_data_path)

run()


text:
package v1

import (
	"github.com/rancher/norman/lifecycle"
	"github.com/rancher/norman/resource"
	v1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

type DeploymentLifecycle interface {
	Create(obj *v1.Deployment) (runtime.Object, error)
	Remove(obj *v1.Deployment) (runtime.Object, error)
	Updated(obj *v1.Deployment) (runtime.Object, error)
}

type deploymentLifecycleAdapter struct {
	lifecycle DeploymentLifecycle
}

func (w *deploymentLifecycleAdapter) HasCreate() bool {
	o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)
	return !ok || o.HasCreate()
}

func (w *deploymentLifecycleAdapter) HasFinalize() bool {
	o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)
	return !ok || o.HasFinalize()
}

func (w *deploymentLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Create(obj.(*v1.Deployment))
	if o == nil {
		return nil, err
	}
	return o, err
}

func (w *deploymentLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Remove(obj.(*v1.Deployment))
	if o == nil {
		return nil, err
	}
	return o, err
}

func (w *deploymentLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Updated(obj.(*v1.Deployment))
	if o == nil {
		return nil, err
	}
	return o, err
}

func NewDeploymentLifecycleAdapter(name string, clusterScoped bool, client DeploymentInterface, l DeploymentLifecycle) DeploymentHandlerFunc {
	if clusterScoped {
		resource.PutClusterScoped(DeploymentGroupVersionResource)
	}
	adapter := &deploymentLifecycleAdapter{lifecycle: l}
	syncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient())
	return func(key string, obj *v1.Deployment) (runtime.Object, error) {
		newObj, err := syncFn(key, obj)
		if o, ok := newObj.(runtime.Object); ok {
			return o, err
		}
		return nil, err
	}
}