text:
// Header page:
//
// For minimum allocation size (8 bytes), bitmap can store used allocations for
// up to 4032*8*8=258048, which is 256KiB minus the header page

#include <assert.h>
#include <stdlib.h>

#include <sys/cdefs.h>
#include <sys/mman.h>

#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>

#include "android-base/macros.h"

#include "anon_vma_naming.h"
#include "Allocator.h"
#include "LinkedList.h"

// runtime interfaces used:
// abort
// assert - fprintf + mmap
// mmap
// munmap
// prctl

constexpr size_t const_log2(size_t n, size_t p = 0) {
  return (n <= 1) ? p : const_log2(n / 2, p + 1);
}

constexpr unsigned int div_round_up(unsigned int x, unsigned int y) {
  return (x + y - 1) / y;
}

static constexpr size_t kPageSize = 4096;
static constexpr size_t kChunkSize = 256 * 1024;
static constexpr size_t kUsableChunkSize = kChunkSize - kPageSize;
static constexpr size_t kMaxBucketAllocationSize = kChunkSize / 4;
static constexpr size_t kMinBucketAllocationSize = 8;
static constexpr unsigned int kNumBuckets = const_log2(kMaxBucketAllocationSize)
    - const_log2(kMinBucketAllocationSize) + 1;
static constexpr unsigned int kUsablePagesPerChunk = kUsableChunkSize
    / kPageSize;

std::atomic<int> heap_count;

class Chunk;

class HeapImpl {
 public:
  HeapImpl();
  ~HeapImpl();
  void* operator new(std::size_t count) noexcept;
  void operator delete(void* ptr);

  void* Alloc(size_t size);
  void Free(void* ptr);
  bool Empty();

  void MoveToFullList(Chunk* chunk, int bucket_);
  void MoveToFreeList(Chunk* chunk, int bucket_);

 private:
  DISALLOW_COPY_AND_ASSIGN(HeapImpl);

  LinkedList<Chunk*> free_chunks_[kNumBuckets];
  LinkedList<Chunk*> full_chunks_[kNumBuckets];

  void MoveToList(Chunk* chunk, LinkedList<Chunk*>* head);
  void* MapAlloc(size_t size);
  void MapFree(void* ptr);
  void* AllocLocked(size_t size);
  void FreeLocked(void* ptr);

  struct MapAllocation {
    void *ptr;
    size_t size;
    MapAllocation* next;
  };
  MapAllocation* map_allocation_list_;
  std::mutex m_;
};

// Integer log 2, rounds down
static inline unsigned int log2(size_t n) {
  return 8 * sizeof(unsigned long long) - __builtin_clzll(n) - 1;
}

static inline unsigned int size_to_bucket(size_t size) {
  if (size < kMinBucketAllocationSize)
    return kMinBucketAllocationSize;
  return log2(size - 1) + 1 - const_log2(kMinBucketAllocationSize);
}

static inline size_t bucket_to_size(unsigned int bucket) {
  return kMinBucketAllocationSize << bucket;
}

static void* MapAligned(size_t size, size_t align) {
  const int prot = PROT_READ | PROT_WRITE;
  const int flags = MAP_ANONYMOUS | MAP_PRIVATE;

  size = (size + kPageSize - 1) & ~(kPageSize - 1);

  // Over-allocate enough to align
  size_t map_size = size + align - kPageSize;
  if (map_size < size) {
    return nullptr;
  }

  void* ptr = mmap(NULL, map_size, prot, flags, -1, 0);
  if (ptr == MAP_FAILED) {
    return nullptr;
  }

  size_t aligned_size = map_size;
  void* aligned_ptr = ptr;

  std::align(align, size, aligned_ptr, aligned_size);

  // Trim beginning
  if (aligned_ptr != ptr) {
    ptrdiff_t extra = reinterpret_cast<uintptr_t>(aligned_ptr)
        - reinterpret_cast<uintptr_t>(ptr);
    munmap(ptr, extra);
    map_size -= extra;
    ptr = aligned_ptr;
  }

  // Trim end
  if (map_size != size) {
    assert(map_size > size);
    assert(ptr != NULL);
    munmap(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(ptr) + size),
        map_size - size);
  }

#define PR_SET_VMA   0x53564d41
#define PR_SET_VMA_ANON_NAME    0
  prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
      reinterpret_cast<uintptr_t>(ptr), size, "leak_detector_malloc");

  return ptr;
}

class Chunk {
 public:
  static void* operator new(std::size_t count) noexcept;
  static void operator delete(void* ptr);
  Chunk(HeapImpl* heap, int bucket);
  ~Chunk() {}

  void *Alloc();
  void Free(void* ptr);
  void Purge();
  bool Empty();

  static Chunk* ptr_to_chunk(void* ptr) {
    return reinterpret_cast<Chunk*>(reinterpret_cast<uintptr_t>(ptr)
        & ~(kChunkSize - 1));
  }
  static bool is_chunk(void* ptr) {
    return (reinterpret_cast<uintptr_t>(ptr) & (kChunkSize - 1)) != 0;
  }

  unsigned int free_count() {
    return free_count_;
  }
  HeapImpl* heap() {
    return heap_;
  }
  LinkedList<Chunk*> node_; // linked list sorted by minimum free count

 private:
  DISALLOW_COPY_AND_ASSIGN(Chunk);
  HeapImpl* heap_;
  unsigned int bucket_;
  unsigned int allocation_size_; // size of allocations in chunk, min 8 bytes
  unsigned int max_allocations_; // maximum number of allocations in the chunk
  unsigned int first_free_bitmap_; // index into bitmap for first non-full entry
  unsigned int free_count_; // number of available allocations
  unsigned int frees_since_purge_; // number of calls to Free since last Purge

  // bitmap of pages that have been dirtied
  uint32_t dirty_pages_[div_round_up(kUsablePagesPerChunk, 32)];

  // bitmap of free allocations.
  uint32_t free_bitmap_[kUsableChunkSize / kMinBucketAllocationSize / 32];

  char data_[0];

  unsigned int ptr_to_n(void* ptr) {
    ptrdiff_t offset = reinterpret_cast<uintptr_t>(ptr)
        - reinterpret_cast<uintptr_t>(data_);
    return offset / allocation_size_;
  }
  void* n_to_ptr(unsigned int n) {
    return data_ + n * allocation_size_;
  }
};
static_assert(sizeof(Chunk) <= kPageSize, "header must fit in page");

// Override new operator on chunk to use mmap to allocate kChunkSize
void* Chunk::operator new(std::size_t count __attribute__((unused))) noexcept {
  assert(count == sizeof(Chunk));
  void* mem = MapAligned(kChunkSize, kChunkSize);
  if (!mem) {
    abort(); //throw std::bad_alloc;
  }

  return mem;
}

// Override new operator on chunk to use mmap to allocate kChunkSize
void Chunk::operator delete(void *ptr) {
  assert(reinterpret_cast<Chunk*>(ptr) == ptr_to_chunk(ptr));
  munmap(ptr, kChunkSize);
}

Chunk::Chunk(HeapImpl* heap, int bucket) :
    node_(this), heap_(heap), bucket_(bucket), allocation_size_(
        bucket_to_size(bucket)), max_allocations_(
        kUsableChunkSize / allocation_size_), first_free_bitmap_(0), free_count_(
        max_allocations_), frees_since_purge_(0) {
  memset(dirty_pages_, 0, sizeof(dirty_pages_));
  memset(free_bitmap_, 0xff, sizeof(free_bitmap_));
}

bool Chunk::Empty() {
  return free_count_ == max_allocations_;
}

void* Chunk::Alloc() {
  assert(free_count_ > 0);

  unsigned int i = first_free_bitmap_;
  while (free_bitmap_[i] == 0)
    i++;
  assert(i < arraysize(free_bitmap_));
  unsigned int bit = __builtin_ffs(free_bitmap_[i]) - 1;
  assert(free_bitmap_[i] & (1U << bit));
  free_bitmap_[i] &= ~(1U << bit);
  unsigned int n = i * 32 + bit;
  assert(n < max_allocations_);

  unsigned int page = n * allocation_size_ / kPageSize;
  assert(page / 32 < arraysize(dirty_pages_));
  dirty_pages_[page / 32] |= 1U << (page % 32);

  free_count_--;
  if (free_count_ == 0) {
    heap_->MoveToFullList(this, bucket_);
  }

  return n_to_ptr(n);
}

void Chunk::Free(void* ptr) {
  assert(is_chunk(ptr));
  assert(ptr_to_chunk(ptr) == this);

  unsigned int n = ptr_to_n(ptr);
  unsigned int i = n / 32;
  unsigned int bit = n % 32;

  assert(i < arraysize(free_bitmap_));
  assert(!(free_bitmap_[i] & (1U << bit)));
  free_bitmap_[i] |= 1U << bit;
  free_count_++;

  if (i < first_free_bitmap_) {
    first_free_bitmap_ = i;
  }

  if (free_count_ == 1) {
    heap_->MoveToFreeList(this, bucket_);
  } else {
    // TODO(ccross): move down free list if necessary
  }

  if (frees_since_purge_++ * allocation_size_ > 16 * kPageSize) {
    Purge();
  }
}

void Chunk::Purge() {
  frees_since_purge_ = 0;

  //unsigned int allocsPerPage = kPageSize / allocation_size_;
}

// Override new operator on HeapImpl to use mmap to allocate a page
void* HeapImpl::operator new(std::size_t count __attribute__((unused)))
    noexcept {
  assert(count == sizeof(HeapImpl));
  void* mem = MapAligned(kPageSize, kPageSize);
  if (!mem) {
    abort(); //throw std::bad_alloc;
  }

  heap_count++;
  return mem;
}

void HeapImpl::operator delete(void *ptr) {
  munmap(ptr, kPageSize);
}

HeapImpl::HeapImpl() :
    free_chunks_(), full_chunks_(), map_allocation_list_(NULL) {
}

bool HeapImpl::Empty() {
  for (unsigned int i = 0; i < kNumBuckets; i++) {
    for (LinkedList<Chunk*> *it = free_chunks_[i].next(); it->data() != NULL; it = it->next()) {
      if (!it->data()->Empty()) {
        return false;
      }
    }
    for (LinkedList<Chunk*> *it = full_chunks_[i].next(); it->data() != NULL; it = it->next()) {
      if (!it->data()->Empty()) {
        return false;
      }
    }
  }

  return true;
}

