text:
package kvstore;

import static autograder.TestUtils.kTimeoutQuick;
import static kvstore.KVConstants.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import autograder.AGCategories.AGTestDetails;
import autograder.AGCategories.AG_PROJ4_CODE;

@RunWith(PowerMockRunner.class)
@PrepareForTest(TPCMasterHandler.class)
public class TPCMasterHandlerGetTest {

    private KVServer server;
    private TPCMasterHandler masterHandler;
    private Socket sock1;
    private Socket sock2;
    private Socket sock3;

    private static final String LOG_PATH = "TPCMasterHandlerTest.log";

    @Before
    public void setupTPCMasterHandler() throws Exception {
        server = new KVServer(10, 10);
        TPCLog log = new TPCLog(LOG_PATH, server);
        Utils.setupMockThreadPool();
        masterHandler = new TPCMasterHandler( 1L, server, log);
    }

    @After
    public void tearDown() {
        server = null;
        masterHandler = null;
        sock1 = null;
        sock2 = null;
        sock3 = null;
        File log = new File(LOG_PATH);

        if (log.exists() && !log.delete()) { // true iff delete failed.
            System.err.printf("deleting log-file at %s failed.\n", log.getAbsolutePath());
        }
    }

    @Test(timeout = kTimeoutQuick)
    @Category(AG_PROJ4_CODE.class)
    @AGTestDetails(points = 1,
        desc = "Test if they can fail to get one value using Handler")
    public void testFailureGet() throws KVException {
        setupSocketSuccess();
        InputStream getreqFile = getClass().getClassLoader().getResourceAsStream("getreq.txt");
        ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
        try {
            doNothing().when(sock1).setSoTimeout(anyInt());
            when(sock1.getInputStream()).thenReturn(getreqFile);
            when(sock1.getOutputStream()).thenReturn(tempOut);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        masterHandler.handle(sock1);

        try {
            doNothing().when(sock3).setSoTimeout(anyInt());
            when(sock3.getInputStream()).thenReturn(new ByteArrayInputStream(tempOut.toByteArray()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        KVMessage check = new KVMessage(sock3);
        assertEquals(RESP, check.getMsgType());
        assertEquals(ERROR_NO_SUCH_KEY, check.getMessage());
    }

    /* begin helper methods. */

    private void setupSocketSuccess() {
        sock1 = mock(Socket.class);
        sock2 = mock(Socket.class);
        sock3 = mock(Socket.class);
    }

}


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_PUT_FILE_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_PUT_FILE_REQUEST_H_

#include "application_manager/commands/command_request_impl.h"
#include "utils/macro.h"
#include "application_manager/application_manager_impl.h"

namespace application_manager {

namespace commands {

/**
 * @brief PutFileRequest command class
 **/
class PutFileRequest : public CommandRequestImpl {
 public:
  /**
   * @brief PutFileRequest class constructor
   *
   * @param message Incoming SmartObject message
   **/
  explicit PutFileRequest(const MessageSharedPtr& message);

  /**
   * @brief PutFileRequest class destructor
   **/
  virtual ~PutFileRequest();

  /**
   * @brief Execute command
   **/
  virtual void Run();

 private:
    int64_t                     offset_;
    std::string                  sync_file_name_;
    int64_t                     length_;
    mobile_apis::FileType::eType file_type_;
    bool                         is_persistent_file_;

    void SendOnPutFileNotification();
  DISALLOW_COPY_AND_ASSIGN(PutFileRequest);
};

}  // namespace commands
}  // namespace application_manager

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_PUT_FILE_REQUEST_H_

redpajama_set_name: RedPajamaGithub


text:
import os
import pathlib
import subprocess
import sys

template_creator_exe = pathlib.Path(__file__).parent/ '..' / 'trinketloader' / 'generate_images_cpp.py'
firmware_hex_path = pathlib.Path(__file__).parent / '.pio' / 'build' / 'attiny85' / 'firmware.hex'
if not firmware_hex_path.exists():
    raise RuntimeError(f'{firmware_hex_path} not found, did you build?')
subprocess.check_call([str(template_creator_exe), str(firmware_hex_path)])
os.chdir('../trinketloader')
subprocess.check_call(['pio', 'run', '-t', 'upload'])


text:
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;
using CefSharp.Example.Filters;

namespace CefSharp.Example
{
    public class RequestHandler : IRequestHandler
    {
        public static readonly string VersionNumberString = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}",
            Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);

        bool IRequestHandler.OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
        {
            return false;
        }

        bool IRequestHandler.OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
        {
            return OnOpenUrlFromTab(browserControl, browser, frame, targetUrl, targetDisposition, userGesture);
        }

        protected virtual bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
        {
            return false;
        }

        bool IRequestHandler.OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //To allow certificate
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        void IRequestHandler.OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
        {
            // TODO: Add your own code here for handling scenarios where a plugin crashed, for one reason or another.
        }

        CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
            //Example of how to set Referer
            // Same should work when setting any header

            // For this example only set Referer when using our custom scheme
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                //Referrer is now set using it's own method (was previously set in headers before)
                request.SetReferrer("http://google.com", ReferrerPolicy.Default);
            }

            //Example of setting User-Agent in every request.
            //var headers = request.Headers;

            //var userAgent = headers["User-Agent"];
            //headers["User-Agent"] = userAgent + " CefSharp";

            //request.Headers = headers;

            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    if (request.Method == "POST")
                    {
                        using (var postData = request.PostData)
                        {
                            if(postData != null)
                            {
                                var elements = postData.Elements;

                                var charSet = request.GetCharSet();

                                foreach (var element in elements)
                                {
                                    if (element.Type == PostDataElementType.Bytes)
                                    {
                                        var body = element.GetBody(charSet);
                                    }
                                }
                            }
                        }
                    }

                    //Note to Redirect simply set the request Url
                    //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase))
                    //{
                    //    request.Url = "https://github.com/";
                    //}

                    //Callback in async fashion
                    //callback.Continue(true);
                    //return CefReturnValue.ContinueAsync;
                }
            }

            return CefReturnValue.Continue;
        }

        bool IRequestHandler.GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.

            callback.Dispose();
            return false;
        }

        void IRequestHandler.OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
        {
            // TODO: Add your own code here for handling scenarios where the Render Process terminated for one reason or another.
            browserControl.Load(CefExample.RenderProcessCrashedUrl);
        }

        bool IRequestHandler.OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //Accept Request to raise Quota
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        void IRequestHandler.OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
        {
            //Example of how to redirect - need to check `newUrl` in the second pass
            //if (string.Equals(frame.GetUrl(), "https://www.google.com/", StringComparison.OrdinalIgnoreCase) && !newUrl.Contains("github"))
            //{
            //	newUrl = "https://github.com";
            //}
        }

        bool IRequestHandler.OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
        {
            return url.StartsWith("mailto");
        }

        void IRequestHandler.OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
        {

        }

        bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            //NOTE: You cannot modify the response, only the request
            // You can now access the headers
            //var headers = response.ResponseHeaders;

            return false;
        }

        IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                if(request.Url.Equals(CefExample.ResponseFilterTestUrl, StringComparison.OrdinalIgnoreCase))
                {
                    return new FindReplaceResponseFilter("REPLACE_THIS_STRING", "This is the replaced string!");
                }

                if (request.Url.Equals("custom://cefsharp/assets/js/application.js", StringComparison.OrdinalIgnoreCase))
                {
                    return new AppendResponseFilter(System.Environment.NewLine + "//CefSharp Appended this comment.");
                }

                return new PassThruResponseFilter();
            }

            return null;
        }

        void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {

        }
    }
}


text:
from lib import citrusleaf
from lib import util
import lib
from telnetlib import Telnet
from time import time
import socket
import threading

def getfqdn(address, timeout=0.5):
    # note: cannot use timeout lib because signal must be run from the
    #       main thread

    result = [address]

    def helper():
        result[0] = socket.getfqdn(address)

    t = threading.Thread(target=helper)

    t.start()

    t.join(timeout)

    return result[0]

