text:
/**
 * This file is part of the CernVM File System.
 */

#ifndef CVMFS_STATISTICS_H_
#define CVMFS_STATISTICS_H_

#include <pthread.h>
#include <stdint.h>

#include <map>
#include <string>
#include <vector>

#include "atomic.h"

#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif

namespace perf {

/**
 * A wrapper around an atomic 64bit signed integer.
 */
class Counter {
 public:
  Counter() { atomic_init64(&counter_); }
  void Inc() { atomic_inc64(&counter_); }
  void Dec() { atomic_dec64(&counter_); }
  int64_t Get() { return atomic_read64(&counter_); }
  void Set(const int64_t val) { atomic_write64(&counter_, val); }
  int64_t Xadd(const int64_t delta) { return atomic_xadd64(&counter_, delta); }

  std::string Print();
  std::string PrintK();
  std::string PrintKi();
  std::string PrintM();
  std::string PrintMi();
  std::string PrintRatio(Counter divider);
  std::string ToString();

 private:
  atomic_int64 counter_;
};

// perf::Func(Counter) is more clear to read in the code
inline void Dec(class Counter *counter) { counter->Dec(); }
inline void Inc(class Counter *counter) { counter->Inc(); }
inline int64_t Xadd(class Counter *counter, const int64_t delta) {
  return counter->Xadd(delta);
}

/**
 * A collection of Counter objects with a name and a description.  Counters in
 * a Statistics class have a name and a description.  Thread-safe.
 */
class Statistics {
 public:
  enum PrintOptions {
    kPrintSimple = 0,
    kPrintHeader
  };

  Statistics();
  ~Statistics();
  Statistics *Fork();
  Counter *Register(const std::string &name, const std::string &desc);
  Counter *Lookup(const std::string &name);
  std::string LookupDesc(const std::string &name);
  std::string PrintList(const PrintOptions print_options);

 private:
  Statistics(const Statistics &other);
  Statistics& operator=(const Statistics &other);
  struct CounterInfo {
    explicit CounterInfo(const std::string &desc) : desc(desc) {
      atomic_init32(&refcnt);
      atomic_inc32(&refcnt);
    }
    atomic_int32 refcnt;
    Counter counter;
    std::string desc;
  };
  std::map<std::string, CounterInfo *> counters_;
  pthread_mutex_t *lock_;
};

/**
 * Allows multiple instance of the same class to use the same Statistics
 * instance.  The "name_major" part is used to contruct counter names in the
 * form name_major.<provided name>
 */
class StatisticsTemplate {
 public:
  StatisticsTemplate(const std::string &name_major, Statistics *statistics)
    : name_major_(name_major), statistics_(statistics)
  { }
  StatisticsTemplate(const std::string &name_sub,
                     const StatisticsTemplate &statistics)
    : name_major_(statistics.name_major_ + "." + name_sub)
    , statistics_(statistics.statistics_)
  { }

  Counter *RegisterTemplated(const std::string &name_minor,
                             const std::string &desc)
  {
    return statistics_->Register(name_major_ + "." + name_minor, desc);
  }

  Statistics *statistics() { return statistics_; }

 private:
  std::string name_major_;
  Statistics *statistics_;
};

/**
 * Keeps track of events over time.  Can be used to query the number of events
 * between now and a point in time in the past.  The time range should be
 * smaller than capacity_s seconds.  Uses a monotonic clock.  Not thread-safe.
 */
class Recorder {
 public:
  Recorder(uint32_t resolution_s, uint32_t capacity_s);

  void Tick();
  void TickAt(uint64_t timestamp);
  uint64_t GetNoTicks(uint32_t retrospect_s) const;

  uint32_t capacity_s() const { return capacity_s_; }
  uint32_t resolution_s() const { return resolution_s_; }

 private:
  /**
   * Records number of ticks (events) per unit of resolution.  A ring buffer.
   * Entries older than capacity_s get overwritten by new events.
   */
  std::vector<uint32_t> bins_;

  /**
   * When the most recent tick occured.
   */
  uint64_t last_timestamp_;

  /**
   * Time window in seconds that the recorder is supposed to remember.
   */
  uint32_t capacity_s_;

  /**
   * Size of the bins for the tick counters.
   */
  uint32_t resolution_s_;

  /**
   * Shorthand for bins_.size(), constant during lifetime of the recorder.
   */
  unsigned no_bins_;
};

/**
 * Writes to multiple recorders.  Recorders with coarsed-grained resolution and
 * a large capacity are combined with precise recorders with shorter capacity.
 * Preferred recorders should be added first because GetNoTicks will use the
 * first recorder with a capacity >= retrospect_s (or the last recorder).
 */
class MultiRecorder {
 public:
  void Tick();
  void TickAt(uint64_t timestamp);
  uint64_t GetNoTicks(uint32_t retrospect_s) const;

  void AddRecorder(uint32_t resolution_s, uint32_t capacity_s);

 private:
  std::vector<Recorder> recorders_;
};

}  // namespace perf

#ifdef CVMFS_NAMESPACE_GUARD
}  // namespace CVMFS_NAMESPACE_GUARD
#endif

#endif  // CVMFS_STATISTICS_H_


text:
from rest_framework import routers
from .views import CourseViewSet, StudentViewSet

router = routers.DefaultRouter()
router.register(r'course', CourseViewSet)
router.register(r'student', StudentViewSet)

redpajama_set_name: RedPajamaGithub


text:
package org.spongepowered.common.bridge.scoreboard;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.Packet;

public interface ServerScoreboardBridge extends ScoreboardBridge {

    void bridge$addPlayer(EntityPlayerMP player, boolean sendPackets);

    void bridge$removePlayer(EntityPlayerMP player, boolean sendPackets);

    void bridge$sendToPlayers(Packet<?> packet);
}


text:
..  Copyright © J David Eisenberg
.. |---| unicode:: U+2014  .. em dash, trimming surrounding whitespace
   :trim:

Manipulating Collections
'''''''''''''''''''''''''

The previous two pages gave you the fundamentals of lists and vectors, but if you think there was something missing, you are correct
You may have been wondering how you work with the items in a collection, one after another.  In this page and the next pages, we will show you three of the most important functions for manipulating collections:  ``map``, ``reduce``, and ``filter``.

The ``map`` function
=======================

You use ``map`` when you want to create a new collection by applying a function to each element of a collection.
For example, let's take the vector of prices ``(def price-vector [3.95 6.80 2.49 5.33 1.99])`` and write a program that will give us a new vector with a 10% discount on each of the prices.
You already know how to do this for a single price:

::

    (defn discount [price]
      (* price 0.90))

What you now need is some way to apply that function to each of the items in ``price-vector``. The ``map`` function does exactly that.

.. activecode:: map-discount
    :caption: Mapping a function over a vector
    :language: clojurescript

    (def price-vector [3.95 6.80 2.49 5.33 1.99])
    (def discount (fn [price]
        (* price 0.90)))

    (map discount price-vector)

The ``map`` function takes two arguments: a function of one parameter, and a collection. In this example, the function is the ``discount`` function, and ``price-vector`` is the collection.

.. note::
    This ``map`` function is not to be confused with the ``map`` collection, which pairs keys and values. Unfortunately, they share the same name, and there's nothing to be done about it.

Here is a short video that may help as well:

.. youtube:: RtUjaxqmaDI
    :height: 315
    :width: 560
    :align: center

Something Important Just Happened
====================================
Up to this point, all of the arguments to functions have been raw data, like numbers and strings.
This is the first time you have seen a function as an argument to another function. I deliberately used the ``(def)`` form instead of ``(defn)`` to remind you that you can bind a function to a symbol, just as you can bind numbers or strings or lists to symbols. In ClojureScript, functions may be considered as another type of data that you can bind to symbols and pass to and from other functions. That's exactly what has happened here: I passed the ``discount`` function as an argument to the ``map`` function.

When you have a function like ``map`` that takes another function as an argument, it is referred to as a *higher-order function*.
(If a function returns another function as a result |---| yes, this is possible |---| it is also a higher-order function.)

Exercises
=========

**Exercise 1:** Write a program that uses ``map`` to convert the ``radius-vector`` to a sequence of circle areas.
You will write a function named ``calculate-area`` that calculates the area of a circle given its radius, then use it as the first argument to ``map``. You can use ``js/Math.PI`` for the value of pi. For extra bonus points, have the program create a vector as its result. (Hint: ``into``)

.. container:: full_width

    .. tabbed:: circle_area

        .. tab:: Your Program

            .. activecode:: circle_area_q
                :language: clojurescript

                (def radius-vector [3 1.5 4])
                ; your code here

        .. tab:: Answer

            .. activecode:: circle_area_answer
                :language: clojurescript

                (def radius-vector [3 1.5 4])
                (defn calculate-area [radius]
                    (* js/Math.PI radius radius))

                (into [] (map calculate-area radius-vector))

**Exercise 2:** Write a program that uses ``map`` to convert the ``price-vector`` to a sequence of prices that have been rounded up to the nearest 10-cent value.
Thus, for the vector ``[3.95 6.80 2.49 5.33 1.99]``, your result should be ``(4 6.8 2.5 5.4 2)`` Write a function named ``round-up-price`` that takes a single price as its argument and returns the result rounded up. For extra bonus points, have the program create a vector as its result. (Hint: ``into``).

Remember in the :doc:`interlude <what_is_programming>` I sang the praises of planning. This is one of those cases. Figuring out how to round 33 cents up to 40 cents, but keeping 30 cents as 30 cents takes a bit of thought and planning.

.. container:: full_width

    .. tabbed:: price_rounding

        .. tab:: Your Program

           .. activecode:: price_rounding_q
                :language: clojurescript

                (def price-vector [3.95 6.80 2.49 5.33 1.99])
                ; your code here

        .. tab:: Answer

            To round up the price, convert the price to cents by multiplying by 100. To get an even multiple of 10, do an integer division by 10, then multiply by 10.
            However, that rounds *down* rather than up; a number like 34 would go to 30 rather than 40. The trick is to add 9 to the original number before rounding down.
            When you do that, a number like 30 |---| which is already a multiple of 10 |---| becomes 39, which rounds back down to 30; but 32 would go up to 41, which rounds down to 40, effectively rounding 32 *up* to 40, the desired result.

            .. activecode:: price_rounding_answer
                :language: clojurescript

                (def price-vector [3.95 6.80 2.49 5.33 1.99])

                (defn round-up-price [price]
                    (let [cents (* price 100)
                          added (+ 9 cents)
                          rounded (* 10 (quot added 10))]
                        (/ rounded 100)))

                (into [] (map round-up-price price-vector))