HeapImpl::~HeapImpl() {
  for (unsigned int i = 0; i < kNumBuckets; i++) {
    while (!free_chunks_[i].empty()) {
      Chunk *chunk = free_chunks_[i].next()->data();
      chunk->node_.remove();
      delete chunk;
    }
    while (!full_chunks_[i].empty()) {
      Chunk *chunk = full_chunks_[i].next()->data();
      chunk->node_.remove();
      delete chunk;
    }
  }
}

void* HeapImpl::Alloc(size_t size) {
  std::lock_guard<std::mutex> lk(m_);
  return AllocLocked(size);
}

void* HeapImpl::AllocLocked(size_t size) {
  if (size > kMaxBucketAllocationSize) {
    return MapAlloc(size);
  }
  int bucket = size_to_bucket(size);
  if (free_chunks_[bucket].empty()) {
    Chunk *chunk = new Chunk(this, bucket);
    free_chunks_[bucket].insert(chunk->node_);
  }
  return free_chunks_[bucket].next()->data()->Alloc();
}

void HeapImpl::Free(void *ptr) {
  std::lock_guard<std::mutex> lk(m_);
  FreeLocked(ptr);
}

void HeapImpl::FreeLocked(void *ptr) {
  if (!Chunk::is_chunk(ptr)) {
    HeapImpl::MapFree(ptr);
  } else {
    Chunk* chunk = Chunk::ptr_to_chunk(ptr);
    assert(chunk->heap() == this);
    chunk->Free(ptr);
  }
}

void* HeapImpl::MapAlloc(size_t size) {
  size = (size + kPageSize - 1) & ~(kPageSize - 1);

  MapAllocation* allocation = reinterpret_cast<MapAllocation*>(AllocLocked(
      sizeof(MapAllocation)));
  void* ptr = MapAligned(size, kChunkSize);
  if (!ptr) {
    FreeLocked(allocation);
    abort(); //throw std::bad_alloc;
  }
  allocation->ptr = ptr;
  allocation->size = size;
  allocation->next = map_allocation_list_;
  map_allocation_list_ = allocation;

  return ptr;
}

void HeapImpl::MapFree(void *ptr) {
  MapAllocation **allocation = &map_allocation_list_;
  while (*allocation && (*allocation)->ptr != ptr)
    allocation = &(*allocation)->next;

  assert(*allocation != nullptr);

  munmap((*allocation)->ptr, (*allocation)->size);
  FreeLocked(*allocation);

  *allocation = (*allocation)->next;
}

void HeapImpl::MoveToFreeList(Chunk *chunk, int bucket) {
  MoveToList(chunk, &free_chunks_[bucket]);
}

void HeapImpl::MoveToFullList(Chunk *chunk, int bucket) {
  MoveToList(chunk, &full_chunks_[bucket]);
}

void HeapImpl::MoveToList(Chunk *chunk, LinkedList<Chunk*>* head) {
  // Remove from old list
  chunk->node_.remove();

  LinkedList<Chunk*> *node = head;
  // Insert into new list, sorted by lowest free count
  while (node->next() != head && node->data() != nullptr
      && node->data()->free_count() < chunk->free_count())
    node = node->next();

  node->insert(chunk->node_);
}

Heap::Heap() {
  // HeapImpl overloads the operator new in order to mmap itself instead of
  // allocating with new.
  // Can't use a shared_ptr to store the result because shared_ptr needs to
  // allocate, and Allocator<T> is still being constructed.
  impl_ = new HeapImpl();
  owns_impl_ = true;
}

Heap::~Heap() {
  if (owns_impl_) {
    delete impl_;
  }
}

void* Heap::allocate(size_t size) {
  return impl_->Alloc(size);
}

void Heap::deallocate(void* ptr) {
  impl_->Free(ptr);
}

void Heap::deallocate(HeapImpl*impl, void* ptr) {
  impl->Free(ptr);
}

bool Heap::empty() {
  return impl_->Empty();
}


text:
package com.google.cloud.logging.spi.v2;

import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogMetricsPagedResponse;

import com.google.api.gax.grpc.ChannelAndExecutor;
import com.google.api.gax.grpc.UnaryCallable;
import com.google.api.gax.protobuf.PathTemplate;
import com.google.logging.v2.CreateLogMetricRequest;
import com.google.logging.v2.DeleteLogMetricRequest;
import com.google.logging.v2.GetLogMetricRequest;
import com.google.logging.v2.ListLogMetricsRequest;
import com.google.logging.v2.ListLogMetricsResponse;
import com.google.logging.v2.LogMetric;
import com.google.logging.v2.UpdateLogMetricRequest;
import com.google.protobuf.Empty;
import io.grpc.ManagedChannel;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

// AUTO-GENERATED DOCUMENTATION AND SERVICE
/**
 * Service Description: Service for configuring logs-based metrics.
 *
 *
This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 *

 *
 * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
 *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
 *   LogMetric response = metricsServiceV2Api.getLogMetric(formattedMetricName);
 * }
 *
 *

 *
 *
Note: close() needs to be called on the metricsServiceV2Api object to clean up resources such
 * as threads. In the example above, try-with-resources is used, which automatically calls close().
 *
 *
The surface of this class includes several types of Java methods for each of the API's
 * methods:
 *
 *

 *
 A "flattened" method. With this type of method, the fields of the request type have been
 *       converted into function parameters. It may be the case that not all fields are available as
 *       parameters, and not every API method will have a flattened method entry point.
 *
 A "request object" method. This type of method only takes one parameter, a request object,
 *       which must be constructed before the call. Not every API method will have a request object
 *       method.
 *
 A "callable" method. This type of method takes no parameters and returns an immutable API
 *       callable object, which can be used to initiate calls to the service.
 *

 *
 *
See the individual methods for example code.
 *
 *
Many parameters require resource names to be formatted in a particular way. To assist with
 * these names, this class includes a format method for each type of name, and additionally a parse
 * method to extract the individual identifiers contained within names that are returned.
 *
 *
This class can be customized by passing in a custom instance of MetricsServiceV2Settings to
 * create(). For example:
 *
 *

 *
 * InstantiatingChannelProvider channelProvider =
 *     MetricsServiceV2Settings.defaultChannelProviderBuilder()
 *         .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
 *         .build();
 * MetricsServiceV2Settings metricsServiceV2Settings =
 *     MetricsServiceV2Settings.defaultBuilder().setChannelProvider(channelProvider).build();
 * MetricsServiceV2Api metricsServiceV2Api =
 *     MetricsServiceV2Api.create(metricsServiceV2Settings);
 *
 *

 */
@javax.annotation.Generated("by GAPIC")
public class MetricsServiceV2Api implements AutoCloseable {
  private final MetricsServiceV2Settings settings;
  private final ScheduledExecutorService executor;
  private final ManagedChannel channel;
  private final List<AutoCloseable> closeables = new ArrayList<>();

  private final UnaryCallable<ListLogMetricsRequest, ListLogMetricsResponse> listLogMetricsCallable;
  private final UnaryCallable<ListLogMetricsRequest, ListLogMetricsPagedResponse>
      listLogMetricsPagedCallable;
  private final UnaryCallable<GetLogMetricRequest, LogMetric> getLogMetricCallable;
  private final UnaryCallable<CreateLogMetricRequest, LogMetric> createLogMetricCallable;
  private final UnaryCallable<UpdateLogMetricRequest, LogMetric> updateLogMetricCallable;
  private final UnaryCallable<DeleteLogMetricRequest, Empty> deleteLogMetricCallable;

  private static final PathTemplate PARENT_PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding("projects/{project}");

  private static final PathTemplate SINK_PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding("projects/{project}/sinks/{sink}");

  private static final PathTemplate METRIC_PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding("projects/{project}/metrics/{metric}");

  private static final PathTemplate LOG_PATH_TEMPLATE =
      PathTemplate.createWithoutUrlEncoding("projects/{project}/logs/{log}");

  /** Formats a string containing the fully-qualified path to represent a parent resource. */
  public static final String formatParentName(String project) {
    return PARENT_PATH_TEMPLATE.instantiate("project", project);
  }

  /** Formats a string containing the fully-qualified path to represent a sink resource. */
  public static final String formatSinkName(String project, String sink) {
    return SINK_PATH_TEMPLATE.instantiate(
        "project", project,
        "sink", sink);
  }

  /** Formats a string containing the fully-qualified path to represent a metric resource. */
  public static final String formatMetricName(String project, String metric) {
    return METRIC_PATH_TEMPLATE.instantiate(
        "project", project,
        "metric", metric);
  }

  /** Formats a string containing the fully-qualified path to represent a log resource. */
  public static final String formatLogName(String project, String log) {
    return LOG_PATH_TEMPLATE.instantiate(
        "project", project,
        "log", log);
  }

  /** Parses the project from the given fully-qualified path which represents a parent resource. */
  public static final String parseProjectFromParentName(String parentName) {
    return PARENT_PATH_TEMPLATE.parse(parentName).get("project");
  }

  /** Parses the project from the given fully-qualified path which represents a sink resource. */
  public static final String parseProjectFromSinkName(String sinkName) {
    return SINK_PATH_TEMPLATE.parse(sinkName).get("project");
  }

  /** Parses the sink from the given fully-qualified path which represents a sink resource. */
  public static final String parseSinkFromSinkName(String sinkName) {
    return SINK_PATH_TEMPLATE.parse(sinkName).get("sink");
  }

  /** Parses the project from the given fully-qualified path which represents a metric resource. */
  public static final String parseProjectFromMetricName(String metricName) {
    return METRIC_PATH_TEMPLATE.parse(metricName).get("project");
  }

  /** Parses the metric from the given fully-qualified path which represents a metric resource. */
  public static final String parseMetricFromMetricName(String metricName) {
    return METRIC_PATH_TEMPLATE.parse(metricName).get("metric");
  }

  /** Parses the project from the given fully-qualified path which represents a log resource. */
  public static final String parseProjectFromLogName(String logName) {
    return LOG_PATH_TEMPLATE.parse(logName).get("project");
  }

