text:
namespace marisa {

inline std::string Trie::operator[](UInt32 key_id) const {
  std::string key;
  restore(key_id, &key);
  return key;
}

inline UInt32 Trie::operator[](const char *str) const {
  return lookup(str);
}

inline UInt32 Trie::operator[](const std::string &str) const {
  return lookup(str);
}

inline UInt32 Trie::lookup(const std::string &str) const {
  return lookup(str.c_str(), str.length());
}

inline std::size_t Trie::find(const std::string &str,
    UInt32 *key_ids, std::size_t *key_lengths,
    std::size_t max_num_results) const {
  return find(str.c_str(), str.length(),
      key_ids, key_lengths, max_num_results);
}

inline std::size_t Trie::find(const std::string &str,
    std::vector<UInt32> *key_ids, std::vector<std::size_t> *key_lengths,
    std::size_t max_num_results) const {
  return find(str.c_str(), str.length(),
      key_ids, key_lengths, max_num_results);
}

inline UInt32 Trie::find_first(const std::string &str,
    std::size_t *key_length) const {
  return find_first(str.c_str(), str.length(), key_length);
}

inline UInt32 Trie::find_last(const std::string &str,
    std::size_t *key_length) const {
  return find_last(str.c_str(), str.length(), key_length);
}

template <typename T>
inline std::size_t Trie::find_callback(const char *str,
    T callback) const {
  MARISA_THROW_IF(empty(), MARISA_STATE_ERROR);
  MARISA_THROW_IF(str == NULL, MARISA_PARAM_ERROR);
  return find_callback_<CQuery>(CQuery(str), callback);
}

template <typename T>
inline std::size_t Trie::find_callback(const char *ptr, std::size_t length,
    T callback) const {
  MARISA_THROW_IF(empty(), MARISA_STATE_ERROR);
  MARISA_THROW_IF((ptr == NULL) && (length != 0), MARISA_PARAM_ERROR);
  return find_callback_<const Query &>(Query(ptr, length), callback);
}

template <typename T>
inline std::size_t Trie::find_callback(const std::string &str,
    T callback) const {
  return find_callback(str.c_str(), str.length(), callback);
}

inline std::size_t Trie::predict(const std::string &str,
    UInt32 *key_ids, std::string *keys, std::size_t max_num_results) const {
  return predict(str.c_str(), str.length(), key_ids, keys, max_num_results);
}

inline std::size_t Trie::predict(const std::string &str,
    std::vector<UInt32> *key_ids, std::vector<std::string> *keys,
    std::size_t max_num_results) const {
  return predict(str.c_str(), str.length(), key_ids, keys, max_num_results);
}

inline std::size_t Trie::predict_breadth_first(const std::string &str,
    UInt32 *key_ids, std::string *keys, std::size_t max_num_results) const {
  return predict_breadth_first(str.c_str(), str.length(),
      key_ids, keys, max_num_results);
}

inline std::size_t Trie::predict_breadth_first(const std::string &str,
    std::vector<UInt32> *key_ids, std::vector<std::string> *keys,
    std::size_t max_num_results) const {
  return predict_breadth_first(str.c_str(), str.length(),
      key_ids, keys, max_num_results);
}

inline std::size_t Trie::predict_depth_first(const std::string &str,
    UInt32 *key_ids, std::string *keys, std::size_t max_num_results) const {
  return predict_depth_first(str.c_str(), str.length(),
      key_ids, keys, max_num_results);
}

inline std::size_t Trie::predict_depth_first(const std::string &str,
    std::vector<UInt32> *key_ids, std::vector<std::string> *keys,
    std::size_t max_num_results) const {
  return predict_depth_first(str.c_str(), str.length(),
      key_ids, keys, max_num_results);
}

template <typename T>
inline std::size_t Trie::predict_callback(
    const char *str, T callback) const {
  return predict_callback_<CQuery>(CQuery(str), callback);
}

template <typename T>
inline std::size_t Trie::predict_callback(
    const char *ptr, std::size_t length,
    T callback) const {
  return predict_callback_<const Query &>(Query(ptr, length), callback);
}

template <typename T>
inline std::size_t Trie::predict_callback(
    const std::string &str, T callback) const {
  return predict_callback(str.c_str(), str.length(), callback);
}

inline bool Trie::empty() const {
  return louds_.empty();
}

inline std::size_t Trie::num_keys() const {
  return num_keys_;
}

inline UInt32 Trie::notfound() {
  return MARISA_NOT_FOUND;
}

inline std::size_t Trie::mismatch() {
  return MARISA_MISMATCH;
}

template <typename T>
inline bool Trie::find_child(UInt32 &node, T query,
    std::size_t &pos) const {
  UInt32 louds_pos = get_child(node);
  if (!louds_[louds_pos]) {
    return false;
  }
  node = louds_pos_to_node(louds_pos, node);
  UInt32 link_id = MARISA_UINT32_MAX;
  do {
    if (has_link(node)) {
      if (link_id == MARISA_UINT32_MAX) {
        link_id = get_link_id(node);
      } else {
        ++link_id;
      }
      std::size_t next_pos = has_trie() ?
          trie_->trie_match<T>(get_link(node, link_id), query, pos) :
          tail_match<T>(node, link_id, query, pos);
      if (next_pos == mismatch()) {
        return false;
      } else if (next_pos != pos) {
        pos = next_pos;
        return true;
      }
    } else if (labels_[node] == query[pos]) {
      ++pos;
      return true;
    }
    ++node;
    ++louds_pos;
  } while (louds_[louds_pos]);
  return false;
}

template <typename T, typename U>
std::size_t Trie::find_callback_(T query, U callback) const {
  std::size_t count = 0;
  UInt32 node = 0;
  std::size_t pos = 0;
  do {
    if (terminal_flags_[node]) {
      ++count;
      if (!callback(node_to_key_id(node), pos)) {
        return count;
      }
    }
  } while (!query.ends_at(pos) && find_child<T>(node, query, pos));
  return count;
}

template <typename T>
inline bool Trie::predict_child(UInt32 &node, T query, std::size_t &pos,
    std::string *key) const {
  UInt32 louds_pos = get_child(node);
  if (!louds_[louds_pos]) {
    return false;
  }
  node = louds_pos_to_node(louds_pos, node);
  UInt32 link_id = MARISA_UINT32_MAX;
  do {
    if (has_link(node)) {
      if (link_id == MARISA_UINT32_MAX) {
        link_id = get_link_id(node);
      } else {
        ++link_id;
      }
      std::size_t next_pos = has_trie() ?
          trie_->trie_prefix_match<T>(
              get_link(node, link_id), query, pos, key) :
          tail_prefix_match<T>(node, link_id, query, pos, key);
      if (next_pos == mismatch()) {
        return false;
      } else if (next_pos != pos) {
        pos = next_pos;
        return true;
      }
    } else if (labels_[node] == query[pos]) {
      ++pos;
      return true;
    }
    ++node;
    ++louds_pos;
  } while (louds_[louds_pos]);
  return false;
}

template <typename T, typename U>
std::size_t Trie::predict_callback_(T query, U callback) const {
  std::string key;
  UInt32 node = 0;
  std::size_t pos = 0;
  while (!query.ends_at(pos)) {
    if (!predict_child<T>(node, query, pos, &key)) {
      return 0;
    }
  }
  query.insert(&key);
  std::size_t count = 0;
  if (terminal_flags_[node]) {
    ++count;
    if (!callback(node_to_key_id(node), key)) {
      return count;
    }
  }
  Cell cell;
  cell.set_louds_pos(get_child(node));
  if (!louds_[cell.louds_pos()]) {
    return count;
  }
  cell.set_node(louds_pos_to_node(cell.louds_pos(), node));
  cell.set_key_id(node_to_key_id(cell.node()));
  cell.set_length(key.length());
  Vector<Cell> stack;
  stack.push_back(cell);
  std::size_t stack_pos = 1;
  while (stack_pos != 0) {
    Cell &cur = stack[stack_pos - 1];
    if (!louds_[cur.louds_pos()]) {
      cur.set_louds_pos(cur.louds_pos() + 1);
      --stack_pos;
      continue;
    }
    cur.set_louds_pos(cur.louds_pos() + 1);
    key.resize(cur.length());
    if (has_link(cur.node())) {
      if (has_trie()) {
        trie_->trie_restore(get_link(cur.node()), &key);
      } else {
        tail_restore(cur.node(), &key);
      }
    } else {
      key += labels_[cur.node()];
    }
    if (terminal_flags_[cur.node()]) {
      ++count;
      if (!callback(cur.key_id(), key)) {
        return count;
      }
      cur.set_key_id(cur.key_id() + 1);
    }
    if (stack_pos == stack.size()) {
      cell.set_louds_pos(get_child(cur.node()));
      cell.set_node(louds_pos_to_node(cell.louds_pos(), cur.node()));
      cell.set_key_id(node_to_key_id(cell.node()));
      stack.push_back(cell);
    }
    stack[stack_pos].set_length(key.length());
    stack[stack_pos - 1].set_node(stack[stack_pos - 1].node() + 1);
    ++stack_pos;
  }
  return count;
}

inline UInt32 Trie::key_id_to_node(UInt32 key_id) const {
  return terminal_flags_.select1(key_id);
}

inline UInt32 Trie::node_to_key_id(UInt32 node) const {
  return terminal_flags_.rank1(node);
}

inline UInt32 Trie::louds_pos_to_node(UInt32 louds_pos,
    UInt32 parent_node) const {
  return louds_pos - parent_node - 1;
}

inline UInt32 Trie::get_child(UInt32 node) const {
  return louds_.select0(node) + 1;
}

inline UInt32 Trie::get_parent(UInt32 node) const {
  return (node > num_first_branches_) ? (louds_.select1(node) - node - 1) : 0;
}

inline bool Trie::has_link(UInt32 node) const {
  return (link_flags_.empty()) ? false : link_flags_[node];
}

inline UInt32 Trie::get_link_id(UInt32 node) const {
  return link_flags_.rank1(node);
}

inline UInt32 Trie::get_link(UInt32 node) const {
  return get_link(node, get_link_id(node));
}

inline UInt32 Trie::get_link(UInt32 node, UInt32 link_id) const {
  return (links_[link_id] * 256) + labels_[node];
}

inline bool Trie::has_link() const {
  return !link_flags_.empty();
}

inline bool Trie::has_trie() const {
  return trie_.get() != NULL;
}

inline bool Trie::has_tail() const {
  return !tail_.empty();
}

}  // namespace marisa

#endif  // MARISA_TRIE_INLINE_H_


text:
package org.sacredscripture.platform.internal.bible;

import org.sacredscripture.platform.bible.Book;
import org.sacredscripture.platform.bible.Content;
import org.sacredscripture.platform.internal.DataModel.ContentTable;

import org.sacredscripturefoundation.commons.entity.EntityImpl;
import org.sacredscripturefoundation.commons.entity.PublicIdProvider;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * This abstract class is the stock implementation of {@link Content}.
 *
 * @author Paul Benedict
 * @since Sacred Scripture Platform 1.0
 */
