text:
package com.twosigma.beakerx.clojure.kernel;

import static com.twosigma.beakerx.DefaultJVMVariables.IMPORTS;
import static com.twosigma.beakerx.kernel.Utils.uuid;
import static java.util.Arrays.stream;

import clojure.lang.LazySeq;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twosigma.beakerx.DisplayerDataMapper;
import com.twosigma.beakerx.clojure.evaluator.ClojureEvaluator;
import com.twosigma.beakerx.clojure.handlers.ClojureCommOpenHandler;
import com.twosigma.beakerx.clojure.handlers.ClojureKernelInfoHandler;
import com.twosigma.beakerx.evaluator.Evaluator;
import com.twosigma.beakerx.handler.KernelHandler;
import com.twosigma.beakerx.kernel.CacheFolderFactory;
import com.twosigma.beakerx.kernel.CloseKernelAction;
import com.twosigma.beakerx.kernel.Kernel;
import com.twosigma.beakerx.kernel.KernelConfigurationFile;
import com.twosigma.beakerx.kernel.EvaluatorParameters;
import com.twosigma.beakerx.kernel.KernelRunner;
import com.twosigma.beakerx.kernel.KernelSocketsFactory;
import com.twosigma.beakerx.kernel.KernelSocketsFactoryImpl;
import com.twosigma.beakerx.kernel.handler.CommOpenHandler;
import com.twosigma.beakerx.kernel.magic.command.MagicCommandTypesFactory;
import com.twosigma.beakerx.kernel.magic.command.functionality.ClasspathAddMvnMagicCommand;
import com.twosigma.beakerx.message.Message;
import com.twosigma.beakerx.mimetype.MIMEContainer;
import jupyter.Displayer;
import jupyter.Displayers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Clojure extends Kernel {

  private Clojure(String sessionId, Evaluator evaluator, KernelSocketsFactory kernelSocketsFactory) {
    super(sessionId, evaluator, kernelSocketsFactory);
  }

  public Clojure(String sessionId, Evaluator evaluator, KernelSocketsFactory kernelSocketsFactory, CloseKernelAction closeKernelAction, CacheFolderFactory cacheFolderFactory) {
    super(sessionId, evaluator, kernelSocketsFactory, closeKernelAction, cacheFolderFactory);
  }

  @Override
  public CommOpenHandler getCommOpenHandler(Kernel kernel) {
    return new ClojureCommOpenHandler(kernel);
  }

  @Override
  public KernelHandler<Message> getKernelInfoHandler(Kernel kernel) {
    return new ClojureKernelInfoHandler(kernel);
  }

  public static void main(final String[] args) throws InterruptedException, IOException {
    KernelRunner.run(() -> {
      String id = uuid();
      KernelSocketsFactoryImpl kernelSocketsFactory = new KernelSocketsFactoryImpl(
              new KernelConfigurationFile(args));
      ClojureEvaluator evaluator = new ClojureEvaluator(id, id, getKernelParameters());
      return new Clojure(id, evaluator, kernelSocketsFactory);
    });
  }

  @Override
  protected void configureMagicCommands() {
    super.configureMagicCommands();
    ClasspathAddMvnMagicCommand mvnMagicCommand = MagicCommandTypesFactory.getClasspathAddMvnMagicCommand(this);
    mvnMagicCommand.addRepo("clojureRepo", "https://clojars.org/repo");
  }

  @Override
  protected void configureJvmRepr() {
    Displayers.register(LazySeq.class, new Displayer<LazySeq>() {
      @Override
      public Map<String, String> display(LazySeq value) {
        return new HashMap<String, String>() {{
          List<String> collect = stream(value.toArray()).map(Object::toString).collect(Collectors.toList());
          put(MIMEContainer.MIME.TEXT_PLAIN, new ArrayList<>(collect).toString());
        }};
      }
    });
    DisplayerDataMapper.register(converter);
  }

  private static ObjectMapper mapper = new ObjectMapper();

  private static DisplayerDataMapper.Converter converter = data -> {
    if (data instanceof Collection) {
      String json = mapper.writeValueAsString(data);
      return mapper.readValue(json, Object.class);
    }
    return data;
  };

  private static EvaluatorParameters getKernelParameters() {
    HashMap<String, Object> kernelParameters = new HashMap<>();
    kernelParameters.put(IMPORTS, new ClojureDefaultVariables().getImports());
    return new EvaluatorParameters(kernelParameters);
  }
}


text:
#ifndef ALEXA_CLIENT_SDK_BLUETOOTHIMPLEMENTATIONS_BLUEZ_INCLUDE_BLUEZ_MEDIAENDPOINT_H_
#define ALEXA_CLIENT_SDK_BLUETOOTHIMPLEMENTATIONS_BLUEZ_INCLUDE_BLUEZ_MEDIAENDPOINT_H_

#include <atomic>
#include <condition_variable>
#include <vector>

#include <AVSCommon/AVS/AudioInputStream.h>
#include <AVSCommon/SDKInterfaces/Bluetooth/Services/A2DPSourceInterface.h>
#include <AVSCommon/Utils/Bluetooth/FormattedAudioStreamAdapter.h>

#include "BlueZ/BlueZDeviceManager.h"
#include "BlueZ/BlueZUtils.h"
#include "BlueZ/MediaContext.h"

#include <gio/gio.h>
#include <sbc/sbc.h>

namespace alexaClientSDK {
namespace bluetoothImplementations {
namespace blueZ {

/**
 * A DBus object implementing the MediaEndpoint1 interface of BlueZ. Registering it with DBus allows BlueZ to use it
 * for audio streaming using A2DP. This particular endpoint implements the SINK case, where remote bluetooth device is
 * streaming audio to our SDK.
 */
class MediaEndpoint : public DBusObject<MediaEndpoint> {
public:
    /**
     * Constructor inherited from @c DBusObject base class. Prepares a DBus object for registration.
     *
     * @param connection DBus connection to register object with.
     * @param endpointPath Object path to register object to.
     */
    MediaEndpoint(std::shared_ptr<DBusConnection> connection, const std::string& endpointPath);

    /**
     * Destructor
     */
    ~MediaEndpoint() override;

    /**
     * A callback called by BlueZ to notify MediaEndpoint of the stream codec configuration selected by both sides.
     *
     * @param arguments Variant containing the codec configuration bytes (4 bytes for SBC)
     * @param invocation DBus method invocation object used to report execution result.
     */
    void onSetConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation);

    /**
     * A callback called by BlueZ to asking MediaEndpoint to select the audio code configuration to use for the audio
     * streaming. BlueZ expects this method to return a variant containing the selected configuration. This
     * configuration will then be provided to the @c onSetConfiguration callback
     *
     * @param arguments Variant containing the available codec configurations. For SBC this is a 4 byte bitmask.
     * @param invocation DBus method invocation object used to report execution result.
     */
    void onSelectConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation);

    /**
     * A callback called by BlueZ to notify MediaEndpoint that it should reset the codec configuration.
     *
     * @param arguments Null
     * @param invocation DBus method invocation object used to report execution result.
     */
    void onClearConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation);

    /**
     * A callback called by BlueZ to notify MediaEndpoint that it is being release and will not be used anymore.
     *
     * @param arguments Null
     * @param invocation DBus method invocation object used to report execution result.
     */
    void onRelease(GVariant* arguments, GDBusMethodInvocation* invocation);

    /**
     * A callback called by @c DeviceManager to notify MediaEndpoint that BlueZ reported a streaming state change.
     *
     * @param newState A new @c MediaStreamingState reported by DBus.
     * @param devicePath DBus object path of the device reporting the state change.
     */
    void onMediaTransportStateChanged(
        avsCommon::utils::bluetooth::MediaStreamingState newState,
        const std::string& devicePath);

    /**
     * Get DBus object path of the media endpoint
     *
     * @return Object path of the media endpoint
     */
    std::string getEndpointPath() const;

    /**
     * Get DBus object path of the device the BlueZ currently uses this media endpoint with for streaming.
     *
     * @return Device object path.
     */
    std::string getStreamingDevicePath() const;

    /**
     * Get the @c FormattedAudioStreamAdapter for the audio stream being received from the remote bluetooth device over
     * A2DP. It is safe to call this method early.
     *
     * @return An @c FormattedAudioStreamAdapter object used by @c MediaEndpoint.
     */
    std::shared_ptr<avsCommon::utils::bluetooth::FormattedAudioStreamAdapter> getAudioStream();

private:
    /**
     * Operating mode of the @c MediaEndpoint and its media stream
     */
    enum class OperatingMode {
        /**
         * There is no streaming currently active. Media streaming thread is waiting for the new mode.
         */
        INACTIVE,

        /**
         * The @c MediaEnpoint is working in SINK mode, receiving audio stream from the remote bluetooth device. Media
         * streaming thread is reading the data from the file descriptor provided by BlueZ.
         */
        SINK,

        /**
         * Reserved for future use.
         */
        SOURCE,

        /**
         * The @c MediaEndpoint has been released and any operation on it should fail. Media streaming thread will
         * stop processing the data and exit as soon as returns from any active blocking operation such as poll() or
         * read().
         */
        RELEASED
    };

    /**
     * Returns a string representation of @c OperatingMode enum class
     * @param mode
     * @return
     */
    std::string operatingModeToString(OperatingMode mode);

    /**
     * A media streaming thread main function.
     */
    void mediaThread();

    /**
     * Set the current operating mode for the media endpoint.
     *
     * @param mode A new operating mode to set.
     */
    void setOperatingMode(OperatingMode mode);

    /**
     * Disconnects the device and enters INACTIVE state.
     *
     * @remarks This method is used by media streaming thread to abort the streaming when error occurs.
     */
    void abortStreaming();

    /**
     * An object path where media endpoint is/should be registered.
     */
    std::string m_endpointPath;

    /**
     * An object path of the device that is currently being used to stream from using this media endpoint.
     */
    std::string m_streamingDevicePath;

    /**
     * Flag signalling that operating mode has changed
     */
    bool m_operatingModeChanged;

    /**
     * Current @c OperatingMode.
     */
    std::atomic<OperatingMode> m_operatingMode;

    /**
     * Buffer used to decode SBC data to. Contains raw PCM data after the decoding.
     */
    std::vector<uint8_t> m_sbcBuffer;