.. _anonymous-functions:

``map`` Shortcut #1: Anonymous Functions
=============================================

If the function you are using in ``map`` is short (as it is in the example with the discount and the circle areas), you don't have to create a new, named function.
Instead, you can define the function right in the call to ``map``.  Here is the discount example, using an *anonymous function* (a function that isn't bound to a symbol).

.. activecode:: map-anonymous
    :caption: Using an anonymous function with map
    :language: clojurescript

    (def price-vector [3.95 6.80 2.49 5.33 1.99])

    (map (fn [price] (* price 0.90)) price-vector)

Now give it a try. Convert the circle area example to use an anonymous function. As before, your goal is a program that uses ``map`` to convert the ``radius-vector`` to a sequence of circle areas.

.. container:: full_width

    .. tabbed:: circle_area_anonymous

        .. tab:: Your Program

            .. activecode:: circle_area_anonymous_q
                :caption: Anonymous Function Exercise
                :language: clojurescript

                (def radius-vector [3 1.5 4])
                ; your code here

        .. tab:: Answer

            .. activecode:: circle_area_anonymous_answer
                :caption: Anonymous Function Exercise Answer
                :language: clojurescript

                (def radius-vector [3 1.5 4])

                (into [] (map (fn [radius] (* js/Math.PI radius radius)) radius-vector))

``map`` Shortcut #2: Even Shorter Function Syntax
=====================================================

You can define an anonymous function in a *very* compact manner. For a function with one parameter, which is what we are using here:

* Drop the ``fn`` and parameter list altogether
* Put a ``#`` before the opening parenthesis
* Use ``%`` in place of the parameter.

Here is the price discount program again, in the short syntax:

.. activecode:: map-anonymous2
    :caption: Using a short syntax anonymous function with map
    :language: clojurescript

    (def price-vector [3.95 6.80 2.49 5.33 1.99])

    (map #(* % 0.90) price-vector)

You can use this shortcut syntax for functions with more than one parameter; you use ``%1`` to stand for the first parameter, ``%2`` for the second, and so on. You could
write the ``average`` function with two parameters as follows. The long form is shown first as a comment for reference.

.. activecode:: average-short-syntax
    :caption: Multiple parameter short syntax function
    :language: clojurescript

    ; (def average (fn [a b] (/ (+ a b) 2.0)))
    (def average #(/ (+ %1 %2) 2.0))

    (average 7 12)

Which Shortcut Should You Use?
================================

When you are learning a foreign language, there are three classes of phrases:

* Phrases you have to know how to say and recognize
* Colloquial phrases that you may use if you feel confident about it
* Phrases you should be able to understand but not be expected to produce on your own

That's how I feel about writing functions for use with ``map``:

* Defining a separate named function always works, and, if you are a beginning programmer, may be the clearest way to express your intention. For a longer function such as the price rounding function, this is almost certainly your best option.
* For very short functions, if you feel comfortable using an anonymous function with ``fn``, go for it.
* You may find that the ultra-short syntax borders on unreadability, so you don't have to use it. Just be aware that other programmers are greatly enamored of it, so you will have to recognize it in their code.


text:
package org.apache.axis2.jaxws.provider;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.text.MessageFormat;
import java.util.UUID;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;

import org.apache.axis2.jaxws.framework.ClientConfigurationContextBinder;
import org.apache.axis2.jaxws.spi.Binding;
import org.apache.axis2.testutils.Axis2Server;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.soap.AddressingFeature;
import javax.xml.ws.RespectBindingFeature;

import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;

public class AddressingProviderTests {
    @ClassRule
    public static Axis2Server server = new Axis2Server("target/addressing-repo");

    @ClassRule
    public static final ClientConfigurationContextBinder binder = new ClientConfigurationContextBinder("target/client-repo");

    private QName serviceName = new QName("http://addressing.provider.jaxws.axis2.apache.org", "AddressingProviderService");
    private QName portName = new QName("http://addressing.provider.jaxws.axis2.apache.org", "AddressingProviderPort");

    static final String START_SOAP = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";

    static final String END_SOAP = "</soap:Body></soap:Envelope>";

    static final String XML_MESSAGE = "<ns2:inMessage xmlns:ns2=\"http://addressing.provider.jaxws.axis2.apache.org\">Hello</ns2:inMessage>";

    static final String SOAP_MESSAGE_1 = START_SOAP +
                      "<soap:Body>" +
                      XML_MESSAGE +
                      END_SOAP;

    static final String SOAP_MESSAGE_2 = START_SOAP +
                      "<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\"><wsa:To>{0}</wsa:To><wsa:MessageID>{1}</wsa:MessageID><wsa:Action>{2}</wsa:Action></soap:Header>" +
                      "<soap:Body>" +
                      XML_MESSAGE +
                      END_SOAP;

    static final String ACTION = "http://addressing.provider.jaxws.axis2.apache.org/AddressingProviderInterface/In";

    private static String getEndpointUrl() throws Exception {
        return server.getEndpoint("AddressingProviderService.AddressingProviderPort");
    }

    /**
     * Inject correct wsa header (wsa:Action must be set the the action of hello operation)
     */
    @Test
    public void testInjectAddressingHeaders() throws Exception {

        Dispatch<SOAPMessage> dispatch = createDispatch();

        String msg = SOAP_MESSAGE_1;
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage request = factory.createMessage(null, new ByteArrayInputStream(msg.getBytes()));

        SOAPMessage response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());

        // Try Again to verify
        response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());
    }

    /**
     * Message already contains wsa headers. Make sure there is no mismatch between
     * SOAPAction and wsa:Action.
     */
    @Test
    public void testWithAddressingHeaders() throws Exception {

        Dispatch<SOAPMessage> dispatch = createDispatch();

        String msg = MessageFormat.format(SOAP_MESSAGE_2,
                                          getEndpointUrl(),
                                          "urn:" + UUID.randomUUID(),
                                          ACTION);

        System.out.println(msg);

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage request = factory.createMessage(null, new ByteArrayInputStream(msg.getBytes()));

        SOAPMessage response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());

        // Try again to verify
        response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());
    }

    /**
     * Message already contains wsa headers. Make sure there is no mismatch between
     * SOAPAction and wsa:Action.
     */
    // Skipping this test until we have a way to register the addressing validator.
    @Ignore
    @Test
    public void testWithRespectBinding() throws Exception {
        Dispatch<SOAPMessage> dispatch = createDispatchWithRespectBinding();

        BindingProvider bp = (BindingProvider) dispatch;
        Binding binding = (Binding) bp.getBinding();

        WebServiceFeature addressingFeature = binding.getFeature(AddressingFeature.ID);
        assertNotNull(addressingFeature);
        assertTrue("Expecting AddressingFeature to be enabled.", addressingFeature.isEnabled());

        WebServiceFeature respectBindingFeature = binding.getFeature(RespectBindingFeature.ID);
        assertNotNull(respectBindingFeature);
        assertTrue("Expecting RespectBindingFeature to be enabled.", respectBindingFeature.isEnabled());

        bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, getEndpointUrl());

        String msg = MessageFormat.format(SOAP_MESSAGE_2,
                                          getEndpointUrl(),
                                          "urn:" + UUID.randomUUID(),
                                          ACTION);

        System.out.println(msg);

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage request = factory.createMessage(null, new ByteArrayInputStream(msg.getBytes()));

        SOAPMessage response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());

        // Try again to verify
        response = dispatch.invoke(request);

        assertResponseXML(response, "Hello Response");

        System.out.println(response.toString());
    }

    private SOAPElement assertResponseXML(SOAPMessage msg, String expectedText) throws Exception {
        assertTrue(msg != null);
        SOAPBody body = msg.getSOAPBody();
        assertTrue(body != null);

        Node invokeElement = (Node) body.getFirstChild();
        assertTrue(invokeElement instanceof SOAPElement);
        assertEquals("outMessage", invokeElement.getLocalName());

        String text = invokeElement.getValue();

        System.out.println("Received: " + text);
        assertEquals("Found ("+ text + ") but expected (" + expectedText + ")", expectedText, text);

        return (SOAPElement) invokeElement;
    }

    private Dispatch<SOAPMessage> createDispatch() throws Exception {
        URL wsdlURL = getWsdl();
        assertNotNull(wsdlURL);
        Service svc = Service.create(wsdlURL, serviceName);

        WebServiceFeature[] wsf = {new AddressingFeature(true)};

        Dispatch<SOAPMessage> dispatch =
            svc.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE, wsf);

        BindingProvider p = (BindingProvider) dispatch;
        p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, getEndpointUrl());

        return dispatch;
    }

    private Dispatch<SOAPMessage> createDispatchWithRespectBinding() throws Exception {
        URL wsdlURL = getWsdl();
        assertNotNull(wsdlURL);
        Service svc = Service.create(wsdlURL, serviceName);

        WebServiceFeature[] wsf = {new AddressingFeature(true), new RespectBindingFeature(true)};

        Dispatch<SOAPMessage> dispatch =
            svc.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE, wsf);

        return dispatch;
    }

    private URL getWsdl() throws Exception {
        String wsdlLocation = "/src/test/servicejars/AddressingProvider/META-INF/AddressingProvider.wsdl";
        String baseDir = new File(System.getProperty("basedir",".")).getCanonicalPath();
        wsdlLocation = new File(baseDir + wsdlLocation).getAbsolutePath();
        File file = new File(wsdlLocation);
        return file.toURI().toURL();
    }

}


text:
package org.jclouds.rackspace.clouddns.v1.features;

import java.util.Map;
import java.util.Set;

import javax.inject.Named;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;
import org.jclouds.Fallbacks.NullOnNotFoundOr404;
import org.jclouds.Fallbacks.VoidOnNotFoundOr404;
import org.jclouds.collect.PagedIterable;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks;
import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest;
import org.jclouds.openstack.v2_0.domain.PaginatedCollection;
import org.jclouds.openstack.v2_0.options.PaginationOptions;
import org.jclouds.rackspace.clouddns.v1.binders.UpdateRecordsToJSON;
import org.jclouds.rackspace.clouddns.v1.config.CloudDNS;
import org.jclouds.rackspace.clouddns.v1.domain.Job;
import org.jclouds.rackspace.clouddns.v1.domain.Record;
import org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;
import org.jclouds.rackspace.clouddns.v1.functions.ParseJob;
import org.jclouds.rackspace.clouddns.v1.functions.ParseOnlyRecord;
import org.jclouds.rackspace.clouddns.v1.functions.ParseRecord;
import org.jclouds.rackspace.clouddns.v1.functions.ParseRecords;
import org.jclouds.rackspace.clouddns.v1.functions.RecordsToPagedIterable;
import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Endpoint;
import org.jclouds.rest.annotations.Fallback;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.Transform;
import org.jclouds.rest.annotations.WrapWith;
import org.jclouds.rest.binders.BindToJsonPayload;