  /** Parses the log from the given fully-qualified path which represents a log resource. */
  public static final String parseLogFromLogName(String logName) {
    return LOG_PATH_TEMPLATE.parse(logName).get("log");
  }

  /** Constructs an instance of MetricsServiceV2Api with default settings. */
  public static final MetricsServiceV2Api create() throws IOException {
    return create(MetricsServiceV2Settings.defaultBuilder().build());
  }

  /**
   * Constructs an instance of MetricsServiceV2Api, using the given settings. The channels are
   * created based on the settings passed in, or defaults for any settings that are not set.
   */
  public static final MetricsServiceV2Api create(MetricsServiceV2Settings settings)
      throws IOException {
    return new MetricsServiceV2Api(settings);
  }

  /**
   * Constructs an instance of MetricsServiceV2Api, using the given settings. This is protected so
   * that it easy to make a subclass, but otherwise, the static factory methods should be preferred.
   */
  protected MetricsServiceV2Api(MetricsServiceV2Settings settings) throws IOException {
    this.settings = settings;
    ChannelAndExecutor channelAndExecutor = settings.getChannelAndExecutor();
    this.executor = channelAndExecutor.getExecutor();
    this.channel = channelAndExecutor.getChannel();

    this.listLogMetricsCallable =
        UnaryCallable.create(settings.listLogMetricsSettings(), this.channel, this.executor);
    this.listLogMetricsPagedCallable =
        UnaryCallable.createPagedVariant(
            settings.listLogMetricsSettings(), this.channel, this.executor);
    this.getLogMetricCallable =
        UnaryCallable.create(settings.getLogMetricSettings(), this.channel, this.executor);
    this.createLogMetricCallable =
        UnaryCallable.create(settings.createLogMetricSettings(), this.channel, this.executor);
    this.updateLogMetricCallable =
        UnaryCallable.create(settings.updateLogMetricSettings(), this.channel, this.executor);
    this.deleteLogMetricCallable =
        UnaryCallable.create(settings.deleteLogMetricSettings(), this.channel, this.executor);

    if (settings.getChannelProvider().shouldAutoClose()) {
      closeables.add(
          new Closeable() {
            @Override
            public void close() throws IOException {
              channel.shutdown();
            }
          });
    }
    if (settings.getExecutorProvider().shouldAutoClose()) {
      closeables.add(
          new Closeable() {
            @Override
            public void close() throws IOException {
              executor.shutdown();
            }
          });
    }
  }

  public final MetricsServiceV2Settings getSettings() {
    return settings;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Lists logs-based metrics.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   for (LogMetric element : metricsServiceV2Api.listLogMetrics(formattedParent).iterateAllElements()) {
   *     // doThingsWith(element);
   *   }
   * }
   *