    /**
     * Mutex synchronizing the state of media thread.
     */
    std::mutex m_mutex;

    /**
     * Mutex synchronizing the creation/querying of the audio @c FormattedAudioStreamAdapter object.
     */
    std::mutex m_streamMutex;

    /**
     * A condition variable to listen for operating state changes.
     */
    std::condition_variable m_modeChangeSignal;

    /**
     * @c FormattedAudioStreamAdapter object exposed to the clients and used to send decoded audio data to.
     */
    std::shared_ptr<avsCommon::utils::bluetooth::FormattedAudioStreamAdapter> m_ioStream;

    /**
     * Buffer for receiving encoded data from BlueZ. This buffer contains RTP packets with SBC packets payload.
     */
    std::vector<uint8_t> m_ioBuffer;

    /**
     * The @c AudioFormat associated with the stream.
     */
    avsCommon::utils::AudioFormat m_audioFormat;

    /**
     * A @c MediaContext instance used to hold the streaming configuration before the actual stream starts. As soon
     * as stream starts this configuration is cleared and will be created again, when streaming configuration changes.
     */
    std::shared_ptr<MediaContext> m_currentMediaContext;

    /*
     * Dedicated thread for I/O.
     */
    std::thread m_thread;
};

}  // namespace blueZ
}  // namespace bluetoothImplementations
}  // namespace alexaClientSDK

#endif  // ALEXA_CLIENT_SDK_BLUETOOTHIMPLEMENTATIONS_BLUEZ_INCLUDE_BLUEZ_MEDIAENDPOINT_H_

redpajama_set_name: RedPajamaGithub


text:
package io.proleap.cobol.asg.metamodel.data.datadescription;

import io.proleap.cobol.asg.metamodel.CobolDivisionElement;
import io.proleap.cobol.asg.metamodel.call.Call;

public interface OccursDepending extends CobolDivisionElement {

	Call getDependingOnCall();

	void setDependingOnCall(Call dependingOnCall);
}


text:
package org.encog.parse.expression.common;

import org.encog.ml.prg.EncogProgram;
import org.encog.ml.prg.ProgramNode;
import org.encog.parse.expression.CommonRender;

public class RenderCommonExpression extends CommonRender {

    private EncogProgram holder;

    public RenderCommonExpression() {
    }

    public String render(final EncogProgram theHolder) {
        this.holder = theHolder;
        ProgramNode node = theHolder.getRootNode();
        return renderNode(node);
    }

    private String renderConst(ProgramNode node) {
        return node.getData()[0].toStringValue();
    }

    private String renderVar(ProgramNode node) {
        int varIndex = (int) node.getData()[0].toIntValue();
        return this.holder.getVariables().getVariableName(varIndex);
    }

    private String renderFunction(ProgramNode node) {
        StringBuilder result = new StringBuilder();
        result.append(node.getName());
        result.append('(');
        for (int i = 0; i < node.getChildNodes().size(); i++) {
            if (i > 0) {
                result.append(',');
            }
            ProgramNode childNode = node.getChildNode(i);
            result.append(renderNode(childNode));
        }
        result.append(')');
        return result.toString();
    }

    private String renderOperator(ProgramNode node) {
        StringBuilder result = new StringBuilder();
        result.append("(");
        result.append(renderNode(node.getChildNode(0)));
        result.append(node.getName());
        result.append(renderNode(node.getChildNode(1)));
        result.append(")");
        return result.toString();
    }

    private String renderNode(ProgramNode node) {
        StringBuilder result = new StringBuilder();

        switch (determineNodeType(node)) {
            case ConstVal:
                result.append(renderConst(node));
                break;
            case Operator:
                result.append(renderOperator(node));
                break;
            case Variable:
                result.append(renderVar(node));
                break;
            case Function:
                result.append(renderFunction(node));
                break;
        }

        return result.toString();
    }
}


text: console.log (typeof (Date()));


text:
package org.vaadin;

import org.vaadin.client.SuggestBoxClientRpc;
import org.vaadin.client.SuggestBoxServerRpc;
import org.vaadin.client.SuggestBoxState;
import org.vaadin.client.SuggestionDto;

import java.util.Set;

/**
 * A {@link SuggestBox} is a text box which displays a
 * set of selections that match the user's input.
 *
 * <pre>
 *   SuggestBox suggestBox = new SuggestBox(){
 *        {@literal @}Override
 *        public Set{@literal <}SuggestionDto{@literal >} getItemSuggestions(String query) {
 *            return ImmutableSet.of(
 *                new SuggestionDto(1, "Cat"),
 *                new SuggestionDto(2, "Dog"),
 *                new SuggestionDto(3, "Horse"),
 *                new SuggestionDto(4, "Carnary")
 *            );
 *        }
 *
 *        {@literal @}Override
 *        public void selectionChanged(int itemId) {
 *          //handle selection here
 *        };
 * </pre>
 *
 * Using the example above, if the user types anything into the text widget,
 * the SuggestBox will display "Cat", "Dog", "Horse" and "Canary" suggestions.
 * Filter logic needs to be implemented here usually.
 */
public abstract class SuggestBox extends com.vaadin.ui.AbstractComponent implements SuggestBoxServerRpc {

    private final SuggestBoxClientRpc clientRpc = getRpcProxy(SuggestBoxClientRpc.class);

    public SuggestBox() {
        this("type query here", 800, 4, true);
    }

    /**
     * @param placeHolderText a text to be displayed when the box is empty, usually something like
     *                        'type your query here'
     * @param delayMilis      the miliseconds to wait for the user to type until a request for
     *                        suggestions is send to the server
     * @param queryMinLength  the minimum length of a query to have to request suggestions
     */
    public SuggestBox(String placeHolderText, int delayMilis, int queryMinLength) {
        this(placeHolderText, delayMilis, queryMinLength, true);
    }

    /**
     * @param placeHolderText          a text to be displayed when the box is empty, usually
     *                                 something like 'type your query here'
     * @param delayMilis               the miliseconds to wait for the user to type until a request
     *                                 for suggestions is send to the server
     * @param queryMinLength           the minimum length of a query to have to request suggestions
     * @param clearInputAfterSelection set to true if the box should be empty after an suggestion
     *                                 was selected
     */
    public SuggestBox(String placeHolderText, int delayMilis, int queryMinLength, boolean clearInputAfterSelection) {
        if (placeHolderText == null || placeHolderText.isEmpty())
            throw new IllegalArgumentException();
        if (delayMilis < 0) throw new IllegalArgumentException();
        if (queryMinLength < 1) throw new IllegalArgumentException();

        registerRpc(this);
        SuggestBoxState state = getState();
        state.placeHolderText = placeHolderText;
        state.delayMilis = delayMilis;
        state.queryMinLength = queryMinLength;
        state.clearInputAfterSelection = clearInputAfterSelection;
    }

    @Override
    protected SuggestBoxState getState() {
        return (SuggestBoxState) super.getState();
    }

    protected abstract Set<SuggestionDto> getSuggestions(String query);

    @Override
    public void suggestFor(String query) {

        if (query == null || query.isEmpty()) throw new IllegalArgumentException();

        Set<SuggestionDto> suggestionDtos = getSuggestions(query);

        clientRpc.showSuggestions(query, suggestionDtos.toArray(new SuggestionDto[suggestionDtos.size()]));
    }
}


text:
<!DOCTYPE HTML>

	<meta charset="UTF-8">
	<title>My Angular Require Seed</title>

	<link href='http://fonts.googleapis.com/css?family=Homenaje' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" type="text/css" href="style/style.css">

Web Audio API: Binaural Sound Positioning

W,S,A,D to move around. The mouse determines the position in which your nose is pointing.
    Use headphones for binaural effect!

Sounds loading...

      <button ng-click="startMusic(0)">Play Music 1</button>
      <button ng-click="startMusic(1)">Play Music 2</button>
      <button ng-click="startMusic(8,true)">Play noise</button>
      <button ng-click="startRobotWalking()">Walking Robot</button>

      <button ng-click="makeItRain(interval)">Make it rain!</button>
      <form>
        Rain intensity

        <input type="radio" ng-model="interval" ng-click="setRainInterval(30)" value="30"> Heavy
        <input type="radio" ng-model="interval" ng-click="setRainInterval(100)" value="100"> Moderate
        <input type="radio" ng-model="interval" ng-click="setRainInterval(500)" value="500"> Low

        choose rain sound:
        <input type="radio" name="s" ng-click="setRainSound(3)" value="500">
        <input type="radio" name="s" ng-click="setRainSound(2)" value="500">
        <input type="radio" name="s" ng-click="setRainSound(4)" value="500">
        <input type="radio" name="s" ng-click="setRainSound(6)" value="500">
        <input type="radio" name="s" ng-click="setRainSound(7)" value="500">

      </form>

    <canvas width="800" height="500" id="canvas" listenermove></canvas>

by justGoscha


text:
import os
import random
import sys
import time

from persistent_queue import PersistentQueue

module_path = os.sep + ".." + os.sep + ".." + os.sep
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + module_path)
import wolk  # noqa

# Enable debug logging by uncommenting the following line
# wolk.logging_config("debug", "wolk.log")