@Endpoint(CloudDNS.class)
@RequestFilters(AuthenticateRequest.class)
public interface RecordApi {

   /**
    * Create Records for a Domain or Subdomain.
    *

    * See
    * Supported Record Types
    *

    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.
    */
   @Named("record:create")
   @POST
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseJob.class)
   @Path("/records")
   Job<Set<RecordDetail>> create(@WrapWith("records") Iterable<Record> createRecords);

   /**
    * This call lists all records configured for the specified domain.
    */
   @Named("record:list")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseRecords.class)
   @Transform(RecordsToPagedIterable.class)
   @Path("/records")
   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)
   PagedIterable<RecordDetail> list();

   /**
    * RecordDetails filtered by type.
    */
   @Named("record:list")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseRecords.class)
   @Transform(RecordsToPagedIterable.class)
   @Path("/records")
   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)
   PagedIterable<RecordDetail> listByType(
         @QueryParam("type") String typeFilter);

   /**
    * RecordDetails filtered by type and data.
    */
   @Named("record:list")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseRecords.class)
   @Transform(RecordsToPagedIterable.class)
   @Path("/records")
   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)
   PagedIterable<RecordDetail> listByTypeAndData(
         @QueryParam("type") String typeFilter,
         @QueryParam("data") String dataFilter);

   /**
    * RecordDetails filtered by name and type.
    */
   @Named("record:list")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseRecords.class)
   @Transform(RecordsToPagedIterable.class)
   @Path("/records")
   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)
   PagedIterable<RecordDetail> listByNameAndType(
         @QueryParam("name") String nameFilter,
         @QueryParam("type") String typeFilter);

   /**
    * Use PaginationOptions to manually control the list of RecordDetail pages returned.
    */
   @Named("record:list")
   @GET
   @ResponseParser(ParseRecords.class)
   @Consumes(MediaType.APPLICATION_JSON)
   @Fallback(KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404.class)
   @Path("/records")
   PaginatedCollection<RecordDetail> list(PaginationOptions options);

   /**
    * RecordDetails filtered by name and type and data.
    */
   @Named("record:get")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseOnlyRecord.class)
   @Path("/records")
   @Fallback(NullOnNotFoundOr404.class)
   @Nullable
   RecordDetail getByNameAndTypeAndData(
         @QueryParam("name") String nameFilter,
         @QueryParam("type") String typeFilter,
         @QueryParam("data") String dataFilter);

   /**
    * Get the details for the specified record in the specified domain.
    */
   @Named("record:get")
   @GET
   @ResponseParser(ParseRecord.class)
   @Consumes(MediaType.APPLICATION_JSON)
   @Path("/records/{recordId}")
   @Fallback(NullOnNotFoundOr404.class)
   @Nullable
   RecordDetail get(@PathParam("recordId") String recordId);

   /**
    * Update the configuration of the specified record in the specified domain.
    *

    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.
    */
   @Named("record:update")
   @PUT
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseJob.class)
   @Path("/records/{recordId}")
   Job<Void> update(
         @PathParam("recordId") String recordId,
         @BinderParam(BindToJsonPayload.class) Record record);

   /**
    * Update the configuration of the specified records in the specified domain.
    *

    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.
    */
   @Named("record:update")
   @PUT
   @Consumes(MediaType.APPLICATION_JSON)
   @ResponseParser(ParseJob.class)
   @Path("/records")
   Job<Void> update(
         @BinderParam(UpdateRecordsToJSON.class) Map<String, Record> idsToRecords);

   /**
    * Delete the specified record in the specified domain.
    *

    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.
    */
   @Named("record:delete")
   @DELETE
   @Fallback(VoidOnNotFoundOr404.class)
   @ResponseParser(ParseJob.class)
   @Path("/records/{recordId}")
   @Consumes("*/*")
   Job<Void> delete(@PathParam("recordId") String recordId);

   /**
    * Delete the specified records in the specified domain.
    *

    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.
    */
   @Named("record:delete")
   @DELETE
   @Fallback(VoidOnNotFoundOr404.class)
   @ResponseParser(ParseJob.class)
   @Path("/records")
   @Consumes("*/*")
   Job<Void> delete(@QueryParam("id") Iterable<String> recordId);
}


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkObjectWrap.h"
#include "vtkPDirectoryWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkStringArrayWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkPDirectoryWrap::ptpl;

VtkPDirectoryWrap::VtkPDirectoryWrap()
{ }

VtkPDirectoryWrap::VtkPDirectoryWrap(vtkSmartPointer<vtkPDirectory> _native)
{ native = _native; }

VtkPDirectoryWrap::~VtkPDirectoryWrap()
{ }

void VtkPDirectoryWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkPDirectory").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("PDirectory").ToLocalChecked(), ConstructorGetter);
}

void VtkPDirectoryWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkPDirectoryWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkObjectWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkPDirectoryWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "Clear", Clear);
	Nan::SetPrototypeMethod(tpl, "clear", Clear);

	Nan::SetPrototypeMethod(tpl, "FileIsDirectory", FileIsDirectory);
	Nan::SetPrototypeMethod(tpl, "fileIsDirectory", FileIsDirectory);

	Nan::SetPrototypeMethod(tpl, "GetFiles", GetFiles);
	Nan::SetPrototypeMethod(tpl, "getFiles", GetFiles);

	Nan::SetPrototypeMethod(tpl, "GetPath", GetPath);
	Nan::SetPrototypeMethod(tpl, "getPath", GetPath);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "Open", Open);
	Nan::SetPrototypeMethod(tpl, "open", Open);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

#ifdef VTK_NODE_PLUS_VTKPDIRECTORYWRAP_INITPTPL
	VTK_NODE_PLUS_VTKPDIRECTORYWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkPDirectoryWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		vtkSmartPointer<vtkPDirectory> native = vtkSmartPointer<vtkPDirectory>::New();
		VtkPDirectoryWrap* obj = new VtkPDirectoryWrap(native);
		obj->Wrap(info.This());
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkPDirectoryWrap::Clear(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->Clear();
}