def return_exceptions(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            args[0].alive = False
            return e

    return wrapper

class Node(object):
    dns_cache = {}

    def __init__(self, address, port=3000, timeout=3, use_telnet=False
                 , user=None, password=None):
        """
        address -- ip or fqdn for this node
        port -- info port for this node
        timeout -- number of seconds to wait before giving up on the node
        If address is ip then get fqdn else get ip
        store ip in self.ip
        store fqdn in self.fqdn
        store port in self.port

        NOTE: would be nice if the port could either be the service or telnet
        access port. Can we detect from the socket?
        ALSO NOTE: May be better to just use telnet instead?
        """
        self._updateIP(address)
        self.port = port
        self.xdr_port = 3004 # TODO: Find the xdr port
        self._timeout = timeout
        self._use_telnet = use_telnet
        self.user = user
        self.password = password
        # hack, _key needs to be defines before info calls... but may have
        # wrong (localhost) address before infoService is called. Will set
        # again after that call.

        self._key = hash(self.createKey(address, self.port))

        try:
            self.node_id = self.infoNode()
            if isinstance(self.node_id, Exception):
                raise self.node_id

            # Original address may not be the service address, the
            # following will ensure we have the service address
            address = self.infoService()[0]
            if isinstance(address, Exception):
                raise address

            # calling update ip again because infoService may have provided a
            # different IP than what was seeded.
            self._updateIP(address)
            self._serviceIPPort = self.createKey(self.ip, self.port)
            self._key = hash(self._serviceIPPort)
            self.alive = True
        except:
            # Node is offline... fake a node
            self.ip = address
            self.fqdn = address
            self.port = port
            self._serviceIPPort = self.createKey(self.ip, self.port)
            self._key = hash(self._serviceIPPort)

            self.node_id = "000000000000000"
            self.alive = False

    @property
    def key(self):
        """Get the value of serviceIPPort"""
        return self._serviceIPPort

    @staticmethod
    def createKey(address, port):
        return "%s:%s"%(address, port)

    def __hash__(self):
        return hash(self._key)

    def __eq__(self, other):
        return self._key == other._key

    def _updateIP(self, address):
        if address not in self.dns_cache:
            self.dns_cache[address] = (socket.gethostbyname(address)
                                       , getfqdn(address))

        self.ip, self.fqdn = self.dns_cache[address]

    def sockName(self, use_fqdn = False):
        if use_fqdn:
            address = self.fqdn
        else:
            address = self.ip

        return self.createKey(address, self.port)

    def __str__(self):
        return self.sockName()

    def isXDREnabled(self):
        config = self.infoGetConfig('xdr')
        if isinstance(config, Exception):
            return False

        xdr_enabled = config['xdr']['enable-xdr']
        return xdr_enabled == 'true'

    @return_exceptions
    @util.cached
    def _infoTelnet(self, command, port = None):
        # TODO: Handle socket failures
        if port == None:
            port = self.port
        try:
            self.sock == self.sock # does self.sock exist?
        except:
            self.sock = Telnet(self.ip, port)

        self.sock.write("%s\n"%command)

        starttime = time()
        result = ""
        while not result:
            result = self.sock.read_very_eager().strip()
            if starttime + self._timeout < time():
                # TODO: rasie appropriate exception
                raise IOError("Could not connect to node %s"%self.ip)
        return result

    @return_exceptions
    @util.cached
    def _infoCInfo(self, command, port = None):
        # TODO: citrusleaf.py does not support passing a timeout default is 0.5s
        if port == None:
            port = self.port

        result = citrusleaf.citrusleaf_info(self.ip, port, command
                                            , user=self.user
                                            , password=self.password)
        if result != -1 and result is not None:
            return result
        else:
            raise IOError(
                "Invalid command or Could not connect to node %s "%self.ip)

    @return_exceptions
    def info(self, command):
        """
        asinfo function equivalent

        Arguments:
        command -- the info command to execute on this node
        """
        if self._use_telnet:
            return self._infoTelnet(command)
        else:
            return self._infoCInfo(command)

    @return_exceptions
    @util.cached
    def xdrInfo(self, command):
        """
        asinfo -p [xdr-port] equivalent

        Arguments:
        command -- the info command to execute on this node
        """

        try:
            return self._infoCInfo(command, self.xdr_port)
        except Exception as e:
            return e

    @return_exceptions
    def infoNode(self):
        """
        Get this nodes id. asinfo -v "node"

        Returns:
        string -- this node's id.
        """

        return self.info("node")

    @return_exceptions
    def _infoServicesHelper(self, services):
        """
        Takes an info services response and returns a list.
        """
        if not services:
            return []

        s = map(util.info_to_tuple, util.info_to_list(services))
        return map(lambda v: (v[0], int(v[1])), s)

    @return_exceptions
    def infoServices(self):
        """
        Get other services this node knows of that are active

        Returns:
        list -- [(ip,port),...]
        """
        services = self.info("services")

        return self._infoServicesHelper(self.info("services"))

    @return_exceptions
    def infoService(self):
        service = self.info("service")
        return tuple(service.split(':'))

    @return_exceptions
    def infoServicesAlumni(self):
        """
        Get other services this node has ever know of

        Returns:
        list -- [(ip,port),...]
        """

        try:
            return self._infoServicesHelper(self.info("services-alumni"))
        except IOError:
            # Possibly old asd without alumni feature
            return self.infoServices()

    @return_exceptions
    def infoStatistics(self):
        """
        Get statistics for this node. asinfo -v "statistics"

        Returns:
        dictionary -- statistic name -> value
        """

        return util.info_to_dict(self.info("statistics"))

    @return_exceptions
    def infoNamespaces(self):
        """
        Get a list of namespaces for this node. asinfo -v "namespaces"

        Returns:
        list -- list of namespaces
        """

        return util.info_to_list(self.info("namespaces"))

    @return_exceptions
    def infoNamespaceStatistics(self, namespace):
        """
        Get statistics for a namespace.

        Returns:
        dict -- {stat_name : stat_value, ...}
        """

        return util.info_to_dict(self.info("namespace/%s"%namespace))

    @return_exceptions
    def infoAllNamespaceStatistics(self):
        namespaces = self.infoNamespaces()

        if isinstance(namespaces, Exception):
            return namespaces

        stats = {}
        for ns in namespaces:
            stats[ns] = self.infoNamespaceStatistics(ns)

        return stats

    @return_exceptions
    def infoSetStatistics(self):
        stats = self.info("sets")
        stats = util.info_to_list(stats)
        stats.pop()
        stats = [util.info_colon_to_dict(stat) for stat in stats]

        sets = {}
        for stat in stats:
            ns_name = stat['ns_name']
            set_name = stat['set_name']

            key = (ns_name, set_name)
            if key not in sets:
                sets[key] = {}
            set_dict = sets[key]

            set_dict.update(stat)

        return sets

    @return_exceptions
    def infoBinStatistics(self):
        stats = util.info_to_list(self.info("bins"))
        stats.pop()
        stats = [value.split(':') for value in stats]
        stat_dict = {}

        for stat in stats:
            values = util.info_to_list(stat[1], ',')
            values = ";".join(filter(lambda v: '=' in v, values))
            values = util.info_to_dict(values)
            stat_dict[stat[0]] = values

        return stat_dict

    @return_exceptions
    def infoXDRStatistics(self):
        """
        Get statistics for XDR

        Returns:
        dict -- {stat_name : stat_value, ...}
        """
        return util.info_to_dict(self.xdrInfo('statistics'))

    @return_exceptions
    def infoGetConfig(self, stanza = "", namespace = ""):
        """
        Get the complete config for a node. This should include the following
        stanzas: Service, Network, XDR, and Namespace
        Sadly it seems Service and Network are not seperable.

        Returns:
        dict -- stanza --> [namespace] --> param --> value
        """
        config = {}
        if stanza == 'namespace':
            if namespace != "":
                config[stanza] = {namespace:util.info_to_dict(
                    self.info("get-config:context=namespace;id=%s"%namespace))}
            else:
                namespace_configs = {}
                namespaces = self.infoNamespaces()
                for namespace in namespaces:
                    namespace_config = self.infoGetConfig('namespace', namespace)
                    namespace_config = namespace_config['namespace'][namespace]
                    namespace_configs[namespace] = namespace_config
                config['namespace'] = namespace_configs

        elif stanza == '':
            config['service'] = util.info_to_dict(self.info("get-config:"))
        elif stanza != 'all':
            config[stanza] = util.info_to_dict(
                self.info("get-config:context=%s"%stanza))
        elif stanza == "all":
            namespace_configs = {}
            namespaces = self.infoNamespaces()
            for namespace in namespaces:
                namespace_config = self.infoGetConfig('namespace', namespace)
                namespace_config = namespace_config['namespace'][namespace]
                namespace_configs[namespace] = namespace_config
            config['namespace'] = namespace_configs
            config['service'] = self.infoGetConfig("service")
            # Server lumps this with service
            # config["network"] = self.infoGetConfig("network")
        return config

    @return_exceptions
    def infoLatency(self):
        tdata = self.info('latency:').split(';')[:-1]
        data = {}
        while tdata != []:
            columns = tdata.pop(0)
            row = tdata.pop(0)

            hist_name, columns = columns.split(':', 1)
            columns = columns.split(',')
            row = row.split(',')
            start_time = columns.pop(0)
            end_time = row.pop(0)
            columns.insert(0, 'Time Span')
            row = [float(r) for r in row]
            row.insert(0, "%s->%s"%(start_time, end_time))

            data[hist_name] = (columns, row)

        return data

    @return_exceptions
    def infoXDRGetConfig(self):
        result = self.xdrInfo('get-config')
        result = {'xdr':util.info_to_dict(result)}
        return result

    @return_exceptions
    def infoHistogram(self, histogram):
        namespaces = self.infoNamespaces()

        data = {}
        for namespace in namespaces:
            datum = self.info("hist-dump:ns=%s;hist=%s"%(namespace
                                                         , histogram))
            datum = datum.split(',')
            datum.pop(0) # don't care about ns, hist_name, or length
            width = int(datum.pop(0))
            datum[-1] = datum[-1].split(';')[0]
            datum = map(int, datum)

            data[namespace] = {'histogram':histogram
                               , 'width':width
                               , 'data':datum}

        return data

    def _parseDunList(self, dun_list):
        c = lib.cluster.Cluster(self.ip)
        lookup = c.node_lookup
        result = set()

        if 'all' in dun_list:
            result.add('all')
        else:
            for node in dun_list:
                if node in lookup:
                    nodes = lookup[node]
                    if len(nodes) == 1:
                        result.add(nodes[0].node_id)
                    else:
                        keys = lookup.getKey(node)
                        raise Exception(
                            "Node Name: %s is not unique, conflicts "%(node) + \
                            "with %s"%(','.join(keys)))

        dun_list = ','.join(sorted(result))
        if not dun_list:
            raise Exception('Did not recieve any valid hosts')

        return dun_list

    @return_exceptions
    def infoDun(self, dun_list):
        dun_list = self._parseDunList(dun_list)
        command = "dun:nodes=%s"%(dun_list)
        result = self.info(command)
        return command, result

    @return_exceptions
    def infoUndun(self, dun_list):
        dun_list = self._parseDunList(dun_list)
        command = "undun:nodes=%s"%(dun_list)
        result = self.info(command)
        return command, result

    @return_exceptions
    def infoSIndex(self):
        return [util.info_to_dict(v, ':')
                for v in util.info_to_list(self.info("sindex"))[:-1]]


text:
<?php

//[tickets_left format="widget"]
function tickets_left( $atts, $content = null ){
//    if (!is_null($content)) {
//        return "
Please, verify your shortcode. This is not an enclosing shortcode.
";
//    }

    $local_attrs = shortcode_atts(array(
        'format' => 'widget'
    ), $atts);

    return "foo = {$local_attrs['format']}";
}

add_shortcode( 'tickets_left', 'tickets_left' );


text:
package org.apache.metamodel.excel;

import java.util.Map;

import org.apache.metamodel.schema.MutableSchema;
import org.apache.metamodel.schema.MutableTable;
import org.apache.metamodel.schema.Schema;
import org.apache.metamodel.schema.Table;
import org.apache.metamodel.schema.TableType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * XML handler for transforming a workbook document into {@link Table}s in a
 * MetaModel {@link Schema}.
 */
final class XlsxWorkbookToTablesHandler extends DefaultHandler {

	private final MutableSchema _schema;
	private final Map<String, String> _tableNamesToRelationshipIds;

	public XlsxWorkbookToTablesHandler(MutableSchema schema,
			Map<String, String> tableNamesToRelationshipIds) {
		_schema = schema;
		_tableNamesToRelationshipIds = tableNamesToRelationshipIds;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if ("sheet".equals(qName)) {
			String name = attributes.getValue("name");
			assert name != null;
			String relationId = attributes.getValue("r:id");
			assert relationId != null;

			if (_schema != null) {
				MutableTable table = new MutableTable(name, TableType.TABLE,
						_schema);
				_schema.addTable(table);
			}
			_tableNamesToRelationshipIds.put(name, relationId);
		}
	}
}


text:
package org.elasticsearch.search;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.search.LeafCollector;
import org.apache.lucene.search.TotalHitCountCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
import org.elasticsearch.search.query.CancellableCollector;
import org.elasticsearch.tasks.TaskCancelledException;
import org.elasticsearch.test.ESTestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class SearchCancellationTests extends ESTestCase {

    static Directory dir;
    static IndexReader reader;

    @BeforeClass
    public static void setup() throws IOException {
        dir = newDirectory();
        RandomIndexWriter w = new RandomIndexWriter(random(), dir);
        // we need at least 2 segments - so no merges should be allowed
        w.w.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);
        w.setDoRandomForceMerge(false);
        indexRandomDocuments(w, TestUtil.nextInt(random(), 2, 20));
        w.flush();
        indexRandomDocuments(w, TestUtil.nextInt(random(), 1, 20));
        reader = w.getReader();
        w.close();
    }

    private static void indexRandomDocuments(RandomIndexWriter w, int numDocs) throws IOException {
        for (int i = 0; i < numDocs; ++i) {
            Document doc = new Document();
            doc.add(new StringField("foo", "bar", Field.Store.NO));
            w.addDocument(doc);
        }
    }

    @AfterClass
    public static void cleanup() throws IOException {
        IOUtils.close(reader, dir);
        dir = null;
        reader = null;
    }

    public void testCancellableCollector() throws IOException {
        TotalHitCountCollector collector = new TotalHitCountCollector();
        AtomicBoolean cancelled = new AtomicBoolean();
        CancellableCollector cancellableCollector = new CancellableCollector(cancelled::get, collector);
        final LeafCollector leafCollector = cancellableCollector.getLeafCollector(reader.leaves().get(0));
        leafCollector.collect(0);
        cancelled.set(true);
        leafCollector.collect(1);
        expectThrows(TaskCancelledException.class, () -> cancellableCollector.getLeafCollector(reader.leaves().get(1)));
    }

}