   *
   * @param parent Required. The resource name containing the metrics. Example:
   *     `"projects/my-project-id"`.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final ListLogMetricsPagedResponse listLogMetrics(String parent) {
    PARENT_PATH_TEMPLATE.validate(parent, "listLogMetrics");
    ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(parent).build();
    return listLogMetrics(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Lists logs-based metrics.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder()
   *     .setParent(formattedParent)
   *     .build();
   *   for (LogMetric element : metricsServiceV2Api.listLogMetrics(request).iterateAllElements()) {
   *     // doThingsWith(element);
   *   }
   * }
   *

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final ListLogMetricsPagedResponse listLogMetrics(ListLogMetricsRequest request) {
    return listLogMetricsPagedCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Lists logs-based metrics.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder()
   *     .setParent(formattedParent)
   *     .build();
   *   ListenableFuture<ListLogMetricsPagedResponse> future = metricsServiceV2Api.listLogMetricsPagedCallable().futureCall(request);
   *   // Do something
   *   for (LogMetric element : future.get().iterateAllElements()) {
   *     // doThingsWith(element);
   *   }
   * }
   *

   */
  public final UnaryCallable<ListLogMetricsRequest, ListLogMetricsPagedResponse>
      listLogMetricsPagedCallable() {
    return listLogMetricsPagedCallable;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Lists logs-based metrics.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder()
   *     .setParent(formattedParent)
   *     .build();
   *   while (true) {
   *     ListLogMetricsResponse response = metricsServiceV2Api.listLogMetricsCallable().call(request);
   *     for (LogMetric element : response.getMetricsList()) {
   *       // doThingsWith(element);
   *     }
   *     String nextPageToken = response.getNextPageToken();
   *     if (!Strings.isNullOrEmpty(nextPageToken)) {
   *       request = request.toBuilder().setPageToken(nextPageToken).build();
   *     } else {
   *       break;
   *     }
   *   }
   * }
   *

   */
  public final UnaryCallable<ListLogMetricsRequest, ListLogMetricsResponse>
      listLogMetricsCallable() {
    return listLogMetricsCallable;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Gets a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   LogMetric response = metricsServiceV2Api.getLogMetric(formattedMetricName);
   * }
   *

   *
   * @param metricName The resource name of the desired metric. Example:
   *     `"projects/my-project-id/metrics/my-metric-id"`.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final LogMetric getLogMetric(String metricName) {
    METRIC_PATH_TEMPLATE.validate(metricName, "getLogMetric");
    GetLogMetricRequest request =
        GetLogMetricRequest.newBuilder().setMetricName(metricName).build();
    return getLogMetric(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Gets a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   GetLogMetricRequest request = GetLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .build();
   *   LogMetric response = metricsServiceV2Api.getLogMetric(request);
   * }
   *

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  private final LogMetric getLogMetric(GetLogMetricRequest request) {
    return getLogMetricCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Gets a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   GetLogMetricRequest request = GetLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .build();
   *   ListenableFuture<LogMetric> future = metricsServiceV2Api.getLogMetricCallable().futureCall(request);
   *   // Do something
   *   LogMetric response = future.get();
   * }
   *

   */
  public final UnaryCallable<GetLogMetricRequest, LogMetric> getLogMetricCallable() {
    return getLogMetricCallable;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   LogMetric response = metricsServiceV2Api.createLogMetric(formattedParent, metric);
   * }
   *

   *
   * @param parent The resource name of the project in which to create the metric. Example:
   *     `"projects/my-project-id"`.
   *
The new metric must be provided in the request.
   * @param metric The new logs-based metric, which must not have an identifier that already exists.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final LogMetric createLogMetric(String parent, LogMetric metric) {
    PARENT_PATH_TEMPLATE.validate(parent, "createLogMetric");
    CreateLogMetricRequest request =
        CreateLogMetricRequest.newBuilder().setParent(parent).setMetric(metric).build();
    return createLogMetric(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   CreateLogMetricRequest request = CreateLogMetricRequest.newBuilder()
   *     .setParent(formattedParent)
   *     .setMetric(metric)
   *     .build();
   *   LogMetric response = metricsServiceV2Api.createLogMetric(request);
   * }
   *

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final LogMetric createLogMetric(CreateLogMetricRequest request) {
    return createLogMetricCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   CreateLogMetricRequest request = CreateLogMetricRequest.newBuilder()
   *     .setParent(formattedParent)
   *     .setMetric(metric)
   *     .build();
   *   ListenableFuture<LogMetric> future = metricsServiceV2Api.createLogMetricCallable().futureCall(request);
   *   // Do something
   *   LogMetric response = future.get();
   * }
   *

   */
  public final UnaryCallable<CreateLogMetricRequest, LogMetric> createLogMetricCallable() {
    return createLogMetricCallable;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates or updates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   LogMetric response = metricsServiceV2Api.updateLogMetric(formattedMetricName, metric);
   * }
   *

   *
   * @param metricName The resource name of the metric to update. Example:
   *     `"projects/my-project-id/metrics/my-metric-id"`.
   *
The updated metric must be provided in the request and have the same identifier that is
   *     specified in `metricName`. If the metric does not exist, it is created.
   * @param metric The updated metric, whose name must be the same as the metric identifier in
   *     `metricName`. If `metricName` does not exist, then a new metric is created.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final LogMetric updateLogMetric(String metricName, LogMetric metric) {
    METRIC_PATH_TEMPLATE.validate(metricName, "updateLogMetric");
    UpdateLogMetricRequest request =
        UpdateLogMetricRequest.newBuilder().setMetricName(metricName).setMetric(metric).build();
    return updateLogMetric(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates or updates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   UpdateLogMetricRequest request = UpdateLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .setMetric(metric)
   *     .build();
   *   LogMetric response = metricsServiceV2Api.updateLogMetric(request);
   * }
   *

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final LogMetric updateLogMetric(UpdateLogMetricRequest request) {
    return updateLogMetricCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Creates or updates a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   LogMetric metric = LogMetric.newBuilder().build();
   *   UpdateLogMetricRequest request = UpdateLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .setMetric(metric)
   *     .build();
   *   ListenableFuture<LogMetric> future = metricsServiceV2Api.updateLogMetricCallable().futureCall(request);
   *   // Do something
   *   LogMetric response = future.get();
   * }
   *

   */
  public final UnaryCallable<UpdateLogMetricRequest, LogMetric> updateLogMetricCallable() {
    return updateLogMetricCallable;
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Deletes a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   metricsServiceV2Api.deleteLogMetric(formattedMetricName);
   * }
   *

   *
   * @param metricName The resource name of the metric to delete. Example:
   *     `"projects/my-project-id/metrics/my-metric-id"`.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  public final void deleteLogMetric(String metricName) {
    METRIC_PATH_TEMPLATE.validate(metricName, "deleteLogMetric");
    DeleteLogMetricRequest request =
        DeleteLogMetricRequest.newBuilder().setMetricName(metricName).build();
    deleteLogMetric(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Deletes a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   DeleteLogMetricRequest request = DeleteLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .build();
   *   metricsServiceV2Api.deleteLogMetric(request);
   * }
   *

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.grpc.ApiException if the remote call fails
   */
  private final void deleteLogMetric(DeleteLogMetricRequest request) {
    deleteLogMetricCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD
  /**
   * Deletes a logs-based metric.
   *
   *
Sample code:
   *
   *

   * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
   *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
   *   DeleteLogMetricRequest request = DeleteLogMetricRequest.newBuilder()
   *     .setMetricName(formattedMetricName)
   *     .build();
   *   ListenableFuture<Void> future = metricsServiceV2Api.deleteLogMetricCallable().futureCall(request);
   *   // Do something
   *   future.get();
   * }
   *

   */
  public final UnaryCallable<DeleteLogMetricRequest, Empty> deleteLogMetricCallable() {
    return deleteLogMetricCallable;
  }

  /**
   * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately
   * cancelled.
   */
  @Override
  public final void close() throws Exception {
    for (AutoCloseable closeable : closeables) {
      closeable.close();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
    echo $HTML->title_panel([
        'heading' => $Lang->get('Listing pages'),
        'button'  => [
                        'text' => $Lang->get('Add page'),
                        'link' => '/core/apps/content/page/add/',
                        'icon' => 'core/plus',
                        'priv' => 'content.pages.create',
                    ]
        ], $CurrentUser);

    $templates        = $Regions->get_templates_in_use();
    $template_options = [];
    if (PerchUtil::count($templates)) {
        foreach ($templates as $template) {
            if ($template['regionTemplate']!='') {
                $template_options[] = array(
                    'value' => $template['regionTemplate'],
                    'title' => $Regions->template_display_name($template['regionTemplate']),
                );
            }
        }
    }

    $Smartbar = new PerchSmartbar($CurrentUser, $HTML, $Lang);

        $Smartbar->add_item([
            'active' => $filter=='all',
            'title'  => 'All',
            'link'   => '/core/apps/content/'
        ]);

        $Smartbar->add_item([
            'active' => $filter=='new',
            'title'  => 'New',
            'link'   => '/core/apps/content/?filter=new'
        ]);

        $Smartbar->add_item([
            'id'      => 'rtf',
            'title'   => 'By Region Type',
            'icon'    => 'core/o-grid',
            'active'  => PerchRequest::get('template'),
            'type'    => 'filter',
            'arg'     => 'template',
            'options' => $template_options,
            'actions' => [

                    ],
            ]);

        $Smartbar->add_item([
            'title'    => 'Reorder Pages',
            'link'     => '/core/apps/content/reorder/',
            'priv'     => 'content.pages.reorder',
            'icon'     => 'core/menu',
            'position' => 'end',
        ]);

        $Smartbar->add_item([
            'title'    => 'Republish',
            'link'     => '/core/apps/content/republish/',
            'priv'     => 'content.pages.republish',
            'icon'     => 'core/documents',
            'position' => 'end',
        ]);

    echo $Smartbar->render();

    echo $HTML->open('div.inner');

    if (PerchUtil::count($pages) > 0) {
    ?>
    <table class="<?php echo ($do_list_collapse?' collapse':''); ?> nested-list" id="content-list">

                <?php echo PerchLang::get('Title'); ?>
                <?php echo PerchLang::get('Regions'); ?>

        <?php

            $icon_page          = PerchUI::icon('core/document', 16, PerchLang::get('Page')).' ';
            $icon_pages         = PerchUI::icon('core/documents', 16, PerchLang::get('Page')).' ';
            $icon_toggle_closed = PerchUI::icon('core/arrow-circle-right', 12, PerchLang::get('Subpages are not shown')).'';
            $icon_toggle_open   = PerchUI::icon('core/arrow-circle-down', 12, PerchLang::get('Subpages are shown')).'';

            $origin = ($Settings->get('content_skip_region_list')->val() ? 'f=pl' : 'f=x');

            foreach($pages as $Page) {

                $delete_link = 'id()) . '" class="button button-small action-alert inline-delete"  data-delete="confirm-cascade" data-msg="'.PerchUtil::html(PerchLang::get('Are you sure? This will delete the page, all the content belonging to the page, and any pages below this page.'), true).'">'.PerchLang::get('Delete').'';

                if ($Page->pagePath()=='*') {
                    $regions = $shared_regions;
                }else{
					$new_only = ($filter=='new'?true:false);
					$template = ($filter=='template'? $template_to_filter: false);

                    $regions = $Regions->get_for_page($Page->id(), $include_shared=false, $new_only, $template);
                }

                if (PerchUtil::count($regions)) {
                    $first_region_for_page = true;

                    // do we have drafts?
                    $page_has_drafts = false;
                    foreach($regions as $Region) {
                        if ($Region->has_draft()) {
                            $page_has_drafts = true;
                            break;
                        }
                    }

                    // Collapsed - no region rows
                    if ((!$do_regions || $do_list_collapse)  && ($Page->subpages() || PerchUtil::count($regions)>1)) {

                        echo '
';

                            $closed = ' closed';
                            $shared = false;

                            if ($Page->pagePath() == '*') $shared = true;

                            if (in_array($Page->id(), $expand_list)) {
                                $closed = false;
                            }

                            echo 'id().'" class="nested-level-'.((int)$Page->pageDepth()-1).' page'.$closed.($do_list_collapse?'':' notoggle').($page_has_drafts?' draft':'').'">';

                            $arg = ($closed ? 'ex' : 'cl');
                            if ($do_list_collapse && $Page->subpages()) echo 'id()).'" class="toggle">'.($closed ? $icon_toggle_closed : $icon_toggle_open).'';

                                echo '  id()).'">'. ($shared ? $icon_pages : $icon_page) .'' . PerchUtil::html($Page->pageNavText()) . '';

							 if ($CurrentUser->has_priv('content.pages.create') && $Page->role_may_create_subpages($CurrentUser) && $Page->pagePath()!='*') {
	                                echo ' id()).'" class="create-subitem">'.PerchUI::icon('core/plus', 8).' '.PerchLang::get('New subpage').'';
	                         }

								// Draft
                                if ($page_has_drafts) echo '';

                            echo ' 	';

                            // Region name / Edit link
                            echo '';
                                $new = false;
                                $count = 0;

								$arr_region_html = array();

                                foreach($regions as $Region) {

                                    if ($Region->role_may_view($CurrentUser, $Settings)) {

    									$region_html = '';

                                        $count++;

                                        // only show 20 items
                                        if ($count <= 20) {

                                            if ($Region->role_may_edit($CurrentUser)) {

                                                // New?
                                                if ($Region->regionNew()) {
                                                    $new = true;
                                                    $region_html .= ' '.PerchLang::get('New').' ';
                                                }

                                                $region_html .= 'id()) . '" class="edit">' . PerchUtil::html($Region->regionKey()) . '';
                                            }else{
                                                $region_html .= ''.PerchUtil::html($Region->regionKey()).'';
                                            }

                                        }

                                        if ($count===20) {
                                            $region_html .= '…';
                                        }

                                        if ($region_html!='') $arr_region_html[] = $region_html;
                                    }
                                }

								echo implode(', ', $arr_region_html);

                            echo '	';

                            // Preview
                            $button = '';
                            $button_count = 0;
                            if ($page_has_drafts && $Region->regionPage() != '*') {
                                $path = rtrim($Settings->get('siteURL')->val(), '/');
                                $button .= 'regionPage()).'?'.PERCH_PREVIEW_ARG.'=all" class="button button-small action-warning viewext">'.PerchLang::get('Preview').'';
                                $button_count++;
                            }

                            if ($Page->role_may_delete($CurrentUser)) {
                                $button .= $delete_link;
                                $button_count++;
                            }

                            if ($button != '') {
                                if ($button_count > 1) {
                                    echo '
'.$button.'
	';
                                } else {
                                    echo ''.$button.' 	';
                                }

                            } else {
                                echo '	';
                            }

                        echo '
';

                    }else{
                        // Expanded region

                        foreach($regions as $Region) {
                            echo '
';
                            if ($first_region_for_page) {

                                $closed = '';
                                $shared = false;

                                if ($Page->pagePath() == '*') $shared = true;

                                if ($do_list_collapse) {
                                    if (!in_array($Page->id(), $expand_list)) {
                                        $closed = ' closed';
                                    }
                                }

                                echo 'id().'" class="nested-level-'.((int)$Page->pageDepth()-1).' page'.$closed.($Page->pagePath()=='*'?' shared':'').($do_list_collapse?'':' notoggle').($page_has_drafts?' draft':'').'">';

                                if ($do_list_collapse && ($Page->subpages() || PerchUtil::count($regions)>1)) {
                                    $arg = ($closed ? 'ex' : 'cl');
                                    echo 'id()).'" class="toggle">+';
                                }

                                    echo '  id()).'">'. ($shared ? $icon_pages : $icon_page) .'' . PerchUtil::html($Page->pageNavText()) . '';

								if ($CurrentUser->has_priv('content.pages.create') && $Page->role_may_create_subpages($CurrentUser) && $Page->pagePath()!='*') {
                                    echo ' id()).'" class="create-subitem">'.PerchUI::icon('core/plus', 8).' '.PerchLang::get('New subpage').'';
                                }

                                     echo ' 	';
                            }else{
                                echo 'pageDepth()).'">-	';
                            }

                            // Region name / Edit link
                            echo '';

                                if ($Region->role_may_view($CurrentUser, $Settings)) {
                                    if ($Region->role_may_edit($CurrentUser)) {
                                        echo ($Region->regionNew() ? ' '.PerchLang::get('New').' ' : '');
                                        echo 'id()) . '" class="edit">' . PerchUtil::html($Region->regionKey()) . '';
                                    }else{
                                        echo ''.PerchUtil::html($Region->regionKey()).'';
                                    }

                                    // Draft
                                    if ($Region->has_draft()) echo '';

                                }

                            echo '	';

                            // Preview / delete
                            $button = '';
                            $button_count = 0;
                            if ($page_has_drafts &&  $Region->regionPage() != '*') {
                                $path = rtrim($Settings->get('siteURL')->val(), '/');
                                $button .= 'regionPage()).'?'.PERCH_PREVIEW_ARG.'=all" class="button button-small action-warning viewext">'.PerchLang::get('Preview').'';
                                $button_count++;
                            }

                            if ($Page->role_may_delete($CurrentUser)) {
                                $button .= $delete_link;
                                $button_count++;
                            }

                            if ($button != '') {
                                if ($button_count>1) {
                                    echo '
'.$button.'
	';
                                } else {
                                    echo ''.$button.' 	';
                                }

                            } else {
                                echo '	';
                            }

                            echo '
';
                            $first_region_for_page = false;
                        }

                    }

                }else{
                    // Page with no regions

                     echo '
';

						$closed = '';

                        if ($do_list_collapse) {
                            if (!in_array($Page->id(), $expand_list)) {
                                $closed = ' closed';
                            }
                        }

                        echo 'id().'" class="nested-level-'.((int)$Page->pageDepth()-1).($do_list_collapse?'':' notoggle').' page'.$closed.'">';

                            if ($do_list_collapse && $Page->subpages()) {
								$arg = ($closed ? 'ex' : 'cl');
                                echo 'id()).'" class="toggle icon">'.($closed ? $icon_toggle_closed : $icon_toggle_open).'';
                            }

	                       echo 'id()).'"> '.$icon_page.'' . PerchUtil::html($Page->pageNavText()) . '';

                           if ($CurrentUser->has_priv('content.pages.create') && $Page->role_may_create_subpages($CurrentUser) && $Page->pagePath()!='*') {
                                    echo ' id()).'" class="create-subitem">'.PerchUI::icon('core/plus', 8).' '.PerchLang::get('New subpage').'';
                            }

                        echo'	';
                        echo '	';

                        // Delete

                        if ($Page->role_may_delete($CurrentUser)) {
                            echo '';
                            echo $delete_link;
                            echo ' 	';
                        } else {
                            echo '	';
                        }

                    echo '
';
                }

            }
        ?>

    <?php
    }else{

        if ($filter == 'all') { ?>

<?php echo PerchLang::get('No content yet?'); ?> <?php echo PerchLang::get('Make sure you have added some editable regions into your page, and then visited that page in your browser. Once you have, the regions should show up here.'); ?>
                <?php echo PerchLang::get('Read the getting started guide to find out more'); ?>…

        <?php
            } else {
        ?>

<?php echo PerchLang::get('Sorry, there\'s currently no content available based on that filter'); ?> - <?php echo PerchLang::get('View all'); ?>

        <?php
            }

    }
    echo $HTML->close('div');


text:
[![CircleCI](https://circleci.com/gh/solidusio-contrib/solidus_subscriptions.svg?style=shield)](https://circleci.com/gh/solidusio-contrib/solidus_subscriptions)
[![codecov](https://codecov.io/gh/solidusio-contrib/solidus_subscriptions/branch/master/graph/badge.svg)](https://codecov.io/gh/solidusio-contrib/solidus_subscriptions)

A Solidus extension to add subscriptions to your store.

## Installation

Add solidus_subscriptions to your Gemfile:

```ruby
gem 'solidus_subscriptions', github: 'solidusio-contrib/solidus_subscriptions'
```

Bundle your dependencies and run the installation generator:

```shell
$ bundle
$ bin/rails generate solidus_subscriptions:install
```

### Guest checkout

Subscriptions require a user to be present to allow them to be managed after they are purchased.

Because of this, you must disable guest checkout for orders which contain `subscription_line_items`.

An example would be adding this to the registration page:

```erb
<%# spree/checkout/registration.html.erb %>
<% if Spree::Config[:allow_guest_checkout] && current_order.subscription_line_items.empty? %>
```

This allows guests to add subscriptions to their carts as guests, but forces them to login or create
an account before purchasing them.

## Usage

### Purchasing subscriptions

By default, only Spree::Variants can be subscribed to. To subscribe to a variant, it must have the
`subscribable` attribute set to true.

To subscribe to a variant, include the following parameters when posting to `/orders/populate`:

```json5
{
  // other add to cart params
  subscription_line_item: {
    quantity: 2,             // number of units in each subscription order
    subscribable_id: 1234,   // which variant the subscription is for
    interval_length: 1,      // time between subscription activations
    interval_units: "month", // plural qualifier for length (day/week/month/year)
    end_date: '2011/12/13'   // stop processing after this date (use null to process ad nauseam)
  }
}
```

This will associate a `SolidusSubscriptions::LineItem` to the line item being added to the cart.

The customer will not be charged for the subscription until it is processed. The subscription line
items should be shown to the user on the cart page by looping over
`Spree::Order#subscription_line_items`.

When the order is finalized, a `SolidusSubscriptions::Subscription` will be created for each group
of subscription line items which can be fulfilled by a single subscription.

#### Example

An order is finalized and has the following associated subscription line items:

1. `{ subscribable_id: 1, interval_length: 1, interval_units: "month" }`
2. `{ subscribable_id: 2, interval_length: 1, interval_units: "month" }`
3. `{ subscribable_id: 1, interval_length: 2, interval_units: "month" }`

This will generate 2 subscriptions: the first related to subscription line items 1 and 2, and the
second related to subscription line item 3.

### Processing subscriptions

To process actionable subscriptions simply run:

```bash
$ bundle exec rake solidus_subscriptions:process
```

The task creates ActiveJob jobs which can be fulfilled by your queue library of choice.

We suggest using the [Whenever](https://github.com/javan/whenever) gem to schedule the task.

### Promotion rules
This extensions adds the following [Promotion rules](https://guides.solidus.io/developers/promotions/promotion-rules.html):
* `SolidusSubscriptions::Promotion::Rules::SubscriptionCreationOrder` which applies if the order is creating a subscription;
* `SolidusSubscriptions::Promotion::Rules::SubscriptionInstallmentOrder` which applies if the order is an installment of a subscription.

### API documentation

You can find the API documentation [here](https://stoplight.io/p/docs/gh/solidusio-contrib/solidus_subscriptions?group=master).

### Churn Buster integration

This extension optionally integrates with [Churn Buster](https://churnbuster.io) for failed payment
recovery. In order to enable the integration, simply add your Churn Buster credentials to your
configuration:

```ruby
SolidusSubscriptions.configure do |config|
  # ...

  config.churn_buster_account_id = 'YOUR_CHURN_BUSTER_ACCOUNT_ID'
  config.churn_buster_api_key = 'YOUR_CHURN_BUSTER_API_KEY'
end
```

The extension will take care of reporting successful/failed payments and payment method changes
to Churn Buster.

### Failed installments retries

The extension generates an installment for each subscription cycle, however some of them can fail
(e.g. for an expired credit card). On each processor run the extension will try to complete all past
failed installments, however this is not always the desired behaviour.

If you want to process only the latest installment in each subscription, regardless of any number of
failed installments prior to that, you can configure the extension like so:

```ruby
SolidusSubscriptions.configure do |config|
  # ...

  config.clear_past_installments = true
end
```

### Minimum cancellation notice

The minimum cancellation notice is set to 0 days by default - users can cancel their subscription whenever they like. To change this, you can configure the extension like this:

```ruby
SolidusSubscriptions.configure do |config|
  # ...

  config.minimum_cancellation_notice = 10.days
end
```

### Subscription product deletion
When a product is soft deleted, its subscription line items need to be deleted as well, in order to avoid error on subscription processing.
If the product class is `Spree::Variant`, this corner case is handled automatically on the variant soft deletion, otherwise it should be handled manually.

## Development

### Testing the extension

First bundle your dependencies, then run `bin/rake`. `bin/rake` will default to building the dummy
app if it does not exist, then it will run specs. The dummy app can be regenerated by using
`bin/rake extension:test_app`.

```shell
bin/rake
```

To run [Rubocop](https://github.com/bbatsov/rubocop) static code analysis run

```shell
bundle exec rubocop
```

When testing your application's integration with this extension you may use its factories.
Simply add this require statement to your spec_helper:

```ruby
require 'solidus_subscriptions/factories'
```

### Running the sandbox

To run this extension in a sandboxed Solidus application, you can run `bin/sandbox`. The path for
the sandbox app is `./sandbox` and `bin/rails` will forward any Rails commands to
`sandbox/bin/rails`.

Here's an example:

```
$ bin/rails server
=> Booting Puma
=> Rails 6.0.2.1 application starting in development
* Listening on tcp://127.0.0.1:3000
Use Ctrl-C to stop
```

### Updating the changelog

Before and after releases the changelog should be updated to reflect the up-to-date status of
the project:

```shell
bin/rake changelog
git add CHANGELOG.md
git commit -m "Update the changelog"
```

### Releasing new versions

Your new extension version can be released using `gem-release` like this:

```shell
bundle exec gem bump -v 1.6.0
bin/rake changelog
git commit -a --amend
git push
bundle exec gem release
```

## License

Copyright (c) 2016 Stembolt, released under the New BSD License

Originally sponsored by [Goby](https://www.goby.co).


text:
<?php

namespace App;

use App\models\User;
use Illuminate\Database\Eloquent\Model;

class CourseJoinRequests extends Model
{
    public static function get_course_join_requests_by_user_id($id)
    {
        $requests = CourseJoinRequests::where('user_id', $id)->get();
        return $requests;
    }

    public static function get_course_join_requests_by_course_id($id)
    {
        $joinrequests = CourseJoinRequests::where('course_id', $id)->get();

        $iterator = 0;
        foreach($joinrequests as $request)
        {
            $joinrequests[$iterator]['theuser'] = User::get_user_by_id($request['user_id']);
            $iterator++;
        }
        return $joinrequests;

    }

    public static function get_course_join_request_by_id($id)
    {
        $course_request = CourseJoinRequests::find($id);
        return $course_request;
    }

    public static function add_new_course_join_request($data)
    {
        $theRequest = new CourseJoinRequests();
        $theRequest->user_id        = $data['user'];
        $theRequest->course_id = $data['course'];
        $theRequest->request_status = 'pending';
        $theRequest->save();
    }

    public static function update_course_join_request_status($id, $new_status)
    {
        $the_request = CourseJoinRequests::find($id);
        $the_request->request_status = $new_status;
        $the_request->save();
    }
}


text:
package eu.fbk.fm.alignments.utils.flink;

import org.apache.flink.api.java.io.TextOutputFormat;
import org.apache.flink.core.fs.FSDataOutputStream;
import org.apache.flink.core.fs.Path;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GzipTextOutputFormat<T> extends TextOutputFormat<T> {

    public GzipTextOutputFormat(Path outputPath) {
        super(outputPath);
    }

    public GzipTextOutputFormat(Path outputPath, String charset) {
        super(outputPath, charset);
    }

    @Override
    public void open(int taskNumber, int numTasks) throws IOException {
        super.open(taskNumber, numTasks);

        this.stream = new GZIPWrappedStream(this.stream, 4096, false);
    }

    @Override
    protected String getDirectoryFileName(int taskNumber) {
        return Integer.toString(taskNumber + 1)+".gz";
    }

    public static class GZIPWrappedStream extends FSDataOutputStream {

        private GZIPOutputStream stream;
        private FSDataOutputStream original;

        public GZIPWrappedStream(FSDataOutputStream original, int size, boolean syncFlush) throws IOException {
            this.stream = new GZIPOutputStream(original, size, syncFlush);
            this.original = original;
        }

        @Override
        public void write(final int b) throws IOException {
            this.stream.write(b);
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            this.stream.write(b, off, len);
        }

        @Override
        public void close() throws IOException {
            this.stream.close();
        }

        @Override
        public void flush() throws IOException {
            this.stream.flush();
        }

        @Override
        public void sync() throws IOException {
            this.original.sync();
        }

        @Override
        public long getPos() throws IOException {
            return this.original.getPos();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NExpect.Interfaces;
using NExpect.MatcherLogic;
using static NExpect.Implementations.MessageHelpers;
using static Imported.PeanutButter.Utils.PyLike;

// ReSharper disable MemberCanBePrivate.Global

namespace NExpect
{
    /// <summary>
    /// Provides testing for reference-checking items in two collections
    /// </summary>
    public static class CollectionItemReferenceMatchers
    {
        /// <summary>
        /// Performs reference-equality testing between two collections
        /// </summary>
        /// <param name="collectionItemsTo"></param>
        /// <param name="other"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IMore<IEnumerable<T>> Be<T>(
            this ICollectionItemsCanAddMatcher<T> collectionItemsTo,
            IEnumerable<T> other
        )
        {
            return collectionItemsTo.Be(
                other,
                NULL_STRING
            );
        }

        /// <summary>
        /// Performs reference-equality testing between two collections
        /// </summary>
        /// <param name="collectionItemsTo"></param>
        /// <param name="other"></param>
        /// <param name="customMessage"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IMore<IEnumerable<T>> Be<T>(
            this ICollectionItemsCanAddMatcher<T> collectionItemsTo,
            IEnumerable<T> other,
            string customMessage
        )
        {
            return collectionItemsTo.Be(
                other,
                () => customMessage
            );
        }

        /// <summary>
        /// Performs reference-equality testing between two collections
        /// </summary>
        /// <param name="collectionItemsTo"></param>
        /// <param name="other"></param>
        /// <param name="customMessageGenerator"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IMore<IEnumerable<T>> Be<T>(
            this ICollectionItemsCanAddMatcher<T> collectionItemsTo,
            IEnumerable<T> other,
            Func<string> customMessageGenerator
        )
        {
            return collectionItemsTo.AddMatcher(actual =>
            {
                if (actual is null || other is null)
                {
                    return new EnforcedMatcherResult(
                        false,
                        FinalMessageFor(
                            () => "Cannot perform item-wise reference checking when one or more collections is null",
                            customMessageGenerator
                        )
                    );
                }

                var actualArray = actual as T[] ?? actual.ToArray();
                var otherArray = other as T[] ?? other.ToArray();
                if (actualArray.Length != otherArray.Length)
                {
                    return new MatcherResult(
                        false,
                        FinalMessageFor(
                            () => $"Collection sizes do not match: {actualArray.Length} vs {otherArray.Length}",
                            customMessageGenerator
                        )
                    );
                }

                var passed = CollectionsAreItemWiseReferenceEqual(actualArray, otherArray);

                return new MatcherResult(
                    passed,
                    FinalMessageFor(
                        () =>
                            $"Expected\n{actualArray.Stringify()}\n{passed.AsNot()}to be item-wise reference-equal to\n{otherArray.Stringify()}",
                        customMessageGenerator
                    )
                );
            });
        }

        private static bool CollectionsAreItemWiseReferenceEqual<T>(
            T[] left,
            T[] right
        )
        {
            var result = true;
            foreach (var pair in Zip(left, right))
            {
                if (!ReferenceEquals(pair.Item1, pair.Item2))
                {
                    result = false;
                    break;
                }
            }

            return result;
        }
    }
}


text:
package keyloader

import (
	zmq "github.com/pebbe/zmq4"

	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func CheckPermissions(path string) error {
	if info, err := os.Stat(path); err == nil && info.Mode() != 0600 {
		return errors.New(fmt.Sprintf("Permissions on '%v' are '%o' but should be 600.", path, info.Mode()))
	}
	return nil
}

/*
 * Loads a zmq curve key pair from disk. If the requested pair cannot be found, a new pair that
 * matches the name is generated.
 */
func InitKeys(private_key_path string) (private_key string, public_key string, err error) {
	if !strings.HasSuffix(private_key_path, ".private") {
		return "", "", errors.New(fmt.Sprintf("Invalid private key path '%v'.", private_key_path))
	}
	if err = CheckPermissions(private_key_path); err != nil {
		return "", "", err
	}

	public_key_path := strings.TrimSuffix(private_key_path, ".private") + ".public"
	if err = CheckPermissions(public_key_path); err != nil {
		return "", "", err
	}
	CheckPermissions(public_key_path)
	private_key_buf, _ := ioutil.ReadFile(private_key_path)
	private_key = string(private_key_buf)
	public_key_buf, _ := ioutil.ReadFile(public_key_path)
	public_key = string(public_key_buf)

	if private_key != "" && public_key != "" {
		return private_key, public_key, nil
	} else if private_key == "" && public_key == "" {
		if public_key, private_key, err = zmq.NewCurveKeypair(); err != nil {
			return "", "", err
		}
		if err = ioutil.WriteFile(private_key_path, []byte(private_key), 0600); err != nil {
			return "", "", err
		}
		if err = ioutil.WriteFile(public_key_path, []byte(public_key), 0600); err != nil {
			return "", "", err
		}
	} else {
		return "", "", errors.New(fmt.Sprintf("Imbalanced key setup: '%v'", private_key_path))
	}

	return private_key, public_key, nil
}


text:
package com.ctrip.framework.apollo.portal.spi;

import com.ctrip.framework.apollo.portal.entity.bo.Email;

public interface EmailService {

  void send(Email email);

}


text:
# include <stdio.h>
# include "c_iraf.h"
# include "hstio.h"

# include "stis.h"
# include "stisvoltages.h"

/* Value to assign if keyword is not found. */
# define DEFAULT_VOLTAGE  (-9999.)

/* This routine gets voltages from the SCI extension header and compares with
   minimum values.  If any voltage is too low, a warning message will be
   printed.

   Phil Hodge, 1998 May 1:
	Function created.

   Phil Hodge, 2001, Aug 27:
	Move this file from cs0 to this directory.  Also, use getKeyD
	instead of Get_KeyD, and print a warning if any of the keywords
	is missing from the header.
*/

int CheckVolt (Hdr *hdr) {

/* argument:
Hdr *hdr         i: SCI extension header
*/

	int status;

	double abav, cdav;	/* amplifier bias voltages */
	double lgcdv;		/* last gate C & D voltage */
	double swalv;		/* summing wells */
	double rcdlv;		/* reset gate C & D low voltage */
	int low_voltage = 0;	/* was any voltage low? */

	/* Get the voltages. */
	status = getKeyD (hdr, "OCBABAV",&abav);
	if (status) {
	    printf ("Warning  Keyword OCBABAV not found.\n");
	    abav = DEFAULT_VOLTAGE;
	}
	status = getKeyD (hdr, "OCBCDAV",&cdav);
	if (status) {
	    printf ("Warning  Keyword OCBCDAV not found.\n");
	    cdav = DEFAULT_VOLTAGE;
	}
	status = getKeyD (hdr, "OCBLGCDV",&lgcdv);
	if (status) {
	    printf ("Warning  Keyword OCBLGCDV not found.\n");
	    lgcdv = DEFAULT_VOLTAGE;
	}
	status = getKeyD (hdr, "OCBSWALV",&swalv);
	if (status) {
	    printf ("Warning  Keyword OCBSWALV not found.\n");
	    swalv = DEFAULT_VOLTAGE;
	}
	status = getKeyD (hdr, "OCBRCDLV",&rcdlv);
	if (status) {
	    printf ("Warning  Keyword OCBRCDLV not found.\n");
	    rcdlv = DEFAULT_VOLTAGE;
	}

	/* Check the voltages against the minimum allowed values. */
	if (abav != DEFAULT_VOLTAGE && abav < MIN_OCBABAV) {
	    low_voltage = 1;
	    printf ("Warning  OCBABAV = %.6g\n", abav);
	}
	if (cdav != DEFAULT_VOLTAGE && cdav < MIN_OCBCDAV) {
	    low_voltage = 1;
	    printf ("Warning  OCBCDAV = %.6g\n", cdav);
	}
	if (lgcdv != DEFAULT_VOLTAGE && lgcdv < MIN_OCBLGCDV) {
	    low_voltage = 1;
	    printf ("Warning  OCBLGCDV = %.6g\n", lgcdv);
	}
	if (swalv != DEFAULT_VOLTAGE && swalv < MIN_OCBSWALV) {
	    low_voltage = 1;
	    printf ("Warning  OCBSWALV = %.6g\n", swalv);
	}
	if (rcdlv != DEFAULT_VOLTAGE && rcdlv < MIN_OCBRCDLV) {
	    low_voltage = 1;
	    printf ("Warning  OCBRCDLV = %.6g\n", rcdlv);
	}

	if (low_voltage) {
	    printf (
	"Warning  Data are likely to be corrupted; CCD settings indicate \\\n");
	    printf (
	"Warning  a cosmic ray induced CCD reset has occured, causing \\\n");
	    printf (
	"Warning  biases and clocking voltages to be incorrectly set.\n");
	}

	return (0);
}


text:
DOCUMENTATION = """
---
module: eos_ethernet
short_description: Manage physical Ethernet interfaces in EOS
description:
  - The eos_ethernet module manages the interface configuration for
    physical Ethernet interfaces on EOS nodes.
version_added: 1.0.0
category: Interfaces
author: Arista EOS+
requirements:
  - Arista EOS 4.13.7M or later with command API enabled
  - Python Client for eAPI 0.3.0 or later
notes:
  - All configuration is idempotent unless otherwise specified
  - Supports eos metaparameters for using the eAPI transport
  - Does not support stateful resource configuration.
options:
  name:
    description:
      - The unique interface identifier name.  The interface name must use
        the full interface name (no abbreviated names).  For example,
        interfaces should be specified as Ethernet1 not Et1
    required: true
    default: null
    choices: []
    aliases: []
    version_added: 1.0.0
  enable:
    description:
      - Configures the administrative state for the interface.  Setting
        the value to true will adminstrative enable the interface and
        setting the value to false will administratively disable the
        interface.  The EOS default value for enable is true
    required: false
    default: true
    choices: ['True', 'False']
    aliases: []
    version_added: 1.0.0
  description:
    description:
      - Configures a one lne ASCII description for the interface.  The EOS
        default value for description is None
    required: false
    default: null
    choices: []
    aliases: []
    version_added: 1.0.0
  sflow:
    description:
      - Configures the adminstrative state of running sflow on the named
        Ethernet interface.  If this value is true, then sflow is enabled
        on the interface and if this value is false, then sflow is disabled
        on this interface.  The EOS default value for sflow is true
    required: false
    default: null
    choices: []
    aliases: []
    version_added: 1.0.0
  flowcontrol_send:
    description:
      - Configures the flowcontrol send value for the named Ethernet
        interface in EOS.  If the value is configured true, then
        control send is enabled (on).  If the value is configured false
        then flowcontrol send is disabled (off).
    required: false
    default: null
    choices: ['True', 'False']
    aliases: []
    version_added: 1.0.0
  flowcontrol_receive:
    description:
      - Configures the flowcontrol receive value for the named Ethernet
        interface in EOS.  If the value is configured true, then
        control receive is enabled (on).  If the value is configured false
        then flowcontrol receive is disabled (off).
    required: false
    default: null
    choices: ['True', 'False']
    aliases: []
    version_added: 1.0.0
"""

EXAMPLES = """

- name: Ensure that Ethernet1/1 is administratively enabled
  eos_ethernet: name=Ethernet1/1 enable=yes

- name: Enable flowcontrol send and receive on Ethernet10
  eos_ethernet: name=Ethernet10 flowcontrol_send=yes flowcontrol_receive=yes

"""
#<<EOS_COMMON_MODULE_START>>

import syslog
import collections

from ansible.module_utils.basic import *

try:
    import pyeapi
    PYEAPI_AVAILABLE = True
except ImportError:
    PYEAPI_AVAILABLE = False

DEFAULT_SYSLOG_PRIORITY = syslog.LOG_NOTICE
DEFAULT_CONNECTION = 'localhost'
TRANSPORTS = ['socket', 'http', 'https', 'http_local']

class EosConnection(object):

    __attributes__ = ['username', 'password', 'host', 'transport', 'port']

    def __init__(self, **kwargs):
        self.connection = kwargs['connection']
        self.transport = kwargs.get('transport')

        self.username = kwargs.get('username')
        self.password = kwargs.get('password')

        self.host = kwargs.get('host')
        self.port = kwargs.get('port')

        self.config = kwargs.get('config')

    def connect(self):
        if self.config is not None:
            pyeapi.load_config(self.config)

        config = dict()

        if self.connection is not None:
            config = pyeapi.config_for(self.connection)
            if not config:
                msg = 'Connection name "{}" not found'.format(self.connection)

        for key in self.__attributes__:
            if getattr(self, key) is not None:
                config[key] = getattr(self, key)

        if 'transport' not in config:
            raise ValueError('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        node = pyeapi.client.Node(connection, **config)

        try:
            node.enable('show version')
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            raise ValueError('unable to connect to {}'.format(node))
        return node

class EosAnsibleModule(AnsibleModule):

    meta_args = {
        'config': dict(),
        'username': dict(),
        'password': dict(),
        'host': dict(),
        'connection': dict(default=DEFAULT_CONNECTION),
        'transport': dict(choices=TRANSPORTS),
        'port': dict(),
        'debug': dict(type='bool', default='false'),
        'logging': dict(type='bool', default='true')
    }

    stateful_args = {
        'state': dict(default='present', choices=['present', 'absent']),
    }

    def __init__(self, stateful=True, autorefresh=False, *args, **kwargs):

        kwargs['argument_spec'].update(self.meta_args)

        self._stateful = stateful
        if stateful:
            kwargs['argument_spec'].update(self.stateful_args)

        ## Ok, so in Ansible 2.0,
        ## AnsibleModule.__init__() sets self.params and then
        ##   calls self.log()
        ##   (through self._log_invocation())
        ##
        ## However, self.log() (overridden in EosAnsibleModule)
        ##   references self._logging
        ## and self._logging (defined in EosAnsibleModule)
        ##   references self.params.
        ##
        ## So ... I'm defining self._logging without "or self.params['logging']"
        ##   *before* AnsibleModule.__init__() to avoid a "ref before def".
        ##
        ## I verified that this works with Ansible 1.9.4 and 2.0.0.2.
        ## The only caveat is that the first log message in
        ##   AnsibleModule.__init__() won't be subject to the value of
        ##   self.params['logging'].
        self._logging = kwargs.get('logging')
        super(EosAnsibleModule, self).__init__(*args, **kwargs)

        self.result = dict(changed=False, changes=dict())

        self._debug = kwargs.get('debug') or self.boolean(self.params['debug'])
        self._logging = kwargs.get('logging') or self.params['logging']

        self.log('DEBUG flag is %s' % self._debug)

        self.debug('pyeapi_version', self.check_pyeapi())
        self.debug('stateful', self._stateful)
        self.debug('params', self.params)

        self._attributes = self.map_argument_spec()
        self.validate()
        self._autorefresh = autorefresh
        self._node = EosConnection(**self.params)
        self._node.connect()

        self._node = self.connect()
        self._instance = None

        self.desired_state = self.params['state'] if self._stateful else None
        self.exit_after_flush = kwargs.get('exit_after_flush')

    @property
    def instance(self):
        if self._instance:
            return self._instance

        func = self.func('instance')
        if not func:
            self.fail('Module does not support "instance"')

        try:
            self._instance = func(self)
        except Exception as exc:
            self.fail('instance[error]: %s' % exc.message)

        self.log("called instance: %s" % self._instance)
        return self._instance

    @property
    def attributes(self):
        return self._attributes

    @property
    def node(self):
        return self._node

    def check_pyeapi(self):
        if not PYEAPI_AVAILABLE:
            self.fail('Unable to import pyeapi, is it installed?')
        return pyeapi.__version__

    def map_argument_spec(self):
        """map_argument_spec maps only the module argument spec to attrs

        This method will map the argumentspec minus the meta_args to attrs
        and return the attrs.  This returns a dict object that includes only
        the original argspec plus the stateful_args (if self._stateful=True)

        Returns:
            dict: Returns a dict object that includes the original
                argument_spec plus stateful_args with values minus meta_args

        """
        keys = set(self.params).difference(self.meta_args)
        attrs = dict()
        attrs = dict([(k, self.params[k]) for k in self.params if k in keys])
        if 'CHECKMODE' in attrs:
            del attrs['CHECKMODE']
        return attrs

    def validate(self):
        for key, value in self.attributes.iteritems():
            func = self.func('validate_%s' % key)
            if func:
                self.attributes[key] = func(value)

    def create(self):
        if not self.check_mode:
            func = self.func('create')
            if not func:
                self.fail('Module must define "create" function')
            return self.invoke(func, self)

    def remove(self):
        if not self.check_mode:
            func = self.func('remove')
            if not func:
                self.fail('Module most define "remove" function')
            return self.invoke(func, self)

    def flush(self, exit_after_flush=False):
        self.exit_after_flush = exit_after_flush

        if self.desired_state == 'present' or not self._stateful:
            if self.instance.get('state') == 'absent':
                changed = self.create()
                self.result['changed'] = changed or True
                self.refresh()
                # After a create command, flush the running-config
                # so we get the latest for any other attributes
                self._node._running_config = None

            changeset = self.attributes.viewitems() - self.instance.viewitems()

            if self._debug:
                self.debug('desired_state', self.attributes)
                self.debug('current_state', self.instance)

            changes = self.update(changeset)
            if changes:
                self.result['changes'] = changes
                self.result['changed'] = True

            self._attributes.update(changes)

            flush = self.func('flush')
            if flush:
                self.invoke(flush, self)

        elif self.desired_state == 'absent' and self._stateful:
            if self.instance.get('state') == 'present':
                changed = self.remove()
                self.result['changed'] = changed or True

        elif self._stateful:
            if self.desired_state != self.instance.get('state'):
                func = self.func(self.desired_state)
                changed = self.invoke(func, self)
                self.result['changed'] = changed or True

        self.refresh()
        # By calling self.instance here we trigger another show running-config
        # all which causes delay.  Only if debug is enabled do we call this
        # since it will display the latest state of the object.
        if self._debug:
            self.result['instance'] = self.instance

        if self.exit_after_flush:
            self.exit()

    def update(self, changeset):
        changes = dict()
        for key, value in changeset:
            if value is not None:
                changes[key] = value
                func = self.func('set_%s' % key)
                if func and not self.check_mode:
                    try:
                        self.invoke(func, self)
                    except Exception as exc:
                        self.fail(exc.message)
        return changes

    def connect(self):
        if self.params['config']:
            pyeapi.load_config(self.params['config'])

        config = dict()

        if self.params['connection']:
            config = pyeapi.config_for(self.params['connection'])
            if not config:
                msg = 'Connection name "%s" not found' % self.params['connection']
                self.fail(msg)

        if self.params['username']:
            config['username'] = self.params['username']

        if self.params['password']:
            config['password'] = self.params['password']

        if self.params['transport']:
            config['transport'] = self.params['transport']

        if self.params['port']:
            config['port'] = self.params['port']

        if self.params['host']:
            config['host'] = self.params['host']

        if 'transport' not in config:
            self.fail('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        self.log('Creating connection with autorefresh=%s' % self._autorefresh)
        node = pyeapi.client.Node(connection, autorefresh=self._autorefresh,
                                  **config)

        try:
            resp = node.enable('show version')
            self.debug('eos_version', resp[0]['result']['version'])
            self.debug('eos_model', resp[0]['result']['modelName'])
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            self.fail('unable to connect to %s' % node)
        else:
            self.log('Connected to node %s' % node)
            self.debug('node', str(node))

        return node

    def config(self, commands):
        self.result['changed'] = True
        if not self.check_mode:
            self.node.config(commands)

    def api(self, module):
        return self.node.api(module)

    def func(self, name):
        return globals().get(name)

    def invoke(self, func, *args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as exc:
            self.fail(exc.message)

    def invoke_function(self, name, *args, **kwargs):
        func = self.func(name)
        if func:
            return self.invoke(func, *args, **kwargs)

    def fail(self, msg):
        self.invoke_function('on_fail', self)
        self.log('ERROR: %s' % msg, syslog.LOG_ERR)
        self.fail_json(msg=msg)

    def exit(self):
        self.invoke_function('on_exit', self)
        self.log('Module completed successfully')
        self.exit_json(**self.result)

    def refresh(self):
        self._instance = None

    def debug(self, key, value):
        if self._debug:
            if 'debug' not in self.result:
                self.result['debug'] = dict()
            self.result['debug'][key] = value

    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

    @classmethod
    def add_state(cls, name):
        cls.stateful_args['state']['choices'].append(name)

#<<EOS_COMMON_MODULE_END>>

def instance(module):
    """ Returns the interface properties for the specified name
    """
    name = module.attributes['name']
    result = module.node.api('interfaces').get(name)
    if not result:
        module.fail('Unknown interface: %s' % name)
    instance = dict(name=name)
    instance['enable'] = not result['shutdown']
    desc = '' if not result['description'] else result['description']
    instance['description'] = desc
    instance['sflow'] = result['sflow']
    instance['flowcontrol_send'] = result['flowcontrol_send'] == 'on'
    instance['flowcontrol_receive'] = result['flowcontrol_receive'] == 'on'
    return instance

def set_description(module):
    """ Configures the description attribute for the interface
    """
    value = module.attributes['description']
    name = module.attributes['name']
    value = None if value == '' else value
    module.log('Invoked set_description for eos_ethernet[%s] '
               'with value %s' % (name, value))
    module.node.api('interfaces').set_description(name, value)

def set_enable(module):
    """ Configures the enable attribute for the interface
    """
    value = module.attributes['enable']
    name = module.attributes['name']
    module.log('Invoked set_enable for eos_ethernet[%s] '
               'with value %s' % (name, value))
    module.node.api('interfaces').set_shutdown(name, disable=value)

def set_sflow(module):
    """ Configures the sflow attribute for the interface
    """
    value = module.attributes['sflow']
    name = module.attributes['name']
    module.log('Invoked set_sflow for eos_ethernet[%s] '
               'with value %s' % (name, value))
    module.node.api('interfaces').set_sflow(name, value)

def set_flowcontrol_send(module):
    """ Configures the flowcontrol send  attribute for the interface
    """
    value = module.attributes['flowcontrol_send']
    value = 'on' if value else 'off'
    name = module.attributes['name']
    module.log('Invoked set_flowcontrol_send for eos_ethernet[%s] '
               'with value %s' % (name, value))
    module.node.api('interfaces').set_flowcontrol_send(name, value)

def set_flowcontrol_receive(module):
    """ Configures the flowcontrol receive attribute for the interface
    """
    value = module.attributes['flowcontrol_receive']
    value = 'on' if value else 'off'
    name = module.attributes['name']
    module.log('Invoked set_flowcontrol_receive for eos_ethernet[%s] '
               'with value %s' % (name, value))
    module.node.api('interfaces').set_flowcontrol_receive(name, value)

def main():
    """ The main module routine called when the module is run by Ansible
    """

    argument_spec = dict(
        name=dict(required=True),
        enable=dict(type='bool', default=True),
        description=dict(),
        sflow=dict(type='bool'),
        flowcontrol_send=dict(type='bool'),
        flowcontrol_receive=dict(type='bool')
    )

    module = EosAnsibleModule(argument_spec=argument_spec,
                              stateful=False,
                              supports_check_mode=True)

    module.flush(True)

main()


text:
VP Agile Innovation - Itero Group, LLC

 Professional Scrum Trainer (Scrum.org)

 agiletodd

 agiletodd

 todd_miller11

tmiller@iterogroup.com

[http://agiletodd.github.io/scrum-quality-software](http://agiletodd.github.io/scrum-quality-software)


text:
class Choose < Formula
  desc "Make choices on the command-line"
  homepage "https://github.com/geier/choose"
  url "https://github.com/geier/choose/archive/v0.1.0.tar.gz"
  sha256 "d09a679920480e66bff36c76dd4d33e8ad739a53eace505d01051c114a829633"
  license "MIT"
  revision 3
  head "https://github.com/geier/choose.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "086ebca8f9bff4d065e788c9076bfe204b958f96b8da0cce142f3c890c38cb75" => :catalina
    sha256 "bef5f7490cf4a45398bfdef4867163957675227e74bab1494ea0da56cda2cda6" => :mojave
    sha256 "f860816e00292d161ed6f6617cef47c3297eb91e9231f3c125ce12b16ad7d220" => :high_sierra
  end

  depends_on "python@3.9"

  conflicts_with "choose-gui", because: "both install a `choose` binary"
  conflicts_with "choose-rust", because: "both install a `choose` binary"

  resource "urwid" do
    url "https://files.pythonhosted.org/packages/45/dd/d57924f77b0914f8a61c81222647888fbb583f89168a376ffeb5613b02a6/urwid-2.1.0.tar.gz"
    sha256 "0896f36060beb6bf3801cb554303fef336a79661401797551ba106d23ab4cd86"
  end

  def install
    xy = Language::Python.major_minor_version "python3"
    ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{xy}/site-packages"

    resource("urwid").stage do
      system "python3", *Language::Python.setup_install_args(libexec)
    end

    bin.install "choose"

    bin.env_script_all_files(libexec/"bin", PYTHONPATH: ENV["PYTHONPATH"])
  end

  test do
    # There isn't really a better test than that the executable exists
    # and is executable because you can't run it without producing an
    # interactive selection ui.
    assert_predicate bin/"choose", :executable?
  end
end


text:
package gwt.material.design.client.js;

import com.google.gwt.core.client.JavaScriptObject;
import gwt.material.design.jquery.client.api.JQueryElement;

/**
 * @author Ben Dol
 */
public class StickyTableOptions extends JavaScriptObject {
    protected StickyTableOptions() {
    }

    //TODO: Convert to JSInterop
    public native final void setScrollableArea(JQueryElement scrollableArea) /*-{
        this.scrollableArea = scrollableArea;
    }-*/;

    public native final void setMarginTop(int marginTop) /*-{
        this.marginTop = marginTop;
    }-*/;

    public static StickyTableOptions create(JQueryElement scrollableArea) {
        return create(scrollableArea, 0);
    }

    public static StickyTableOptions create(JQueryElement scrollableArea, int marginTop) {
        StickyTableOptions obj = JavaScriptObject.createObject().cast();
        obj.setScrollableArea(scrollableArea);
        obj.setMarginTop(marginTop);
        return obj;
    }
}


text:
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var snanstdevtk = require( './snanstdevtk.native.js' );
var ndarray = require( './ndarray.native.js' );

// MAIN //

setReadOnly( snanstdevtk, 'ndarray', ndarray );

// EXPORTS //

module.exports = snanstdevtk;


text:
package com.example.madiskar.experiencesamplingapp.receivers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;

import com.example.madiskar.experiencesamplingapp.services.NotificationService;
import com.example.madiskar.experiencesamplingapp.data_types.Study;
import com.example.madiskar.experiencesamplingapp.local_database.DBHandler;

import java.util.ArrayList;
import java.util.Calendar;

public class ResponseReceiver extends WakefulBroadcastReceiver {

    private Study study;
    private SharedPreferences sharedPref;

    public ResponseReceiver(Study study) {
        this.study = study;
    }
    public ResponseReceiver () {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        long id = intent.getLongExtra("studyId", 0);

        Study studyParam = null;
        for (Study s: DBHandler.getInstance(context).getAllStudies()) {
            if (s.getId() == (int) id) {
                studyParam = s;
            }
        }
        Intent serviceIntent = NotificationService.createIntentNotificationService(context, studyParam);
        if (serviceIntent != null) {
            startWakefulService(context, serviceIntent);
        }
    }

    public void setupAlarm(Context context, boolean firstTime) {

        sharedPref = context.getSharedPreferences("com.example.madiskar.ExperienceSampler", Context.MODE_PRIVATE);

        if (sharedPref.getInt(String.valueOf(study.getId()),0) == 0) {
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt(String.valueOf(study.getId()), 0);
            editor.apply();
        }

        int interval = study.getMinTimeBetweenNotifications();
        Intent intent = new Intent(context, ResponseReceiver.class);
        long id = study.getId();

        PendingIntent alarmIntent = getPendingIntent(context, intent, id);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (firstTime) {
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + interval * 60 * 1000,
                    interval * 60 * 1000,
                    alarmIntent);
        }
        else {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt(String.valueOf(study.getId()), 0);
            editor.apply();

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), interval * 60 * 1000 , alarmIntent);
        }
    }

    public static void cancelExistingAlarm(Context context, Intent intent, int i, boolean broadcast) {
        try{
            PendingIntent pendingIntent = null;
            if (broadcast)
                pendingIntent = PendingIntent.getBroadcast(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT); //VB SIIN 0 PANNA VIIMASEKS FLAG.. ASEMEL
            else
                pendingIntent = PendingIntent.getActivity(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT); //VB SIIN 0 PANNA VIIMASEKS FLAG.. ASEMEL
            AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            am.cancel(pendingIntent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static PendingIntent getPendingIntent(Context context, Intent intent, long id) {
        intent.putExtra("studyId", id);
        return PendingIntent.getBroadcast(context, (int) id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}