void VtkPDirectoryWrap::FileIsDirectory(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->FileIsDirectory(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkPDirectoryWrap::GetFiles(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	vtkStringArray * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetFiles();
	VtkStringArrayWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkStringArrayWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkStringArrayWrap *w = new VtkStringArrayWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkPDirectoryWrap::GetPath(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetPath();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkPDirectoryWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	vtkPDirectory * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkPDirectoryWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkPDirectoryWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkPDirectoryWrap *w = new VtkPDirectoryWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkPDirectoryWrap::Open(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->Open(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkPDirectoryWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkPDirectoryWrap *wrapper = ObjectWrap::Unwrap<VtkPDirectoryWrap>(info.Holder());
	vtkPDirectory *native = (vtkPDirectory *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
		vtkPDirectory * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObjectBase *) a0->native.GetPointer()
		);
		VtkPDirectoryWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkPDirectoryWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkPDirectoryWrap *w = new VtkPDirectoryWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
@interface PodsDummy_Pods_kuaichaSport : NSObject
@end
@implementation PodsDummy_Pods_kuaichaSport
@end


text:
package org.oscm.serviceprovisioningservice.local;

import javax.ejb.Local;

import org.oscm.domobjects.Product;
import org.oscm.internal.types.exception.ConcurrentModificationException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.types.exception.ValidationException;
import org.oscm.internal.vo.VOPriceModelLocalization;
import org.oscm.internal.vo.VOServiceLocalization;

@Local
public interface ServiceProvisioningServiceLocalizationLocal {

    /**
     * Checks if the current caller is allowed to change the localization of the
     * marketable service with the given key;
     *
     * @param serviceKey
     * @return
     * @throws ObjectNotFoundException
     */
    public boolean checkIsAllowedForLocalizingService(final long serviceKey)
            throws ObjectNotFoundException;

    /**
     * Returns the localized texts for a marketable service.
     *

     * Required role: none
     *
     * @param service
     *            the service to get the localized texts for
     * @return a VOServiceLocalization object with the localized
     *         texts
     * @throws ObjectNotFoundException
     *             if the service is not found
     * @throws OperationNotPermittedException
     *             if the calling user does not have read access to the service
     */
    public VOServiceLocalization getServiceLocalization(Product service)
            throws ObjectNotFoundException, OperationNotPermittedException;

    /**
     * Saves localized texts of a marketable service.
     *

     * Required role: service manager of the supplier organization that owns the
     * service
     *
     * @param serviceKey
     *            the service key for which the localized texts are to be saved
     * @param localization
     *            a VOServiceLocalization object with the localized
     *            texts to save
     * @throws ObjectNotFoundException
     *             if the service is not found
     * @throws OperationNotPermittedException
     *             if the calling user does not have write access to the service
     * @throws ValidationException
     *             if one of the localized texts is longer than 100 bytes
     * @throws ConcurrentModificationException
     *             if the stored service or texts are changed by another user in
     *             the time between reading and writing them
     */
    public void saveServiceLocalization(long serviceKey,
            VOServiceLocalization localization) throws ObjectNotFoundException,
            OperationNotPermittedException, ValidationException,
            ConcurrentModificationException;

    /**
     * Returns the localized texts for a price model.
     *

     * Required role: none
     *
     * @param serviceKey
     *            the serviceKey to get the localized texts for
     * @return a VOPriceModelLocalization object with the localized
     *         texts
     * @throws ObjectNotFoundException
     *             if the price model is not found
     * @throws OperationNotPermittedException
     *             if the calling user does not have read access to the price
     *             model
     */
    public VOPriceModelLocalization getPriceModelLocalization(long serviceKey)
            throws ObjectNotFoundException, OperationNotPermittedException;

    /**
     * Saves the localized texts for a price model.
     *

     * Required role: reseller organization that owns the price model
     *
     * @param serviceKey
     *            the key of the service for which the localized texts are to be
     *            saved
     * @param true if the price model is chargeable, false otherwise
     * @param localization
     *            a VOPriceModelLocalization object with the
     *            localized texts to save
     * @throws ObjectNotFoundException
     *             if the service is not found
     * @throws OperationNotPermittedException
     *             if the calling user does not have write access to the price
     *             model
     * @throws ConcurrentModificationException
     *             if the stored price model or texts are changed by another
     *             user in the time between reading and writing them
     */
    public void savePriceModelLocalizationForReseller(long serviceKey,
            boolean isChargable, VOPriceModelLocalization localization)
            throws ObjectNotFoundException, OperationNotPermittedException,
            ConcurrentModificationException;

    /**
     * Saves the localized texts for a price model.
     *

     * Required role: service manager of the supplier organization that owns the
     * price model
     *
     * @param priceModelKey
     *            the key of the price model for which the localized texts are
     *            to be saved
     * @param true if the price model is chargeable, false otherwise
     * @param localization
     *            a VOPriceModelLocalization object with the
     *            localized texts to save
     * @throws ObjectNotFoundException
     *             if the price model is not found
     * @throws OperationNotPermittedException
     *             if the calling user does not have write access to the price
     *             model
     * @throws ConcurrentModificationException
     *             if the stored price model or texts are changed by another
     *             user in the time between reading and writing them
     */
    public void savePriceModelLocalizationForSupplier(long priceModelKey,
            boolean isChargable, VOPriceModelLocalization localization)
            throws ObjectNotFoundException, OperationNotPermittedException,
            ConcurrentModificationException;
}


text:
package com.lspooo.plugin.camera;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.lspooo.plugin.camera.listener.CaptureListener;
import com.lspooo.plugin.camera.listener.ClickListener;
import com.lspooo.plugin.camera.listener.ReturnListener;
import com.lspooo.plugin.camera.listener.TypeListener;

public class CaptureLayout extends FrameLayout {

    private CaptureButton captureBtn;
    private TypeButton confirmBtn;
    private TypeButton cancelBtn;
    private ReturnButton returnBtn;
    private TextView tipTv;

    private CaptureListener captureListener;
    private TypeListener typeListener;
    private ReturnListener returnListener;      //退出按钮监听

    private int widgetWidth;
    private int widgetHeight;
    private int buttonSize;
    private boolean isFirst = true;

    public CaptureLayout(Context context) {
        this(context, null);
    }

    public CaptureLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CaptureLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initWidgetSize(context);
        initView();
    }

    private void initWidgetSize(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            widgetWidth = outMetrics.widthPixels;
        } else {
            widgetWidth = outMetrics.widthPixels / 2;
        }
        buttonSize = (int) (widgetWidth / 4.5f);
        widgetHeight = buttonSize + (buttonSize / 5) * 2 + 100;
    }

    private void initView() {
        setWillNotDraw(false);
        //拍照按钮
        captureBtn = new CaptureButton(getContext(), buttonSize);
        LayoutParams captureBtnParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        captureBtnParam.gravity = Gravity.CENTER;
        captureBtn.setLayoutParams(captureBtnParam);
        captureBtn.setCaptureListener(new CaptureListener() {
            @Override
            public void takePictures() {
                if (captureListener != null) {
                    captureListener.takePictures();
                }
            }

            @Override
            public void recordShort(long time) {
                if (captureListener != null) {
                    captureListener.recordShort(time);
                }
                startAlphaAnimation();
            }

            @Override
            public void recordStart() {
                if (captureListener != null) {
                    captureListener.recordStart();
                }
                startAlphaAnimation();
            }

            @Override
            public void recordEnd(long time) {
                if (captureListener != null) {
                    captureListener.recordEnd(time);
                }
                startAlphaAnimation();
                startTypeBtnAnimator();
            }

            @Override
            public void recordZoom(float zoom) {
                if (captureListener != null) {
                    captureListener.recordZoom(zoom);
                }
            }

            @Override
            public void recordError() {
                if (captureListener != null) {
                    captureListener.recordError();
                }
            }
        });

        //取消按钮
        cancelBtn = new TypeButton(getContext(), TypeButton.TYPE_CANCEL, buttonSize);
        final LayoutParams cancelBtnParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        cancelBtnParam.gravity = Gravity.CENTER_VERTICAL;
        cancelBtnParam.setMargins((widgetWidth / 4) - buttonSize / 2, 0, 0, 0);
        cancelBtn.setLayoutParams(cancelBtnParam);
        cancelBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (typeListener != null) {
                    typeListener.cancel();
                }
                startAlphaAnimation();
            }
        });

        //确认按钮
        confirmBtn = new TypeButton(getContext(), TypeButton.TYPE_CONFIRM, buttonSize);
        LayoutParams confirmBtnParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        confirmBtnParam.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        confirmBtnParam.setMargins(0, 0, (widgetWidth / 4) - buttonSize / 2, 0);
        confirmBtn.setLayoutParams(confirmBtnParam);
        confirmBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (typeListener != null) {
                    typeListener.confirm();
                }
                startAlphaAnimation();
            }
        });

        //返回按钮
        returnBtn = new ReturnButton(getContext(), (int) (buttonSize / 2.5f));
        LayoutParams returnBtnParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        returnBtnParam.gravity = Gravity.CENTER_VERTICAL;
        returnBtnParam.setMargins(widgetWidth / 6, 0, 0, 0);
        returnBtn.setLayoutParams(returnBtnParam);
        returnBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (returnListener != null) {
                    returnListener.onReturn();
                }
            }
        });

        tipTv = new TextView(getContext());
        LayoutParams txt_param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        txt_param.gravity = Gravity.CENTER_HORIZONTAL;
        txt_param.setMargins(0, 0, 0, 0);
        tipTv.setText("轻触拍照,长按摄像");
        tipTv.setTextColor(0xFFFFFFFF);
        tipTv.setGravity(Gravity.CENTER);
        tipTv.setLayoutParams(txt_param);

        this.addView(captureBtn);
        this.addView(cancelBtn);
        this.addView(confirmBtn);
        this.addView(returnBtn);
        this.addView(tipTv);

        cancelBtn.setVisibility(GONE);
        confirmBtn.setVisibility(GONE);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widgetWidth, widgetHeight);
    }

    public void startTypeBtnAnimator() {
        //拍照录制结果后的动画
        returnBtn.setVisibility(GONE);
        captureBtn.setVisibility(GONE);
        cancelBtn.setVisibility(VISIBLE);
        confirmBtn.setVisibility(VISIBLE);
        cancelBtn.setClickable(false);
        confirmBtn.setClickable(false);
        ObjectAnimator animator_cancel = ObjectAnimator.ofFloat(cancelBtn, "translationX", widgetWidth / 4, 0);
        ObjectAnimator animator_confirm = ObjectAnimator.ofFloat(confirmBtn, "translationX", -widgetWidth / 4, 0);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(animator_cancel, animator_confirm);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                cancelBtn.setClickable(true);
                confirmBtn.setClickable(true);
            }
        });
        set.setDuration(200);
        set.start();
    }

    /**************************************************
     * 对外提供的API                      *
     **************************************************/
    public void resetCaptureLayout() {
        captureBtn.resetState();
        cancelBtn.setVisibility(GONE);
        confirmBtn.setVisibility(GONE);
        returnBtn.setVisibility(VISIBLE);
    }

    public void startAlphaAnimation() {
        if (isFirst) {
            ObjectAnimator animator_txt_tip = ObjectAnimator.ofFloat(tipTv, "alpha", 1f, 0f);
            animator_txt_tip.setDuration(500);
            animator_txt_tip.start();
            isFirst = false;
        }
    }

    public void setTextWithAnimation(String tip) {
        tipTv.setText(tip);
        ObjectAnimator animator_txt_tip = ObjectAnimator.ofFloat(tipTv, "alpha", 0f, 1f, 1f, 0f);
        animator_txt_tip.setDuration(2500);
        animator_txt_tip.start();
    }

    public void setDuration(int duration) {
        captureBtn.setDuration(duration);
    }

    public void setButtonFeatures(int state) {
        captureBtn.setButtonFeatures(state);
    }

    public void setTip(String tip) {
        tipTv.setText(tip);
    }

    public void showTip() {
        tipTv.setVisibility(VISIBLE);
    }

    public void setTypeListener(TypeListener typeListener) {
        this.typeListener = typeListener;
    }

    public void setCaptureListener(CaptureListener captureListener) {
        this.captureListener = captureListener;
    }

    public void setReturnLisenter(ReturnListener returnListener) {
        this.returnListener = returnListener;
    }
}


text:
<!-- IBM_PROLOG_BEGIN_TAG                                                   -->
<!-- This is an automatically generated prolog.                             -->
<!--                                                                        -->
<!-- $Source: src/import/chips/centaur/procedures/xml/error_info/p9c_memory_mss_termination_control_errors.xml $ -->
<!--                                                                        -->
<!-- OpenPOWER HostBoot Project                                             -->
<!--                                                                        -->
<!-- Contributors Listed Below - COPYRIGHT 2016,2017                        -->
<!-- [+] International Business Machines Corp.                              -->
<!--                                                                        -->
<!--                                                                        -->
<!-- Licensed under the Apache License, Version 2.0 (the "License");        -->
<!-- you may not use this file except in compliance with the License.       -->
<!-- You may obtain a copy of the License at                                -->
<!--                                                                        -->
<!--     http://www.apache.org/licenses/LICENSE-2.0                         -->
<!--                                                                        -->
<!-- Unless required by applicable law or agreed to in writing, software    -->
<!-- distributed under the License is distributed on an "AS IS" BASIS,      -->
<!-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        -->
<!-- implied. See the License for the specific language governing           -->
<!-- permissions and limitations under the License.                         -->
<!--                                                                        -->
<!-- IBM_PROLOG_END_TAG                                                     -->

<!-- -->
<!-- @file memory_mss_termination_control.xml -->
<!-- @brief Error xml for termination control -->
<!-- -->
<!-- *HWP HWP Owner: Luke Mulkey <lwmulkey@us.ibm.com> -->
<!-- *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> -->
<!-- *HWP FW Owner: Bill Hoffa <wghoffa@us.ibm.com> -->
<!-- *HWP Team: Memory -->
<!-- *HWP Level: 1 -->
<!-- *HWP Consumed by: FSP:HB -->
<!-- -->