text:
import identity from 'lodash-es/identity';
import {createAction} from 'redux-actions';

export const projectCompiled = createAction(
  'PROJECT_COMPILED',
  identity,
  (_source, timestamp = Date.now()) => ({timestamp}),
);

export const projectCompilationFailed = createAction(
  'PROJECT_COMPILATION_FAILED',
);

export const refreshPreview = createAction('REFRESH_PREVIEW', timestamp => ({
  timestamp,
}));


text:
package ru.job4j.testtask;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import java.util.Iterator;
import java.util.Comparator;

/**
 * operations with order books.
 */
public class OrderBooksCreation {
    /**
     * divide orders to buy orders & sell orders.
     * @param map - map ouf compound orders.
     */
    void divideToBuyAndSell(HashMap<String, Order> map) {
        List<Order> list = new ArrayList<>(map.values());
        List<Order> listBuy = new ArrayList<>();
        List<Order> listSell = new ArrayList<>();

        for (Order tempOrder : list) {
            if (tempOrder.isOperation()) {
                listBuy.add(tempOrder);
            } else {
                listSell.add(tempOrder);
            }
        }
        listBuy.sort(Comparator.comparing(Order::getPrice));
        listSell.sort(Comparator.comparing(Order::getPrice));
        Collection<Order> addedVolumesListBuy = onePriceOneOrder(listBuy);
        Collection<Order> addedVolumesListSell = onePriceOneOrder(listSell);

        pairCompare(addedVolumesListBuy, addedVolumesListSell);
    }

    /**
     * compound orders with one price.
     * @param list - list of all orders (buy or sell).
     * @return - Collection with exclusive price and compounded volumes of orders with the same price.
     */
    private Collection<Order> onePriceOneOrder(List<Order> list) {
        TreeMap<Double, Order> mapReady = new TreeMap<>();
        int sum = 0;
        for (Order tempOrder : list) {
            if (mapReady.containsKey(tempOrder.getPrice())) {
                sum += tempOrder.getVolume();
                mapReady.put(tempOrder.getPrice(), tempOrder.setVolume(sum));
            } else {
                mapReady.put(tempOrder.getPrice(), tempOrder);
                sum = tempOrder.getVolume();
            }
        }
        return mapReady.values();
    }