def main():
    """
    Demonstrate all functionality of wolk module.

    Create actuation handler and actuator status provider
    for switch and slider actuators.

    Create configuration handler and configuration provider
    for 4 types of configuration options.

    Create a custom queue to store messages on disk
    before sending them to the platform.

    Create a firmware installer and handler
    for enabling firmware update.

    Pass all of these to a WolkConnect class
    and start a loop to send different types of random readings.
    """
    # Insert the device credentials received
    # from WolkAbout IoT Platform when creating the device
    # List actuator references included on your device
    device = wolk.Device(
        key="device_key", password="some_password", actuator_references=["SW", "SL"]
    )

    class ActuatorSimulator:
        def __init__(self, inital_value):
            self.value = inital_value

    switch = ActuatorSimulator(False)
    slider = ActuatorSimulator(0)

    class ConfigurationSimulator:
        def __init__(self, inital_value):
            self.value = inital_value

    configuration_1 = ConfigurationSimulator(0)
    configuration_2 = ConfigurationSimulator(False)
    configuration_3 = ConfigurationSimulator("configuration_3")
    configuration_4 = ConfigurationSimulator(
        ("configuration_4a", "configuration_4b", "configuration_4c")
    )

    # Provide a way to read actuator status if your device has actuators
    class ActuatorStatusProviderImpl(wolk.ActuatorStatusProvider):
        def get_actuator_status(self, reference):
            if reference == "SW":
                return wolk.ActuatorState.READY, switch.value
            elif reference == "SL":
                return wolk.ActuatorState.READY, slider.value

    # Provide an actuation handler if your device has actuators
    class ActuationHandlerImpl(wolk.ActuationHandler):
        def handle_actuation(self, reference, value):
            print("Setting actuator " + reference + " to value: " + str(value))
            if reference == "SW":
                switch.value = value

            elif reference == "SL":
                slider.value = value

    # Provide a configuration handler if your device has configuration options
    class ConfigurationHandlerImpl(wolk.ConfigurationHandler):
        def handle_configuration(self, configuration):
            for key, value in configuration.items():
                if key == "config_1":
                    configuration_1.value = value
                elif key == "config_2":
                    configuration_2.value = value
                elif key == "config_3":
                    configuration_3.value = value
                elif key == "config_4":
                    configuration_4.value = value

    # Provide a way to read current device configuration
    class ConfigurationProviderImpl(wolk.ConfigurationProvider):
        def get_configuration(self):
            configuration = dict()
            configuration["config_1"] = configuration_1.value
            configuration["config_2"] = configuration_2.value
            configuration["config_3"] = configuration_3.value
            configuration["config_4"] = configuration_4.value
            return configuration

    # Custom queue example
    class FilesystemOutboundMessageQueue(wolk.OutboundMessageQueue):
        def __init__(self, path="."):
            if path == ".":
                self.queue = PersistentQueue("FileOutboundMessageQueue")
            else:
                self.queue = PersistentQueue("FileOutboundMessageQueue", path)

        def put(self, message):
            self.queue.push(message)

        def get(self):
            message = self.queue.pop()
            self.queue.flush()
            return message

        def peek(self):
            if not self.queue.peek():
                self.queue.clear()
                return None
            else:
                return self.queue.peek()

    filesystemOutboundMessageQueue = FilesystemOutboundMessageQueue()

    # Extend this class to handle the installing of the firmware file
    class MyFirmwareInstaller(wolk.FirmwareInstaller):
        def __init__(self):
            pass

        def install_firmware(self, firmware_file_path):
            """Handle the installing of the firmware file here."""
            print("Installing firmware from path: " + firmware_file_path)
            os._exit(0)

    # Enable firmware update on your device
    # Implement wolk.FirmwareURLDownloadHandler to enable URL download
    firmware_handler = wolk.FileSystemFirmwareHandler(
        version="1.0",
        chunk_size=1024 * 1024,
        max_file_size=100 * 1024 * 1024,
        download_location="",
        firmware_installer=MyFirmwareInstaller(),
        firmware_url_download_handler=None,
    )

    # Pass your device, actuation handler and actuator status provider
    # Pass configuration handler and provider
    # Pass custom outbound message queue implementation
    # Enable firmware update by passing a firmware handler
    try:
        wolk_device = wolk.WolkConnect(
            device=device,
            protocol=wolk.Protocol.JSON_SINGLE,
            actuation_handler=ActuationHandlerImpl(),
            actuator_status_provider=ActuatorStatusProviderImpl(),
            configuration_handler=ConfigurationHandlerImpl(),
            configuration_provider=ConfigurationProviderImpl(),
            outbound_message_queue=filesystemOutboundMessageQueue,
            firmware_handler=firmware_handler,
            host="api-demo.wolkabout.com",
            port=8883,
            ca_cert=".." + os.sep + ".." + os.sep + "wolk" + os.sep + "ca.crt",
        )
    except RuntimeError as e:
        print(str(e))
        sys.exit(1)

    # Establish a connection to the WolkAbout IoT Platform
    print("Connecting to WolkAbout IoT Platform")
    try:
        wolk_device.connect()
    except RuntimeError as e:
        print(str(e))
        sys.exit(1)

    wolk_device.publish_configuration()
    wolk_device.publish_actuator_status("SW")
    wolk_device.publish_actuator_status("SL")

    publish_period_seconds = 5

    while True:
        try:
            timestamp = int(round(time.time() * 1000))
            temperature = random.uniform(15, 30)
            humidity = random.uniform(10, 55)
            pressure = random.uniform(975, 1030)
            accelerometer = (
                random.uniform(0, 100),
                random.uniform(0, 100),
                random.uniform(0, 100),
            )
            if humidity > 50:
                # Adds an alarm event to the queue
                wolk_device.add_alarm("HH", True)
            else:
                wolk_device.add_alarm("HH", False)
            # Adds a sensor reading to the queue
            wolk_device.add_sensor_reading("T", temperature, timestamp)
            wolk_device.add_sensor_reading("H", humidity, timestamp)
            wolk_device.add_sensor_reading("P", pressure, timestamp)
            wolk_device.add_sensor_reading("ACL", accelerometer, timestamp)

            # Publishes all sensor readings and alarms from the queue
            # to the WolkAbout IoT Platform
            print("Publishing buffered messages")
            wolk_device.publish()
            time.sleep(publish_period_seconds)
        except KeyboardInterrupt:
            print("Received KeyboardInterrupt, quitting")
            os._exit(0)

if __name__ == "__main__":
    main()


text:
var _path = require('path');
var rootDir = _path.dirname(_path.dirname(__dirname));
var assert = require('assert');
var osjs = require(rootDir + '/src/server/node/node_modules/osjs/osjs.js');
var osjsServer = require(rootDir + '/src/server/node/http.js');
var serverRoot = _path.join(_path.dirname(_path.dirname(__dirname)), 'src', 'server', 'node');

var instance = osjs.init({
  dirname: serverRoot,
  root: rootDir,
  dist: 'dist-dev',
  logging: false,
  nw: false
});

var response = {};
var request = {
  session: {
    get: function(key) {
      if ( key === 'username' ) {
        return 'demo';
      }
      return null;
    },
    set: function() {
    }
  }
};

process.chdir(rootDir);

/////////////////////////////////////////////////////////////////////////////
// PREPARATION
/////////////////////////////////////////////////////////////////////////////

describe('Prepare', function() {
  var fs = require('fs');

  /*
  describe('#handler', function() {
    it('handler should be set to demo', function() {
      assert.equal('demo', instance.config.handler);
    });
  });
  */

  describe('#vfs', function() {
    var testPath = instance.vfs.getRealPath('home:///', instance.config, request);

    it('read access to demo area', function() {
      if ( fs.accessSync ) {
        assert.doesNotThrow(function() {
          fs.accessSync(testPath.root, fs.R_OK);
        }, Error);
      } else {
        assert.equal(true, true);
      }
    });

    it('write access to demo area', function() {
      if ( fs.accessSync ) {
        assert.doesNotThrow(function() {
          fs.accessSync(testPath.root, fs.W_OK);
        }, Error);
      } else {
        assert.equal(true, true);
      }
    });
  });

});

/////////////////////////////////////////////////////////////////////////////
// VFS
/////////////////////////////////////////////////////////////////////////////