<hwpErrors>
<hwpError>
  <rc>RC_CEN_CONFIG_DRV_IMP_INVALID_INPUT</rc>
  <description>
    The config_drv_imp utility function received a bad parameter
  </description>
  <ffdc>PORT_PARAM</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_CONFIG_RCV_IMP_INVALID_INPUT</rc>
  <description>
    The config_rcv_imp utility function received a bad parameter
  </description>
  <ffdc>PORT_PARAM</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_CONFIG_SLEW_RATE_INVALID_INPUT</rc>
  <description>
    The config_slew_rate utility function received a bad parameter
  </description>
  <ffdc>PORT_PARAM</ffdc>
  <ffdc>SLEW_TYPE_PARAM</ffdc>
  <ffdc>SLEW_IMP_PARAM</ffdc>
  <ffdc>SLEW_RATE_PARAM</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_CONFIG_WR_DRAM_VREF_INVALID_INPUT</rc>
  <description>
    The config_wr_dram_vref utility function received a bad parameter
  </description>
  <ffdc>PORT_PARAM</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_CONFIG_RD_CEN_VREF_INVALID_INPUT</rc>
  <description>
    The config_rd_cen_vref utility function received a bad parameter
  </description>
  <ffdc>PORT_PARAM</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_INVALID_DRAM_GEN</rc>
  <description>
    mss_slew_cal found an invalid DRAM type in ATTR_EFF_DRAM_GEN (not DDR3/4)
  </description>
  <ffdc>DRAM_GEN</ffdc>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_INVALID_FREQ</rc>
  <description>
    mss_slew_cal found a zero frequency in ATTR_MSS_FREQ
  </description>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

<registerFfdc>
  <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT0</id>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P0_ADR0</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P0_ADR1</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P0_ADR2</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P0_ADR3</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P0_0</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P0_1</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P0_2</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P0_3</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P0_4</scomRegister>
</registerFfdc>

<registerFfdc>
  <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT1</id>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P1_ADR0</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P1_ADR1</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P1_ADR2</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_ADR_IO_SLEW_CTL_VALUE_P1_ADR3</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P1_0</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P1_1</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P1_2</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P1_3</scomRegister>
  <scomRegister>CEN_MBA_DDRPHY_DP18_IO_TX_CONFIG0_P1_4</scomRegister>
</registerFfdc>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_TIMEOUT_PORT0</rc>
  <description>
      mss_slew_cal found slew calibration timeout on MBA port 0
  </description>
  <ffdc>DATA_ADR</ffdc>
  <ffdc>IMP</ffdc>
  <ffdc>SLEW</ffdc>
  <ffdc>STAT_REG</ffdc>
  <collectRegisterFfdc>
    <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT0</id>
    <target>MBA_IN_ERROR</target>
    <targetType>TARGET_TYPE_MBA</targetType>
  </collectRegisterFfdc>
  <callout>
    <target>MBA_IN_ERROR</target>
    <priority>HIGH</priority>
  </callout>
  <deconfigure>
    <target>MBA_IN_ERROR</target>
  </deconfigure>
  <gard>
    <target>MBA_IN_ERROR</target>
  </gard>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_TIMEOUT_PORT1</rc>
  <description>
      mss_slew_cal found slew calibration timeout on MBA port 1
  </description>
  <ffdc>DATA_ADR</ffdc>
  <ffdc>IMP</ffdc>
  <ffdc>SLEW</ffdc>
  <ffdc>STAT_REG</ffdc>
  <collectRegisterFfdc>
    <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT1</id>
    <target>MBA_IN_ERROR</target>
    <targetType>TARGET_TYPE_MBA</targetType>
  </collectRegisterFfdc>
  <callout>
    <target>MBA_IN_ERROR</target>
    <priority>HIGH</priority>
  </callout>
  <deconfigure>
    <target>MBA_IN_ERROR</target>
  </deconfigure>
  <gard>
    <target>MBA_IN_ERROR</target>
  </gard>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_ERROR_PORT0</rc>
  <description>
      mss_slew_cal found slew calibration error on MBA port 0
  </description>
  <ffdc>DATA_ADR</ffdc>
  <ffdc>IMP</ffdc>
  <ffdc>SLEW</ffdc>
  <ffdc>STAT_REG</ffdc>
  <collectRegisterFfdc>
    <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT0</id>
    <target>MBA_IN_ERROR</target>
    <targetType>TARGET_TYPE_MBA</targetType>
  </collectRegisterFfdc>
  <callout>
    <target>MBA_IN_ERROR</target>
    <priority>HIGH</priority>
  </callout>
  <deconfigure>
    <target>MBA_IN_ERROR</target>
  </deconfigure>
  <gard>
    <target>MBA_IN_ERROR</target>
  </gard>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_SLEW_CAL_ERROR_PORT1</rc>
  <description>
      mss_slew_cal found slew calibration error on MBA port 1
  </description>
  <ffdc>DATA_ADR</ffdc>
  <ffdc>IMP</ffdc>
  <ffdc>SLEW</ffdc>
  <ffdc>STAT_REG</ffdc>
  <collectRegisterFfdc>
    <id>REG_FFDC_MSS_SLEW_CAL_FAILURE_PORT1</id>
    <target>MBA_IN_ERROR</target>
    <targetType>TARGET_TYPE_MBA</targetType>
  </collectRegisterFfdc>
  <callout>
    <target>MBA_IN_ERROR</target>
    <priority>HIGH</priority>
  </callout>
  <deconfigure>
    <target>MBA_IN_ERROR</target>
  </deconfigure>
  <gard>
    <target>MBA_IN_ERROR</target>
  </gard>
</hwpError>

<hwpError>
  <rc>RC_CEN_MSS_IMP_INPUT_ERROR</rc>
  <!-- TODO Remove when all HWPs using it are using their own Error XML file -->
  <description>Impedance is invalid for driver/receiver type.</description>
  <callout>
    <procedure>CODE</procedure>
    <priority>HIGH</priority>
  </callout>
</hwpError>

</hwpErrors>


text:
const registerLoader = require('@sanity/plugin-loader')

// eslint-disable-next-line no-process-env
registerLoader({basePath: process.env.SANITY_BASE_PATH || process.cwd(), stubCss: true})


text:
import sublime_plugin
import sublime
import os
import threading
import fnmatch
import re
import timeit
import ntpath
import json

class Util():
	@staticmethod
	def log(tag, message):
		print("{tag}: {message}".format(tag = tag, message = message))

	@staticmethod
	def status(message):
		sublime.status_message("{message}".format(message = message))

	@staticmethod
	def isMatchUnixPatterns(text, patterns):
		for pattern in patterns:
			if fnmatch.fnmatch(text, pattern):
				return True
		return False

	@staticmethod
	def filterByUnixPatterns(texts, patterns, keep_if_match):
		filtered_texts = []
		for text in texts:
			if keep_if_match == Util.isMatchUnixPatterns(text, patterns):
				filtered_texts.append(text)

		return filtered_texts

	'''
		Extract directory/file name from a path.
		Ex:
		Inputs:		'a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 'a/b/../../a/b/c/', 'a/b/../../a/b/c'
		Outputs:	'c', 'c', 'c', 'c', 'c', 'c', 'c'
		Ref: http://stackoverflow.com/questions/8384737/python-extract-file-name-from-path-no-matter-what-the-os-path-format
	'''
	@staticmethod
	def getBasenameFromPath(path):
		head, tail = ntpath.split(path)
		return tail or ntpath.basename(head)

class Settings():
	def __init__(self, view, setting_name):
		self.default = sublime.load_settings("{setting_name}.sublime-settings".format(setting_name = setting_name))
		self.user = view.settings().get("{setting_name}".format(setting_name = setting_name), {})

	def get(self, fieldName, defaultValue):
		return self.user.get(fieldName, self.default.get(fieldName, defaultValue))

class TodoSearchEngine():
	TAG = "ReviewMyself.TodoSearchEngine"

	def __init__(self):
		self.paths_to_search = []
		self.todo_filter = None
		self.priority_filter = None
		self.ignored_dir_patterns = []
		self.only_care_file_patterns = []
		self.counter = Counter()

	def hasIgnoredDirs(self):
		return len(self.ignored_dir_patterns) > 0

	def hasOnlyCareFiles(self):
		return len(self.only_care_file_patterns) > 0

	'''
	pseudocode:
		each path in paths:
			check exists
			if is file path:
				yeild it
			else
				if has only care files:
					only keep those files

				if has ignored dirs:
					remove ignored dirs

				yeild rest of files
	'''
	def walk(self):
		for path_to_search in self.paths_to_search:
			path_to_search = os.path.realpath(os.path.expanduser(os.path.abspath(path_to_search)))

			if os.path.exists(path_to_search):
				if os.path.isfile(path_to_search):
					yield path_to_search # if user indicated a file, that mean he/she want to scan that file, so just yield it

				for dirpath, dirnames, filenames in os.walk(path_to_search, topdown = True):
					if self.hasOnlyCareFiles():
						filenames[:] = Util.filterByUnixPatterns(texts = filenames, patterns = self.only_care_file_patterns, keep_if_match = True)

					if self.hasIgnoredDirs():
						dirnames[:] = Util.filterByUnixPatterns(texts = dirnames, patterns = self.ignored_dir_patterns, keep_if_match = False)

					for filename in filenames:
						filepath = os.path.join(dirpath, filename)
						yield filepath

	def search(self):
		for filepath in self.walk():
			try:
				file_stream = open(filepath, 'r', encoding='utf-8')
				for linenum, line in enumerate(file_stream, 1):
					match = self.todo_filter.search(line)
					if match:
						match_groups = match.groupdict()

						todo = ""
						if "todo" in match_groups:
							todo = str(match_groups["todo"]).strip()

						if todo:
							match = self.priority_filter.search(todo)

							priority = 9999 #TODO: unhardcode max priority #p3
							if match:
								match_groups = match.groupdict()
								if "priority" in match_groups:
									priority = int(match_groups["priority"])
									todo = todo.replace(match.group(0), "")

							yield {
								'filepath': filepath,
								'linenum': linenum,
								'todo': todo,
								'priority': priority
							}

			except Exception as e:
				file_stream = None
				Util.log(TodoSearchEngine.TAG, r"Can't read '{filepath}', error: {exception_info}".format(
					filepath = filepath,
					exception_info = e))

			finally:
				self.counter.increment()
				if file_stream is not None:
					file_stream.close()