    /**
     * compare orders in buy list and in sell list to get deal.
     * @param listB - list with buy orders.
     * @param listS - list with sell orders.
     */
    private void pairCompare(Collection<Order> listB, Collection<Order> listS) {
        List<Order> listBuy = new ArrayList<>(listB);
        List<Order> listSell = new ArrayList<>(listS);
        listBuy.sort(Comparator.comparing(Order::getPrice));
        listSell.sort(Comparator.comparing(Order::getPrice));
        Iterator<Order> iterBuy = listBuy.iterator();
        Iterator<Order> iterSell = listSell.iterator();
        Order tempBuy = iterBuy.next();
        Order tempSell = iterSell.next();
        while (iterBuy.hasNext() && iterSell.hasNext()) {
            int newVolume = Math.max(tempBuy.getVolume(), tempSell.getVolume())
                    - Math.min(tempBuy.getVolume(), tempSell.getVolume()
            );
            if (tempBuy.getPrice() >= tempSell.getPrice()) {
                if (tempBuy.getVolume() == tempSell.getVolume()) {
                    iterBuy.remove();
                    iterSell.remove();
                    tempBuy = iterBuy.next();
                    tempSell = iterSell.next();
                } else {
                    if (tempBuy.getVolume() - tempSell.getVolume() > 0) {
                        tempBuy.setVol(newVolume);
                        iterSell.remove();
                        tempSell = iterSell.next();
                    } else {
                        tempSell.setVol(newVolume);
                        iterBuy.remove();
                        tempBuy = iterBuy.next();
                    }
                }
            } else {
                tempBuy = iterBuy.next();
            }

            // весь этот код ниже в этом методе, только для обработки последнего ордера в любом из списков.
            // очень много занимает, но я не нашел алгоритма сократить.
            // по идее, можно вынести общий код, но тогда нужно отправлять в метод не только списки ордеров
            // но и создавать внутри метода итераторы. По итогу сильного сокращения кода не добиться этим способом.
            if (!iterBuy.hasNext() && iterSell.hasNext()) {
                while (true) {
                    if (tempSell.getPrice() > tempBuy.getPrice()) {
                        break;
                    }
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() > tempBuy.getVolume()) {
                        tempSell.setVol(tempSell.getVolume() - tempBuy.getVolume());
                        iterBuy.remove();
                        break;
                    }
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() < tempBuy.getVolume()) {
                        tempBuy.setVol(tempBuy.getVolume() - tempSell.getVolume());
                        iterSell.remove();
                        if (iterSell.hasNext()) {
                            tempSell = iterSell.next();
                        }
                        continue;
                    }
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() == tempBuy.getVolume()) {
                        iterBuy.remove();
                        iterSell.remove();
                        break;
                    }
                }
            }

            if (!iterSell.hasNext() && iterBuy.hasNext()) {
                while (true) {
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() < tempBuy.getVolume()) {
                        tempBuy.setVol(tempBuy.getVolume() - tempSell.getVolume());
                        iterSell.remove();
                        break;
                    }
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() > tempBuy.getVolume()) {
                        tempSell.setVol(tempSell.getVolume() - tempBuy.getVolume());
                        iterBuy.remove();
                        if (iterBuy.hasNext()) {
                            tempBuy = iterBuy.next();
                        }
                        continue;
                    }
                    if (tempBuy.getPrice() >= tempSell.getPrice() && tempSell.getVolume() == tempBuy.getVolume()) {
                        iterBuy.remove();
                        iterSell.remove();
                        break;
                    }
                }
            }
            if (!iterSell.hasNext() && !iterBuy.hasNext()) {
                if (tempSell.getVolume() > tempBuy.getVolume()) {
                    tempSell.setVol(tempSell.getVolume() - tempBuy.getVolume());
                    iterBuy.remove();
                } else if (tempSell.getVolume() < tempBuy.getVolume()) {
                    tempBuy.setVol(tempBuy.getVolume() - tempSell.getVolume());
                    iterSell.remove();
                } else {
                    iterBuy.remove();
                    iterSell.remove();
                }
            }
        }

        printResult(listBuy, listSell);
    }

    /**
     * print result.
     * @param listBuy - finish buy orders with lower price than "deal price".
     * @param listSell - finish sell orders with higherer price than "deal price".
     */
    private void printResult(List<Order> listBuy, List<Order> listSell) {
        System.out.println("---------------------------------ASK");
        for (int i = listSell.size() - 1; i >= 0; i--) {
            System.out.print("---------------------------------" + listSell.get(i));
        }
        System.out.println("BID");
        for (int i = listBuy.size() - 1; i >= 0; i--) {
            System.out.print(listBuy.get(i));
        }
        System.out.println();
    }
}


text:
@import Cocoa;

#import "BrowserPane.h"

@interface BrowserPaneTemplate : NSWindowController {
	IBOutlet BrowserPane * browserPane;
}

@property(strong) NSArray * topObjects;

@property (nonatomic, readonly, strong) BrowserPane *mainView;

@end


text:
namespace base {

class MessagePump;
class RunLoop;

// A simple thread abstraction that establishes a MessageLoop on a new thread.
// The consumer uses the MessageLoop of the thread to cause code to execute on
// the thread.  When this object is destroyed the thread is terminated.  All
// pending tasks queued on the thread's message loop will run to completion
// before the thread is terminated.
//
// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS!  See ~Thread().
//
// After the thread is stopped, the destruction sequence is:
//
//  (1) Thread::CleanUp()
//  (2) MessageLoop::~MessageLoop
//  (3.b)    MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
//
// This API is not thread-safe: unless indicated otherwise its methods are only
// valid from the owning sequence (which is the one from which Start() is
// invoked, should it differ from the one on which it was constructed).
class BASE_EXPORT Thread : PlatformThread::Delegate {
 public:
  struct BASE_EXPORT Options {
    typedef Callback<std::unique_ptr<MessagePump>()> MessagePumpFactory;

    Options();
    Options(MessageLoop::Type type, size_t size);
    Options(const Options& other);
    ~Options();

    // Specifies the type of message loop that will be allocated on the thread.
    // This is ignored if message_pump_factory.is_null() is false.
    MessageLoop::Type message_loop_type = MessageLoop::TYPE_DEFAULT;

    // Specifies timer slack for thread message loop.
    TimerSlack timer_slack = TIMER_SLACK_NONE;

    // Used to create the MessagePump for the MessageLoop. The callback is Run()
    // on the thread. If message_pump_factory.is_null(), then a MessagePump
    // appropriate for |message_loop_type| is created. Setting this forces the
    // MessageLoop::Type to TYPE_CUSTOM.
    MessagePumpFactory message_pump_factory;

    // Specifies the maximum stack size that the thread is allowed to use.
    // This does not necessarily correspond to the thread's initial stack size.
    // A value of 0 indicates that the default maximum should be used.
    size_t stack_size = 0;

    // Specifies the initial thread priority.
    ThreadPriority priority = ThreadPriority::NORMAL;

    // If false, the thread will not be joined on destruction. This is intended
    // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN
    // semantics. Non-joinable threads can't be joined (must be leaked and
    // can't be destroyed or Stop()'ed).
    // TODO(gab): allow non-joinable instances to be deleted without causing
    // user-after-frees (proposal @ https://crbug.com/629139#c14)
    bool joinable = true;
  };

  // Constructor.
  // name is a display string to identify the thread.
  explicit Thread(const std::string& name);

  // Destroys the thread, stopping it if necessary.
  //
  // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
  // guarantee Stop() is explicitly called before the subclass is destroyed).
  // This is required to avoid a data race between the destructor modifying the
  // vtable, and the thread's ThreadMain calling the virtual method Run().  It
  // also ensures that the CleanUp() virtual method is called on the subclass
  // before it is destructed.
  ~Thread() override;

#if defined(OS_WIN)
  // Causes the thread to initialize COM.  This must be called before calling
  // Start() or StartWithOptions().  If |use_mta| is false, the thread is also
  // started with a TYPE_UI message loop.  It is an error to call
  // init_com_with_mta(false) and then StartWithOptions() with any message loop
  // type other than TYPE_UI.
  void init_com_with_mta(bool use_mta) {
    DCHECK(!message_loop_);
    com_status_ = use_mta ? MTA : STA;
  }
#endif

  // Starts the thread.  Returns true if the thread was successfully started;
  // otherwise, returns false.  Upon successful return, the message_loop()
  // getter will return non-null.
  //
  // Note: This function can't be called on Windows with the loader lock held;
  // i.e. during a DllMain, global object construction or destruction, atexit()
  // callback.
  bool Start();