@Entity
@Table(name = ContentTable.TABLE_NAME)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = ContentTable.COLUMN_DISCRIMINATOR, discriminatorType = DiscriminatorType.INTEGER)
public abstract class ContentImpl extends EntityImpl<Long> implements Content, PublicIdProvider<String> {

    /*
     * Implementing PublicIdProvider shouldn't be necessary here, but HHH cannot
     * proxy getPublicIdProvider() and lazy-load the value in the subclasses
     * without it (always null). Bug in Javassist? Need to check if this problem
     * still exists in HHH 5.x before reporting it.
     */

    @Column(name = ContentTable.COLUMN_PUBLIC_ID)
    private String publicId;

    @ManyToOne(targetEntity = BookImpl.class, optional = false)
    @JoinColumn(name = ContentTable.COLUMN_BOOK_ID)
    private Book book;

    @Column(name = ContentTable.COLUMN_POSITION)
    private int order;

    @Column(name = ContentTable.COLUMN_CODE)
    private String code;

    @Override
    public Book getBook() {
        return book;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public int getOrder() {
        return order;
    }

    @Override
    public String getPublicId() {
        return publicId;
    }

    @Override
    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public void setCode(String code) {
        this.code = (code != null ? code.toLowerCase() : null);
    }

    @Override
    public void setOrder(int order) {
        if (order < 0) {
            throw new IllegalArgumentException("Order must be >= 0");
        }
        this.order = order;
    }

    public void setPublicId(String publicId) {
        this.publicId = publicId;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

	<meta charset="UTF-8">
	<title>Angular Datetime</title>

	<link rel="stylesheet" href="https://rawgit.com/eight04/end2end/master/dist/end2end.css">

Angular Datetime Demo Page

To use the directive, add datetime="date-format" attribute to your input.

	<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="data.myDate" class="form-control">

myDate = {{data.myDate | json}}

<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="myDate">

To set a date, just set your model to a Date object. Set to null to remove it.

		<button class="btn-default" ng-click="reset()">Reset</button>
		<button class="btn-default" ng-click="clear()">Clear</button>

<button ng-click="myDate = new Date">reset</button>

min / max

Validation for min/max date. The min/max attribute will be used to construct the date object.

	<form name="minmaxForm">
		<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="data.myDate" class="form-control" min="{{data.min.toUTCString()}}" max="{{data.max.toUTCString()}}" name="input">
	</form>

input.$error = {{minmaxForm.input.$error | json}}

<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="myDate" min="Jan 1, 2010" max="Dec 31, 2019">

			Min
			<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="data.min" class="form-control">

			Max
			<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="data.max" class="form-control">

required

ng-invalid-required will be added to the class list when all parts are empty.

	<form name="requireForm">
		<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="data.myDate" class="form-control" required name="input">
	</form>

input.$error = {{requireForm.input.$error | json}}

<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="myDate" required>

Use ng-require.

	<form name="ngRequireForm">
		<input type="checkbox" ng-model="isRequired">Required
		<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-required="isRequired" class="form-control" ng-model="data.myDate" name="input">
	</form>

input.$error = {{ngRequireForm.input.$error | json}}

model-format

With this attribute, it will convert the model into a date string automatically.

	<input type="text" class="form-control" datetime="medium" ng-model="data.myDateString" datetime-model="yyyy-MM-dd HH:mm:ss">

myDateString = {{data.myDateString | json}}

<input type="text" datetime="medium" datetime-model="yyyy-MM-dd HH:mm:ss" ng-model="myDateString">

datetime-timezone

By the default, angular-datetime will format the date in the local timezone. Use datetime-timezone to specify a different timezone.

	<input type="text" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate" class="form-control" datetime-timezone="+0000">

myDate = {{data.myDate | json}}

<input type="text" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="myDate" datetime-timezone="+0000">

Also support expression.

	<input type="text" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate" class="form-control" datetime-timezone="data.myTimezone">

myDate = {{data.myDate | json}}
myTimezone = {{data.myTimezone | json}}

<input type="text" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate" datetime-timezone="myTimezone">

			Timezone
			<input type="text" ng-model="data.myTimezone" pattern="[+-]\d{2}:?\d{2}" class="form-control">

datetime-separator

By the default, you can use left/right keys to navigate between each part of date. With this attribute, you will be able to use different keys to jump to next part.

	<input type="text" class="form-control" datetime="dd.MM.yyyy" ng-model="data.myDate" datetime-separator=",.-/">

<input type="text" datetime="dd.MM.yyyy" ng-model="myDate" datetime-separator=",.-/">

Localizable formats

The parser supports localizable formats in Angular.

			{{format}}
			<input type="text" datetime="{{format}}" class="form-control" ng-model="data.myDate">

Other tests

		Duplicate name test
		<input type="text" datetime=",sss .sss" ng-model="data.myDate" class="form-control" id="duplicate-name">

			MySQL date part
			<input type="text" class="form-control" datetime="yyyy-MM-dd" ng-model="data.myDate">

			Default timezone
			<input type="text" class="form-control" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate">

			UTC timezone
			<input type="text" class="form-control" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate" datetime-timezone="+0000">

			Custom Europe/Moscow timezone
			<input type="text" class="form-control" datetime="yyyy-MM-dd HH:mm:ssZ" ng-model="data.myDate" datetime-timezone="+0300">

			datetime-model with min/max
			<input type="text" class="form-control" datetime="yyyy-MM-dd" datetime-model="yyyy-MM-ddTHH:mm:ssZZ" ng-model="data.myDateString2" min="Jan 1, 2000">

{{data.myDateString2 | json}}


text:
/* Author: Mingcheng Chen */

import java.util.Random;
import java.util.ArrayList;

public class QLearningAgent implements Agent {
  public QLearningAgent() {
    this.rand = new Random();
  }

  public void initialize(int numOfStates, int numOfActions) {
    this.qValue = new double[numOfStates][numOfActions];
    this.numOfStates = numOfStates;
    this.numOfActions = numOfActions;
  }

  /*private double bestUtility(int state) {

  }*/

  public int chooseAction(int state) {
		if(this.rand.nextDouble()<epsilon) return this.rand.nextInt(numOfActions);

		int action;
		int[] bestActions=new int[this.numOfActions];
		double maxQ=this.qValue[state][0];
		int numMax=1;

		bestActions[0]=0;

		for(action=1;action<numOfActions;action++){
			if(this.qValue[state][action]==maxQ){
				bestActions[numMax]=action;
				numMax++;
			}
			else if(this.qValue[state][action]>maxQ){
				bestActions[0]=action;
				numMax=1;
				maxQ=this.qValue[state][action];
			}
		}

		return bestActions[this.rand.nextInt(numMax)];
  }

  public void updatePolicy(double reward, int action,
                           int oldState, int newState) {
		this.qValue[oldState][action]=this.qValue[oldState][action]+rate*(reward+discount*this.qValue[newState][chooseAction(newState)]-this.qValue[oldState][action]);
  }

  public Policy getPolicy() {
  	int state;
  	int [] actions=new int[this.numOfStates];
  	double maxQ;
  	int numMax;
  	int curaction;
  	int[] bestActions=new int[this.numOfActions];

		for(state=0;state<numOfStates;state++){
			maxQ=this.qValue[state][0];
			numMax=1;

			bestActions[0]=0;

			for(curaction=1;curaction<numOfActions;curaction++){
				if(this.qValue[state][curaction]==maxQ){
					bestActions[numMax]=curaction;
					numMax++;
				}
				else if(this.qValue[state][curaction]>maxQ){
					bestActions[0]=curaction;
					numMax=1;
					maxQ=this.qValue[state][curaction];
				}
			}
			actions[state]=bestActions[this.rand.nextInt(numMax)];
		}

		Policy p=new Policy(actions);

		return p;
  }

  private static final double discount = 0.9;
  private static final double rate = 0.1;
  private static final double epsilon = 0.05;

	private Random rand;
  private int numOfStates;
  private int numOfActions;
  private double[][] qValue;
}


text:
$(function () {
    selectGameMenu();

    registerAllEvents();
});

/**
 * select current game menu item
 * @return {null}
 */
function selectGameMenu () {
    var pathname = window.location.pathname;

    if (pathname === "/home") {
        pathname = "/game/cqticket";
    }

    $(".container .row .col-md-3 .list-group a").filter(".active").removeClass("active");

    $(".container .row .col-md-3 .list-group a").filter("[href*=\'"+ pathname +"\']").addClass("active");
}

/**
 * register category click event
 * @return {null}
 */
function registerCategoryEvent () {

    $("#category button").each(function () {
        $(this).click(function () {
            $("#category button").filter(".btn-primary").removeClass("btn-primary").addClass("btn-default");
            $(this).removeClass("btn-default").addClass("btn-primary");
        });
    });
}

/**
 * register sub cateogry click event
 * @return {null}
 */
function registerSubCategoryEvent () {
    $("#sub_category button").each(function () {
        $(this).click(function () {
            $("#sub_category button").filter(".btn-primary").removeClass("btn-primary").addClass("btn-default");
            $(this).removeClass("btn-default").addClass("btn-primary");
        });
    });
}

/**
 * register all events
 * @return {null}
 */
function registerAllEvents () {
    registerCategoryEvent();

    registerSubCategoryEvent();
}


text:
package com.evernote.android.job;

import android.app.Service;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager.WakeLock;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;

import com.evernote.android.job.util.Device;
import com.evernote.android.job.util.JobCat;
import com.evernote.android.job.util.support.PersistableBundleCompat;

import java.lang.ref.WeakReference;

/**
 * Base class for running delayed jobs. A {@link Job} is executed in a background thread.
 *
 * @author rwondratschek
 */
@SuppressWarnings({"unused", "WeakerAccess"})
public abstract class Job {

    private static final JobCat CAT = new JobCat("Job");

    public enum Result {
        /**
         * Indicates that {@link #onRunJob(Params)} was successful.
         */
        SUCCESS,
        /**
         * Indicates that {@link #onRunJob(Params)} failed, but the {@link Job} shouldn't be rescheduled.
         *
         *

         *

         *
         * Periodic jobs will continue to run. The failure count of the job is incremented, what
         * can be helpful in the next interval.
         *
         * @see Params#getFailureCount()
         */
        FAILURE,
        /**
         * Indicates that {@link #onRunJob(Params)} failed and the {@link Job} should be rescheduled
         * with the defined back-off criteria. Note that returning {@code RESCHEDULE} for a periodic
         * {@link Job} is invalid and ignored.
         *
         *

         *

         *
         * Returning RESCHEDULE for periodic jobs has the same effect as returning FAILURE.
         */
        RESCHEDULE
    }

    private Params mParams;
    private WeakReference<Context> mContextReference;
    private Context mApplicationContext;

    private volatile boolean mCanceled;
    private volatile boolean mDeleted;
    private volatile long mFinishedTimeStamp = -1;

    private Result mResult = Result.FAILURE;

    private final Object mMonitor = new Object();

    /**
     * This method is invoked from a background thread. You should run your desired task here.
     * This method is thread safe. Each time a job starts executing a new instance of your {@link Job}
     * is instantiated. You can identify your {@link Job} with the passed {@code params}.
     *
     *

     *

     *
     * You should call {@link #isCanceled()} frequently for long running jobs and stop your
     * task if necessary.
     *
     *

     *

     *
     * A {@link WakeLock} is acquired for 3 minutes for each {@link Job}. If your task
     * needs more time, then you need to create an extra {@link WakeLock}.
     *
     * @param params The parameters for this concrete job.
     * @return The result of this {@link Job}. Note that returning {@link Result#RESCHEDULE} for a periodic
     * {@link Job} is invalid and ignored.
     */
    @NonNull
    @WorkerThread
    protected abstract Result onRunJob(@NonNull Params params);

    /**
     * This method is intended to be overwritten. It is called once when the job is still running, but was
     * canceled. This can happen when the system wants to stop the job or if you manually cancel the job
     * yourself. It's a good indicator to stop your work and maybe retry your job later again. Alternatively,
     * you can also call {@link #isCanceled()}.
     *
     * @see #isCanceled()
     */
    protected void onCancel() {
        // override me
    }

    /*package*/ final Result runJob() {
        try {
            // daily jobs check the requirements manually
            if (this instanceof DailyJob || meetsRequirements(true)) {
                mResult = onRunJob(getParams());
            } else {
                mResult = getParams().isPeriodic() ? Result.FAILURE : Result.RESCHEDULE;
            }

            return mResult;

        } finally {
            mFinishedTimeStamp = System.currentTimeMillis();
        }
    }

    /**
     * This method is called if you returned {@link Result#RESCHEDULE} in {@link #onRunJob(Params)}
     * and the {@link Job} was successfully rescheduled. The new rescheduled {@link JobRequest} has
     * a new ID. Override this method if you want to be notified about the change.
     *
     * @param newJobId The new ID of the rescheduled {@link JobRequest}.
     */
    @SuppressWarnings("UnusedParameters")
    @WorkerThread
    protected void onReschedule(int newJobId) {
        // override me
    }

    /**
     * Checks all requirements for this job. It's also possible to check all requirements separately
     * with the corresponding methods.
     *
     * @return Whether all set requirements are met.
     */
    protected boolean meetsRequirements() {
        return meetsRequirements(false);
    }

    /*package*/ boolean meetsRequirements(boolean checkRequirementsEnforced) {
        if (checkRequirementsEnforced && !getParams().getRequest().requirementsEnforced()) {
            return true;
        }

        if (!isRequirementChargingMet()) {
            CAT.w("Job requires charging, reschedule");
            return false;
        }
        if (!isRequirementDeviceIdleMet()) {
            CAT.w("Job requires device to be idle, reschedule");
            return false;
        }
        if (!isRequirementNetworkTypeMet()) {
            CAT.w("Job requires network to be %s, but was %s", getParams().getRequest().requiredNetworkType(),
                    Device.getNetworkType(getContext()));
            return false;
        }
        if (!isRequirementBatteryNotLowMet()) {
            CAT.w("Job requires battery not be low, reschedule");
            return false;
        }

        if (!isRequirementStorageNotLowMet()) {
            CAT.w("Job requires storage not be low, reschedule");
            return false;
        }

        return true;
    }

    /**
     * @return {@code false} if the {@link Job} requires the device to be charging and it isn't charging.
     * Otherwise always returns {@code true}.
     */
    protected boolean isRequirementChargingMet() {
        return !(getParams().getRequest().requiresCharging() && !Device.getBatteryStatus(getContext()).isCharging());
    }

    /**
     * @return {@code false} if the {@link Job} requires the device to be idle and it isn't idle. Otherwise
     * always returns {@code true}.
     */
    protected boolean isRequirementDeviceIdleMet() {
        return !(getParams().getRequest().requiresDeviceIdle() && !Device.isIdle(getContext()));
    }

    /**
     * @return Whether the battery not low requirement is met. That's true either if it's not a requirement
     * or if the battery actually isn't low. The battery is low, if less than 15% are left and the device isn't
     * charging.
     */
    protected boolean isRequirementBatteryNotLowMet() {
        return !(getParams().getRequest().requiresBatteryNotLow() && Device.getBatteryStatus(getContext()).isBatteryLow());
    }

    /**
     * @return Whether the storage not low requirement is met. That's true either if it's not a requirement
     * or if the storage actually isn't low.
     */
    protected boolean isRequirementStorageNotLowMet() {
        return !(getParams().getRequest().requiresStorageNotLow() && Device.isStorageLow());
    }

    /**
     * @return {@code false} if the {@link Job} requires the device to be in a specific network state and it
     * isn't in this state. Otherwise always returns {@code true}.
     */
    protected boolean isRequirementNetworkTypeMet() {
        JobRequest.NetworkType requirement = getParams().getRequest().requiredNetworkType();
        if (requirement == JobRequest.NetworkType.ANY) {
            return true;
        }

        JobRequest.NetworkType current = Device.getNetworkType(getContext());

        switch (requirement) {
            case CONNECTED:
                return current != JobRequest.NetworkType.ANY;
            case NOT_ROAMING:
                return current == JobRequest.NetworkType.NOT_ROAMING || current == JobRequest.NetworkType.UNMETERED || current == JobRequest.NetworkType.METERED;
            case UNMETERED:
                return current == JobRequest.NetworkType.UNMETERED;
            case METERED:
                return current == JobRequest.NetworkType.CONNECTED || current == JobRequest.NetworkType.NOT_ROAMING;
            default:
                throw new IllegalStateException("not implemented");
        }
    }

    @SuppressWarnings("UnusedReturnValue")
    /*package*/ final Job setRequest(JobRequest request, @NonNull Bundle transientExtras) {
        mParams = new Params(request, transientExtras);
        return this;
    }

    /**
     * @return The same parameters like passed to {@link #onRunJob(Params)}.
     */
    @NonNull
    protected final Params getParams() {
        return mParams;
    }

    /*package*/ final Job setContext(Context context) {
        mContextReference = new WeakReference<>(context);
        mApplicationContext = context.getApplicationContext();
        return this;
    }

    /**
     * @return The {@link Context} running this {@link Job}. In most situations it's a {@link Service}.
     * If this context already was destroyed for some reason, then the application context is returned.
     * Never returns {@code null}.
     */
    @NonNull
    protected final Context getContext() {
        Context context = mContextReference.get();
        return context == null ? mApplicationContext : context;
    }

    /**
     * Cancel this {@link Job} if it hasn't finished, yet.
     */
    public final void cancel() {
        cancel(false);
    }

    /*package*/ final boolean cancel(boolean deleted) {
        synchronized (mMonitor) {
            if (!isFinished()) {
                if (!mCanceled) {
                    mCanceled = true;
                    onCancel();
                }
                mDeleted |= deleted;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * @return {@code true} if this {@link Job} was canceled.
     */
    protected final boolean isCanceled() {
        synchronized (mMonitor) {
            return mCanceled;
        }
    }

    /**
     * @return {@code true} if the {@link Job} finished.
     */
    public final boolean isFinished() {
        synchronized (mMonitor) {
            return mFinishedTimeStamp > 0;
        }
    }

    /*package*/ final long getFinishedTimeStamp() {
        synchronized (mMonitor) {
            return mFinishedTimeStamp;
        }
    }

    /*package*/ final Result getResult() {
        return mResult;
    }

    /*package*/ final boolean isDeleted() {
        synchronized (mMonitor) {
            return mDeleted;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Job job = (Job) o;

        return mParams.equals(job.mParams);
    }

    @Override
    public int hashCode() {
        return mParams.hashCode();
    }

    @Override
    public String toString() {
        return "job{"
                + "id=" + mParams.getId()
                + ", finished=" + isFinished()
                + ", result=" + mResult
                + ", canceled=" + mCanceled
                + ", periodic=" + mParams.isPeriodic()
                + ", class=" + getClass().getSimpleName()
                + ", tag=" + mParams.getTag()
                + '}';
    }

    /**
     * Holds several parameters for the {@link Job} execution.
     */
    public static final class Params {

        private final JobRequest mRequest;
        private PersistableBundleCompat mExtras;
        private Bundle mTransientExtras;

        private Params(@NonNull JobRequest request, @NonNull Bundle transientExtras) {
            mRequest = request;
            mTransientExtras = transientExtras;
        }

        /**
         * @return The unique ID for this {@link Job}.
         * @see JobRequest#getJobId()
         */
        public int getId() {
            return mRequest.getJobId();
        }

        /**
         * @return The tag for this {@link Job} which was passed in the constructor of the {@link JobRequest.Builder}.
         * @see JobRequest#getTag()
         */
        public String getTag() {
            return mRequest.getTag();
        }

        /**
         * @return Whether this {@link Job} is periodic or not. If this {@link Job} is periodic, then
         * you shouldn't return {@link Result#RESCHEDULE} as result.
         * @see JobRequest#isPeriodic()
         */
        public boolean isPeriodic() {
            return mRequest.isPeriodic();
        }

        /**
         * @return {@code true} if this job was scheduled at an exact time by calling {@link JobRequest.Builder#setExact(long)}.
         * @see JobRequest#isExact()
         */
        public boolean isExact() {
            return mRequest.isExact();
        }

        /**
         * Only valid if the job isn't periodic.
         *
         * @return The start of the time frame when the job will run after it's been scheduled.
         * @see JobRequest#getStartMs()
         */
        public long getStartMs() {
            return mRequest.getStartMs();
        }

        /**
         * Only valid if the job isn't periodic.
         *
         * @return The end of the time frame when the job will run after it's been scheduled.
         * @see JobRequest#getEndMs()
         */
        public long getEndMs() {
            return mRequest.getEndMs();
        }

        /**
         * Only valid if the job is periodic.
         *
         * @return The interval in which the job runs once.
         * @see JobRequest#getIntervalMs()
         */
        public long getIntervalMs() {
            return mRequest.getIntervalMs();
        }

        /**
         * Flex time for this job. Only valid if this is a periodic job. The job can execute
         * at any time in a window of flex length at the end of the period.
         *
         * @return How close to the end of an interval a periodic job is allowed to run.
         * @see JobRequest#getFlexMs()
         */
        public long getFlexMs() {
            return mRequest.getFlexMs();
        }

        /**
         * Returns the time when this job was scheduled.
         *

         *

         * Note that this value is only useful for non-periodic jobs. The time for periodic
         * jobs is inconsistent. Sometimes it will return the value when the periodic job was scheduled
         * for the first time and sometimes it will be updated after each period. The reason for this
         * limitation is the flex parameter, which was backported to older Android versions. You can
         * only rely on this value during the first interval of the periodic job.
         *
         * @return The time when the job was scheduled.
         */
        public long getScheduledAt() {
            return mRequest.getScheduledAt();
        }

        /**
         * Only valid if the job isn't periodic.
         *
         * @return The initial back-off time which is increasing depending on the {@link #getBackoffPolicy()}
         * if the job fails multiple times.
         * @see JobRequest#getBackoffMs()
         */
        public long getBackoffMs() {
            return mRequest.getBackoffMs();
        }

        /**
         * Only valid if the job isn't periodic.
         *
         * @return The back-off policy if a job failed and is rescheduled.
         * @see JobRequest#getBackoffPolicy()
         */
        public JobRequest.BackoffPolicy getBackoffPolicy() {
            return mRequest.getBackoffPolicy();
        }

        /**
         * Call {@link #isRequirementChargingMet()} to check whether this requirement is fulfilled.
         *
         * @return If {@code true}, then the job should only run if the device is charging.
         * @see JobRequest#requiresCharging()
         */
        public boolean requiresCharging() {
            return mRequest.requiresCharging();
        }

        /**
         * Call {@link #isRequirementDeviceIdleMet()} to check whether this requirement is fulfilled.
         *
         * @return If {@code true}, then job should only run if the device is idle.
         * @see JobRequest#requiresDeviceIdle()
         */
        public boolean requiresDeviceIdle() {
            return mRequest.requiresDeviceIdle();
        }

        /**
         * Call {@link #isRequirementNetworkTypeMet()} to check whether this requirement is fulfilled.
         *
         * @return The network state which is required to run the job.
         * @see JobRequest#requiredNetworkType()
         */
        public JobRequest.NetworkType requiredNetworkType() {
            return mRequest.requiredNetworkType();
        }

        /**
         * @return If {@code true}, then the job should only run if the battery isn't low.
         */
        public boolean requiresBatteryNotLow() {
            return mRequest.requiresBatteryNotLow();
        }

        /**
         * @return If {@code true}, then the job should only run if the battery isn't low.
         */
        public boolean requiresStorageNotLow() {
            return mRequest.requiresStorageNotLow();
        }

        /**
         * @return If {@code true}, then all requirements are checked before the job runs. If one requirement
         * isn't met, then the job is rescheduled right away.
         * @see JobRequest#requirementsEnforced()
         */
        public boolean requirementsEnforced() {
            return mRequest.requirementsEnforced();
        }

        /**
         * The failure count increases if a non periodic {@link Job} was rescheduled or if a periodic
         * {@link Job} wasn't successful.
         *
         * @return How often the job already has failed.
         */
        public int getFailureCount() {
            return mRequest.getFailureCount();
        }

        /**
         * Returns the time the job did run the last time. This is only useful for periodic jobs, daily jobs
         * or jobs which were rescheduled. If the job didn't run, yet, then it returns 0.
         *
         * @return The last time the rescheduled or periodic job did run.
         */
        public long getLastRun() {
            return mRequest.getLastRun();
        }

        /**
         * Returns whether this is a transient jobs. WARNING: It's not guaranteed that a transient job
         * will run at all, e.g. rebooting the device or force closing the app will cancel the
         * job.
         *
         * @return If this is a transient job.
         */
        public boolean isTransient() {
            return mRequest.isTransient();
        }

        /**
         * Returns the transient extras you passed in when constructing this job with
         * {@link JobRequest.Builder#setTransientExtras(Bundle)}. WARNING: It's not guaranteed that a transient job
         * will run at all, e.g. rebooting the device or force closing the app will cancel the
         * job.
         *
         *

         *

         *
         * This will never be {@code null}. If you did not set any extras this will be an empty bundle.
         *
         * @return The transient extras you passed in when constructing this job.
         */
        @NonNull
        public Bundle getTransientExtras() {
            return mTransientExtras;
        }

        /**
         * @return Extra arguments for this {@link Job}. Never returns {@code null}.
         */
        @NonNull
        public PersistableBundleCompat getExtras() {
            if (mExtras == null) {
                mExtras = mRequest.getExtras();
                if (mExtras == null) {
                    mExtras = new PersistableBundleCompat();
                }
            }
            return mExtras;
        }

        /*package*/ JobRequest getRequest() {
            return mRequest;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Params params = (Params) o;

            return mRequest.equals(params.mRequest);
        }

        @Override
        public int hashCode() {
            return mRequest.hashCode();
        }
    }
}


text:
/* eslint-disable react/display-name */
import { ComponentChildren, Fragment, FunctionalComponent, h } from 'preact';
import CodeWrap from '../../components/code-wrap';
import { stringifyFormElement } from '../../lib/audits/audit-util';
import {
  handleHighlightClick,
  handleHighlightMouseEnter,
  handleHighlightMouseLeave,
} from '../../lib/element-highlighter';
import { escapeRegExp, pluralize } from '../../lib/string-util';
import style from './style.css';

interface Props {
  item: AuditResult;
}

interface AuditTypePresenter {
  title: ComponentChildren | ((result: AuditResult) => ComponentChildren);
  render: (result: AuditResult) => ComponentChildren;
  references: LearnMoreReference[];
}

type ItemRenderer<T> = (item: TreeNodeWithContext<T>) => ComponentChildren | null;

function defaultItemAsCodeRenderer<T>(codeItem: TreeNodeWithContext<T>) {
  return {stringifyFormElement(codeItem)};
}

function defaultItemRenderer<T>(
  item: TreeNodeWithContext<T>,
  itemAsCodeRenderer: (codeItem: TreeNodeWithContext<T>) => JSX.Element = defaultItemAsCodeRenderer,
  extraContext?: (contextItem: TreeNodeWithContext<T>) => ComponentChildren | undefined,
) {
  return (
    <Fragment>
       handleHighlightClick(item)}
        onMouseEnter={() => handleHighlightMouseEnter(item)}
        onMouseLeave={() => handleHighlightMouseLeave(item)}
      >
        {itemAsCodeRenderer(item)}

      {extraContext ? extraContext(item) : null}
    </Fragment>
  );
}

function defaultItemsPresenter<T>(
  items: TreeNodeWithContext<T>[],
  itemRenderer: ItemRenderer<T> = defaultItemRenderer,
): JSX.Element {
  return (

      {items.map((item, index) => (

{itemRenderer(item)}

      ))}

  );
}

function suggestionItemRenderer<T extends ContextSuggestion>(
  item: TreeNodeWithContext<T>,
  itemAsCodeRenderer: (codeItem: TreeNodeWithContext<T>) => JSX.Element = defaultItemAsCodeRenderer,
): JSX.Element {
  return defaultItemRenderer(
    item,
    codeItem => itemAsCodeRenderer(codeItem),
    () =>
      item.context?.suggestion ? (

          Did you mean {item.context?.suggestion}?

      ) : null,
  );
}

function duplicateItemRenderer<T extends ContextDuplicates>(
  item: TreeNodeWithContext<T>,
  itemAsCodeRenderer: (codeItem: TreeNodeWithContext<T>) => JSX.Element = defaultItemAsCodeRenderer,
): JSX.Element {
  return defaultItemRenderer(
    item,
    codeItem => itemAsCodeRenderer(codeItem),
    () =>
      item.context?.duplicates?.length
        ? item.context?.duplicates.map((dup, index) => (
            <Fragment key={index}>, {defaultItemRenderer(dup, itemAsCodeRenderer)}</Fragment>
          ))
        : null,
  );
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const auditPresenters: { [auditType: string]: AuditTypePresenter } = {
  'autocomplete-attribute': {
    title: 'Increase conversions by including autocomplete attributes',
    render: result => (
      <Fragment>

          Found {pluralize(result.items.length, 'a form field', 'form fields')} with no autocomplete{' '}
          attribute, even though an appropriate value is available:

        {defaultItemsPresenter(result.items, (item: TreeNodeWithContext<ContextAutocompleteValue>) =>
          defaultItemRenderer(
            item,
            () => (
              <CodeWrap
                text={stringifyFormElement(item)}
                emphasize={item.context?.id ? `id="${item.context?.id}"` : `name="${item.context?.name}"`}
              />
            ),
            () => (

                  Add autocomplete="{item.context?.id ?? item.context?.name}" to this element.

            ),
          ),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'Help users to avoid re-entering data',
        url: 'https://web.dev/sign-in-form-best-practices/#autofill',
      },
    ],
  },
  'autocomplete-empty': {
    title: 'Increase conversions by using correct autocomplete attributes',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'a form field', 'form fields')} with empty autocomplete values:

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer(item, () => (
            <CodeWrap text={stringifyFormElement(item)} emphasize={new RegExp(' autocomplete="\\s*"')} />
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'The HTML autocomplete attribute: Values',
        url: 'https://developer.mozilla.org/docs/Web/HTML/Attributes/autocomplete#values',
      },
    ],
  },
  'autocomplete-off': {
    title: (
      <Fragment>
        Setting autocomplete="off" doesn't always work as expected
      </Fragment>
    ),
    render: result => (
      <Fragment>

          Found {pluralize(result.items.length, 'a form field', 'form fields')} with autocomplete="off"

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer(item, () => (
            <CodeWrap text={stringifyFormElement(item)} emphasize={new RegExp(' autocomplete="off"')} />
          )),
        )}

          Although autocomplete="off" is{' '}

            valid HTML
          {' '}
          and has legitimate use cases, it can be problematic for users (forcing them to reenter data) and may not work
          as expected (such as with autofill behaviour in name, address and payment forms).

      </Fragment>
    ),
    references: [
      {
        title: 'HTML spec autocomplete attribute information',
        url: 'https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete-off',
      },
      {
        title: 'The HTML autocomplete attribute: Values',
        url: 'https://developer.mozilla.org/docs/Web/HTML/Attributes/autocomplete#values',
      },
    ],
  },
  'autocomplete-valid': {
    title: 'Increase conversions by using correct autocomplete attributes',
    render: result => (
      <Fragment>

          Found {pluralize(result.items.length, 'a form field', 'form fields')} with invalid autocomplete{' '}
          values:

        {defaultItemsPresenter(result.items, item =>
          suggestionItemRenderer<ContextSuggestion>(item, codeItem => {
            return (
              <CodeWrap
                text={stringifyFormElement(item)}
                emphasize={new RegExp(`autocomplete="[^"]*(${escapeRegExp(codeItem.context?.token)})`)}
              />
            );
          }),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'The HTML autocomplete attribute',
        url: 'https://developer.mozilla.org/docs/Web/HTML/Attributes/autocomplete',
      },
    ],
  },
  'form-empty': {
    title: 'Forms should contain form fields',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'a form', 'forms')} without any form fields:

        {defaultItemsPresenter(result.items)}
      </Fragment>
    ),
    references: [
      {
        title: 'MDN: The HTML form element',
        url: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form',
      },
    ],
  },
  'input-label': {
    title:
      'Help your users using alternate input methods complete this form by ensuring each field is correctly labeled',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'an input field', 'input fields')} without a corresponding label:

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer<ContextReasons>(
            item,
            codeItem => (
              <CodeWrap
                text={stringifyFormElement(codeItem)}
                emphasize={codeItem.context?.reasons
                  .filter(reason => reason.type === 'id')
                  .map(reason => new RegExp(` id="(${escapeRegExp(reason.reference)})"`))}
              />
            ),
            contextItem => (
              <Fragment>

                  {(contextItem.context?.reasons ?? []).map((reason, index) => (

                      {reason.type === 'id' ? 'There are no labels that reference this field.' : null}
                      {reason.type === 'aria-labelledby' ? (
                        <Fragment>
                          None of the referenced labels exist:
                          {reason.reference
                            .split(' ')
                            .filter(Boolean)
                            .map((id, idIndex) => (
                              <Fragment key={idIndex}>
                                {idIndex ? ', ' : ''}

                                  {id}

                              </Fragment>
                            ))}
                        </Fragment>
                      ) : null}

                  ))}

              </Fragment>
            ),
          ),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'MDN: Labels',
        url: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label',
      },
    ],
  },
  'input-type-valid': {
    title: 'Unrecognized input types can lead to unexpected and inconsistent user experiences',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'an input field', 'input fields')} with invalid types:

        {defaultItemsPresenter(result.items, item =>
          suggestionItemRenderer<ContextSuggestion>(item, codeItem => {
            return (
              <CodeWrap
                text={stringifyFormElement(codeItem)}
                emphasize={new RegExp(`type="(${escapeRegExp(codeItem.context?.token)})"`)}
              />
            );
          }),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'MDN: The Input (Form Input) element',
        url: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types',
      },
    ],
  },
  'invalid-attributes': {
    title: 'Input and control elements with unrecognized attributes may not be achieving the desired outcome',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'an element', 'elements')} with invalid attributes

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer<ContextInvalidAttributes>(
            item,
            codeItem => {
              return (
                <CodeWrap
                  text={stringifyFormElement(
                    item,
                    codeItem.context!.invalidAttributes.map(invalid => invalid.attribute),
                  )}
                  emphasize={codeItem.context!.invalidAttributes.map(
                    invalid => new RegExp(` (${escapeRegExp(invalid.attribute)})((?==)|(?=[^"]*$)|(?![^"]+(?<!=)"))`),
                  )}
                />
              );
            },
            contextItem => (
              <Fragment>

                  {contextItem.context!.invalidAttributes.map((context, index) => (

                      {context.attribute}
                      {context.suggestion ? (

                          {' '}
                          - did you mean {context.suggestion}?

                      ) : null}

                  ))}

              </Fragment>
            ),
          ),
        )}

          Consider using{' '}

            data attributes
          {' '}
          instead of non-standard attributes.

      </Fragment>
    ),
    references: [
      {
        title: 'MDN article: Using data attributes',
        url: 'https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes',
      },
      {
        title: 'HTML Living Standard: Forms',
        url: 'https://html.spec.whatwg.org/multipage/forms.html',
      },
    ],
  },
  'label-empty': {
    title: 'Labels must have text content',
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'an empty label', 'empty labels')}:

        {defaultItemsPresenter(result.items)}
      </Fragment>
    ),
    references: [
      {
        title: 'Empty or Missing Form Label',
        url: 'https://equalizedigital.com/accessibility-checker/empty-missing-form-label',
      },
    ],
  },
  'label-no-field': {
    title: 'Make forms easier to use and more accessible by associating every label with a form field',
    render: result => (
      <Fragment>

          Found {pluralize(result.items.length, "a label that wasn't", "labels that weren't")} associated with a form
          field:

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer<ContextReasons>(
            item,
            codeItem => (
              <CodeWrap
                text={stringifyFormElement(codeItem)}
                emphasize={codeItem.context?.reasons
                  .map(
                    reason =>
                      (reason.type === 'id'
                        ? new RegExp(` id="(${escapeRegExp(reason.reference)})"`)
                        : reason.type === 'for'
                        ? new RegExp(` for="(${escapeRegExp(reason.reference)})"`)
                        : reason.type === 'empty-for'
                        ? new RegExp(` (for="")`)
                        : null)!,
                  )
                  .filter(Boolean)}
              />
            ),
            contextItem => (
              <Fragment>

                  {(contextItem.context?.reasons ?? []).map((reason, index) => (

                      {reason.type === 'id' ? (
                        <Fragment>
                          There are no form fields which reference label {reason.reference}
                        </Fragment>
                      ) : null}
                      {reason.type === 'for' ? (
                        <Fragment>
                          There are no form fields with id="{reason.reference}"
                          {reason.suggestion ? (
                            <Fragment>
                              , did you mean {reason.suggestion}?
                            </Fragment>
                          ) : null}
                        </Fragment>
                      ) : null}
                      {reason.type === 'empty-for' ? (
                        <Fragment>
                          The for attribute should not be empty
                        </Fragment>
                      ) : null}

                  ))}

              </Fragment>
            ),
          ),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'MDN: Labels',
        url: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label',
      },
    ],
  },
  'label-unique-text': {
    title: 'Labels within the same form should have unique text values',
    render: result => (
      <Fragment>

Found labels with the same text:

        {defaultItemsPresenter(result.items, item =>
          duplicateItemRenderer(item, codeItem => (
            <CodeWrap text={stringifyFormElement(item)} emphasize={new RegExp('>([^<]+)<')} />
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'Duplicate Form Label',
        url: 'https://equalizedigital.com/accessibility-checker/duplicate-form-label/',
      },
    ],
  },
  'label-unique': {
    title:
      'Form fields with multiple labels may make it difficult for tools such as screen readers to correctly identify form fields',
    render: result => (
      <Fragment>

          Found labels with the same for attribute:

        {defaultItemsPresenter(result.items, item =>
          duplicateItemRenderer(item, codeItem => (
            <CodeWrap text={stringifyFormElement(item)} emphasize={new RegExp(' for="([^"]*)"')} />
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'Duplicate Form Label',
        url: 'https://equalizedigital.com/accessibility-checker/duplicate-form-label/',
      },
    ],
  },
  'label-valid-elements': {
    title: "Don't put headings or interactive elements in labels.",
    render: result => (
      <Fragment>

Found {pluralize(result.items.length, 'a label', 'labels')} containing a heading or interactive element:

        {defaultItemsPresenter(result.items, item =>
          defaultItemRenderer<ContextFields>(item, defaultItemAsCodeRenderer, contextItem => (
            <Fragment>
              {' contains the following elements: '}
              {contextItem.context!.fields.map((field, index) => (
                <Fragment key={index}>
                  {index ? ', ' : ''}
                  {field.name}
                </Fragment>
              ))}
            </Fragment>
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'Label element: Accessibility concerns',
        url: 'https://developer.mozilla.org/docs/Web/HTML/Element/label#accessibility_concerns',
      },
    ],
  },
  'missing-identifier': {
    title: (
      <Fragment>
        Form fields should have an id or a name
      </Fragment>
    ),
    render: result => (
      <Fragment>

          Found {pluralize(result.items.length, 'a form field', 'form fields')} with no id attribute and no{' '}
          name attribute:

        {defaultItemsPresenter(result.items)}
      </Fragment>
    ),
    references: [
      {
        title: 'The HTML name attribute',
        url: 'https://developer.mozilla.org/docs/Web/HTML/Element/input#htmlattrdefname',
      },
    ],
  },
  'unique-ids': {
    title: (
      <Fragment>
        Form fields must have unique id values
      </Fragment>
    ),
    render: result => (
      <Fragment>

          Found form fields with duplicate id attributes:

        {defaultItemsPresenter(result.items, item =>
          duplicateItemRenderer(item, codeItem => (
            <CodeWrap
              text={stringifyFormElement(codeItem)}
              emphasize={new RegExp(` id="(${escapeRegExp(codeItem.attributes.id)})"`)}
            />
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'ID attribute value must be unique',
        url: 'https://dequeuniversity.com/rules/axe/4.2/duplicate-id-active',
      },
    ],
  },
  'unique-names': {
    title: (
      <Fragment>
        Fields in the same form must have unique name values
      </Fragment>
    ),
    render: result => (
      <Fragment>

          Found fields in the same form with duplicate name attributes:

        {defaultItemsPresenter(result.items, item =>
          duplicateItemRenderer(item, codeItem => (
            <CodeWrap
              text={stringifyFormElement(codeItem)}
              emphasize={new RegExp(` name="(${escapeRegExp(codeItem.attributes.name)})"`)}
            />
          )),
        )}
      </Fragment>
    ),
    references: [
      {
        title: 'The input element name attribute',
        url: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefname',
      },
    ],
  },
};

const ResultItem: FunctionalComponent<Props> = props => {
  const presenter = auditPresenters[props.item.auditType];

  return (

{presenter.title}

{presenter.render(props.item)}

      {presenter.references.length ? (

          Learn more:{' '}
          {presenter.references.map((ref, index) => (

              {index ? ', ' : ''}

                {ref.title}

          ))}

      ) : null}

  );
};

export default ResultItem;


text:
package util

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
	"strings"
)

// A PaginationResponse represents a response with pagination information
type PaginationResult struct {
	TotalCount int
	PageNumber int
	PageSize   int
}

type Pagination struct {
	PageNumber int
	PageSize   int
}

// NextPage gets the next page of the result set
func (r *PaginationResult) NextPage() *Pagination {
	if r.PageNumber*r.PageSize >= r.TotalCount {
		return nil
	}
	return &Pagination{PageNumber: r.PageNumber + 1, PageSize: r.PageSize}
}

// providerID
// 1) the id of the instance in the alicloud API. Use '.' to separate providerID which looks like 'cn-hangzhou.i-v98dklsmnxkkgiiil7'. The format of "REGION.NODEID"
// 2) the id for an instance in the kubernetes API, which has 'alicloud://' prefix. e.g. alicloud://cn-hangzhou.i-v98dklsmnxkkgiiil7
func NodeFromProviderID(providerID string) (string, string, error) {
	if strings.HasPrefix(providerID, "alicloud://") {
		k8sName := strings.Split(providerID, "://")
		if len(k8sName) < 2 {
			return "", "", fmt.Errorf("alicloud: unable to split instanceid and region from providerID, error unexpected providerID=%s", providerID)
		} else {
			providerID = k8sName[1]
		}
	}

	name := strings.Split(providerID, ".")
	if len(name) < 2 {
		return "", "", fmt.Errorf("alicloud: unable to split instanceid and region from providerID, error unexpected providerID=%s", providerID)
	}
	return name[0], name[1], nil
}

func ProviderIDFromInstance(region, instance string) string {
	return fmt.Sprintf("%s.%s", region, instance)
}

func SDKError(api string, err error) error {
	if err == nil {
		return err
	}
	switch err := err.(type) {
	case *tea.SDKError:
		if err == nil || err.Message == nil {
			return err
		}
		attr := strings.Split(tea.StringValue(err.Message), "request id:")
		if len(attr) < 2 {
			return err
		}
		err.SetErrMsg(fmt.Sprintf("[SDKError] API: %s,StatusCode: %d, ErrorCode: %s, RequestId: %s, Message: %s",
			api, tea.IntValue(err.StatusCode), tea.StringValue(err.Code), attr[1], attr[0]))
		return err
	case *errors.ServerError:
		return fmt.Errorf("[SDKError] API: %s, ErrorCode: %s, RequestId: %s, Message: %s",
			api, err.ErrorCode(), err.RequestId(), err.Message())
	default:
		return err
	}
}


text:
#ifndef VV_CREATE_DIALOG_H
#define VV_CREATE_DIALOG_H

#include "precompiled.h"
#include "vvDialog.h"
#include "vvValidatorMessageBoxReporter.h"
#include "vvSyncTargetsControl.h"

/**
 * A dialog box used to create a working copy in a directory.
 * Allows the user to attach the working copy to:
 * (1) an existing repo (checkout)
 * (2) a brand new repo (init)
 * (3) a freshly cloned repo (clone, checkout)
 */
class vvCreateDialog : public vvDialog
{
// types
public:
	/**
	 * Actions the user might select to create a freshly cloned repo to create the working copy from.
	 */
	enum CloneAction
	{
		CLONE_NOTHING, //< User chose not to create a new repo.  Clone source is not valid.
		CLONE_EMPTY,   //< User chose to create a new blank repo.  Clone source is not valid.
		CLONE_LOCAL,   //< User chose to clone a local repo.  The clone source will be the name.
		CLONE_REMOTE,  //< User chose to clone a remote repo.  The clone source will be a URL.
	};

	/**
	 * Methods that the user can use to select which revision to checkout into the new working copy.
	 */
	enum CheckoutType
	{
		CHECKOUT_BRANCH,    //< User chose to checkout the head revision of a branch.  Checkout target is the branch name.
		CHECKOUT_CHANGESET, //< User chose to checkout a specific changeset.  Checkout target will be the changeset ID.
		CHECKOUT_TAG,       //< User chose to checkout a tagged revision.  Checkout target will be the tag name.
	};

// functionality
public:
	/**
	 * Creates the actual dialog window.
	 */
	virtual bool Create(
		wxWindow*        pParent,                                 //< [in] The new dialog's parent window, or NULL if it won't have one.
		const wxString&  sFolder,                                 //< [in] The folder to create a working copy in.
		class vvVerbs&   cVerbs,                                  //< [in] The vvVerbs implementation to retrieve local repo and config info from.
		class vvContext& cContext,                                //< [in] Context to use with pVerbs.
		const wxString&  sRepoName       = wxEmptyString,         //< [in] The name of the repo to pre-select.
		CloneAction      eCloneAction    = CLONE_NOTHING,         //< [in] the clone action to pre-select.
		const wxString&  sCloneSource    = wxEmptyString,         //< [in] The clone source to pre-select.  Where it's placed depends on eCloneAction.
		CheckoutType     eCheckoutType   = CHECKOUT_BRANCH,       //< [in] The checkout type to pre-select.
		const wxString&  sCheckoutTarget = vvVerbs::sszMainBranch //< [in] The checkout target to pre-select.  Where it's placed depends on eCheckoutType.
		);

	/**
	 * Transfers our internal data to our widgets.
	 */
	virtual bool TransferDataToWindow();

	/**
	 * Stores data from our widgets to our internal data.
	 */
	virtual bool TransferDataFromWindow();

	/**
	 * Retrieves the name of the repo chosen by the user to create the working copy from.
	 * Might be the name of a repo that doesn't yet exist, check GetCloneAction.
	 */
	const wxString& GetRepo() const;

	/**
	 * Gets the action chosen by the user for attaching to a freshly cloned repo.
	 */
	CloneAction GetCloneAction() const;

	/**
	 * The source that the user wants to clone a repo from prior to attaching to it.
	 * Check GetCloneAction to determine whether it's a remote URL or another local repo name.
	 */
	const wxString& GetCloneSource() const;

	/**
	 * The descriptor of a repo that will be used for the shared users option to init.
	 */
	const wxString& GetSharedUsersRepo() const;

	/**
	 * Gets the type of checkout the user wants to perform to populate the new working copy.
	 * If they chose to checkout a particular revision, use GetCheckoutTarget to get the appropriate target.
	 */
	CheckoutType GetCheckoutType() const;

	/**
	 * The target that the user is checking out from the repo.
	 * Might be the name of a tag, branch, changeset, etc.  Use GetCheckoutType to tell.
	 */
	const wxString& GetCheckoutTarget() const;

	/**
	 * If the user picks a branch with multiple heads, then they will be required to
	 * pick which head.  The result from the vvCreateDialog will be a changeset checkout,
	 * and this method will return the branch to attach to.
	 */
	const wxString& GetBranchAttachment() const;

	/**
	 * Ask the RevSpec Control to disambiguate the branch
	 */
	bool DisambiguateBranch();

	/**
	 *
	 */
	void vvCreateDialog::SetRepo(const wxString& sRepo);

// internal functionality
protected:
	/**
	 * Update the visible/enabled state of all controls, based on the current values.
	 */
	void UpdateDisplay();

// event handlers
protected:
	void OnControlValueChange(wxCommandEvent& cEvent);

// private data
private:
	// internal data
	wxString     msRepoName;       //< The name of the repo to create the working copy from.
	CloneAction  meCloneAction;    //< The action to take to create a freshly cloned repo.
	wxString     msCloneSource;    //< The source to create a freshly cloned repo from.
	CheckoutType meCheckoutType;   //< The method to use to checkout a revision from the repo.
	wxString     msCheckoutTarget; //< The target revision to checkout from the repo.
	wxString	 msBranchAttachment; //< A branch to attach to after the checkout.  This is necessary in some cases when a branch has multiple heads.

	// widgets
	wxChoice*               mwRepo;
	wxTextCtrl*             mwNew_Name;
	wxRadioButton*          mwNew_Remote_Select;
	vvSyncTargetsControl*   mwNew_Remote_Value;
	wxRadioButton*          mwNew_Local_Select;
	wxChoice*               mwNew_Local_Value;
	wxRadioButton*          mwNew_Empty_Select;
	wxStaticText*           mwNew_Empty_Value;

	wxChoice*               mwShareUsersChoice;
	wxCheckBox*				mwShareUsers;
	wxString				msShareUserRepo;

	class vvRevSpecControl* mwRevision;

	// misc
	vvValidatorMessageBoxReporter mcValidatorReporter; //< Reporter that will display validation errors.

// macro declarations
private:
	DECLARE_DYNAMIC_CLASS(vvCreateDialog);
	DECLARE_EVENT_TABLE();
};

#endif


text:
var Stream      = require('stream').Stream;
var util        = require('util');
var spawn       = require('child_process').spawn;
var PngSplitter = require('./PngSplitter');

module.exports = PngEncoder;
util.inherits(PngEncoder, Stream);
function PngEncoder(options) {
  Stream.call(this);

  options = options || {};

  this.writable = true;
  this.readable = true;

  this._spawn       = options.spawn || spawn;
  this._imageSize   = options.imageSize || null;
  this._frameRate   = options.frameRate || 5;
  this._pngSplitter = options.pngSplitter || new PngSplitter();
  this._log         = options.log;
  this._ffmpeg      = undefined;
  this._ending      = false;
}

PngEncoder.prototype.write = function(buffer) {
  if (!this._ffmpeg) {
    this._initFfmpegAndPipes();
  }

  return this._ffmpeg.stdin.write(buffer);
};

PngEncoder.prototype._initFfmpegAndPipes = function() {
  this._ffmpeg = this._spawnFfmpeg();

  // @TODO: Make this more sophisticated for somehow and figure out how it
  // will work with the planned new data recording system.
  if (this._log) {
    this._ffmpeg.stderr.pipe(this._log);
  }

  this._ffmpeg.stdout.pipe(this._pngSplitter);
  this._pngSplitter.on('data', this.emit.bind(this, 'data'));

  this._ffmpeg.stdout.on('data', (data) => {});
  this._ffmpeg.stderr.on('data', (data) => {console.log(data.toString())});

  // 'error' can be EPIPE if ffmpeg does not exist. We handle this with the
  // 'exit' event below.
  this._ffmpeg.stdin.on('error', function() {});

  this._ffmpeg.stdin.on('drain', this.emit.bind(this, 'drain'));

  var self = this;
  // Since node 0.10, spawn emits 'error' when the child can't be spawned.
  // http://nodejs.org/api/child_process.html#child_process_event_error
  this._ffmpeg.on('error', function(err) {
    if (err.code === 'ENOENT') {
      self.emit('error', new Error('Ffmpeg was not found. Have you installed the ffmpeg package?'));
    } else {
      self.emit('error', new Error('Unexpected error when launching ffmpeg:' + err.toString()));
    }
  });

  this._ffmpeg.on('exit', function(code) {
    if (code === 0) {
      // we expected ffmpeg to exit
      if (self._ending) {
        self.emit('end');
        return;
      }

      self.emit('error', new Error('Unexpected ffmpeg exit with code 0.'));
      return;
    }

    // 127 is used by the OS to indicate that ffmpeg was not found
    // required when using node < 0.10
    if (code === 127) {
      self.emit('error', new Error('Ffmpeg was not found / exit code 127.'));
      return;
    }

    self.emit('error', new Error('Ffmpeg exited with error code: ' + code));
  });
};

PngEncoder.prototype._spawnFfmpeg = function() {
  var ffmpegOptions = [];
  ffmpegOptions.push('-i', '-'); // input flag
  ffmpegOptions.push('-f', 'image2pipe'); // format flag
  if(this._imageSize){
    ffmpegOptions.push('-s', this._imageSize); // size flag
  }
  //ffmpegOptions.push('-timelimit', '10')
  ffmpegOptions.push('-vcodec', 'png'); // codec flag
  ffmpegOptions.push('-r', this._frameRate); // framerate flag
  ffmpegOptions.push('-'); // output
  // @TODO allow people to configure the ffmpeg path
  return this._spawn('ffmpeg', ffmpegOptions);
};

PngEncoder.prototype.end = function() {
  // No data handled yet? Nothing to do for ending.
  if (!this._ffmpeg) {
    return;
  }

  this._ending = true;
  this._ffmpeg.stdin.end();
};


text:
package no.priv.garshol.duke.utils;

import java.util.Properties;
import no.priv.garshol.duke.DukeConfigException;

/**
 * Utilities for making Java Properties objects easier to deal with.
 */
public class PropertyUtils {

  /**
   * Used for getting required properties, will throw an exception if
   * the property is not specified.
   */
  public static String get(Properties props, String name) {
    String value = props.getProperty(name);
    if (value == null)
      throw new DukeConfigException("Required property " + name +
                                    " not specified");
    return value;
  }

  /**
   * Returns the value of an optional property, if the property is
   * set.  If it is not set defval is returned.
   */
  public static String get(Properties props, String name, String defval) {
    String value = props.getProperty(name);
    if (value == null)
      value = defval;
    return value;
  }

  /**
   * Returns the value of an optional property, if the property is
   * set.  If it is not set defval is returned.
   */
  public static int get(Properties props, String name, int defval) {
    String value = props.getProperty(name);
    if (value == null)
      return defval;
    return Integer.parseInt(value);
  }

}


text:
import type { BoxProps } from './Box';
import type { Color, Display, Strict } from '../themes/types';
import type { TextProps } from './Text';
import Button from './Button';
import React from 'react';
import Text from './Text';
import styled from './styled';

// Checkbox with SVG icon.
//  - flaticon.com
//  - thenounproject.com

export type CheckboxProps = {
  checkboxStyle?: Strict<BoxProps>,
  color?: Color,
  disabled?: boolean,
  display?: Display,
  field: Object, // TODO: Create type Field in fields.
  label?: string,
  labelPosition?: 'left' | 'right',
  labelStyle?: Strict<TextProps>,
  size?: number,
  svgIconChecked?: React$Element<any>,
  svgIconUnchecked?: React$Element<any>,
};

const SvgIcon = ({ color, size, svgIcon, ...props }) => {
  // Note how we can create styled componets on the fly when we need.
  const StyledSvgIcon = styled((theme, { size }) => ({
    $extends: [Text, ({
      ...props,
    }: Strict<TextProps>)],
    // Note String() to bypass type checking. We don't have typed for SVG yet.
    [String('fill')]: theme.colors[color],
    height: theme.typography.fontSize(size),
    width: theme.typography.fontSize(size),
  }), ({ className }) => React.cloneElement(svgIcon, { className }));
  return (
    <StyledSvgIcon size={size} />
  );
};

const defaultSvgIconChecked = (
  <svg viewBox="0 0 32 32">
    <path d="M2 15 L6 11 L14 19 L28 5 L32 9 L14 27 z" />
  </svg>
);

const defaultSvgIconUnchecked = (
  <svg viewBox="-16 -16 512 512">
    <path d="M405.333,106.667v298.666H106.667V106.667H405.333 M405.333,64H106.667C83.198,64,64,83.198,64,106.667v298.666    C64,428.802,83.198,448,106.667,448h298.666C428.802,448,448,428.802,448,405.333V106.667C448,83.198,428.802,64,405.333,64    L405.333,64z" />
  </svg>
);

const onClick = field => () => field.onChange({ value: !field.value });

const margin = {
  marginLeft: 0.4,
  marginRight: 1.6,
};

const Checkbox = ({
  checkboxStyle,
  color = 'black',
  disabled,
  display = 'flex',
  field,
  label,
  labelPosition = 'right',
  labelStyle,
  size = 0,
  svgIconChecked = defaultSvgIconChecked,
  svgIconUnchecked = defaultSvgIconUnchecked,
}: Strict<CheckboxProps>) => (
  <Button
    alignItems="center"
    disabled={disabled}
    display={display}
    inline
    noOutline // TODO: Fix accessibility somehow.
    onClick={onClick(field)}
    paddingHorizontal={0}
    {...checkboxStyle}
  >
    {label && labelPosition === 'left' &&
      <Text
        color={color}
        size={size}
        {...labelStyle}
      >{label}</Text>
    }
    <SvgIcon
      color={color}
      size={size}
      {...(label && labelPosition === 'left' ? margin : {})}
      svgIcon={field.value ? svgIconChecked : svgIconUnchecked}
    />
    {label && labelPosition === 'right' &&
      <Text
        color={color}
        size={size}
        {...margin}
        {...labelStyle}
      >{label}</Text>
    }
  </Button>
);

export default Checkbox;


text:
<?php declare(strict_types=1);

namespace Ajaxray\PHPWatermark\CommandBuilders;

final class PDFCommandBuilder extends AbstractCommandBuilder implements WatermarkCommandBuilderInterface
{
    /** @inheritDoc */
    public function getImageMarkCommand(string $markerImage, string $output, array $options): string
    {
        list($source, $destination) = $this->prepareContext($output, $options);
        $marker = escapeshellarg($markerImage);

        $opacity = $this->getMarkerOpacity();
        $anchor = $this->getAnchor();
        $offset = $this->getImageOffset();

        return sprintf(
            "convert %s %s  miff:- | convert -density 100 %s null: - -%s -%s -quality 100 -compose multiply -layers composite %s",
            $marker,
            $opacity,
            $source,
            $anchor,
            $offset,
            $destination
        );
    }

    /** @inheritDoc */
    public function getTextMarkCommand(string $text, string $output, array $options): string
    {
        list($source, $destination) = $this->prepareContext($output, $options);
        $text = escapeshellarg($text);

        $anchor = $this->getAnchor();
        $rotate = $this->getRotate();
        $font = $this->getFont();

        list($light, $dark) = $this->getDuelTextColor();
        list($offsetLight, $offsetDark) = $this->getDuelTextOffset();

        return sprintf(
            "convert %s -%s -quality 100 -density 100 %s -%s -annotate %s%s %s -%s -annotate %s%s %s  %s",
            $source,
            $anchor,
            $font,
            $light,
            $rotate,
            $offsetLight,
            $text,
            $dark,
            $rotate,
            $offsetDark,
            $text,
            $destination
        );
    }

    private function getMarkerOpacity(): string
    {
        $opacity = $this->getOpacity() * 100;

        return "-alpha set -channel A -evaluate set {$opacity}%";
    }

    protected function getDuelTextOffset(): array
    {
        $offset = $this->getOffset();

        return [
            "+{$offset[0]}+{$offset[1]}",
            '+'.($offset[0] + 1) .'+'. ($offset[1] + 1),
        ];
    }

    protected function getRotate(): string
    {
        return empty($this->options['rotate']) ? '' : "{$this->options['rotate']}x{$this->options['rotate']}";
    }

    protected function getDuelTextColor(): array
    {
        return [
            "fill \"rgba(255,255,255,{$this->getOpacity()})\"",
            "fill \"rgba(0,0,0,{$this->getOpacity()})\"",
        ];
    }
}


text:
package openccsensors.common.sensor;

import java.util.HashMap;

import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.world.World;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.InventoryUtils;

public abstract class TileSensor {

	public boolean isValidTarget(Object target) {
		return false;
	}

	public HashMap getDetails(TileEntity tile, ChunkCoordinates sensorPos) {

		HashMap response = new HashMap();
		HashMap position = new HashMap();

		position.put("X", tile.xCoord - sensorPos.posX);
		position.put("Y", tile.yCoord - sensorPos.posY);
		position.put("Z", tile.zCoord - sensorPos.posZ);
		response.put("Position", position);

		ItemStack stack = new ItemStack(tile.getBlockType(), 1, tile.getBlockMetadata());

		response.put("Name", InventoryUtils.getNameForItemStack(stack));
		response.put("RawName", InventoryUtils.getRawNameForStack(stack));
		response.put("DamageValue", stack.getItemDamage());

		return response;
	}

	public HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier) {

		HashMap targets = new HashMap();
		int distance = (int) tier.getMultiplier();

		for (int x = -distance; x <= distance; x++) {
			for (int y = -distance; y <= distance; y++) {
				for (int z = -distance; z <= distance; z++) {

					int tileX = x + (int)location.posX;
					int tileY = y + (int)location.posY;
					int tileZ = z + (int)location.posZ;

					String name = String.format("%s,%s,%s", x, y, z);

					TileEntity tile = world.getTileEntity(tileX, tileY, tileZ);

					if (isValidTarget(tile)) {
						targets.put(name, tile);
					}

				}
			}
		}

		return targets;

	}
}


text:
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<form method="post" class="form-stacked" action="<?php echo $view->action('save_interface_settings')?>" enctype="multipart/form-data" >

<?php echo Loader::helper('validation/token')->output('save_interface_settings')?>

<?php if (!Config::get('concrete.white_label.background_image')) { ?>

    <?php echo t('Background Image')?>

<?php echo $form->radio('DASHBOARD_BACKGROUND_IMAGE', '', $DASHBOARD_BACKGROUND_IMAGE)?> <?php echo t('Pull a picture of the day from concrete5.org (Default)')?>

<?php echo $form->radio('DASHBOARD_BACKGROUND_IMAGE', 'none', $DASHBOARD_BACKGROUND_IMAGE)?> <?php echo t('None')?>

<?php echo $form->radio('DASHBOARD_BACKGROUND_IMAGE', 'custom', $DASHBOARD_BACKGROUND_IMAGE)?> <?php echo t('Specify Custom Image')?>

    <div id="custom-background-image" <?php if ($DASHBOARD_BACKGROUND_IMAGE != 'custom') { ?>style="display: none" <?php } ?>>

        <?php echo Loader::helper('concrete/asset_library')->image('DASHBOARD_BACKGROUND_IMAGE_CUSTOM_FILE_ID', DASHBOARD_BACKGROUND_IMAGE_CUSTOM_FILE_ID, t('Choose Image'), $imageObject)?>

<?php  } else { ?>
    <?php echo t('Options disabled, interface settings are specified in config/site.php.')?>
<?php } ?>

            <button type="submit" class="btn btn-primary pull-right"><?php echo t('Save')?></button>

</form>

<?php echo Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>


text:
// Generated by gtkmmproc -- DO NOT MODIFY!

#include <gtkmm/textchildanchor.h>
#include <gtkmm/private/textchildanchor_p.h>

// -*- c++ -*-
/* $Id: textchildanchor.ccg,v 1.1 2003/01/21 13:40:42 murrayc Exp $ */

/*
 *
 * Copyright 1998-2002 The gtkmm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <gtk/gtk.h>

namespace
{
} // anonymous namespace

namespace Glib
{

Glib::RefPtr<Gtk::TextChildAnchor> wrap(GtkTextChildAnchor* object, bool take_copy)
{
  return Glib::RefPtr<Gtk::TextChildAnchor>( dynamic_cast<Gtk::TextChildAnchor*> (Glib::wrap_auto ((GObject*)(object), take_copy)) );
  //We use dynamic_cast<> in case of multiple inheritance.
}

} /* namespace Glib */

namespace Gtk
{

/* The *_Class implementation: */

const Glib::Class& TextChildAnchor_Class::init()
{
  if(!gtype_) // create the GType if necessary
  {
    // Glib::Class has to know the class init function to clone custom types.
    class_init_func_ = &TextChildAnchor_Class::class_init_function;

    // This is actually just optimized away, apparently with no harm.
    // Make sure that the parent type has been created.
    //CppClassParent::CppObjectType::get_type();

    // Create the wrapper type, with the same class/instance size as the base type.
    register_derived_type(gtk_text_child_anchor_get_type());

    // Add derived versions of interfaces, if the C type implements any interfaces:

  }

  return *this;
}

void TextChildAnchor_Class::class_init_function(void* g_class, void* class_data)
{
  BaseClassType *const klass = static_cast<BaseClassType*>(g_class);
  CppClassParent::class_init_function(klass, class_data);

}

Glib::ObjectBase* TextChildAnchor_Class::wrap_new(GObject* object)
{
  return new TextChildAnchor((GtkTextChildAnchor*)object);
}

/* The implementation: */

GtkTextChildAnchor* TextChildAnchor::gobj_copy()
{
  reference();
  return gobj();
}

TextChildAnchor::TextChildAnchor(const Glib::ConstructParams& construct_params)
:
  Glib::Object(construct_params)
{

}

TextChildAnchor::TextChildAnchor(GtkTextChildAnchor* castitem)
:
  Glib::Object((GObject*)(castitem))
{}

TextChildAnchor::~TextChildAnchor()
{}

TextChildAnchor::CppClassType TextChildAnchor::textchildanchor_class_; // initialize static member

GType TextChildAnchor::get_type()
{
  return textchildanchor_class_.init().get_type();
}

GType TextChildAnchor::get_base_type()
{
  return gtk_text_child_anchor_get_type();
}

TextChildAnchor::TextChildAnchor()
:
  // Mark this class as non-derived to allow C++ vfuncs to be skipped.
  Glib::ObjectBase(0),
  Glib::Object(Glib::ConstructParams(textchildanchor_class_.init()))
{

}

Glib::RefPtr<TextChildAnchor> TextChildAnchor::create()
{
  return Glib::RefPtr<TextChildAnchor>( new TextChildAnchor() );
}
Glib::ListHandle<Widget*> TextChildAnchor::get_widgets()
{
  return Glib::ListHandle<Widget*>(gtk_text_child_anchor_get_widgets(gobj()), Glib::OWNERSHIP_SHALLOW);
}

Glib::ListHandle<const Widget*> TextChildAnchor::get_widgets() const
{
  return Glib::ListHandle<const Widget*>(gtk_text_child_anchor_get_widgets(const_cast<GtkTextChildAnchor*>(gobj())), Glib::OWNERSHIP_SHALLOW);
}

bool TextChildAnchor::get_deleted() const
{
  return gtk_text_child_anchor_get_deleted(const_cast<GtkTextChildAnchor*>(gobj()));
}

} // namespace Gtk


text:
using namespace LightBulb;

AbstractLearningRule* PigChaseEvolution::createLearningRate()
{
	// Setup learning rule options
	EvolutionLearningRuleOptions options;
	options.creationCommands.push_back(new ConstantCreationCommand(getIntegerPreference(PREFERENCE_CREATE_UP_TO)));
	options.reuseCommands.push_back(new ConstantReuseCommand(new BestReuseSelector(), 1));
	options.selectionCommands.push_back(new BestSelectionCommand(getIntegerPreference(PREFERENCE_POPULATION_SIZE)));
	options.mutationsCommands.push_back(new ConstantMutationCommand(new AgentMutationAlgorithm(getDoublePreference(PREFERENCE_MUTATIONSTRENGTH_CHANGESPEED), 1), new RandomSelector(new RankBasedRandomFunction()), getDoublePreference(PREFERENCE_MUTATION_PERCENTAGE)));
	options.recombinationCommands.push_back(new ConstantRecombinationCommand(new RecombinationAlgorithm(), new RandomSelector(new RankBasedRandomFunction()), getDoublePreference(PREFERENCE_RECOMBINATION_PERCENTAGE)));

	// Create the learning rule for the first population
	fillDefaultEvolutionLearningRule1Options(options);
	EvolutionLearningRule* learningRule1 = new EvolutionLearningRule(options);

	// Create the learning rule for the second population
	fillDefaultEvolutionLearningRule2Options(options);
	EvolutionLearningRule* learningRule2 = new EvolutionLearningRule(options);

	// Combine both learning rules as a new one
	CoevolutionLearningRuleOptions coevolutionLearningRuleOptions;
	coevolutionLearningRuleOptions.learningRule1 = learningRule1;
	coevolutionLearningRuleOptions.learningRule2 = learningRule2;
	coevolutionLearningRuleOptions.maxIterationsPerTry = 8000;
	fillDefaultLearningRuleOptions(coevolutionLearningRuleOptions);
	return new CoevolutionLearningRule(coevolutionLearningRuleOptions);
}

FeedForwardNetworkTopologyOptions PigChaseEvolution::getNetworkOptions(int inputSize)
{
	FeedForwardNetworkTopologyOptions options;
	options.enableShortcuts = getBooleanPreference(PREFERENCE_SHORTCUT_ENABLE);

	// Adds layer sizes
	options.neuronsPerLayerCount.push_back(inputSize);
	options.neuronsPerLayerCount.push_back(getIntegerPreference(PREFERENCE_NEURON_COUNT_FIRST_LAYER));
	if (getBooleanPreference(PREFERENCE_SECOND_LAYER_ENABLE))
		options.neuronsPerLayerCount.push_back(getIntegerPreference(PREFERENCE_NEURON_COUNT_SECOND_LAYER));
	options.neuronsPerLayerCount.push_back(3);

	// Determine which activation functionn we should use
	options.descriptionFactory = new DifferentNeuronDescriptionFactory(new NeuronDescription(new WeightedSumFunction(), new RectifierFunction()), new NeuronDescription(new WeightedSumFunction(), new BinaryFunction()));
	return options;
}

AbstractEvolutionEnvironment* PigChaseEvolution::createEnvironment()
{
	// Create first combining strategy
	cs1 = new MalmoCombiningStrategy(getIntegerPreference(PREFERENCE_COMPETITIONS_SIZE));

	FeedForwardNetworkTopologyOptions options = getNetworkOptions(32);

	// Create first environment
	Malmo* malmo1 = new Malmo(options, false, cs1, new MalmoFitnessFunction(), &hof1, &hof2);

	cs1->setSecondEnvironment(static_cast<Malmo&>(*parasiteEnvironment.get()));
	cs2->setSecondEnvironment(*malmo1);

	return malmo1;

}

AbstractEvolutionEnvironment* PigChaseEvolution::createParasiteEnvironment()
{
	// Create second combining strategy
	cs2 = new MalmoCombiningStrategy(getIntegerPreference(PREFERENCE_COMPETITIONS_SIZE));

	// Create hall of fame algorithms (not used)
	hof1.reset(new RandomHallOfFameAlgorithm(getIntegerPreference(PREFERENCE_HALLOFFAME_COMPETITIONS_SIZE)));
	hof2.reset(new RandomHallOfFameAlgorithm(getIntegerPreference(PREFERENCE_HALLOFFAME_COMPETITIONS_SIZE)));

	FeedForwardNetworkTopologyOptions options = getNetworkOptions(16);

	// Create second environment
	return new Malmo(options, true, cs2, new MalmoFitnessFunction(), &hof2, &hof1);
}

PigChaseEvolution::PigChaseEvolution()
{
	// Register window
	addCustomSubApp(new MalmoTopDownWindowFactory());
	// Add preferences
	addPreference(new DoublePreference(PREFERENCE_MUTATION_PERCENTAGE, 1.8, 0, 3));
	addPreference(new DoublePreference(PREFERENCE_RECOMBINATION_PERCENTAGE, 0.3, 0, 3));
	addPreference(new DoublePreference(PREFERENCE_TOPOLOGY_MUTATION_PERCENTAGE, 0, 0, 3));
	addPreference(new IntegerPreference(PREFERENCE_POPULATION_SIZE, 150, 1, 1000));
	addPreference(new IntegerPreference(PREFERENCE_CREATE_UP_TO, 250, 1, 1000));
	addPreference(new IntegerPreference(PREFERENCE_COMPETITIONS_SIZE, 25, 1, 1000));
	addPreference(new IntegerPreference(PREFERENCE_HALLOFFAME_COMPETITIONS_SIZE, 0, 1, 1000));
	addPreference(new BooleanPreference(PREFERENCE_SHORTCUT_ENABLE, false));
	addPreference(new IntegerPreference(PREFERENCE_NEURON_COUNT_FIRST_LAYER, 32, 1, 30));
	addPreference(new BooleanPreference(PREFERENCE_SECOND_LAYER_ENABLE, false));
	addPreference(new IntegerPreference(PREFERENCE_NEURON_COUNT_SECOND_LAYER, 32, 1, 30));
	addPreference(new DoublePreference(PREFERENCE_MUTATIONSTRENGTH_CHANGESPEED, 1.6, 0, 2));
	addPreference(new DoublePreference(PREFERENCE_WEIGHTDECAY_FAC, 0, 0.003, 0.3));
}

std::string PigChaseEvolution::getOriginalName() const
{
	return "PigChase Coevolution experiment";
}

std::string PigChaseEvolution::getDescription() const
{
	return "Tries to solve the PigChase challenge with coevolution";
}

AbstractTrainingPlan * PigChaseEvolution::createNewFromSameType() const
{
	return new PigChaseEvolution();
}

std::string PigChaseEvolution::getLearningRuleName() const
{
	return CoevolutionLearningRule::getName();
}


text:
var f = function () { console.log ("hello"); }
var o = {}

o.someFunc = function () { console.log ("hello again"); }

f();
o.someFunc();


text:
namespace QuickFAST{
  namespace Communication{
    class BufferedRawFileReceiver;
    /// @brief smart pointer to a BufferedRawFileReceiver
    typedef boost::shared_ptr<BufferedRawFileReceiver> BufferedRawFileReceiverPtr;
  }
}
#endif // BUFFEREDRAWFILERECEIVER_FWD_H


text:
#if !defined (__GLIB_GOBJECT_H_INSIDE__) && !defined (GOBJECT_COMPILATION)
#error "Only <glib-object.h> can be included directly."
#endif

#ifndef __G_BOXED_H__
#define __G_BOXED_H__

#include        <gobject/gtype.h>

#ifndef __GI_SCANNER__
#include        <gobject/glib-types.h>
#endif

G_BEGIN_DECLS

/* --- type macros --- */
#define G_TYPE_IS_BOXED(type)      (G_TYPE_FUNDAMENTAL (type) == G_TYPE_BOXED)
/**
 * G_VALUE_HOLDS_BOXED:
 * @value: a valid #GValue structure
 *
 * Checks whether the given #GValue can hold values derived
 * from type %G_TYPE_BOXED.
 *
 * Returns: %TRUE on success.
 */
#define G_VALUE_HOLDS_BOXED(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_BOXED))

/* --- typedefs --- */
/**
 * GBoxedCopyFunc:
 * @boxed: The boxed structure to be copied.
 *
 * This function is provided by the user and should produce a copy
 * of the passed in boxed structure.
 *
 * Returns: The newly created copy of the boxed structure.
 */
typedef gpointer (*GBoxedCopyFunc) (gpointer boxed);

/**
 * GBoxedFreeFunc:
 * @boxed: The boxed structure to be freed.
 *
 * This function is provided by the user and should free the boxed
 * structure passed.
 */
typedef void (*GBoxedFreeFunc) (gpointer boxed);

/* --- prototypes --- */
gpointer g_boxed_copy                     (GType boxed_type,
                                           gconstpointer  src_boxed);
void     g_boxed_free                     (GType          boxed_type,
                                           gpointer       boxed);
void     g_value_set_boxed                (GValue        *value,
                                           gconstpointer  v_boxed);
void     g_value_set_static_boxed         (GValue        *value,
                                           gconstpointer  v_boxed);
void     g_value_take_boxed               (GValue        *value,
                                           gconstpointer  v_boxed);
GLIB_DEPRECATED_FOR(g_value_take_boxed)
void     g_value_set_boxed_take_ownership (GValue        *value,
                                           gconstpointer  v_boxed);
gpointer g_value_get_boxed                (const GValue  *value);
gpointer g_value_dup_boxed                (const GValue  *value);

/* --- convenience --- */
GType    g_boxed_type_register_static     (const gchar   *name,
                                           GBoxedCopyFunc boxed_copy,
                                           GBoxedFreeFunc boxed_free);

/* --- GObject boxed types --- */
/**
 * G_TYPE_CLOSURE:
 *
 * The #GType for #GClosure.
 */
#define G_TYPE_CLOSURE (g_closure_get_type ())

/**
 * G_TYPE_VALUE:
 *
 * The type ID of the "GValue" type which is a boxed type,
 * used to pass around pointers to GValues.
 */
#define G_TYPE_VALUE (g_value_get_type ())

GType   g_closure_get_type         (void) G_GNUC_CONST;
GType   g_value_get_type           (void) G_GNUC_CONST;

G_END_DECLS

#endif  /* __G_BOXED_H__ */