class ResultView():
	@staticmethod
	def get():
		active_window = sublime.active_window()
		for view in active_window.views():
			if ResultView.isResultView(view):
				return view

		result_view = active_window.new_file()
		result_view.set_name('ReviewMyself')
		result_view.set_scratch(True)
		result_view.settings().set('review_myself_view', True)
		result_view.settings().set('command_mode', True)
		result_view.settings().set('word_wrap', False)
		result_view.settings().set("line_numbers", False)
		settings = Settings(result_view, "ReviewMyself")
		result_view.settings().set("color_scheme", settings.get("color_scheme", ""))
		result_view.assign_syntax(r"Packages/Review Myself/ReviewMyself.tmLanguage")

		return result_view

	@staticmethod
	def isResultView(view):
		return view.settings().get("review_myself_view", False) == True

class ReviewMyselfShowResultCommand(sublime_plugin.TextCommand):
	def run(self, edit, **args):
		paths_to_search = args.get("paths_to_search", [])
		results = args.get("results", [])
		results = sorted(results, key=lambda result: (result['priority'])) # sort by priority
		#TODO: implement todo group by "From" #p2
		processed_file_count = args.get("processed_file_count", 0)
		processed_time = args.get("processed_time", 0)

		result_view = ResultView.get()
		result_view.erase(edit, sublime.Region(0, result_view.size()))

		result_view.settings().set("paths_to_search", paths_to_search)

		search_session_info = ""
		search_session_info += "{0:12} [".format("# From:")
		for index, path_to_search in enumerate(paths_to_search, 1):
			search_session_info += "{0}".format(Util.getBasenameFromPath(path_to_search))
			if index != len(paths_to_search):
				search_session_info += ", "
		search_session_info += "]\n"
		search_session_info += "{0:12} {1}\n".format("# No.Files:", processed_file_count)
		search_session_info += "{0:12} {1}s\n".format("# Time:", processed_time)
		search_session_info += "\n\n"

		result_view.insert(edit, result_view.size(), search_session_info)

		settings = Settings(self.view, "ReviewMyself")

		todo_result_pattern = ""
		todo_result_pattern += u"{index:<5}"
		todo_result_pattern += u"{filepath}"
		show_linenum = settings.get("show_linenum", False)
		if show_linenum:
			todo_result_pattern += u":{linenum:<5}"
		todo_result_pattern += u" => "
		todo_result_pattern += u"{priority}"
		todo_result_pattern += u"{todo}"

		result_regions = []

		for index, result in enumerate(results, 1):
			minimized_filepath = result["filepath"]
			for path_to_search in paths_to_search:
				if minimized_filepath.startswith(path_to_search):
					minimized_filepath = minimized_filepath.replace(path_to_search, Util.getBasenameFromPath(path_to_search))

			formatted_result = todo_result_pattern.format(
				index = "{0}.".format(index),
				filepath = minimized_filepath,
				linenum = result['linenum'],
				priority = "p{0}.".format(result["priority"]) if result["priority"] != 9999 else "", #TODO: unhardcode max priority #p3
				todo = result["todo"])

			result_region_start = result_view.size()
			result_view.insert(edit, result_region_start, formatted_result)
			result_region_stop = result_view.size()
			result_view.insert(edit, result_view.size(), u'\n')

			result_regions.append(sublime.Region(result_region_start, result_region_stop))

		result_view.add_regions('result_regions', result_regions, '')

		region_to_result_dict = dict(('{0},{1}'.format(region.a, region.b), result) for region, result in zip(result_regions, results))
		result_view.settings().set('region_to_result_dict', region_to_result_dict)

		result_view.settings().set("selected_index", -1)
		result_view.run_command("review_myself_navigate_result", {"direction": "down"})

		#TODO: sync usage text with user key map settings #p3
		usage_text = ""
		usage_text += "\n\n"
		usage_text += "# Usage:\n"
		usage_text += "#\t {0:20} = next todo\n".format("s")
		usage_text += "#\t {0:20} = previous todo\n".format("w")
		usage_text += "#\t {0:20} = refresh result\n".format("r")
		usage_text += "#\t {0:20} = goto todo location\n".format("f or enter")
		usage_text += "#\t {0:20} = open context panel\n".format("d")
		usage_text += "#\t {0:20} = close context panel\n".format("a")
		usage_text += "#\t {0:20} = select todo\n".format("move caret, then tab")
		result_view.insert(edit, result_view.size(), usage_text)

		#TODO: implement on the fly settings #p2

		sublime.active_window().focus_view(result_view)

class SearchThread(threading.Thread):
	def __init__(self, search_engine, onSearchingDone):
		self.search_engine = search_engine
		self.onSearchingDone = onSearchingDone
		threading.Thread.__init__(self)

	def run(self):
		self.search_engine.counter.startTimer()
		results = list(self.search_engine.search())
		self.search_engine.counter.stopTimer()
		self.onSearchingDone(results, self.search_engine.counter)

class Counter():
	def __init__(self):
		self.current = 0
		self.start_time = 0
		self.stop_time = 0
		self.lock = threading.RLock()

	def __str__(self):
		return "{0}".format(self.current)

	def startTimer(self):
		self.start_time = timeit.default_timer()

	def stopTimer(self):
		self.stop_time = timeit.default_timer()

	def getDeltaTime(self):
		return round(self.stop_time - self.start_time, 2)

	def increment(self):
		with self.lock:
			self.current += 1
		sublime.status_message("ReviewMyself: {0} files processed".format(self.current))

class ReviewMyselfImpl(sublime_plugin.TextCommand):
	def run(self, edit, paths, append = False):
		settings = Settings(self.view, "ReviewMyself")

		if append:
			result_view = ResultView.get()
			result_view_settings = result_view.settings()
			self.paths_to_search = result_view_settings.get("paths_to_search", [])
			print("paths_to_search: ", self.paths_to_search)
			print("new_paths: ", paths)
			for new_path in paths:
				duplicate = False
				for old_path in self.paths_to_search:
					if new_path == old_path:
						duplicate = True
						break
				if not duplicate:
					self.paths_to_search.append(new_path)
		else:
			self.paths_to_search = paths

		for path in self.paths_to_search[:]:
			if os.path.isdir(path):
				spec_file_path = os.path.join(path, '.local.reviewmyself')
				if os.path.exists(spec_file_path):
					spec_file = open(spec_file_path, 'rt', encoding = 'utf-8')
					spec = json.load(spec_file)
					only_care_paths = spec.get('only_care_paths')
					if only_care_paths and len(only_care_paths) > 0:
						self.paths_to_search.remove(path)
						for only_care_path in only_care_paths:
							only_care_path = os.path.realpath(os.path.expanduser(os.path.abspath(os.path.join(path, only_care_path))))
							if os.path.exists(only_care_path):
								self.paths_to_search.append(only_care_path)

		self.is_ignore_case = settings.get("is_ignore_case", True)
		self.todo_patterns = settings.get("todo_patterns", [])
		self.priority_patterns = settings.get("priority_patterns", [])
		self.ignored_dir_patterns = settings.get("ignored_dir_patterns", [])
		self.only_care_file_patterns = settings.get("only_care_file_patterns", [])

		self.search_engine = TodoSearchEngine()
		self.search_engine.paths_to_search = self.paths_to_search
		self.search_engine.todo_filter = re.compile("|".join(self.todo_patterns), re.IGNORECASE if self.is_ignore_case else 0)
		self.search_engine.priority_filter = re.compile("|".join(self.priority_patterns), re.IGNORECASE if self.is_ignore_case else 0)
		self.search_engine.ignored_dir_patterns = self.ignored_dir_patterns
		self.search_engine.only_care_file_patterns = self.only_care_file_patterns

		self.search_thread = SearchThread(self.search_engine, self.onSearchingDone)
		self.search_thread.start()

	def onSearchingDone(self, results, counter):
		self.view.run_command("review_myself_show_result", {
			"paths_to_search": self.paths_to_search,
			"results": results,
			"processed_file_count": counter.current,
			"processed_time": counter.getDeltaTime()
			})

class ReviewMyselfAutoModeCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		folders_in_project = self.view.window().folders()
		if folders_in_project:
			self.view.run_command("review_myself_impl", {
				"paths": folders_in_project
				})

class ReviewMyselfCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfCommand"

	def run(self, edit, mode):
		if mode == "auto":
			self.view.run_command("review_myself_auto_mode")
		elif mode == "manual":
			#TODO: implement manual mode #p3
			Util.status("ReviewMyself: Manual mode is under construction!")
		else:
			Util.status("ReviewMyself: '{0}' mode is not supported yet! What matter with your settings ?".format(mode))

class ReviewMyselfNavigateResultCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfNavigateResultCommand"

	def run(self, edit, direction):
		view_settings = self.view.settings()
		result_regions = self.view.get_regions("result_regions")
		result_region_cout = len(result_regions)

		if result_region_cout <= 0:
			return

		selected_index = int(view_settings.get("selected_index", -1))

		if direction == "up":
			selected_index -= 1
		elif direction == "down":
			selected_index += 1
		else:
			Util.status("ReviewMyself: Incorrect navigation direction. Check settings!")
			return

		if selected_index < 0:
			selected_index = result_region_cout - 1
		elif selected_index > result_region_cout - 1:
			selected_index = 0

		view_settings.set('selected_index', selected_index)

		selected_region = result_regions[selected_index]
		self.view.add_regions('selected_region', [selected_region], "selected", "", sublime.DRAW_SOLID_UNDERLINE|sublime.DRAW_NO_FILL)
		self.view.show(selected_region)

		settings = Settings(self.view, "ReviewMyself")
		if view_settings.get("auto_show_context", settings.get("auto_show_context", True)):
			self.view.run_command("review_myself_goto", {"preview": True})

class ReviewMyselfGotoCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfGotoCommand"

	def run(self, edit, preview = False):
		view_settings = self.view.settings()
		result_regions = self.view.get_regions("result_regions")
		result_region_cout = len(result_regions)

		if result_region_cout <= 0:
			return

		selected_index = int(view_settings.get("selected_index", -1))
		if selected_index < 0 or selected_index > result_region_cout - 1:
			Util.status("ReviewMyself: Select a todo first!")
			return;

		selected_region = result_regions[selected_index]
		region_to_result_dict = self.view.settings().get('region_to_result_dict')

		result = region_to_result_dict.get('{0},{1}'.format(selected_region.a, selected_region.b)) # use dict.get() instead dict[] to avoid KeyError exception
		if result is not None:
			active_window = self.view.window()
			file_path = result['filepath']

			if preview:
				active_window.run_command("set_layout", {
					"cols": [0.0, 1.0],
					"rows": [0.0, 0.5, 1.0],
					"cells": [[0, 0, 1, 1], [0, 1, 1, 2]]
					})

				active_window.focus_group(1)

				opened_file_view = active_window.find_open_file(file_path)
				if opened_file_view is not None:
					active_window.set_view_index(opened_file_view, 1, 0)

				new_view = active_window.open_file("{filepath}:{linenum}".format(filepath = file_path, linenum = result['linenum']), sublime.ENCODED_POSITION|sublime.TRANSIENT)
				active_window.focus_view(self.view)
			else:
				self.view.run_command("review_myself_close_context_panel")
				new_view = active_window.open_file("{filepath}:{linenum}".format(filepath = file_path, linenum = result['linenum']), sublime.ENCODED_POSITION)

class ReviewMyselfRefreshResultCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfRefreshResultCommand"

	def run(self, edit):
		view_settings = self.view.settings()
		paths_to_search = view_settings.get("paths_to_search", [])

		self.view.run_command("review_myself_impl", {"paths": paths_to_search})

class ReviewMyselfReviewCurrentFileCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfReviewCurrentFileCommand"

	def run(self, edit, append = False):
		active_window = sublime.active_window()
		active_view = active_window.active_view()

		if active_view:
			file_name = active_view.file_name()
			if file_name:
				paths_to_search = [file_name]
				self.view.run_command("review_myself_impl", {
					"paths": paths_to_search,
					"append": append
					})

class ReviewMyselfSelectResultCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfSelectResultCommand"

	def run(self, edit):
		view_settings = self.view.settings()
		result_regions = self.view.get_regions("result_regions")
		result_region_cout = len(result_regions)

		if result_region_cout <= 0:
			return

		if self.view.sel():
			selected_region = self.view.line(self.view.sel()[0].end())
			if selected_region in result_regions:
				selected_index = result_regions.index(selected_region)
				view_settings.set('selected_index', selected_index)

				self.view.add_regions('selected_region', [selected_region], "selected", "", sublime.DRAW_SOLID_UNDERLINE|sublime.DRAW_NO_FILL)
				self.view.show(selected_region)

				settings = Settings(self.view, "ReviewMyself")
				if view_settings.get("auto_show_context", settings.get("auto_show_context", True)):
					self.view.run_command("review_myself_goto", {"preview": True})