  // Starts the thread. Behaves exactly like Start in addition to allow to
  // override the default options.
  //
  // Note: This function can't be called on Windows with the loader lock held;
  // i.e. during a DllMain, global object construction or destruction, atexit()
  // callback.
  bool StartWithOptions(const Options& options);

  // Starts the thread and wait for the thread to start and run initialization
  // before returning. It's same as calling Start() and then
  // WaitUntilThreadStarted().
  // Note that using this (instead of Start() or StartWithOptions() causes
  // jank on the calling thread, should be used only in testing code.
  bool StartAndWaitForTesting();

  // Blocks until the thread starts running. Called within StartAndWait().
  // Note that calling this causes jank on the calling thread, must be used
  // carefully for production code.
  bool WaitUntilThreadStarted() const;

  // Signals the thread to exit and returns once the thread has exited. The
  // Thread object is completely reset and may be used as if it were newly
  // constructed (i.e., Start may be called again). Can only be called if
  // |joinable_|.
  //
  // Stop may be called multiple times and is simply ignored if the thread is
  // already stopped or currently stopping.
  //
  // NOTE: If you are a consumer of Thread, it is not necessary to call this
  // before deleting your Thread objects, as the destructor will do it.
  // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
  void Stop();

  // Signals the thread to exit in the near future.
  //
  // WARNING: This function is not meant to be commonly used. Use at your own
  // risk. Calling this function will cause message_loop() to become invalid in
  // the near future. This function was created to workaround a specific
  // deadlock on Windows with printer worker thread. In any other case, Stop()
  // should be used.
  //
  // StopSoon should not be called multiple times as it is risky to do so. It
  // could cause a timing issue in message_loop() access. Call Stop() to reset
  // the thread object once it is known that the thread has quit.
  void StopSoon();

  // Returns the message loop for this thread.  Use the MessageLoop's
  // PostTask methods to execute code on the thread.  This only returns
  // non-null after a successful call to Start.  After Stop has been called,
  // this will return nullptr.
  //
  // NOTE: You must not call this MessageLoop's Quit method directly.  Use
  // the Thread's Stop method instead.
  //
  // In addition to this Thread's owning sequence, this can also safely be
  // called from the underlying thread itself.
  MessageLoop* message_loop() const {
    // This class doesn't provide synchronization around |message_loop_| and as
    // such only the owner should access it (and the underlying thread which
    // never sees it before it's set). In practice, many callers are coming from
    // unrelated threads but provide their own implicit (e.g. memory barriers
    // from task posting) or explicit (e.g. locks) synchronization making the
    // access of |message_loop_| safe... Changing all of those callers is
    // unfeasible; instead verify that they can reliably see
    // |message_loop_ != nullptr| without synchronization as a proof that their
    // external synchronization catches the unsynchronized effects of Start().
    // TODO(gab): Despite all of the above this test has to be disabled for now
    // per crbug.com/629139#c6.
    // DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
    //        id_ == PlatformThread::CurrentId() || message_loop_)
    //     << id_ << " vs " << PlatformThread::CurrentId();
    return message_loop_;
  }

  // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask
  // methods to execute code on the thread. Returns nullptr if the thread is not
  // running (e.g. before Start or after Stop have been called). Callers can
  // hold on to this even after the thread is gone; in this situation, attempts
  // to PostTask() will fail.
  //
  // In addition to this Thread's owning sequence, this can also safely be
  // called from the underlying thread itself.
  scoped_refptr<SingleThreadTaskRunner> task_runner() const {
    // Refer to the DCHECK and comment inside |message_loop()|.
    DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
           id_ == PlatformThread::CurrentId() || message_loop_)
        << id_ << " vs " << PlatformThread::CurrentId();
    return message_loop_ ? message_loop_->task_runner() : nullptr;
  }

  // Returns the name of this thread (for display in debugger too).
  const std::string& thread_name() const { return name_; }

  // Returns the thread ID.  Should not be called before the first Start*()
  // call.  Keeps on returning the same ID even after a Stop() call. The next
  // Start*() call renews the ID.
  //
  // WARNING: This function will block if the thread hasn't started yet.
  //
  // This method is thread-safe.
  PlatformThreadId GetThreadId() const;

  // Returns true if the thread has been started, and not yet stopped.
  bool IsRunning() const;

 protected:
  // Called just prior to starting the message loop
  virtual void Init() {}

  // Called to start the run loop
  virtual void Run(RunLoop* run_loop);

  // Called just after the message loop ends
  virtual void CleanUp() {}

  static void SetThreadWasQuitProperly(bool flag);
  static bool GetThreadWasQuitProperly();

  // Bind this Thread to an existing MessageLoop instead of starting a new one.
  void SetMessageLoop(MessageLoop* message_loop);

 private:
#if defined(OS_WIN)
  enum ComStatus {
    NONE,
    STA,
    MTA,
  };
#endif

  // PlatformThread::Delegate methods:
  void ThreadMain() override;

  void ThreadQuitHelper();

#if defined(OS_WIN)
  // Whether this thread needs to initialize COM, and if so, in what mode.
  ComStatus com_status_ = NONE;
#endif

  // Mirrors the Options::joinable field used to start this thread. Verified
  // on Stop() -- non-joinable threads can't be joined (must be leaked).
  bool joinable_ = true;

  // If true, we're in the middle of stopping, and shouldn't access
  // |message_loop_|. It may non-nullptr and invalid.
  // Should be written on the thread that created this thread. Also read data
  // could be wrong on other threads.
  bool stopping_ = false;

  // True while inside of Run().
  bool running_ = false;
  mutable base::Lock running_lock_;  // Protects |running_|.

  // The thread's handle.
  PlatformThreadHandle thread_;
  mutable base::Lock thread_lock_;  // Protects |thread_|.

  // The thread's id once it has started.
  PlatformThreadId id_ = kInvalidThreadId;
  mutable WaitableEvent id_event_;  // Protects |id_|.

  // The thread's MessageLoop and RunLoop. Valid only while the thread is alive.
  // Set by the created thread.
  MessageLoop* message_loop_ = nullptr;
  RunLoop* run_loop_ = nullptr;

  // True only if |message_loop_| was externally provided by |SetMessageLoop()|
  // in which case this Thread has no underlying |thread_| and should merely
  // drop |message_loop_| on Stop().
  bool using_external_message_loop_ = false;

  // Stores Options::timer_slack_ until the message loop has been bound to
  // a thread.
  TimerSlack message_loop_timer_slack_ = TIMER_SLACK_NONE;

  // The name of the thread.  Used for debugging purposes.
  const std::string name_;

  // Signaled when the created thread gets ready to use the message loop.
  mutable WaitableEvent start_event_;

  // This class is not thread-safe, use this to verify access from the owning
  // sequence of the Thread.
  SequenceChecker owning_sequence_checker_;

  DISALLOW_COPY_AND_ASSIGN(Thread);
};

}  // namespace base

#endif  // BASE_THREADING_THREAD_H_


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _XYFrame2 = require("./XYFrame");

var _XYFrame3 = _interopRequireDefault(_XYFrame2);

var _MiniMap = require("./MiniMap");

var _MiniMap2 = _interopRequireDefault(_MiniMap);

var _propTypes = require("prop-types");

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// components

var MinimapXYFrame = function (_XYFrame) {
  _inherits(MinimapXYFrame, _XYFrame);

  function MinimapXYFrame(props) {
    _classCallCheck(this, MinimapXYFrame);

    var _this = _possibleConstructorReturn(this, (MinimapXYFrame.__proto__ || Object.getPrototypeOf(MinimapXYFrame)).call(this, props));

    _this.generateMinimap = _this.generateMinimap.bind(_this);
    return _this;
  }

  _createClass(MinimapXYFrame, [{
    key: "generateMinimap",
    value: function generateMinimap() {
      var miniDefaults = {
        title: "",
        position: [0, 0],
        size: [this.props.size[0], this.props.size[1] * 0.25],
        xAccessor: this.props.xAccessor,
        yAccessor: this.props.yAccessor,
        points: this.props.points,
        lines: this.props.lines,
        areas: this.props.areas,
        lineDataAccessor: this.props.lineDataAccessor,
        xBrushable: true,
        yBrushable: true,
        brushStart: function brushStart() {},
        brush: function brush() {},
        brushEnd: function brushEnd() {},
        lineType: this.props.lineType
      };

      var combinedOptions = _extends(miniDefaults, this.props.minimap);

      combinedOptions.hoverAnnotation = false;

      return _react2.default.createElement(_MiniMap2.default, combinedOptions);
    }
  }, {
    key: "render",
    value: function render() {
      var miniMap = this.generateMinimap();
      var options = {};
      if (this.props.renderBefore) {
        options.beforeElements = miniMap;
      } else {
        options.afterElements = miniMap;
      }

      return this.renderBody(options);
    }
  }]);

  return MinimapXYFrame;
}(_XYFrame3.default);