describe('VFS', function() {
  var str = 'Mocha Testing';

  describe('#exists', function() {
    it('should not find folder', function(done) {
      var file = {path: 'home:///.mocha'};

      instance.vfs.exists(file, function(error, result) {
        assert.equal(false, error);
        assert.equal(false, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#exists', function() {
    it('should not find file', function(done) {
      instance.vfs.exists({path: 'home:///.mocha/test.txt'}, function(error, result) {
        assert.equal(false, error);
        assert.equal(false, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#mkdir', function() {
    it('should create folder without error', function(done) {
      instance.vfs.mkdir({path: 'home:///.mocha'}, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#write', function() {
    it('should write file without error', function(done) {
      var data = (new Buffer(str).toString('base64'));
      var file = {
        path: 'home:///.mocha/test.txt',
        data: 'data:text/plain;base64,' + data
      };
      instance.vfs.write(file, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#read', function() {
    it('should read file without error', function(done) {
      instance.vfs.read({path: 'home:///.mocha/test.txt'}, function(error, result) {
        assert.equal(false, error);

        var result = result.replace(/^data\:(.*);base64\,/, '') || '';
        result = new Buffer(result, 'base64').toString('utf8');

        assert.equal(str, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#scandir', function() {
    it('should find file (path and mime) without error', function(done) {
      var tst = 'home:///.mocha/test.txt';
      var found = {};
      instance.vfs.scandir({path: 'home:///.mocha'}, function(error, result) {
        assert.equal(false, error);

        try {
          result.forEach(function(f) {
            if ( f.filename === 'test.txt' ) {
              found = {
                path: f.path,
                mime: f.mime
              };
            }
          });
        } catch ( e ) {};
        assert.equal(tst, found.path);
        assert.equal('text/plain', found.mime);
        done();
      }, request, instance.config);
    });
  });

  describe('#move', function() {
    it('should rename/move file without error', function(done) {
      var file = {
        src: 'home:///.mocha/test.txt',
        dest: 'home:///.mocha/test2.txt'
      };
      instance.vfs.move(file, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#copy', function() {
    it('should copy file without error', function(done) {
      var file = {
        src: 'home:///.mocha/test2.txt',
        dest: 'home:///.mocha/test3.txt'
      };
      instance.vfs.copy(file, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#copy', function() {
    it('should copy folder without error', function(done) {
      var file = {
        src: 'home:///.mocha',
        dest: 'home:///.mocha-copy'
      };
      instance.vfs.copy(file, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });

  describe('#fileinfo', function() {
    it('should get file information without error', function(done) {
      instance.vfs.fileinfo({path: 'home:///.mocha/test2.txt'}, function(error, result) {
        assert.equal(false, error);
        assert.equal('home:///.mocha/test2.txt', result.path);
        assert.equal('test2.txt', result.filename);
        assert.equal('text/plain', result.mime);
        done();
      }, request, instance.config);
    });
  });

  describe('#delete', function() {
    it('should delete file without error', function(done) {
      instance.vfs.delete({path: 'home:///.mocha/test2.txt'}, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });

    it('should delete folder without error', function(done) {
      instance.vfs.delete({path: 'home:///.mocha'}, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });

    it('should delete copied folder without error', function(done) {
      instance.vfs.delete({path: 'home:///.mocha-copy'}, function(error, result) {
        assert.equal(false, error);
        assert.equal(true, result);
        done();
      }, request, instance.config);
    });
  });
});

/////////////////////////////////////////////////////////////////////////////
// APIS
/////////////////////////////////////////////////////////////////////////////

describe('API', function() {

  describe('Application API', function() {
    describe('#call', function() {
      it('should return dummy data', function(done) {
        instance.api.application({
          path: 'default/Settings',
          method: 'test',
          'arguments': {}
        }, function(error, result) {
          assert.equal(false, error);
          assert.equal('test', result);
          done();
        }, request, response, instance.config);
      });

      it('should trigger error on invalid method', function(done) {
        instance.api.application({
          path: 'default/Settings',
          method: 'xxx',
          'arguments': {}
        }, function(error, result) {
          assert.notEqual(null, error);
          done();
        }, request, response, instance.config);
      });

      it('should trigger error on invalid package', function(done) {
        instance.api.application({
          path: 'doesnotexist/PackageName',
          method: 'xxx',
          'arguments': {}
        }, function(error, result) {
          assert.notEqual(null, error);
          done();
        }, request, response, instance.config);
      });
    });
  });

  /*
  describe('cURL', function() {
    describe('#HEAD', function() {
      it('successfull HEAD request', function(done) {
        instance.api.curl({
          method: 'HEAD',
          url: 'http://os.js.org/test/curl-example.html'
        }, function(error, result) {
          assert.equal(false, error);
          assert.equal(200, result.httpCode);
          done();
        }, request, response, instance.config);
      });
    });

    describe('#GET', function() {
      var testFor = '<!DOCTYPE html>OS.js Test\n';
      it('successfull GET request', function(done) {
        instance.api.curl({
          method: 'GET',
          url: 'http://os.js.org/test/curl-example.html'
        }, function(error, result) {
          assert.equal(false, error);
          assert.equal(200, result.httpCode);
          assert.equal(testFor, result.body);
          done();
        }, request, response, instance.config);
      });

      it('successfull GET binary/raw request', function(done) {
        instance.api.curl({
          method: 'GET',
          binary: true,
          url: 'http://os.js.org/test/curl-example.html'
        }, function(error, result) {
          var data = 'data:application/octet-stream;base64,' + (new Buffer(testFor).toString('base64'));
          assert.equal(false, error);
          assert.equal(200, result.httpCode);
          assert.equal(data, result.body);
          done();
        }, request, response, instance.config);
      });
    });

    describe('#POST', function() {
      var testFor = '<!DOCTYPE html>OS.js Test';
      it('successfull POST request', function(done) {
        instance.api.curl({
          method: 'POST',
          url: 'http://os.js.org/test/curl-example.html'
        }, function(error, result) {
          assert.equal(false, error);
          assert.equal(405, result.httpCode); // Should be 405 because of github pages
          done();
        }, request, response, instance.config);
      });
    });

  });
  */

});

/////////////////////////////////////////////////////////////////////////////
// SERVER
/////////////////////////////////////////////////////////////////////////////

describe('Node HTTP Server', function() {
  var req = require('request');
  var port = 8009;
  var url  = 'http://localhost:' + port.toString();

  function post(uurl, data, cb, cookie) {

    var opts = {
      url: uurl,
      method: 'POST',
      json: data
    };

    if ( cookie ) {
      var j = req.jar();
      var ck = req.cookie(cookie);
      j.setCookie(ck, url);
      opts.jar = j;
    }

    req(opts, function(error, response, body) {
      cb((error || false), response, (error ? false : body));
    });
  }

  before(function () {
    osjsServer.listen({
      port: port,
      dirname: serverRoot,
      root: rootDir,
      dist: 'dist-dev',
      logging: false,
      nw: false
    });
  });

  describe('#index', function() {
    it('should return 200', function(done) {
      req({
        method: 'GET',
        url: url
      }, function(error, res) {
        assert.equal(200, res.statusCode);
        done();
      });
    });
  });

  var cookie;
  describe('#login', function() {
    it('should return 200 with proper json result', function(done) {
      var data = {
        username: 'demo',
        password: 'demo'
      };

      var exp = {
        userData: {
          id: 0,
          username: 'demo',
          name: 'Demo User',
          groups: [ 'admin' ]
        },
        userSettings: {}
      };

      post(url + '/API/login', data, function(err, res, body) {
        assert.equal(false, err);
        assert.equal(200, res.statusCode);
        assert.equal(false, body.error);
        var expc = {
          userData: body.result.userData,
          userSettings: body.result.userSettings,
        };
        assert.equal(JSON.stringify(exp), JSON.stringify(expc));

        cookie = res.headers['set-cookie'][0];
        done();
      });
    });
  });

  describe('#api', function() {
    it('w/session - should return 200 with proper response', function(done) {
      var data = {
        path: 'default/Settings',
        method: 'test'
      };

      var sessid = null;

      post(url + '/API/application', data, function(err, res, body) {
        assert.equal(false, err);
        assert.equal(200, res.statusCode);
        assert.equal(false, body.error);
        assert.equal('test', body.result);
        done();
      }, cookie);
    });
  });

  after(function () {
    osjsServer.close();
  });
});


text:
package org.sphalerite.bukkit.plugins;

import org.bukkit.Location;
import org.bukkit.Material;

public class Teleporter extends PortRune {
	private static final long serialVersionUID = 7243429873329918434L;
	public Teleporter(Location location) {
		super(location);
	}
	public Teleporter(SerializableLocation location, PortSignature sig) {
		super(location, sig);
	}
	protected final Material getOutsideBlock() {return Material.DIAMOND_BLOCK;}
	protected final Material getCentreBlock() {return Material.REDSTONE_BLOCK;}
}


text:
package slieb.blendercss.internal;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;

import static java.lang.String.format;
import static org.apache.commons.io.FilenameUtils.getExtension;

@Singleton
public class FileGenerator {

    private final MessageDigest md;

    private final File workingDirectory;

    @Inject
    public FileGenerator(@Named("workingDirectory") File workingDirectory) {
        this.workingDirectory = workingDirectory;
        try {
            this.md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public File getOutputDirectory(String dirName) {
        return new File(workingDirectory, dirName);
    }

    private File getTempDirectory() {
        return getOutputDirectory("preprocessed");
    }

    public File getCacheDirectory() {
        return getOutputDirectory("cache");
    }

    private String getMD5(String message) throws IOException {
        String digest;
        try {
            byte[] hash = md.digest(message.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder(2 * hash.length);
            for (byte b : hash) {
                sb.append(format("%02x", b & 0xff));
            }
            digest = sb.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return digest;
    }

    public File getOutputFileFor(GssResource input, String outputExt) throws IOException {
        String md5String = getMD5(input.getFileName());
        String extension = outputExt != null ? outputExt : getExtension(input.getFileName());
        String name = format("%s.%s", md5String, extension);
        return new File(getTempDirectory(), name);
    }
}


text:
[![Gem Version](https://badge.fury.io/rb/waiting_rspec_matchers.svg)](https://rubygems.org/gems/waiting_rspec_matchers)
[![Build Status](https://travis-ci.org/abotalov/waiting_rspec_matchers.svg?branch=master)](https://travis-ci.org/abotalov/waiting_rspec_matchers)

When writing end-to-end tests there is often a necessity to wait for something to happen. Libraries like Capybara, Watir-Webdriver provide some functionality to ease it but this functionality doesn't cover all needed cases. Sometimes you need to wait for a more specific condition.

This is where this gem aims to help.

If `some_name` rspec matcher exists, WaitingRspecMatchers provides you `become_some_name` matcher that does the same as `some_name` matcher but also waits for that matcher to succeed.

The benefit of using this gem over solutions like [wait_until](https://gist.github.com/jnicklas/d8da686061f0a59ffdf7), [retryable](https://github.com/carlo/retryable), [tries](https://github.com/krautcomputing/tries) is that those solutions don't integrate with RSpec and thus don't provide useful enough error messages.

## Setup

To install, add this line to your Gemfile and run bundle install:

```ruby
gem 'waiting_rspec_matchers'
```

Then you should include it in e.g. `spec_helper.rb`:

```ruby
RSpec.configure do |config|
  config.include WaitingRspecMatchers
end
```

## Usage examples (inspiration)

* reload page until some element/text appears:

```ruby
# setup Capybara
expect do
  visit 'path'
  page
end.to become_have_css('#id', wait: 0) # `expect(page).to have_css('#id', wait: 0)` is internally invoked by this gem
```

* check that page url is "some_string" or will become "some_string":

```ruby
# setup Capybara
expect { page.current_url }.to become_eq('http://www.google.com/')
```

* wait for element attribute to include a specific string:

```ruby
# setup Capybara
el = find('#id')
expect { el[:class] }.to become_include('some_class')
```

* assert that 3 requests url of which contains `/path` pass through proxy

```ruby
# setup proxy
expect { proxy.har.entries.count { |e| e.request.url[/\/path/]} }.to become_eq(3)
```

## Changing wait time

You can specify a wait time (amount of time that gem will retry supplied block of code) and delay (period between retries).

You can either change default values (it will take effect for all matchers):

```ruby
WaitingRspecMatchers.configure do |config|
  config.default_wait_time = 2
  config.default_delay = 0.05
end
```

or set it on per-matcher basis:

```ruby
expect { some_code }.to become_eq(3).during(2).delay(0.05)
expect { some_code }.to become_eq(3).during(2)
expect { some_code }.to become_eq(3).delay(0.05)
```


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace AntMe
{
    /// <summary>
    /// KeyValueDesciption-Container for e.g.: Settings or Localizations
    /// </summary>
    public class KeyValueStore
    {

        /// <summary>
        /// Dictionary for all Values and Discriptions
        /// key = Typename:Keyname (e.g.: "AntMe.Factions.AntFaction:InitialAnthillCount","AntMe.Basics.Items.AntItem:AntRadius")
        /// </summary>
        private Dictionary<string, ValueDescriptionEntry> Storage;

        /// <summary>
        /// Dictionary for informations and comments about the KeyValueStore (will be saved).
        /// </summary>
        public Dictionary<string, string> Common { get; private set; }

        private int nextId = 1;
        private readonly Tracer tracer = new Tracer("AntMe.Core.KeyValueStore");

        /// <summary>
        /// Default Constructor
        /// </summary>
        public KeyValueStore()
        {
            Storage = new Dictionary<string, ValueDescriptionEntry>();
            Common = new Dictionary<string, string>();
        }

        /// <summary>
        /// Initialize a new KeyValueStore with the given Stream.
        /// </summary>
        /// <param name="stream">Stream</param>
        public KeyValueStore(Stream stream) : this()
        {
            Load(stream);
        }

        /// <summary>
        /// Initialize a new KeyValueStore with the given KeyValueStore File.
        /// </summary>
        /// <param name="filename">Dateinamen</param>
        public KeyValueStore(string filename) : this()
        {
            using (Stream stream = File.Open(filename, FileMode.Open))
            {
                Load(stream);
            }
        }

        /// <summary>
        /// Initialize a new KeyValueStore with another KeyValueStore-Instance as source.
        /// </summary>
        /// <param name="keyValueStore">Source KeyValueStore</param>
        public KeyValueStore(KeyValueStore keyValueStore) : this()
        {
            Merge(keyValueStore);
        }

        /// <summary>
        /// Generates the Full Key out of Type and Key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Full Key</returns>
        private static string FullKey<T>(string key)
        {
            return FullKey(typeof(T).FullName, key);
        }

        /// <summary>
        /// Generates the Full Key out of Type and Key.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Full Key</returns>
        private static string FullKey(Type type, string key)
        {
            return FullKey(type.FullName, key);
        }

        /// <summary>
        /// Generates the Full Key out of TypeKey and Key.
        /// </summary>
        /// <param name="typeKey">TypeKey</param>
        /// <param name="key">Key</param>
        /// <returns>Full Key</returns>
        private static string FullKey(string typeKey, string key)
        {
            if (!Regex.IsMatch(typeKey, @"\w+|\d+|\.|\+|(\<\w+|\d+|\.|\+|\>)"))
                throw new ArgumentException("The TypeKey matches not the definition: " + '"' + typeKey + '"');
            return string.Format("{0}:{1}", typeKey, key);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set<T>(string key, string value, string description = null)
        {
            Set(FullKey<T>(key), value, description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set<T>(string key, int value, string description = null)
        {
            Set(FullKey<T>(key), value.ToString(), description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set<T>(string key, float value, string description = null)
        {
            Set(FullKey<T>(key), value.ToString(CultureInfo.InvariantCulture), description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set<T>(string key, bool value, string description = null)
        {
            Set(FullKey<T>(key), value.ToString(), description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="key">Full key (incl. Type and Key)</param>
        /// <param name="valueDescriptionEntry">ValueDescriptionEntry</param>
        private void Set(string key, ValueDescriptionEntry valueDescriptionEntry)
        {
            Set(key, valueDescriptionEntry.Value, valueDescriptionEntry.Description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="key">Full key (incl. Type and Key)</param>
        /// <param name="value"> Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(string key, string value, string description = null)
        {
            // TODO: Check right syntax (full.type.name:key)
            ValueDescriptionEntry entry;
            if (!Storage.TryGetValue(key, out entry))
            {
                entry = new ValueDescriptionEntry() { Value = value, Description = description };
                Storage[key] = entry;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(value))
                    entry.Value = value;
                if (!string.IsNullOrWhiteSpace(description))
                    entry.Description = description;
            }
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="key">Full key (incl. Type and Key)</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(string key, int value, string description = null)
        {
            Set(key, value.ToString(CultureInfo.InvariantCulture), description);
        }

        /// <summary>
        /// Sets the value for the given Key.
        /// </summary>
        /// <param name="key">Full Settings Key (incl. Type and Key)</param>
        /// <param name="value">Settings Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(string key, float value, string description = null)
        {
            Set(key, value.ToString(CultureInfo.InvariantCulture), description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="key">Full key (incl. Type and Key)</param>
        /// <param name="value"> Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(string key, bool value, string description = null)
        {
            Set(key, value.ToString(), description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(Type type, string key, string value, string description = null)
        {
            Set(FullKey(type, key), value, description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(Type type, string key, int value, string description = null)
        {
            Set(FullKey(type, key), value, description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(Type type, string key, bool value, string description = null)
        {
            Set(FullKey(type, key), value, description);
        }

        /// <summary>
        /// Sets the Value and the Discription for the given Key.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="description">Optional Description for this key</param>
        public void Set(Type type, string key, float value, string description = null)
        {
            Set(FullKey(type, key), value, description);
        }

        /// <summary>
        /// Enumerates all Settings Keys.
        /// </summary>
        public IEnumerable<string> Keys
        {
            get { return Storage.Keys; }
        }

        /// <summary>
        /// Clones the instance of the KeyValueStore
        /// </summary>
        /// <returns>Full Copy of the KeyValueStore</returns>
        public KeyValueStore Clone()
        {
            KeyValueStore newStore = new KeyValueStore();
            newStore.Merge(this);
            return newStore;
        }

        /// <summary>
        /// Merge information with the given KeyValueStore-Instance.
        /// </summary>
        /// <param name="stream">Source KeyValueStore-Stream</param>
        public void Merge(Stream stream)
        {
            Merge(new KeyValueStore(stream));
        }

        /// <summary>
        /// Merge information with the given KeyValueStore-Instance.
        /// </summary>
        /// <param name="filename">Source KeyValueStore-File</param>
        public void Merge(string filename)
        {
            Merge(new KeyValueStore(filename));
        }

        /// <summary>
        /// Merge information with the given KeyValueStore-Instance.
        /// </summary>
        /// <param name="keyValueStore">Source KeyValueStore</param>
        public void Merge(KeyValueStore keyValueStore)
        {
            // merge storage dictonary
            foreach (var key in keyValueStore.Storage.Keys)
            {
                ValueDescriptionEntry newVDE;
                keyValueStore.Storage.TryGetValue(key, out newVDE);
                if (Storage.Keys.Contains(key))
                {
                    ValueDescriptionEntry orgVDE;
                    Storage.TryGetValue(key, out orgVDE);
                    if (orgVDE == null)
                        orgVDE = new ValueDescriptionEntry();
                    if (string.IsNullOrEmpty(newVDE.Value))
                        newVDE.Value = orgVDE.Value;
                    if (string.IsNullOrEmpty(newVDE.Description))
                        newVDE.Description = orgVDE.Description;

                    Storage[key] = newVDE;
                }
                else
                {
                    Storage.Add(key, newVDE != null ? newVDE : new ValueDescriptionEntry());
                }
            }

            // merge common dictonary
            foreach (var key in keyValueStore.Common.Keys)
            {
                string newValue;
                keyValueStore.Common.TryGetValue(key, out newValue);

                if (Common.Keys.Contains(key))
                {
                    string orgValue;
                    Common.TryGetValue(key, out orgValue);

                    if (string.IsNullOrEmpty(newValue))
                        newValue = orgValue;

                    Common[key] = newValue;
                }
                else
                {
                    Common.Add(key, newValue);
                }

            }
        }

        /// <summary>
        /// Gets the Description with the given Object-Key interpreted as String.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Description</returns>
        public string GetDescription<T>(string key)
        {
            return GetDescription(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Description with the given Object-Key interpreted as String.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Description</returns>
        public string GetDescription(Type type, string key)
        {
            return GetDescription(FullKey(type, key));
        }

        /// <summary>
        /// Gets the Description with the given Object-Key interpreted as String.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Description</returns>
        public string GetDescription(string key)
        {
            ValueDescriptionEntry result;
            if (Storage.TryGetValue(key, out result))
                return result.Description;
            return string.Empty;
        }

        /// <summary>
        /// Gets the Value with the given Object-Key interpreted as String.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public string GetString<T>(string key)
        {
            return GetString(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Value with the given Object-Key interpreted as String.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public string GetString(Type type, string key)
        {
            return GetString(FullKey(type, key));
        }

        /// <summary>
        /// Gets the Value with the given Key interpreted as String.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Value</returns>
        public string GetString(string key)
        {
            ValueDescriptionEntry result;
            if (Storage.TryGetValue(key, out result))
                return result.Value;
            return string.Empty;
        }

        /// <summary>
        /// Gets the Value with the given Key interpreted as Integer.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public int? GetInt<T>(string key)
        {
            return GetInt(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Value with the given Key interpreted as Integer.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public int? GetInt(Type type, string key)
        {
            return GetInt(FullKey(type, key));
        }

        /// <summary>
        /// Sets the Value with the given Key interpreted as Integer.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Value</returns>
        public int? GetInt(string key)
        {
            string value = GetString(key);
            int result;
            if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
                return result;
            return null;
        }

        /// <summary>
        /// Sets the Value with the given Key interpreted as Bool.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public bool? GetBool<T>(string key)
        {
            return GetBool(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Value with the given Key interpreted as Bool.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public bool? GetBool(Type type, string key)
        {
            return GetBool(FullKey(type, key));
        }

        /// <summary>
        /// Sets the Value with the given Key interpreted as Bool.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Value</returns>
        public bool? GetBool(string key)
        {
            string value = GetString(key);
            bool result;
            if (bool.TryParse(value, out result))
                return result;
            return null;
        }

        /// <summary>
        /// Sets the Value with the given Key interpreted as Float.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public float? GetFloat<T>(string key)
        {
            return GetFloat(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Value with the given Key interpreted as Float.
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="key">Key</param>
        /// <returns>Value</returns>
        public float? GetFloat(Type type, string key)
        {
            return GetFloat(FullKey(type, key));
        }

        /// <summary>
        /// Sets the Value with the given Key interpreted as Float.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Value</returns>
        public float? GetFloat(string key)
        {
            string value = GetString(key);
            float result;
            if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
                return result;
            return null;
        }

        /// <summary>
        /// Gets the Description with the given Key interpreted as String.
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Description</returns>
        private ValueDescriptionEntry GetValueDescriptionEntry<T>(string key)
        {
            return GetValueDescriptionEntry(FullKey<T>(key));
        }

        /// <summary>
        /// Gets the Description with the given Key interpreted as String.
        /// </summary>
        /// <param name="key">Full Key (incl. Type and Key)</param>
        /// <returns>Description</returns>
        private ValueDescriptionEntry GetValueDescriptionEntry(string key)
        {
            ValueDescriptionEntry result;
            if (Storage.TryGetValue(key, out result))
                return result;
            return null;
        }

        private void Load(Stream stream)
        {

            List<string> Errors = new List<string>();

            using (StreamReader sr = new StreamReader(stream))
            {
                int currentLine = 0;
                string currentTypeKey = "";

                while (sr.Peek() >= 0)
                {
                    currentLine++;
                    bool waitforTypeKey = false;
                    string rawData = sr.ReadLine();
                    string editedData = rawData.TrimStart(' ').TrimEnd(' ');

                    if (editedData.StartsWith("["))
                    {
                        if (editedData.IndexOf(']') == -1)
                        {
                            waitforTypeKey = true;
                            Errors.Add(string.Format("ERROR Line {0}: missing ']' (end of TypeKey deklaration)", currentLine.ToString()));
                            tracer.Trace(System.Diagnostics.TraceEventType.Error, nextId++, string.Format("ERROR Line {0}: missing ']' (end of TypeKey deklaration)", currentLine.ToString()));
                            continue;
                        }

                        currentTypeKey = editedData.Substring(1, editedData.IndexOf(']') - 1).TrimStart(' ').TrimEnd(' ');
                        continue;
                    }
                    else if (waitforTypeKey)
                        continue;
                    else if (editedData.Contains("="))
                    {

                        string key = editedData.Substring(0, editedData.IndexOf('=')).TrimEnd(' ');
                        editedData = editedData.Remove(0, editedData.IndexOf('=') + 1);

                        if (currentTypeKey == "Common")
                        {
                            Common.Add(key, editedData.TrimStart(' ').TrimEnd(' '));
                            continue;
                        }
                        ValueDescriptionEntry VDE = new ValueDescriptionEntry();

                        if (editedData.IndexOf("//") >= 0)
                        {
                            VDE.Value = editedData.Substring(0, editedData.IndexOf("//")).TrimStart(' ').TrimEnd(' ');
                            VDE.Description = editedData.Remove(0, editedData.IndexOf("//") + 2).TrimStart(' ').TrimEnd(' ');
                        }
                        else
                        {
                            VDE.Value = editedData.TrimStart(' ').TrimEnd(' ');
                        }

                        if (string.IsNullOrWhiteSpace(VDE.Value))
                        {
                            Errors.Add(string.Format("ERROR Line {0}: missing Value", currentLine.ToString()));
                            tracer.Trace(System.Diagnostics.TraceEventType.Error, nextId++, string.Format("ERROR Line {0}: missing Value", currentLine.ToString()));
                        }
                        Set(FullKey(currentTypeKey, key), VDE);

                    }
                    else if (string.IsNullOrWhiteSpace(editedData))
                    {
                        continue;
                    }
                    else
                    {
                        Errors.Add(string.Format("ERROR Line {0}: could not be deserialized, make sure it matches the Format([TYPEKEY] or KEY=VALUE//DESCRIPTION)", currentLine.ToString()));
                        tracer.Trace(System.Diagnostics.TraceEventType.Error, nextId++, string.Format("ERROR Line {0}: could not be deserialized, make sure it matches the Format([TYPEKEY] or KEY=VALUE//DESCRIPTION)", currentLine.ToString()));
                    }
                }
                sr.Close();
            }

            if (Errors.Count > 0)
                throw new AggregateException(string.Join(Environment.NewLine, Errors.ToArray()));
        }

        /// <summary>
        /// Saves all Settings to a File.
        /// </summary>
        /// <param name="filename">Filename</param>
        /// <param name="alignedValues">Optional easy to read output</param>
        public void Save(string filename, bool alignedValues = false)
        {
            using (Stream stream = File.Open(filename, FileMode.Create))
            {
                Save(stream, alignedValues);
            }
        }

        /// <summary>
        /// Saves all Settings to a File.
        /// </summary>
        /// <param name="stream">Output Stream</param>
        /// <param name="alignedValues">Optional easy to read output</param>
        public void Save(Stream stream, bool alignedValues = false)
        {

            StreamWriter sw = new StreamWriter(stream);

            if (Common.Count > 0)
            {
                sw.WriteLine("[Common]");
                foreach (var item in Common)
                {
                    sw.WriteLine("{0}={1}", item.Key, item.Value);
                }
                sw.WriteLine("");
            }

            string[] keytemp = Keys.ToArray();

            var typeKeys = keytemp.Select(k => k.Substring(0, k.IndexOf(':'))).Distinct();

            foreach (var typekey in typeKeys.OrderBy(k => k))
            {
                sw.WriteLine("[{0}]", typekey);

                int keyLength = 1;
                int valueLength = 1;

                if (alignedValues)
                {
                    foreach (var key in Storage.Where(k => k.Key.StartsWith(string.Format("{0}:", typekey))).Select(k => k.Key.Substring(k.Key.IndexOf(":") + 1)).ToArray())
                    {
                        string fullkey = string.Format("{0}:{1}", typekey, key);
                        ValueDescriptionEntry VDE = GetValueDescriptionEntry(fullkey);
                        keyLength = Math.Max(keyLength, key.Length);
                        valueLength = Math.Max(valueLength, VDE.Value.Length);
                    }
                }

                foreach (var key in Storage.Where(k => k.Key.StartsWith(string.Format("{0}:", typekey))).Select(k => k.Key.Substring(k.Key.IndexOf(":") + 1)).ToArray())
                {
                    string fullkey = string.Format("{0}:{1}", typekey, key);
                    ValueDescriptionEntry VDE = GetValueDescriptionEntry(fullkey);
                    string description = " // ";
                    if (string.IsNullOrWhiteSpace(VDE.Description))
                        description = string.Empty;
                    else
                        description += VDE.Description;
                    sw.WriteLine("{0}={1}{2}", key.ToString().PadRight(keyLength), (VDE.Value?.ToString(CultureInfo.InvariantCulture) ?? "").PadRight(valueLength), description);
                }
                sw.WriteLine();

            }
            sw.Flush();
            //sw.Dispose(); //TODO: Dispose was not used, because it closes the baseStream (.Net 4.5 has an option in the constructor to avoid this)

        }

        /// <summary>
        /// Nested class for data storing.
        /// </summary>
        private class ValueDescriptionEntry
        {

            public string Value { get; set; }

            public string Description { get; set; }

        }

    }
}


text:
<?php

    return array(

        'create.success'                    => ':article :model a été créé avec succès.',
        'create.error'                      => 'On a rencontré un problème en creant :article :model.',

        'edit.success'                      => ':article :model a été changé avec succès.',
        'edit.error'                        => 'On a rencontré un problème en changeant :article :model.',

        'delete.success'                    => ':article :model a été effacé avec succès.',
        'delete.error'                      => 'On a rencontré un problème en effaceant :article :model.',

        'approve.success'                   => ':article :model a été approuvé avec succès.',

        'reject.success'                    => ':article :model a été rejeté avec succès.',

        'error.notFound'                    => ':article :model ne peut pas être a trouvé dans le base de données.',

    );


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<title>Spacious</title>
	<link rel="icon" href="icon-spacious.png">
	<link href="css/main.css" rel="stylesheet">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">

 Spacious

We have space...

							 Dashboard

							 Search routes

							 Stelar view

							 About

							 Contact Us!

							 I am admin

				<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
					Select Data from routes

				</button>


text:
//
//  ViewController.m
//  Overlay-Graphics
//
//  Created by Sridhar on 28/02/14.
//  Copyright (c) 2014 Tokbox. All rights reserved.
//

#import "ViewController.h"
#import <OpenTok/OpenTok.h>
#import "TBExampleVideoView.h"
#import "TBExampleOverlayView.h"
#import "TBExampleVideoCapture.h"

@interface ViewController () <OTSessionDelegate, OTSubscriberKitDelegate, OTPublisherDelegate, TBExampleVideoViewDelegate>
@property (nonatomic) OTSession *session;
@property (nonatomic) OTPublisher *publisher;
@property (nonatomic) OTSubscriber *subscriber;
@property (nonatomic) TBExampleVideoView *publisherVideoView;
@property (nonatomic) TBExampleVideoView *subscriberVideoView;
@end

@implementation ViewController
static double widgetHeight = 240;
static double widgetWidth = 320;

// *** Fill the following variables using your own Project info  ***
// ***          https://dashboard.tokbox.com/projects            ***
// Replace with your OpenTok API key
static NSString *const kApiKey = @"";
// Replace with your generated session ID
static NSString *const kSessionId = @"";
// Replace with your generated token
static NSString *const kToken = @"";

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Step 1: As the view comes into the foreground, initialize a new instance
    // of OTSession and begin the connection process.
    _session = [[OTSession alloc] initWithApiKey:kApiKey
                                       sessionId:kSessionId
                                        delegate:self];
    [self doConnect];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (BOOL)shouldAutorotate {
    return UIUserInterfaceIdiomPhone != [[UIDevice currentDevice] userInterfaceIdiom];
}
#pragma mark - OpenTok methods

/**
 * Asynchronously begins the session connect process. Some time later, we will
 * expect a delegate method to call us back with the results of this action.
 */
- (void)doConnect
{
    OTError *error = nil;
    [_session connectWithToken:kToken error:&error];
    if (error)
    {
        [self showAlert:[error localizedDescription]];
    }
}

/**
 * Sets up an instance of OTPublisher to use with this session. OTPubilsher
 * binds to the device camera and microphone, and will provide A/V streams
 * to the OpenTok session.
 */
- (void)doPublish
{
    OTPublisherSettings *pubSettings = [[OTPublisherSettings alloc] init];
    pubSettings.name = [[UIDevice currentDevice] name];
    _publisher = [[OTPublisher alloc]
                  initWithDelegate:self
                  settings:pubSettings];

    TBExampleVideoCapture* videoCapture =
    [[[TBExampleVideoCapture alloc] init] autorelease];
    [_publisher setVideoCapture:videoCapture];

    _publisherVideoView =
    [[TBExampleVideoView alloc] initWithFrame:CGRectMake(0,0,1,1)
                                     delegate:self
                                         type:OTVideoViewTypePublisher
                                  displayName:nil];

    // Set mirroring only if the front camera is being used.
    [_publisherVideoView.videoView setMirroring:
     (AVCaptureDevicePositionFront == videoCapture.cameraPosition)];
    [_publisher setVideoRender:_publisherVideoView];

    OTError *error = nil;
    [_session publish:_publisher error:&error];
    if (error)
    {
        [self showAlert:[error localizedDescription]];
    }

    [_publisherVideoView setFrame:CGRectMake(0, 0, widgetWidth, widgetHeight)];
    [self.view addSubview:_publisherVideoView];
}

/**
 * Cleans up the publisher and its view. At this point, the publisher should not
 * be attached to the session any more.
 */
- (void)cleanupPublisher {
    [_publisher.view removeFromSuperview];
    _publisher = nil;
    // this is a good place to notify the end-user that publishing has stopped.
}

/**
 * Instantiates a subscriber for the given stream and asynchronously begins the
 * process to begin receiving A/V content for this stream. Unlike doPublish,
 * this method does not add the subscriber to the view hierarchy. Instead, we
 * add the subscriber only after it has connected and begins receiving data.
 */
- (void)doSubscribe:(OTStream*)stream
{
    _subscriber = [[OTSubscriber alloc] initWithStream:stream
                                              delegate:self];

    _subscriberVideoView =
    [[TBExampleVideoView alloc] initWithFrame:CGRectMake(0,0,1,1)
                                     delegate:self
                                         type:OTVideoViewTypeSubscriber
                                  displayName:nil];

    [_subscriber setVideoRender:_subscriberVideoView];
    OTError *error = nil;
    [_session subscribe:_subscriber error:&error];
    if (error)
    {
        [self showAlert:[error localizedDescription]];
    }
    _subscriber.audioLevelDelegate = self;
}

/**
 * Cleans the subscriber from the view hierarchy, if any.
 * NB: You do *not* have to call unsubscribe in your controller in response to
 * a streamDestroyed event. Any subscribers (or the publisher) for a stream will
 * be automatically removed from the session during cleanup of the stream.
 */
- (void)cleanupSubscriber
{
    [_subscriber.view removeFromSuperview];
    _subscriber = nil;
}

# pragma mark - OTSession delegate callbacks

- (void)sessionDidConnect:(OTSession*)session
{
    NSLog(@"sessionDidConnect (%@)", session.sessionId);

    // Step 2: We have successfully connected, now instantiate a publisher and
    // begin pushing A/V streams into OpenTok.
    [self doPublish];
}

- (void)sessionDidDisconnect:(OTSession*)session
{
    NSString* alertMessage =
    [NSString stringWithFormat:@"Session disconnected: (%@)",
     session.sessionId];
    NSLog(@"sessionDidDisconnect (%@)", alertMessage);
}

- (void)session:(OTSession*)mySession
  streamCreated:(OTStream *)stream
{
    NSLog(@"session streamCreated (%@)", stream.streamId);

    // Step 3a: Begin subscribing to a stream we
    // have seen on the OpenTok session.
    if (nil == _subscriber)
    {
        [self doSubscribe:stream];
    }
}

- (void)session:(OTSession*)session
streamDestroyed:(OTStream *)stream
{
    NSLog(@"session streamDestroyed (%@)", stream.streamId);

    if ([_subscriber.stream.streamId isEqualToString:stream.streamId])
    {
        [self cleanupSubscriber];
    }
}

- (void)  session:(OTSession *)session
connectionCreated:(OTConnection *)connection
{
    NSLog(@"session connectionCreated (%@)", connection.connectionId);
}

- (void)    session:(OTSession *)session
connectionDestroyed:(OTConnection *)connection
{
    NSLog(@"session connectionDestroyed (%@)", connection.connectionId);
    if ([_subscriber.stream.connection.connectionId
         isEqualToString:connection.connectionId])
    {
        [self cleanupSubscriber];
    }
}

- (void) session:(OTSession*)session
didFailWithError:(OTError*)error
{
    NSLog(@"didFailWithError: (%@)", error);
}

# pragma mark - OTSubscriber delegate callbacks

- (void)subscriberDidConnectToStream:(OTSubscriberKit*)subscriber
{
    NSLog(@"subscriberDidConnectToStream (%@)",
          subscriber.stream.connection.connectionId);
    [_subscriberVideoView setFrame:CGRectMake(0, widgetHeight, widgetWidth,
                                          widgetHeight)];
    [self.view addSubview:_subscriberVideoView];
}

- (void)subscriber:(OTSubscriberKit*)subscriber
  didFailWithError:(OTError*)error
{
    NSLog(@"subscriber %@ didFailWithError %@",
          subscriber.stream.streamId,
          error);
}

# pragma mark - OTPublisher delegate callbacks

- (void)publisher:(OTPublisherKit *)publisher
    streamCreated:(OTStream *)stream
{
    NSLog(@"Publishing");
}

- (void)publisher:(OTPublisherKit*)publisher
  streamDestroyed:(OTStream *)stream
{
    if ([_subscriber.stream.streamId isEqualToString:stream.streamId])
    {
        [self cleanupSubscriber];
    }

    [self cleanupPublisher];
}

- (void)publisher:(OTPublisherKit*)publisher
 didFailWithError:(OTError*) error
{
    NSLog(@"publisher didFailWithError %@", error);
    [self cleanupPublisher];
}

- (void)showAlert:(NSString *)string
{
    // show alertview on main UI
	dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Message from video session"
                                                                         message:string
                                                                  preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertVC animated:YES completion:nil];
    });
}

- (void)     session:(OTSession*)session
archiveStartedWithId:(NSString *)archiveId
                name:(NSString *)name
{
    NSLog(@"session archiving started with id:%@ name:%@", archiveId, name);
    TBExampleOverlayView *overlayView =
    [(TBExampleVideoView *)[_publisher view] overlayView];
    [overlayView startArchiveAnimation];
}

- (void)     session:(OTSession*)session
archiveStoppedWithId:(NSString *)archiveId
{
    NSLog(@"session archiving stopped with id:%@", archiveId);
    TBExampleOverlayView *overlayView =
    [(TBExampleVideoView *)[_publisher view] overlayView];
    [overlayView stopArchiveAnimation];
}

- (void)subscriberVideoDisabled:(OTSubscriberKit*)subscriber
                         reason:(OTSubscriberVideoEventReason)reason
{
    [(TBExampleVideoView*)subscriber.videoRender audioOnlyView].hidden = NO;

    if (reason == OTSubscriberVideoEventQualityChanged)
        [[(TBExampleVideoView*)subscriber.videoRender overlayView]
         showVideoDisabled];

    _subscriber.audioLevelDelegate = self;
}

- (void)subscriberVideoEnabled:(OTSubscriberKit*)subscriber
                        reason:(OTSubscriberVideoEventReason)reason
{
    [(TBExampleVideoView*)subscriber.videoRender audioOnlyView].hidden = YES;

    if (reason == OTSubscriberVideoEventQualityChanged)
        [[(TBExampleVideoView*)subscriber.videoRender overlayView] resetView];

    _subscriber.audioLevelDelegate = nil;
}

- (void)subscriberVideoDisableWarning:(OTSubscriberKit*)subscriber
{
    NSLog(@"subscriberVideoDisableWarning");
    [[(TBExampleVideoView*)subscriber.videoRender overlayView]
     showVideoMayDisableWarning];
}

- (void)subscriberVideoDisableWarningLifted:(OTSubscriberKit*)subscriber
{
    NSLog(@"subscriberVideoDisableWarningLifted");
    [[(TBExampleVideoView*)subscriber.videoRender overlayView] resetView];
}

- (void)subscriber:(OTSubscriberKit *)subscriber
 audioLevelUpdated:(float)audioLevel{
    float db = 20 * log10(audioLevel);
    float floor = -40;
    float level = 0;
    if (db > floor) {
        level = db + fabsf(floor);
        level /= fabsf(floor);
    }
    _subscriberVideoView.audioLevelMeter.level = level;
}

#pragma mark - OTVideoViewDelegate

- (void)videoViewDidToggleCamera:(TBExampleVideoView*)videoView {
    if (videoView == _publisherVideoView) {
        [((TBExampleVideoCapture*)_publisher.videoCapture) toggleCameraPosition];
    }
}

- (void)videoView:(TBExampleVideoView*)videoView
publisherWasMuted:(BOOL)publisherMuted
{
    [_publisher setPublishAudio:!publisherMuted];
}

- (void)videoView:(TBExampleVideoView*)videoView
subscriberVolumeWasMuted:(BOOL)subscriberMuted
{
    [_subscriber setSubscribeToAudio:!subscriberMuted];
}

@end


text:
function LineRatioTile() {
    this.object = "";
  }

  function getLineRatioChartFormValues() {
    var period = $("#line-ratio-time-unit").val();
    var timeframe = $(".line-ratio-timeframe").val();
    var chartField = $("#line-ratio-field").val();
    var uniqueKey = $("#line-ratio-uniquekey").val();
    //var ignoreDigits = $(".stackedBar-ignored-digits").val();
    var numeratorField = $("#line-ratio-numerator-field").val();
    var denominatorField = $("#line-ratio-denominator-field").val();

    if(uniqueKey == "none" || uniqueKey == "" || uniqueKey == null) {
      uniqueKey = null;
    } else {
      uniqueKey = currentFieldList[parseInt(uniqueKey)].field
    }

    if (chartField == "none") {
      return [[], false];
    }
    chartField = currentFieldList[parseInt(chartField)].field;
    return {
      "period": period
      , "timeframe": timeframe
      , "uniqueKey": uniqueKey
      , "lineRatioField": chartField
      , "numerator" : numeratorField
      , "denominator" : denominatorField
    };
  }

  function setLineRatioChartFormValues(object) {
    $("#line-ratio-time-unit").val(object.tileContext.period);
    $("#line-ratio-time-unit").selectpicker('refresh');
    $("#line-ratio-timeframe").val(object.tileContext.timeframe);
    $("#line-ratio-field").val(parseInt(currentFieldList.findIndex(x => x.field == object.tileContext.lineRatioField)));
    $("#line-ratio-field").selectpicker('refresh');
    $("#line-ratio-uniquekey").val(parseInt(currentFieldList.findIndex(x => x.field == object.tileContext.uniqueKey)));
    $("#line-ratio-uniquekey").selectpicker('refresh');
    //$(".line-ratio-ignored-digits").val(parseInt(object.tileContext.ignoreDigits == undefined ? 0 : object.tileContext.ignoreDigits));

    $("#line-ratio-numerator-field").val((object.tileContext.numerator == undefined ? '' : object.tileContext.numerator));

      $("#line-ratio-denominator-field").val((object.tileContext.denominator == undefined ? '' : object.tileContext.denominator));
  }

  function clearLineRatioChartForm() {
    $('.lineRatioForm')[0].reset();
    $(".lineRatioForm").find('.selectpicker').selectpicker('refresh');
  }

  LineRatioTile.prototype.getQuery = function (object) {
    this.object = object;
    var filters = [];
    if(globalFilters) {
      filters.push(timeValue(object.tileContext.period, object.tileContext.timeframe, getGlobalFilters()))
    } else {
      filters.push(timeValue(object.tileContext.period, object.tileContext.timeframe, getPeriodSelect(object.id)))
    }

    if(object.tileContext.filters) {
      for (var i = 0; i < object.tileContext.filters.length; i++) {
        filters.push(object.tileContext.filters[i]);
      }
    }

    var templateFilters = isAppendTemplateFilters(object.tileContext.table);
    if(templateFilters.length > 0) {
      filters = filters.concat(templateFilters);
    }

    var data = {
      "opcode": "trend"
      , "table": object.tileContext.table
      , "filters": filters
      , "uniqueCountOn": object.tileContext.uniqueKey && object.tileContext.uniqueKey != "none" ? object.tileContext.uniqueKey : null
      , "field": object.tileContext.lineRatioField
      , period: periodFromWindow(object.tileContext.period, (globalFilters ? getGlobalFilters() : getPeriodSelect(object.id)))
    }
    var refObject = this.object;
    $.ajax({
      method: "post"
      , dataType: 'json'
      , accepts: {
        json: 'application/json'
      }
      , url: apiUrl + "/v1/analytics"
      , contentType: "application/json"
      , data: JSON.stringify(data)
      , success: $.proxy(this.getData, this)
      ,error: function(xhr, textStatus, error) {
        showFetchError(refObject, "refresh", JSON.parse(xhr.responseText));
      }
    });
  }

  LineRatioTile.prototype.getData = function (data) {
    var dataLength = Object.keys(data.trends).length;
   if(dataLength > 0) {
      /**
   * Check special character exist
   * if exist split by space
   * loop array and get values from response
   * if unable to get value from response
   * set value as zero
   * eval numerator and denominator strings
   */
  var format = /^[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
  var numeratorObject =  {};
  var numeratorCount = [];
  var denominatorCount = [];
  var denominatorObject = {};

  var numerator = this.object.tileContext.numerator;
  var denominator = this.object.tileContext.denominator;

  /**
   * Separate numerator and denominator and store count of that
   */
  if(isSpecialCharacter(numerator)) {
    var numeratorSplitArray = numerator.split(" ");
    for(var i = 0; i < numeratorSplitArray.length; i++) {
      if(!format.test(numeratorSplitArray[i])) { // check string or special character
        var string = data.trends[numeratorSplitArray[i]];
        numeratorObject[numeratorSplitArray[i]] =  data.trends[numeratorSplitArray[i]];
        numeratorCount.push(data.trends[numeratorSplitArray[i]].length);
      }
    }
  } else {
    numeratorObject[numerator] = data.trends[numerator];
    numeratorCount.push(data.trends[numerator].length);
  }

  if(isSpecialCharacter(denominator)) {
    var denominatorSplitArray = denominator.split(" ");
    for(var i = 0; i < denominatorSplitArray.length; i++) {
      if(!format.test(denominatorSplitArray[i])) { // check string or special character
        var string = data.trends[denominatorSplitArray[i]];
        denominatorObject[denominatorSplitArray[i]] =  data.trends[denominatorSplitArray[i]];
        denominatorCount.push(data.trends[denominatorSplitArray[i]].length);
      }
    }
  } else {
    denominatorObject[denominator] = data.trends[denominator];
    denominatorCount.push(data.trends[denominator].length);
  }

  // find least number of iteration
  var combinedNumberOfCount = numeratorCount.concat(denominatorCount);
  var numberofIteration = Math.min.apply(null,combinedNumberOfCount);

  var newData = [];
  newData.push(['date', 'count']);

  var finalNumerator = []; // to calculate formula
  var finalDenominator = [];

  var numeratorkeys; // separate keys alone
  var denominatorkeys;

  numeratorkeys = Object.keys(numeratorObject);
  denominatorkeys = Object.keys(denominatorObject);

  var evalString = "";
  var period = 0;

  // loop till figured out least number
  for(var resultLoop = 0; resultLoop < numberofIteration; resultLoop++ )
  {
    if(isSpecialCharacter(numerator)) {
      var resultNumerator = numerator.split(" ");
      for(var i = 0; i < resultNumerator.length; i++) {
        if(format.test(resultNumerator[i])) { // check string or special character
          evalString+= resultNumerator[i];
        } else {
          var string = numeratorObject[resultNumerator[i]][resultLoop].count;
          evalString+= string == undefined ? 0 : string;
          period = (numeratorObject[resultNumerator[i]][resultLoop].period == undefined ? 0 : numeratorObject[resultNumerator[i]][resultLoop].period);
        }
      }
    } else {
      var countVariable = numeratorObject[numerator][resultLoop].count;
      evalString+= countVariable == undefined ? 0 : countVariable;
      period = (numeratorObject[numerator][resultLoop].period == undefined ? 0 : numeratorObject[numerator][resultLoop].period);
    }
    finalNumerator.push({"period": period, "count": eval(evalString)});
    evalString = "";
    period = 0;
  }

  for(var resultLoop = 0; resultLoop < numberofIteration; resultLoop++ )
  {
    if(isSpecialCharacter(denominator)) {
      var resultNumerator = denominator.split(" ");
      for(var i = 0; i < resultNumerator.length; i++) {
        if(format.test(resultNumerator[i])) { // check string or special character
          evalString+= resultNumerator[i];
        } else {
          var string = denominatorObject[resultNumerator[i]][resultLoop].count;
          evalString+= string == undefined ? 0 : string;
          period = (denominatorObject[resultNumerator[i]][resultLoop].period == undefined ? 0 : denominatorObject[resultNumerator[i]][resultLoop].period);
        }
      }
    } else {
      var countVariable = denominatorObject[denominator][resultLoop].count;
      evalString+= countVariable == undefined ? 0 : countVariable;
      period = (denominatorObject[denominator][resultLoop].period == undefined ? 0 : denominatorObject[denominator][resultLoop].period);
    }
    finalDenominator.push({"period": period, "count": eval(evalString)});
    evalString = "";
    period = 0;
  }

  // Loop final value and calculate percentage
  for(var finalValue = 0; finalValue < finalNumerator.length; finalValue++) {
    var denominatorTotal;
    var numeratorTotal;

    if(finalDenominator[finalValue]) { // check value exist
      denominatorTotal = finalDenominator[finalValue].count
    }

    if(finalNumerator[finalValue]) {// check value exist
      numeratorTotal = finalNumerator[finalValue].count;
    }

    var percentage = (denominatorTotal/numeratorTotal*100);

    if(isNaN(percentage))// if nan
      percentage = 0;

    if(percentage == "Infinity") // if 4/0*100 = infinity, if this is true set percentage as 0
      percentage = 0;

    newData.push([finalNumerator[finalValue].period, (percentage / Math.pow(10, 0))]);
  }
  this.render(newData, dataLength);
  } else {
    this.render([], dataLength);
  }
}

  LineRatioTile.prototype.render = function (rows, dataLength) {
    if(dataLength == 0)
      showFetchError(this.object, "data", null);
    else
      hideFetchError(this.object);

    var object = this.object;
    var chartDiv = $("#"+object.id).find(".chart-item");
    var borderColorArray = ["#9e8cd9", "#f3a534", "#9bc95b", "#50e3c2"];
    var ctx = chartDiv.find("#" + object.id);

    if(dataLength == 0) {
      ctx.hide();
    } else {
      ctx.show();
      ctx.width(ctx.width - 100);
      ctx.height(fullWidgetChartHeight());
      var plot = $.plot(ctx, [
        {
          data: rows
          , color: "#FF69B4",
            }
      , ], {
        series: {
          stack: true,
          lines: {
            show: true
            , lineWidth: 1.0
            , color: "red"
            , fill: false
            , fillColor: {
              colors: [{
                opacity: 0.7
              }, {
                opacity: 0.1
              }]
            }
          }
          , points: {
            show: true
          }
          , shadowSize: 0
          , curvedLines: { active: true }
        }
        , xaxis: {
          tickLength: 0
          , mode: "time"
          , timezone: "browser"
          , timeformat: axisTimeFormat(object.tileContext.period, (globalFilters ? getGlobalFilters() : getPeriodSelect(object.id)))
        , }
        , yaxis: {
          markingsStyle: 'dashed',
            tickFormatter: function(val, axis) {
            return numDifferentiation(val);
          },
        }
        , grid: {
          hoverable: true
          , color: "#B2B2B2"
          , show: true
          , borderWidth: {
            top: 0
            , right: 0
            , bottom: 1
            , left: 1
          }
          , borderColor: "#EEEEEE"
        , }
        , tooltip: false
        , tooltipOpts: {
          content: ""
        }
        , colors: [borderColorArray[Math.floor(Math.random()*borderColorArray.length)]]
      , });

      function showTooltip(x, y, xValue, yValue) {
        var a = axisTimeFormatNew(object.tileContext.period, (globalFilters ? getGlobalFilters() : getPeriodSelect(object.id)));
        $('

'+yValue+'

' + moment(xValue).format(a) + '

').css( {
          position: 'absolute',
          display: 'none',
          top: y - 60,
          left: x - 2,
        }).appendTo("body").fadeIn(200);
      }

      var previousPoint = null;
      $(ctx).bind("plothover", function (event, pos, item) {
        if (item) {
          if (previousPoint != item.datapoint) {
            previousPoint = item.datapoint;

            $("#flot-custom-tooltip").remove();
            var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(1);
            showTooltip(item.pageX, item.pageY, Number(x), y);
          }
        } else {
          $("#flot-custom-tooltip").remove();
          clicksYet = false;
          previousPoint = null;
        }
      });
    }
  }