class ReviewMyselfSetAutoShowContext(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfToggleAutoShowContext"

	def run(self, edit, enable):
		view_settings = self.view.settings()
		view_settings.set("auto_show_context", enable)

		if enable:
			self.view.run_command("review_myself_goto", { "preview": True })
		else:
			self.view.run_command("review_myself_close_context_panel")

class ReviewMyselfCloseContextPanel(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfCloseContextView"

	def run(self, edit):
		self.view.window().run_command("set_layout", {
				"cols": [0.0, 1.0],
				"rows": [0.0, 1.0],
				"cells": [[0, 0, 1, 1]]
			})

class ReviewMyselfOpeningFilesCommand(sublime_plugin.TextCommand):
	TAG = "ReviewMyself.ReviewMyselfOpeningFilesCommand"

	def run(self, edit):
		active_window = self.view.window()
		opening_views = active_window.views()

		if not opening_views:
			Util.status("ReviewMyself: Not found any opening files")
			return

		paths_to_search = []
		for view in opening_views:
			file_name = view.file_name()
			if file_name:
				paths_to_search.append(file_name)

		self.view.run_command("review_myself_impl", { "paths": paths_to_search })


text:
import React, {Component} from 'react';
import {MAPBOX_STYLES, GITHUB_TREE} from '../constants/defaults';
import App from 'website-examples/3d-tiles/app';

import makeExample from '../components/example';

class Tiles3DDemo extends Component {
  static title = 'City of Melbourne 3D Point Cloud';

  static code = `${GITHUB_TREE}/examples/website/3d-tiles`;

  static parameters = {};

  static mapStyle = MAPBOX_STYLES.DARK;

  static renderInfo(meta) {
    if (!meta.attributions) {
      return null;
    }
    const {attributions} = meta;
    return (

          {Boolean(attributions.length) && Tileset Credentials}
          {attributions.map(attribution => (

          ))}

    );
  }

  _updateAttributions = (attributions) => {
    this.props.onStateChange({attributions});
  }

  render() {
    return <App {...this.props} updateAttributions={this._updateAttributions} />;
  }
}

export default makeExample(Tiles3DDemo);


text:
package app

import (
	"time"

	"github.com/uber/tchannel-go"
	"go.uber.org/zap"

	"github.com/jaegertracing/jaeger/model"
	"github.com/jaegertracing/jaeger/storage/spanstore"

	"github.com/jaegertracing/jaeger/cmd/collector/app/sanitizer"
	"github.com/jaegertracing/jaeger/pkg/queue"
)

type spanProcessor struct {
	queue           *queue.BoundedQueue
	metrics         *SpanProcessorMetrics
	preProcessSpans ProcessSpans
	filterSpan      FilterSpan             // filter is called before the sanitizer but after preProcessSpans
	sanitizer       sanitizer.SanitizeSpan // sanitizer is called before processSpan
	processSpan     ProcessSpan
	logger          *zap.Logger
	spanWriter      spanstore.Writer
	reportBusy      bool
	numWorkers      int
}

type queueItem struct {
	queuedTime time.Time
	span       *model.Span
}

// NewSpanProcessor returns a SpanProcessor that preProcesses, filters, queues, sanitizes, and processes spans
func NewSpanProcessor(
	spanWriter spanstore.Writer,
	opts ...Option,
) SpanProcessor {
	sp := newSpanProcessor(spanWriter, opts...)

	sp.queue.StartConsumers(sp.numWorkers, func(item interface{}) {
		value := item.(*queueItem)
		sp.processItemFromQueue(value)
	})

	sp.queue.StartLengthReporting(1*time.Second, sp.metrics.QueueLength)

	return sp
}

func newSpanProcessor(spanWriter spanstore.Writer, opts ...Option) *spanProcessor {
	options := Options.apply(opts...)
	handlerMetrics := NewSpanProcessorMetrics(
		options.serviceMetrics,
		options.hostMetrics,
		options.extraFormatTypes)
	droppedItemHandler := func(item interface{}) {
		handlerMetrics.SpansDropped.Inc(1)
	}
	boundedQueue := queue.NewBoundedQueue(options.queueSize, droppedItemHandler)

	sp := spanProcessor{
		queue:           boundedQueue,
		metrics:         handlerMetrics,
		logger:          options.logger,
		preProcessSpans: options.preProcessSpans,
		filterSpan:      options.spanFilter,
		sanitizer:       options.sanitizer,
		reportBusy:      options.reportBusy,
		numWorkers:      options.numWorkers,
		spanWriter:      spanWriter,
	}
	sp.processSpan = ChainedProcessSpan(
		options.preSave,
		sp.saveSpan,
	)

	return &sp
}

// Stop halts the span processor and all its go-routines.
func (sp *spanProcessor) Stop() {
	sp.queue.Stop()
}

func (sp *spanProcessor) saveSpan(span *model.Span) {
	startTime := time.Now()
	if err := sp.spanWriter.WriteSpan(span); err != nil {
		sp.logger.Error("Failed to save span", zap.Error(err))
	} else {
		sp.metrics.SavedBySvc.ReportServiceNameForSpan(span)
	}
	sp.metrics.SaveLatency.Record(time.Now().Sub(startTime))
}

func (sp *spanProcessor) ProcessSpans(mSpans []*model.Span, spanFormat string) ([]bool, error) {
	sp.preProcessSpans(mSpans)
	sp.metrics.GetCountsForFormat(spanFormat).Received.Inc(int64(len(mSpans)))
	sp.metrics.BatchSize.Update(int64(len(mSpans)))
	retMe := make([]bool, len(mSpans))
	for i, mSpan := range mSpans {
		ok := sp.enqueueSpan(mSpan, spanFormat)
		if !ok && sp.reportBusy {
			return nil, tchannel.ErrServerBusy
		}
		retMe[i] = ok
	}
	return retMe, nil
}

func (sp *spanProcessor) processItemFromQueue(item *queueItem) {
	sp.processSpan(sp.sanitizer(item.span))
	sp.metrics.InQueueLatency.Record(time.Now().Sub(item.queuedTime))
}

func (sp *spanProcessor) enqueueSpan(span *model.Span, originalFormat string) bool {
	spanCounts := sp.metrics.GetCountsForFormat(originalFormat)
	spanCounts.ReceivedBySvc.ReportServiceNameForSpan(span)

	if !sp.filterSpan(span) {
		spanCounts.Rejected.Inc(int64(1))
		return true // as in "not dropped", because it's actively rejected
	}
	item := &queueItem{
		queuedTime: time.Now(),
		span:       span,
	}
	addedToQueue := sp.queue.Produce(item)
	if !addedToQueue {
		sp.metrics.ErrorBusy.Inc(1)
	}
	return addedToQueue
}


text:
class CreatePins < ActiveRecord::Migration
  def change
    create_table :pins do |t|
      t.string :title
      t.text :description

      t.timestamps null: false
    end
  end
end


text:
<?php echo _l('client_add_edit_profile'); ?>

    <?php echo form_open($this->uri->uri_string(),array('class'=>'client-form','autocomplete'=>'off')); ?>

                    <?php echo _l( 'customer_profile_details'); ?>

                    <?php echo _l( 'billing_shipping'); ?>

            <?php if(isset($client)){ ?>

                    <?php echo _l( 'customer_contacts'); ?>

                    <?php echo _l( 'customer_admins'); ?>

            <?php } ?>

                <?php if(!isset($client) || isset($client) && !is_empty_customer_company($client->userid)) { ?>

                           <input type="checkbox" name="show_primary_contact"<?php if(isset($client) && $client->show_primary_contact == 1){echo ' checked';}?> value="1" id="show_primary_contact">
                           <?php echo _l('show_primary_contact',_l('invoices').', '._l('estimates').', '._l('payments')); ?>

                   <?php } ?>

                    <?php
                    $value=( isset($client) ? $client->company : ''); ?>
                    <?php $attrs = (isset($client) ? array() : array('autofocus'=>true)); ?>
                    <?php echo render_input( 'company', 'client_company',$value,'text',$attrs); ?>
                    <?php $value=( isset($client) ? $client->phonenumber : ''); ?>
                    <?php echo render_input( 'phonenumber', 'client_phonenumber',$value); ?>
                    <?php
                    if(get_option('company_requires_vat_number_field') == 1){
                        $value=( isset($client) ? $client->vat : '');
                        echo render_input( 'vat', 'client_vat_number',$value);
                    }
                    $s_attrs = array('data-none-selected-text'=>_l('system_default_string'));
                    $selected = '';
                    if(isset($client) && client_have_transactions($client->userid)){
                      $s_attrs['disabled'] = true;
                  }
                  foreach($currencies as $currency){
                    if(isset($client)){
                      if($currency['id'] == $client->default_currency){
                        $selected = $currency['id'];
                    }
                }
            }
            ?>
            <?php if(!isset($client)){ ?>
            <i class="fa fa-question-circle" data-toggle="tooltip" data-title="<?php echo _l('customer_currency_change_notice'); ?>">
            <?php } ?>
            <?php echo render_select('default_currency',$currencies,array('id','name','symbol'),'invoice_add_edit_currency',$selected,$s_attrs); ?>

                <?php echo _l('localization_default_language'); ?>

                <select name="default_language" id="default_language" class="form-control selectpicker" data-none-selected-text="<?php echo _l('dropdown_non_selected_tex'); ?>">
                    <option value=""><?php echo _l('system_default_string'); ?></option>
                    <?php foreach(list_folders(APPPATH .'language') as $language){
                        $selected = '';
                        if(isset($client)){
                           if($client->default_language == $language){
                              $selected = 'selected';
                          }
                      }
                      ?>
                      <option value="<?php echo $language; ?>" <?php echo $selected; ?>><?php echo ucfirst($language); ?></option>
                      <?php } ?>
                  </select>

              <a href="#" class="pull-left mright5" onclick="fetch_lat_long_from_google_cprofile(); return false;" data-toggle="tooltip" data-title="<?php echo _l('fetch_from_google') . ' - ' . _l('customer_fetch_lat_lng_usage'); ?>">
              <?php $value=( isset($client) ? $client->latitude : ''); ?>
              <?php echo render_input( 'latitude', 'customer_latitude',$value); ?>
              <?php $value=( isset($client) ? $client->longitude : ''); ?>
              <?php echo render_input( 'longitude', 'customer_longitude',$value); ?>

            <?php $value=( isset($client) ? $client->address : ''); ?>
            <?php echo render_input( 'address', 'client_address',$value); ?>
            <?php $value=( isset($client) ? $client->city : ''); ?>
            <?php echo render_input( 'city', 'client_city',$value); ?>
            <?php $value=( isset($client) ? $client->state : ''); ?>
            <?php echo render_input( 'state', 'client_state',$value); ?>
            <?php $value=( isset($client) ? $client->zip : ''); ?>
            <?php echo render_input( 'zip', 'client_postal_code',$value); ?>
            <?php $countries= get_all_countries();
            $customer_default_country = get_option('customer_default_country');
            $selected =( isset($client) ? $client->country : $customer_default_country);
            echo render_select( 'country',$countries,array( 'country_id',array( 'short_name')), 'clients_country',$selected,array('data-none-selected-text'=>_l('dropdown_non_selected_tex')));
            ?>
            <?php $value=( isset($client) ? $client->website : ''); ?>
            <?php echo render_input( 'website', 'client_website',$value); ?>
            <?php
            $selected = array();
            if(isset($customer_groups)){
                foreach($customer_groups as $group){
                   array_push($selected,$group['groupid']);
               }
           }
           echo render_select('groups_in[]',$groups,array('id','name'),'customer_groups',$selected,array('multiple'=>true),array(),'','',false);
           ?>

        <?php $rel_id=( isset($client) ? $client->userid : false); ?>
        <?php echo render_custom_fields( 'customers',$rel_id); ?>

<?php if(isset($client)){ ?>

    <?php if(has_permission('customers','','create') || is_customer_admin($client->userid)){
        $disable_new_contacts = false;
        if(is_empty_customer_company($client->userid) && total_rows('tblcontacts',array('userid'=>$client->userid)) == 1){
           $disable_new_contacts = true;
       }
       ?>
       <div class="inline-block"<?php if($disable_new_contacts){ ?> data-toggle="tooltip" data-title="<?php echo _l('customer_contact_person_only_one_allowed'); ?>"<?php } ?>>
        <a href="#" onclick="contact(<?php echo $client->userid; ?>); return false;" class="btn btn-info mbot25<?php if($disable_new_contacts){echo ' disabled';} ?>"><?php echo _l('new_contact'); ?>

    <?php } ?>
    <?php
    $table_data = array(_l('client_firstname'),_l('client_lastname'),_l('client_email'),_l('contact_position'),_l('client_phonenumber'),_l('contact_active'),_l('clients_list_last_login'));
    $custom_fields = get_custom_fields('contacts',array('show_on_table'=>1));
    foreach($custom_fields as $field){
       array_push($table_data,$field['name']);
   }
   array_push($table_data,_l('options'));
   echo render_datatable($table_data,'contacts'); ?>

    <?php if (has_permission('customers', '', 'create') || has_permission('customers', '', 'edit')) { ?>
    <?php echo _l('assign_admin'); ?>
    <?php } ?>

                <?php echo _l('staff_member'); ?>
                <?php echo _l('customer_admin_date_assigned'); ?>
                <?php if(has_permission('customers','','create') || has_permission('customers','','edit')){ ?>
                <?php echo _l('options'); ?>
                <?php } ?>

            <?php foreach($customer_admins as $c_admin){ ?>

                <a href="<?php echo admin_url('profile/'.$c_admin['staff_id']); ?>">
                    <?php echo staff_profile_image($c_admin['staff_id'], array(
                        'staff-profile-image-small',
                        'mright5'
                        ));
                        echo get_staff_full_name($c_admin['staff_id']); ?>

                    <td data-order="<?php echo $c_admin['date_assigned']; ?>"><?php echo _dt($c_admin['date_assigned']); ?>
                    <?php if(has_permission('customers','','create') || has_permission('customers','','edit')){ ?>

                        <a href="<?php echo admin_url('clients/delete_customer_admin/'.$client->userid.'/'.$c_admin['staff_id']); ?>" class="btn btn-danger _delete btn-icon">

                    <?php } ?>

                <?php } ?>

    <?php } ?>

<?php echo _l('billing_address'); ?> <?php echo _l('customer_billing_same_as_profile'); ?>

                        <?php $value=( isset($client) ? $client->billing_street : ''); ?>
                        <?php echo render_input( 'billing_street', 'billing_street',$value); ?>
                        <?php $value=( isset($client) ? $client->billing_city : ''); ?>
                        <?php echo render_input( 'billing_city', 'billing_city',$value); ?>
                        <?php $value=( isset($client) ? $client->billing_state : ''); ?>
                        <?php echo render_input( 'billing_state', 'billing_state',$value); ?>
                        <?php $value=( isset($client) ? $client->billing_zip : ''); ?>
                        <?php echo render_input( 'billing_zip', 'billing_zip',$value); ?>
                        <?php $selected=( isset($client) ? $client->billing_country : '' ); ?>
                        <?php echo render_select( 'billing_country',$countries,array( 'country_id',array( 'short_name')), 'billing_country',$selected,array('data-none-selected-text'=>_l('dropdown_non_selected_tex'))); ?>

                            <i class="fa fa-question-circle" data-toggle="tooltip" data-title="<?php echo _l('customer_shipping_address_notice'); ?>">
                            <?php echo _l('shipping_address'); ?> <?php echo _l('customer_billing_copy'); ?>

                            <?php $value=( isset($client) ? $client->shipping_street : ''); ?>
                            <?php echo render_input( 'shipping_street', 'shipping_street',$value); ?>
                            <?php $value=( isset($client) ? $client->shipping_city : ''); ?>
                            <?php echo render_input( 'shipping_city', 'shipping_city',$value); ?>
                            <?php $value=( isset($client) ? $client->shipping_state : ''); ?>
                            <?php echo render_input( 'shipping_state', 'shipping_state',$value); ?>
                            <?php $value=( isset($client) ? $client->shipping_zip : ''); ?>
                            <?php echo render_input( 'shipping_zip', 'shipping_zip',$value); ?>
                            <?php $selected=( isset($client) ? $client->shipping_country : $customer_default_country ); ?>
                            <?php echo render_select( 'shipping_country',$countries,array( 'country_id',array( 'short_name')), 'shipping_country',$selected,array('data-none-selected-text'=>_l('dropdown_non_selected_tex'))); ?>

                        <?php if(isset($client) &&
                        (total_rows('tblinvoices',array('clientid'=>$client->userid)) > 0 || total_rows('tblestimates',array('clientid'=>$client->userid)) > 0)){ ?>

                                    <input type="checkbox" name="update_all_other_transactions" id="update_all_other_transactions">

                                        <?php echo _l('customer_update_address_info_on_invoices'); ?>

                                <?php echo _l('customer_update_address_info_on_invoices_help'); ?>

                        <?php } ?>

        <button class="btn btn-info mtop20 only-save customer-form-submiter">
            <?php echo _l( 'submit'); ?>
        </button>
        <?php if(!isset($client)){ ?>
        <button class="btn btn-info mtop20 save-and-add-contact customer-form-submiter">
            <?php echo _l( 'save_customer_and_add_contact'); ?>
        </button>
        <?php } ?>

<?php echo form_close(); ?>

<?php if(isset($client)){ ?>
<?php if (has_permission('customers', '', 'create') || has_permission('customers', '', 'edit')) { ?>

        <?php echo form_open(admin_url('clients/assign_admins/'.$client->userid)); ?>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

<?php echo _l('assign_admin'); ?>

                <?php
                $selected = array();
                foreach($customer_admins as $c_admin){
                   array_push($selected,$c_admin['staff_id']);
               }
               echo render_select('customer_admins[]',$staff,array('staffid',array('firstname','lastname')),'',$selected,array('multiple'=>true),array(),'','',false); ?>

            <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo _l('close'); ?></button>
            <button type="submit" class="btn btn-info"><?php echo _l('submit'); ?></button>

    <?php echo form_close(); ?>

<?php } ?>
<?php } ?>