MinimapXYFrame.propTypes = {
  size: _propTypes2.default.array,
  xAccessor: _propTypes2.default.func,
  yAccessor: _propTypes2.default.func,
  points: _propTypes2.default.array,
  lines: _propTypes2.default.array,
  areas: _propTypes2.default.array,
  lineDataAccessor: _propTypes2.default.func,
  lineType: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]),
  minimap: _propTypes2.default.object,
  renderBefore: _propTypes2.default.oneOfType([_propTypes2.default.array, _propTypes2.default.object])
};

exports.default = MinimapXYFrame;
module.exports = exports['default'];


text:
"""Tests for consumer_tracking_pipeline_visitor."""

import logging
import unittest

from apache_beam import pvalue
from apache_beam.io import iobase
from apache_beam.io import Read
from apache_beam.pipeline import Pipeline
from apache_beam.pvalue import AsList
from apache_beam.runners.direct import DirectRunner
from apache_beam.runners.direct.consumer_tracking_pipeline_visitor import ConsumerTrackingPipelineVisitor
from apache_beam.transforms import CoGroupByKey
from apache_beam.transforms import Create
from apache_beam.transforms import DoFn
from apache_beam.transforms import FlatMap
from apache_beam.transforms import Flatten
from apache_beam.transforms import ParDo

# Disable frequent lint warning due to pipe operator for chaining transforms.
# pylint: disable=expression-not-assigned
# pylint: disable=pointless-statement

class ConsumerTrackingPipelineVisitorTest(unittest.TestCase):

  def setUp(self):
    self.pipeline = Pipeline(DirectRunner())
    self.visitor = ConsumerTrackingPipelineVisitor()

  def test_root_transforms(self):
    root_create = Create([[1, 2, 3]])

    class DummySource(iobase.BoundedSource):
      pass

    root_read = Read(DummySource())
    root_flatten = Flatten(pipeline=self.pipeline)

    pbegin = pvalue.PBegin(self.pipeline)
    pcoll_create = pbegin | 'create' >> root_create
    pbegin | 'read' >> root_read
    pcoll_create | FlatMap(lambda x: x)
    [] | 'flatten' >> root_flatten

    self.pipeline.visit(self.visitor)

    root_transforms = sorted(
        [t.transform for t in self.visitor.root_transforms])

    self.assertEqual(root_transforms, sorted(
        [root_read, root_create, root_flatten]))

    pbegin_consumers = sorted(
        [c.transform for c in self.visitor.value_to_consumers[pbegin]])
    self.assertEqual(pbegin_consumers, sorted([root_read, root_create]))
    self.assertEqual(len(self.visitor.step_names), 4)

  def test_side_inputs(self):

    class SplitNumbersFn(DoFn):

      def process(self, element):
        if element < 0:
          yield pvalue.SideOutputValue('tag_negative', element)
        else:
          yield element

    class ProcessNumbersFn(DoFn):

      def process(self, element, negatives):
        yield element

    root_create = Create([[-1, 2, 3]])

    result = (self.pipeline
              | 'create' >> root_create
              | ParDo(SplitNumbersFn()).with_outputs('tag_negative',
                                                     main='positive'))
    positive, negative = result
    positive | ParDo(ProcessNumbersFn(), AsList(negative))

    self.pipeline.visit(self.visitor)

    root_transforms = sorted(
        [t.transform for t in self.visitor.root_transforms])
    self.assertEqual(root_transforms, sorted([root_create]))
    self.assertEqual(len(self.visitor.step_names), 4)
    self.assertEqual(len(self.visitor.views), 1)
    self.assertTrue(isinstance(self.visitor.views[0],
                               pvalue.ListPCollectionView))

  def test_co_group_by_key(self):
    emails = self.pipeline | 'email' >> Create([('joe', 'joe@example.com')])
    phones = self.pipeline | 'phone' >> Create([('mary', '111-222-3333')])
    {'emails': emails, 'phones': phones} | CoGroupByKey()

    self.pipeline.visit(self.visitor)

    root_transforms = sorted(
        [t.transform for t in self.visitor.root_transforms])
    self.assertEqual(len(root_transforms), 2)
    self.assertGreater(
        len(self.visitor.step_names), 3)  # 2 creates + expanded CoGBK
    self.assertEqual(len(self.visitor.views), 0)

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  unittest.main()


text:
#include <sndfile.h>
#include "rtpapi.h"
#include "codecapi.h"
#include "wavfile_filter.h"
#include "options.h"
#include "misc.h"

wr_errorcode_t wr_wavfile_filter_start(wr_rtp_filter_t * filter)
{

    SNDFILE * file;
    SF_INFO file_info;
    wr_encoder_t * codec;
    wr_rtp_packet_t rtp_packet;
    int sequence_number = 0;
    int rtp_timestamp = 0;
    struct timeval packet_start_timestamp;
    struct timeval packet_end_timestamp;

    gettimeofday(&packet_start_timestamp, NULL);
    timeval_copy(&packet_end_timestamp, &packet_start_timestamp);

    int rtp_in_frame = iniparser_getpositiveint(wr_options.output_options, "global:rtp_in_frame", 1);
    int frames_count = 0;

    /* open WAV file */
    file = sf_open(wr_options.filename, SFM_READ, &file_info);
    if (!file){
        wr_set_error("cannot open or render sound file");
        return WR_FATAL;
    }
    if (file_info.samplerate != 8000){
        wr_set_error("this tool works only with .wav files in 8kHz, rerecord your signal or resample it (with sox for example)\n");
        return WR_FATAL;
    }

    list_iterator_start(wr_options.codec_list);
    if (list_iterator_hasnext(wr_options.codec_list)){
        codec = (wr_encoder_t*)list_iterator_next(wr_options.codec_list);
        wr_rtp_packet_init(&rtp_packet, codec->payload_type, sequence_number, 1, rtp_timestamp, packet_start_timestamp);
    }else{
        wr_set_error("no codec is found");
        return WR_FATAL;
    }

    wr_rtp_filter_notify_observers(filter, TRANSMISSION_START, NULL);

    /* One cycle iteration encode one data frame */
    while(codec){
        int   input_buffer_size = (*codec->get_input_buffer_size)(codec->state);
        int   output_buffer_size = (*codec->get_output_buffer_size)(codec->state);
        short input_buffer[input_buffer_size];
        char output_buffer[output_buffer_size];

        bzero(input_buffer, input_buffer_size);
        bzero(output_buffer, output_buffer_size);

        input_buffer_size = sf_read_short(file, input_buffer, input_buffer_size);
        if (!input_buffer_size){ /*EOF*/
            if (frames_count){
                wr_rtp_filter_notify_observers(filter, NEW_PACKET, &rtp_packet);
                wr_rtp_packet_destroy(&rtp_packet);
                frames_count = 0;
                sequence_number++;
                timeval_copy(&packet_start_timestamp, &packet_end_timestamp);
                wr_rtp_packet_init(&rtp_packet, codec->payload_type, sequence_number, 0, rtp_timestamp, packet_start_timestamp);
            }
            sf_seek(file, 0, SEEK_SET);
            if (list_iterator_hasnext(wr_options.codec_list)){
                codec = (wr_encoder_t*)list_iterator_next(wr_options.codec_list);
            }else{
                codec = NULL;
                list_iterator_stop(wr_options.codec_list);
            }
            continue;
        }
        output_buffer_size = (*codec->encode)(codec->state, input_buffer, output_buffer);
        wr_rtp_packet_add_frame(&rtp_packet, output_buffer, output_buffer_size,  1000 * input_buffer_size / file_info.samplerate);
        timeval_increment(&packet_end_timestamp, 1e6 * input_buffer_size / file_info.samplerate);
        rtp_timestamp += input_buffer_size;
        frames_count++;
        if (frames_count == rtp_in_frame){
            wr_rtp_filter_notify_observers(filter, NEW_PACKET, &rtp_packet);
            wr_rtp_packet_destroy(&rtp_packet);
            frames_count = 0;
            sequence_number++;
            timeval_copy(&packet_start_timestamp, &packet_end_timestamp);
            wr_rtp_packet_init(&rtp_packet, codec->payload_type, sequence_number, 0, rtp_timestamp, packet_start_timestamp);
        }
    }
    wr_rtp_filter_notify_observers(filter, TRANSMISSION_END, NULL);
    sf_close(file);
}


text:
using GPONMonitor.Models;
using GPONMonitor.Models.OnuFactory;
using GPONMonitor.ViewModels;
using Lextm.SharpSnmpLib;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace GPONMonitor.Services
{
    public interface IDataService
    {
        IEnumerable<OltConfigurationViewModel> GetConfiguredOltListAsync();
        Task<string> GetOltDescriptionAsync(uint oltId);
        Task<string> GetOltUptimeAsync(uint oltId);
        Task<string> GetOltFirmwareVersionAsync(uint oltId);
        Task<IEnumerable<OnuShortDescription>> GetOnuDescriptionListAsync(uint oltId);
        Task<IOnuFactory> GetOnuStateAsync(uint oltId, uint oltPortId, uint onuId);
        Task<string> GetStringPropertyAsync(uint oltId, string snmpOid);
        Task<int?> GetIntPropertyAsync(uint oltId, string snmpOid);
        Task<IList<Variable>> SetStringPropertyAsync(uint oltId, string oid, string data);
        Task<IList<Variable>> SetIntPropertyAsync(uint oltId, string oid, int data);
    }
}


text:
<?php
/**
 * Math
 */
namespace LanguageStatement\LanguageExtension\Math;

class Math
{
    /*
         * 数学扩展
    BC Math
    GMP
    Lapack
    Math
    Statistics
    Trader
         */
}


text:
package org.apache.commons.net.ftp;

/**
 * FTPReply stores a set of constants for FTP reply codes. To interpret the meaning of the codes, familiarity with RFC 959 is assumed. The mnemonic constant
 * names are transcriptions from the code descriptions of RFC 959.
 * <p>
 * TODO replace with an enum
 */

public final class FTPReply {

    public static final int RESTART_MARKER = 110;
    public static final int SERVICE_NOT_READY = 120;
    public static final int DATA_CONNECTION_ALREADY_OPEN = 125;
    public static final int FILE_STATUS_OK = 150;
    public static final int COMMAND_OK = 200;
    public static final int COMMAND_IS_SUPERFLUOUS = 202;
    public static final int SYSTEM_STATUS = 211;
    public static final int DIRECTORY_STATUS = 212;
    public static final int FILE_STATUS = 213;
    public static final int HELP_MESSAGE = 214;
    public static final int NAME_SYSTEM_TYPE = 215;
    public static final int SERVICE_READY = 220;
    public static final int SERVICE_CLOSING_CONTROL_CONNECTION = 221;
    public static final int DATA_CONNECTION_OPEN = 225;
    public static final int CLOSING_DATA_CONNECTION = 226;
    public static final int ENTERING_PASSIVE_MODE = 227;
    /** @since 2.2 */
    public static final int ENTERING_EPSV_MODE = 229;
    public static final int USER_LOGGED_IN = 230;
    public static final int FILE_ACTION_OK = 250;
    public static final int PATHNAME_CREATED = 257;
    public static final int NEED_PASSWORD = 331;
    public static final int NEED_ACCOUNT = 332;
    public static final int FILE_ACTION_PENDING = 350;
    public static final int SERVICE_NOT_AVAILABLE = 421;
    public static final int CANNOT_OPEN_DATA_CONNECTION = 425;
    public static final int TRANSFER_ABORTED = 426;
    public static final int FILE_ACTION_NOT_TAKEN = 450;
    public static final int ACTION_ABORTED = 451;
    public static final int INSUFFICIENT_STORAGE = 452;
    public static final int UNRECOGNIZED_COMMAND = 500;
    public static final int SYNTAX_ERROR_IN_ARGUMENTS = 501;
    public static final int COMMAND_NOT_IMPLEMENTED = 502;
    public static final int BAD_COMMAND_SEQUENCE = 503;
    public static final int COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER = 504;
    public static final int NOT_LOGGED_IN = 530;
    public static final int NEED_ACCOUNT_FOR_STORING_FILES = 532;
    public static final int FILE_UNAVAILABLE = 550;
    public static final int PAGE_TYPE_UNKNOWN = 551;
    public static final int STORAGE_ALLOCATION_EXCEEDED = 552;
    public static final int FILE_NAME_NOT_ALLOWED = 553;

    // FTPS Reply Codes

    /** @since 2.0 */
    public static final int SECURITY_DATA_EXCHANGE_COMPLETE = 234;
    /** @since 2.0 */
    public static final int SECURITY_DATA_EXCHANGE_SUCCESSFULLY = 235;
    /** @since 2.0 */
    public static final int SECURITY_MECHANISM_IS_OK = 334;
    /** @since 2.0 */
    public static final int SECURITY_DATA_IS_ACCEPTABLE = 335;
    /** @since 2.0 */
    public static final int UNAVAILABLE_RESOURCE = 431;
    /** @since 2.2 */
    public static final int BAD_TLS_NEGOTIATION_OR_DATA_ENCRYPTION_REQUIRED = 522;
    /** @since 2.0 */
    public static final int DENIED_FOR_POLICY_REASONS = 533;
    /** @since 2.0 */
    public static final int REQUEST_DENIED = 534;
    /** @since 2.0 */
    public static final int FAILED_SECURITY_CHECK = 535;
    /** @since 2.0 */
    public static final int REQUESTED_PROT_LEVEL_NOT_SUPPORTED = 536;

    // IPv6 error codes
    // Note this is also used as an FTPS error code reply
    /** @since 2.2 */
    public static final int EXTENDED_PORT_FAILURE = 522;

    /**
     * Determine if a reply code is a negative permanent response. All codes beginning with a 5 are negative permanent responses. The FTP server will send a
     * negative permanent response on the failure of a command that cannot be reattempted with success.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a negative permanent response, false if not.
     */
    public static boolean isNegativePermanent(final int reply) {
        return reply >= 500 && reply < 600;
    }

    /**
     * Determine if a reply code is a negative transient response. All codes beginning with a 4 are negative transient responses. The FTP server will send a
     * negative transient response on the failure of a command that can be reattempted with success.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a negative transient response, false if not.
     */
    public static boolean isNegativeTransient(final int reply) {
        return reply >= 400 && reply < 500;
    }

    /**
     * Determine if a reply code is a positive completion response. All codes beginning with a 2 are positive completion responses. The FTP server will send a
     * positive completion response on the final successful completion of a command.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a positive completion response, false if not.
     */
    public static boolean isPositiveCompletion(final int reply) {
        return reply >= 200 && reply < 300;
    }

    /**
     * Determine if a reply code is a positive intermediate response. All codes beginning with a 3 are positive intermediate responses. The FTP server will send
     * a positive intermediate response on the successful completion of one part of a multi-part sequence of commands. For example, after a successful USER
     * command, a positive intermediate response will be sent to indicate that the server is ready for the PASS command.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a positive intermediate response, false if not.
     */
    public static boolean isPositiveIntermediate(final int reply) {
        return reply >= 300 && reply < 400;
    }

    /**
     * Determine if a reply code is a positive preliminary response. All codes beginning with a 1 are positive preliminary responses. Postitive preliminary
     * responses are used to indicate tentative success. No further commands can be issued to the FTP server after a positive preliminary response until a
     * follow up response is received from the server.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a positive preliminary response, false if not.
     */
    public static boolean isPositivePreliminary(final int reply) {
        return reply >= 100 && reply < 200;
    }

    /**
     * Determine if a reply code is a protected response.
     *
     * @param reply The reply code to test.
     * @return True if a reply code is a protected response, false if not.
     * @since 3.0
     */
    public static boolean isProtectedReplyCode(final int reply) {
        // actually, only 3 protected reply codes are
        // defined in RFC 2228: 631, 632 and 633.
        return reply >= 600 && reply < 700;
    }

    // Cannot be instantiated
    private FTPReply() {
    }

}


text:
beachesApp.controller('NavController', function($scope, $state, Auth, Message){
  $scope.signedIn = Auth.isAuthenticated;

  $scope.logout = function(){
    Auth.logout();
  }

  Auth.currentUser().then(function (user){
    $scope.user = user;
  });

  $scope.$on('devise:new-registration', function (e, user){
    $scope.user = user;
  });

  $scope.$on('devise:login', function (e, user){
    $scope.user = user;
  });

  $scope.$on('devise:logout', function (e, user){
    $scope.user = {}
    Message.success("Signed out successfully.")
    $state.go('home')
  });
})


text:
package scrupal.admin

import play.api.routing.sird._

import scrupal.core._

class AdminModuleProvider extends {
  val id = 'AdminModuleProvider
} with Provider with Enablee {
  def provide = {
    case GET(p"/module/") ⇒ Reactor.from { Response("foo", Successful) }
  }
}


text:
package com.intellij.execution.process;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.PtyCommandLine;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.nio.charset.Charset;
import java.util.concurrent.Future;

public class OSProcessHandler extends BaseOSProcessHandler {
  private static final Logger LOG = Logger.getInstance("#com.intellij.execution.process.OSProcessHandler");

  private boolean myHasPty;
  private boolean myDestroyRecursively = true;

  public OSProcessHandler(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
    this(commandLine.createProcess(), commandLine.getCommandLineString(), commandLine.getCharset());
    setHasPty(commandLine instanceof PtyCommandLine);
  }

  @Deprecated
  /**
   * @deprecated use {@link OSProcessHandler#OSProcessHandler(Process, String)} or any other ctr instead
   */
  public OSProcessHandler(@NotNull Process process) {
    this(process, null);
  }

  /**
   *
   * @param commandLine must be not empty
   */
  public OSProcessHandler(@NotNull Process process, /*NotNull*/ String commandLine) {
    this(process, commandLine, EncodingManager.getInstance().getDefaultCharset());
  }

  /**
   *
   * @param commandLine must be not empty
   */
  public OSProcessHandler(@NotNull Process process, /*@NotNull*/ String commandLine, @Nullable Charset charset) {
    super(process, commandLine, charset);
  }

  @NotNull
  @Override
  protected Future<?> executeOnPooledThread(@NotNull Runnable task) {
    return super.executeOnPooledThread(task);  // to maintain binary compatibility?
  }

  protected boolean shouldDestroyProcessRecursively() {
    // Override this method if you want to kill process recursively (whole process try) by default
    // such behaviour is better than default java one, which doesn't kill children processes
    return myDestroyRecursively;
  }

  public void setShouldDestroyProcessRecursively(boolean destroyRecursively) {
    myDestroyRecursively = destroyRecursively;
  }

  @Override
  protected void doDestroyProcess() {
    // Override this method if you want to customize default destroy behaviour, e.g.
    // if you want use some soft-kill.
    final Process process = getProcess();
    if (shouldDestroyProcessRecursively() && processCanBeKilledByOS(process)) {
      killProcessTree(process);
    }
    else {
      process.destroy();
    }
  }

  public static boolean processCanBeKilledByOS(Process process) {
    return !(process instanceof SelfKiller);
  }

  /**
   * Kills the whole process tree asynchronously.
   * As a potentially time-consuming operation, it's executed asynchronously on a pooled thread.
   *
   * @param process Process
   */
  protected void killProcessTree(@NotNull final Process process) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      killProcessTreeSync(process);
    }
    else {
      executeOnPooledThread(new Runnable() {
        @Override
        public void run() {
          killProcessTreeSync(process);
        }
      });
    }
  }

  private void killProcessTreeSync(@NotNull Process process) {
    LOG.debug("killing process tree");
    final boolean destroyed = OSProcessManager.getInstance().killProcessTree(process);
    if (!destroyed) {
      if (isTerminated(process)) {
        LOG.warn("Process has been already terminated: " + myCommandLine);
      }
      else {
        LOG.warn("Cannot kill process tree. Trying to destroy process using Java API. Cmdline:\n" + myCommandLine);
        process.destroy();
      }
    }
  }

  private static boolean isTerminated(@NotNull Process process) {
    try {
      process.exitValue();
      return true;
    }
    catch (IllegalThreadStateException e) {
      return false;
    }
  }

  /**
   * In case of pty this process handler will use blocking read. The value should be set before
   * startNotify invocation. It is set by default in case of using GeneralCommandLine based constructor.
   *
   * @param hasPty true if process is pty based
   */
  public void setHasPty(boolean hasPty) {
    myHasPty = hasPty;
  }

  @Override
  protected boolean useNonBlockingRead() {
    if (myHasPty) {
      // blocking read in case of pty based process
      return false;
    }
    else {
      return super.useNonBlockingRead();
    }
  }
}


text:
/******************************************************************

 iLBC Speech Coder ANSI-C Source Code

 WebRtcIlbcfix_MyCorr.h

******************************************************************/

#ifndef MODULES_AUDIO_CODING_CODECS_ILBC_MAIN_SOURCE_MY_CORR_H_
#define MODULES_AUDIO_CODING_CODECS_ILBC_MAIN_SOURCE_MY_CORR_H_

#include "defines.h"

/*----------------------------------------------------------------*
 * compute cross correlation between sequences
 *---------------------------------------------------------------*/

void WebRtcIlbcfix_MyCorr(
    int32_t* corr,  /* (o) correlation of seq1 and seq2 */
    const int16_t* seq1,  /* (i) first sequence */
    size_t dim1,  /* (i) dimension first seq1 */
    const int16_t* seq2, /* (i) second sequence */
    size_t dim2   /* (i) dimension seq2 */
                          );

#endif


text:
FROM zalari/composer
MAINTAINER Christian Ulbrich <christian.ulbrich@zalari.de>

# Install latest HEAD Drush using Composer
RUN composer global require drush/drush:dev-master

# Setup the symlink
RUN ln -sf $COMPOSER_HOME/vendor/bin/drush.php /usr/local/bin/drush

# Display which version of Drush was installed
RUN drush --version

# Update the entry point of the application
ENTRYPOINT ["drush"]


text:
package io.edgeg.gtm.intellij;

import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.event.EditorMouseListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.VirtualFile;

class GTMEditorMouseListener implements EditorMouseListener {

    @Override
    public void mousePressed(EditorMouseEvent editorMouseEvent) {
        final FileDocumentManager instance = FileDocumentManager.getInstance();
        final VirtualFile file = instance.getFile(editorMouseEvent.getEditor().getDocument());
        if (file != null) {
            GTMRecord.record(file.getPath(), editorMouseEvent.getEditor().getProject());
        }
    }

    @Override
    public void mouseClicked(EditorMouseEvent editorMouseEvent) {
    }

    @Override
    public void mouseReleased(EditorMouseEvent editorMouseEvent) {
    }

    @Override
    public void mouseEntered(EditorMouseEvent editorMouseEvent) {
    }

    @Override
    public void mouseExited(EditorMouseEvent editorMouseEvent) {
    }
}


text:
	<form data-ng-submit="create()" novalidate>

New Schedule

           Home

         		<input class="form-control btn btn-info" type="submit">

Schedule ID

     <input class="form-control" type="text" data-ng-model="schid" id="did" placeholder="Schedule Id" required/>

Name

            <input class="form-control" type="text" data-ng-model="name" id="name"  placeholder="Name"/>

Type

            <input class="form-control" type="text" data-ng-model="type" id="type"  placeholder="Type"/>

Start Time

    <input class="form-control" ng-click="getClock1()" type="text" data-ng-model="start1" readonly>
    <timepicker-directive ng-show="clockVisible1" input-model="start1"></timepicker-directive>

End Time

    <input class="form-control" ng-click="getClock2()" type="text" data-ng-model="end1" readonly>
    <timepicker-directive ng-show="clockVisible2" input-model="end1"></timepicker-directive>

Days

  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Please select">Checked option </button>

<input type="checkbox" data-ng-model="day1" ng-click="" id="Monday">Monday

<input type="checkbox" data-ng-model="day2"  ng-click=""  id="Tuesday">Tuesday

<input type="checkbox" data-ng-model="day3"  ng-click=""  id="Wednesday">Wednesday

<input type="checkbox" data-ng-model="day4"  ng-click=""  id="Thursday">Thursday

<input type="checkbox" data-ng-model="day5"  ng-click=""  id="Friday">Friday

<input type="checkbox" data-ng-model="day6"  ng-click=""  id="Saturday">Saturday

<input type="checkbox" data-ng-model="day7"  ng-click=""  id="Sunday">Sunday

Condition

   <select class="form-control" data-ng-model="switchon" ng-options="sm.feature for sm in switch"></select>

Daily

    	<input type="checkbox" data-ng-model="daily" value="">

Devices
      <select class="form-control" data-ng-model="devices" ng-options="sm.name for sm in deviceList">                          </select>

Smart Plug

    	<select class="form-control" data-ng-model="smartplugs" ng-options="sm.name for sm in smartplugList"></select>

Description

  <textarea class="form-control" rows="2" data-ng-model="description" id="description" placeholder="Description"/>

	</form>