text:
RADConnector::RADConnector(const char* name) {
  _name = name;
  _http = ESP8266WebServer(RAD_HTTP_PORT);
  _subscriptionCount = 0;
  _lastWrite = 0;
}

static const char* HEADERS[] = {
  HEADER_HOST,
  HEADER_CALLBACK,
  HEADER_NT,
  HEADER_TIMEOUT
};

void RADConnector::add(RADFeature* feature) {
  _features.add(feature);
}

RADSubscription* RADConnector::subscribe(RADFeature* feature, EventType type,
                                    const char* callback, int timeout) {
  RADSubscription* s;
  RADFeature* f;
  for(int i = 0; i < _subscriptions.size(); i++) {
    s = _subscriptions.get(i);
    f = s->getFeature();
    if(feature == f && s->getType() == type && strcmp(s->getCallback(), callback) == 0) {
      unsubscribe(i);
      i -= 1;
    }
  }

  _subscriptionCount += 1;
  char sid[SSDP_UUID_SIZE];
  uint32_t chipId = ESP.getChipId();
  sprintf(sid, "38323636-4558-4dda-9188-cd%02x%02x%02x%04x",
  (uint16_t) ((chipId >> 16) & 0xff),
  (uint16_t) ((chipId >>  8) & 0xff),
  (uint16_t)   chipId        & 0xff ,
              _subscriptionCount);
  s = new RADSubscription(feature, sid, type, callback, timeout);
  _subscriptions.add(s);
  feature->add(s);
  _subscriptionsChanged = true;
  return s;
}

void RADConnector::unsubscribe(int index) {
  RADSubscription* s;
  s = _subscriptions.get(index);
  _subscriptions.remove(index);
  RADFeature* feature = s->getFeature();
  feature->remove(s);
  delete s;
  _subscriptionsChanged = true;
}

bool RADConnector::begin(void) {

  // Start the SPIFFS object
  SPIFFS.begin();

  // Load the existing subscriptions from SPIFFS
  if(SPIFFS.exists(RAD_SUBSCRIPTIONS_FILE)) {
    File f = SPIFFS.open(RAD_SUBSCRIPTIONS_FILE, "r");
    // Check if file opened sucessfully
    if(f) {
      String subcription_data = f.readString();
      f.close();
      StaticJsonBuffer<2048> jsonBuffer;
      JsonObject& subscription_json = jsonBuffer.parseObject(subcription_data);
      if(subscription_json.containsKey("count")) {
        _subscriptionCount = subscription_json["count"];
      }
      if(subscription_json.containsKey("subscriptions")) {
        JsonArray& subscription_array = subscription_json["subscriptions"];
        RADFeature* feature;
        RADSubscription* s;
        for (auto value : subscription_array) {
          JsonObject& subscription = value.as<JsonObject&>();
          // TODO: print out the data for testing
          if(!subscription.containsKey("id") ||
             !subscription.containsKey("feature_id") ||
             !subscription.containsKey("type") ||
             !subscription.containsKey("callback") ||
             !subscription.containsKey("timeout") ||
             !subscription.containsKey("calls") ||
             !subscription.containsKey("errors")) {
            continue;
          } else {
            const char* id = subscription["id"];
            const char* feature_id = subscription["feature_id"];
            EventType type = getEventType(subscription["type"]);
            const char* callback = subscription["callback"];
            int timeout = subscription["timeout"];
            int calls = subscription["calls"];
            int errors = subscription["errors"];
            feature = getFeature(feature_id);
            if(feature == NULL) {
              continue;
            }
            s = new RADSubscription(feature, id, type, callback, timeout);
            _subscriptions.add(s);
            feature->add(s);
          }
        }
      }
    }
  }

  // Prepare the uuid
  uint32_t chipId = ESP.getChipId();
  sprintf(_uuid, "38323636-4558-4dda-9188-cda0e6%02x%02x%02x",
  (uint16_t) ((chipId >> 16) & 0xff),
  (uint16_t) ((chipId >>  8) & 0xff),
  (uint16_t)   chipId        & 0xff);

  // Prepare the info response
  char buffer[512];
  sprintf(buffer, _info_template,
    _name,
    _uuid
  );
  _info = String(buffer);

  // Debugging...
  // Serial.println("ChipId: ");
  // Serial.println(chipId);
  // Serial.println((uint16_t) ((chipId >> 16) & 0xff));
  // Serial.println((uint16_t) ((chipId >>  8) & 0xff));
  // Serial.println((uint16_t)   chipId        & 0xff);
  // Serial.print("IP address: ");
  // Serial.println(WiFi.localIP());

  // Add the HTTP handlers
  _http.on(RAD_INFO_PATH, std::bind(&RADConnector::handleInfo, this));
  _http.on(RAD_FEATURES_PATH, std::bind(&RADConnector::handleFeatures, this));
  _http.on(RAD_SUBSCRIPTIONS_PATH, std::bind(&RADConnector::handleSubscriptions, this, (RADFeature*)NULL));
  _http.on(RAD_COMMANDS_PATH, std::bind(&RADConnector::handleCommands, this, (RADFeature*)NULL));
  _http.on(RAD_EVENTS_PATH, std::bind(&RADConnector::handleEvents, this, (RADFeature*)NULL));

  // Loop through features and add HTTP handlers
  RADFeature* _http_feature = NULL;
  char _path_buffer[255];
  for(int i = 0; i < _features.size(); i++) {
    _http_feature = _features.get(i);
    snprintf(_path_buffer, sizeof(_path_buffer), RAD_FEATURES_PATH "/%s" RAD_SUBSCRIPTIONS_PATH, _http_feature->getId());
    _http.on(_path_buffer, std::bind(&RADConnector::handleSubscriptions, this, _http_feature));
    snprintf(_path_buffer, sizeof(_path_buffer), RAD_FEATURES_PATH "/%s" RAD_COMMANDS_PATH, _http_feature->getId());
    _http.on(_path_buffer, std::bind(&RADConnector::handleCommands, this, _http_feature));
    snprintf(_path_buffer, sizeof(_path_buffer), RAD_FEATURES_PATH "/%s" RAD_EVENTS_PATH, _http_feature->getId());
    _http.on(_path_buffer, std::bind(&RADConnector::handleEvents, this, _http_feature));
  }

  // Prepare the SSDP configuration
  _http.collectHeaders(HEADERS, 4);
  _http.begin();
  SSDP.setDeviceType(RAD_DEVICE_TYPE);
  SSDP.setName(_name);
  SSDP.setURL("");
  SSDP.setSchemaURL("");
  SSDP.setSerialNumber(WiFi.macAddress());
  SSDP.setModelName(RAD_MODEL_NAME);
  SSDP.setModelNumber(RAD_MODEL_NUM);
  SSDP.setModelURL(RAD_INFO_URL);
  SSDP.setManufacturer("NA");
  SSDP.setManufacturerURL(RAD_INFO_URL);
  SSDP.setHTTPPort(RAD_HTTP_PORT);
  SSDP.begin();
}

void RADConnector::update(void) {
  // loop
  _http.handleClient();
  yield(); // Allow WiFi stack a chance to run

  long current = millis();
  // Check for expired subscriptions
  RADSubscription* s;
  for(int i = 0; i < _subscriptions.size(); i++) {
    s = _subscriptions.get(i);
    if(!s->isActive(current)) {
      //Serial.println("Found expired subscription!");
      unsubscribe(i);
      i -= 1;
    }
  }
  yield(); // Allow WiFi stack a chance to run

  // Check to see if we need to write to SPIFFS
  if(_subscriptionsChanged && current - _lastWrite >= RAD_MIN_WRITE_INTERVAL) {
    // TODO: Write subscriptions to file
    // Serial.println("Writing subscriptions to file!");
    _lastWrite = current;
    _subscriptionsChanged = false;
  }
  yield(); // Allow WiFi stack a chance to run

}

RADFeature* RADConnector::getFeature(const char* feature_id) {
  RADFeature* feature = NULL;
  for(int i = 0; i < _features.size(); i++) {
    if(strcmp(_features.get(i)->getId(), feature_id) == 0) {
      feature = _features.get(i);
      break;
    }
  }
  return feature;
}

void RADConnector::handleInfo(void) {
  Serial.println("/");
  if(_http.method() == HTTP_GET) {
    _http.send(200, "application/json", _info);
  } else {
    _http.send(405);
  }
}

void RADConnector::handleFeatures() {
  Serial.println("RADConnector::handleFeatures");
  int code = 200;
  if(_http.method() == HTTP_GET) {
    // Prepare the JSON response
    StaticJsonBuffer<1024> featuresBuffer;
    char featuresString[1024];
    char linkBuff[255];
    JsonArray& features = featuresBuffer.createArray();
    RADFeature* feature;
    for(int i = 0; i < _features.size(); i++) {
      feature = _features.get(i);
      JsonObject& feature_json = features.createNestedObject();
      feature_json["id"] = feature->getId();
      feature_json["name"] = feature->getName();
      feature_json["type"] = sendFeatureType(feature->getType());
      feature_json["description"] = "";
      JsonObject& links_json = feature_json.createNestedObject("links");
      snprintf(linkBuff, sizeof(linkBuff), RAD_FEATURES_PATH "/%s", feature->getId());
      links_json["details"] = String(linkBuff);
      snprintf(linkBuff, sizeof(linkBuff), RAD_FEATURES_PATH "/%s" RAD_COMMANDS_PATH, feature->getId());
      links_json["commands"] = String(linkBuff);
      snprintf(linkBuff, sizeof(linkBuff), RAD_FEATURES_PATH "/%s" RAD_SUBSCRIPTIONS_PATH, feature->getId());
      links_json["subscriptions"] = String(linkBuff);
      snprintf(linkBuff, sizeof(linkBuff), RAD_FEATURES_PATH "/%s" RAD_EVENTS_PATH, feature->getId());
      links_json["events"] = String(linkBuff);
    }
    features.printTo(featuresString, sizeof(featuresString));
    _http.send(code, "application/json", featuresString);
  } else {
    _http.send(405);
  }
}

void RADConnector::handleSubscriptions(RADFeature* feature) {
  Serial.println("RADConnector::handleSubscriptions");
  int code = 200;
  long current = millis();
  if(_http.method() == HTTP_GET) {
    // Prepare the JSON response
    StaticJsonBuffer<1024> subscriptionsBuffer;
    char subscriptionsString[1024];
    JsonArray& subscriptions = subscriptionsBuffer.createArray();
    RADFeature* featureIt;
    RADSubscription* subscription;
    for(int i = 0; i < _subscriptions.size(); i++) {
      subscription = _subscriptions.get(i);
      if(subscription->isActive(current)) {
        featureIt = subscription->getFeature();
        if(feature != NULL && feature != featureIt) continue;
        JsonObject& subscription_json = subscriptions.createNestedObject();
        subscription_json["id"] = subscription->getSid();
        subscription_json["feature_id"] = featureIt->getId();
        subscription_json["event_type"] = sendEventType(subscription->getType());
        subscription_json["callback"] = subscription->getCallback();
        subscription_json["timeout"] = subscription->getTimeout();
        subscription_json["duration"] = subscription->getDuration(current);
      }
    }
    subscriptions.printTo(subscriptionsString, sizeof(subscriptionsString));
    _http.send(code, "application/json", subscriptionsString);
  // POST Method
  } else if(_http.method() == HTTP_POST) {
    String message = "";
    StaticJsonBuffer<255> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(_http.arg("plain"));
    if(feature == NULL && !root.containsKey("feature_id")) {
      code = 400;
      message = "{\"error\": \"Missing required property 'feature_id'.\"}";
    } else if(!root.containsKey("event_type")) {
      code = 400;
      message = "{\"error\": \"Missing required property 'event_type'.\"}";
    } else if(!root.containsKey("callback")) {
      code = 400;
      message = "{\"error\": \"Missing required property 'callback'.\"}";
    } else {
      EventType type = getEventType(root["event_type"]);
      const char* callback = root["callback"];
      int timeout = RAD_MIN_TIMEOUT;
      if(root.containsKey("timeout")) {
        timeout = root["timeout"];
      }
      RADFeature* featureTarget;
      if(feature == NULL) {
        const char* feature_id = root["feature_id"];
        featureTarget = getFeature(feature_id);
      } else {
        featureTarget = feature;
      }
      if (featureTarget == NULL) {
        code = 400;
        message = "{\"error\": \"Feature could not be located.\"}";
      } else if(type == NullEvent) {
        code = 400;
        message = "{\"error\": \"Unsuported event type.\"}";
      } else if(timeout < RAD_MIN_TIMEOUT) {
        code = 400;
        message = "{\"error\": \"The timeout property can not be less than 600 seconds.\"}";
      } else {
        RADSubscription* subscription = subscribe(featureTarget, type, callback, timeout);
        char sid[100];
        snprintf(sid, sizeof(sid), "uuid:%s", subscription->getSid());
        _http.sendHeader("SID", sid);
        _http.sendHeader(HEADER_TIMEOUT, String(timeout));
      }
    }
    _http.send(code, "application/json", message);
  } else {
    _http.send(405);
  }
}

void RADConnector::handleCommands(RADFeature* feature) {
  Serial.println("RADConnector::handleCommands");
  int code = 200;
  uint8_t value;
  bool result = false;
  RADPayload* response = NULL;
  String message = "";
  if(_http.method() == HTTP_POST) {
    Serial.println("RADConnector::handleCommands - POST");
    StaticJsonBuffer<255> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(_http.arg("plain"));
    if(feature == NULL && !root.containsKey("feature_id")) {
      code = 400;
      message = "{\"error\": \"Missing required property, 'feature_id'.\"}";
    }else  if(!root.containsKey("command_type")) {
      code = 400;
      message = "{\"error\": \"Missing required property, 'command_type'.\"}";
    } else {
      RADFeature* featureTarget;
      if(feature == NULL) {
        const char* feature_id = root["feature_id"];
        featureTarget = getFeature(feature_id);
      } else {
        featureTarget = feature;
      }
      if(featureTarget == NULL) {
        code = 400;
        message = "{\"error\": \"Invalid 'feature_id' value.\"}";
      } else {
        CommandType type = getCommandType(root["command_type"]);
        switch(type) {
          case Set:
            Serial.println("RADConnector::handleCommands - case Set:");
            if(!root.containsKey("data")) {
              code = 400;
              message = "{\"error\": \"Missing required property, 'data'.\"}";
            } else {
              if(root["data"].is<bool>()) {
                result = execute(featureTarget->getId(), Set, (bool)root["data"].as<bool>(), (RADPayload*)NULL);
              } else if(root["data"].is<int>()) {
                // TODO: handle
              } else if(root["data"].is<char*>()) {
                // TODO: handle base64 encoded data
              }
            }
            break;
          case Get:
            response = new RADPayload();
            result = execute(featureTarget->getId(), Get, response);
            if(result && response != NULL) {
              switch(response->type) {
                case BoolPayload:
                  if(response->data[0]) {
                    message = "{\"data\": true}";
                  } else {
                    message = "{\"data\": false}";
                  }
                  break;
                case BytePayload:
                  char buff[100];
                  snprintf(buff, sizeof(buff), "{\"data\": %d}", response->data[0]);
                  message = buff;
                  break;
                case ByteArrayPayload:
                  // TODO: handle get payload
                  break;
              }
            } else {
              code = 500;
              message = "{\"error\": \"Failure.\"}";
            }
            break;
          default:
            code = 400;
            message = "{\"error\": \"Unsuported command type.\"}";
            break;
        }
      }
    }
    _http.send(code, "application/json", message);
  } else {
    _http.send(405);
  }
}

void RADConnector::handleEvents(RADFeature* feature) {
  Serial.println("RADConnector::handleEvents");
  _http.send(200, "application/json", "RADConnector::handleEvents");
  return;
}

bool RADConnector::execute(const char* feature_id, CommandType command_type, RADPayload* response) {
  Serial.println("RADConnector::execute - empty");
  return execute(feature_id, command_type, (RADPayload*)NULL, response);
}

bool RADConnector::execute(const char* feature_id, CommandType command_type, bool data, RADPayload* response) {
  Serial.print("RADConnector::execute - bool = ");
  Serial.println(data);
  RADPayload* payload = RADConnector::BuildPayload(data);
  bool result = execute(feature_id, command_type, payload, response);
  delete payload;
  return result;
}

bool RADConnector::execute(const char* feature_id, CommandType command_type, uint8_t data, RADPayload* response) {
  Serial.println("RADConnector::execute - byte");
  RADPayload* payload = RADConnector::BuildPayload(data);
  bool result = execute(feature_id, command_type, payload, response);
  delete payload;
  return result;
}

bool RADConnector::execute(const char* feature_id, CommandType command_type, RADPayload* payload, RADPayload* response) {
  Serial.println("RADConnector::execute - payload");
  RADFeature* feature;
  bool result = false;
  for(int i = 0; i < _features.size(); i++) {
    feature = _features.get(i);
    if(strcmp(feature->getId(), feature_id) == 0) {
      result = feature->execute(command_type, payload, response);
      break;
    }
  }
  return result;
}

RADPayload* RADConnector::BuildPayload(bool data) {
  RADPayload* payload = new RADPayload();
  payload->type = BoolPayload;
  payload->len = 1;
  payload->data = (uint8_t*)malloc(payload->len * sizeof(uint8_t));
  if(data) {
    payload->data[0] = 255;
  } else {
    payload->data[0] = 0;
  }
  return payload;
}

RADPayload* RADConnector::BuildPayload(uint8_t data) {
  RADPayload* payload = new RADPayload();
  payload->type = BytePayload;
  payload->len = 1;
  payload->data = (uint8_t*)malloc(payload->len * sizeof(uint8_t));
  payload->data[0] = data;
  return payload;
}

RADPayload* RADConnector::BuildPayload(uint8_t* data, uint8_t len) {
  RADPayload* payload = new RADPayload();
  payload->type = ByteArrayPayload;
  payload->len = len;
  payload->data = data;
  return payload;
}


text:
<?php

namespace Pair;

class Schedule {

	/**
	 * Current DateTime.
	 * @var DateTime;
	 */
	private $now;

	/**
	 * Function to call.
	 * @var NULL|callable
	 */
	private $functionToRun;

	/**
	 * Callable function's parameters (optional).
	 * @var mixed
	 */
	private $params;

	/**
	 * Flag to enable action execution.
	 * @var bool
	 */
	private $timeToRun = FALSE;

	public function __construct() {

		$this->now = new \DateTime();

	}

	/**
	 * Assign the method to be launched and any parameters to the object.
	 *
	 * @param callable $functionToRun
	 * @param mixed|null $params
	 * @return Schedule
	 */
	public function command(callable $functionToRun, $params=NULL): self {

		$this->params = $params;

		// reset the value for next calls on the same instance object
		$this->timeToRun = FALSE;

		if (is_callable($functionToRun)) {
			$this->functionToRun = $functionToRun;
		}

		return $this;

	}

	/**
	 * Run the required user function.
	 * @return bool
	 */
	private function handle(): bool {

		if (!$this->timeToRun or !$this->functionToRun) {
			return FALSE;
		}

		if (FALSE === call_user_func($this->functionToRun, $this->params)) {
			return FALSE;
		}

		return TRUE;

	}

	/**
	 * Run the task every minute.
	 * @return bool
	 */
	public function everyMinute(): bool {

		$this->timeToRun = TRUE;

		return $this->handle();

	}

	/**
	 * Run the task every two minutes.
	 * @return bool
	 */
	public function everyTwoMinutes(): bool {

		if (intval($this->now->format('i'))%2 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every three minutes.
	 * @return bool
	 */
	public function everyThreeMinutes(): bool {

		if (intval($this->now->format('i'))%3 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every four minutes.
	 * @return bool
	 */
	public function everyFourMinutes(): bool {

		if (intval($this->now->format('i'))%4 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every five minutes.
	 * @return bool
	 */
	public function everyFiveMinutes(): bool {

		if (intval($this->now->format('i'))%5 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every ten minutes.
	 * @return bool
	 */
	public function everyTenMinutes(): bool {

		if (intval($this->now->format('i'))%10 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every fifteen minutes.
	 * @return bool
	 */
	public function everyFifteenMinutes(): bool {

		if (intval($this->now->format('i'))%15 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every thirty minutes.
	 * @return bool
	 */
	public function everyThirtyMinutes(): bool {

		if (intval($this->now->format('i'))%30 == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every hour.
	 * @return bool
	 */
	public function hourly(): bool {

		if (intval($this->now->format('i')) == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every hour at {$minutes} minutes past the hour.
	 * @param int $minutes
	 * @return bool
	 */
	public function hourlyAt(int $minutes): bool {

		if (intval($this->now->format('i')) == $minutes) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every two hours.
	 * @return bool
	 */
	public function everyTwoHours(): bool {

		if (intval($this->now->format('H'))%2 == 0 and intval($this->now->format('i')) == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every three hours.
	 * @return bool
	 */
	public function everyThreeHours(): bool {

		if (intval($this->now->format('H'))%3 == 0 and intval($this->now->format('i')) == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every four hours.
	 * @return bool
	 */
	public function everyFourHours(): bool {

		if (intval($this->now->format('H'))%4 == 0 and intval($this->now->format('i')) == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every six hours.
	 * @return bool
	 */
	public function everySixHours(): bool {

		if (intval($this->now->format('H'))%6 == 0 and intval($this->now->format('i')) == 0) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every day at midnight.
	 * @return bool
	 */
	public function daily(): bool {

		if ($this->now->format('H:i') == '00:00') {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every day at {$time}.
	 * @param string $time
	 * @return bool
	 */
	public function dailyAt(string $time): bool {

		if ($this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task daily at {$time1} & {$time2}.
	 * @param string $time1
	 * @param string $time2
	 * @return bool
	 */
	public function twiceDaily(string $time1, string $time2): bool {

		if (in_array($this->now->format('H:i'), [$time1, $time2])) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every Sunday at 00:00.
	 * @return bool
	 */
	public function weekly(): bool {

		if (intval($this->now->format('w')) == 0 and $this->now->format('H:i') == '00:00') {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every {dayOfTheWeek} at {time}.
	 * @param int $dayOfTheWeek
	 * @param string $time
	 * @return bool
	 */
	public function weeklyOn(int $dayOfTheWeek, string $time): bool {

		if (intval($this->now->format('w')) == $dayOfTheWeek and $this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task on the first day of every month at 00:00.
	 * @return bool
	 */
	public function monthly(): bool {

		if (intval($this->now->format('d')) == 1 and $this->now->format('H:i') == '00:00') {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every month on the {$dayOfTheMonth} at {$time}.
	 * @param int $dayOfTheMonth
	 * @param string $time
	 * @return bool
	 */
	public function monthlyOn(int $dayOfTheMonth, string $time): bool {

		if (intval($this->now->format('d')) == $dayOfTheMonth and $this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task monthly on the {$dayOfTheMonth1} and {$dayOfTheMonth2} at {$time}.
	 * @param int $dayOfTheMonth1
	 * @param int $dayOfTheMonth2
	 * @param string $time
	 * @return bool
	 */
	public function twiceMonthly(int $dayOfTheMonth1, int $dayOfTheMonth2, string $time): bool {

		if (in_array(intval($this->now->format('d')), [$dayOfTheMonth1,$dayOfTheMonth2]) and $this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task on the last day of the month at {$time}.
	 * @param string $time
	 * @return bool
	 */
	public function lastDayOfMonth(string $time): bool {

		if (intval($this->now->format('d')) == intval($this->now->format('t')) and $this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task on the first day of every quarter at 00:00.
	 * @return bool
	 */
	public function quarterly(): bool {

		if ((intval($this->now->format('m'))-1) %3 == 0 and intval($this->now->format('d')) == 1 and $this->now->format('H:i') == '00:00') {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task on the first day of every year at 00:00.
	 * @return bool
	 */
	public function yearly(): bool {

		if (intval($this->now->format('m')) == 1 and intval($this->now->format('d')) == 1 and $this->now->format('H:i') == '00:00') {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

	/**
	 * Run the task every year in {$month}, on day of month {$dayOfTheMonth1} at {$time}.
	 * @param int $month
	 * @param int $dayOfTheMonth
	 * @param string $time
	 * @return bool
	 */
	public function yearlyOn(int $month, int $dayOfTheMonth, string $time): bool {

		if (intval($this->now->format('m')) == $month and intval($this->now->format('d')) == $dayOfTheMonth and $this->now->format('H:i') == $time) {
			$this->timeToRun = TRUE;
		}

		return $this->handle();

	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.taotao.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.entity.TbItem;
import com.taotao.entity.TbItemExample;
import com.taotao.mapper.TbItemMapper;

public class PageHelperTest {

	@Test
	public void pageHelperTest(){
		//创建一个spring容器
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
		//从spring容器中获得Mapper的代理对象
		TbItemMapper mapper = applicationContext.getBean(TbItemMapper.class);
		//执行查询,并分页
		TbItemExample example = new TbItemExample();
		//分页处理
		PageHelper.startPage(1,10);
		List<TbItem> list = mapper.selectByExample(example);
		//取商品列表
		for(TbItem item:list){
			System.out.println(item.getTitle());
		}
		//取分页信息
		PageInfo<TbItem> pageInfo = new PageInfo<TbItem>(list);
		Long total = pageInfo.getTotal();

		System.out.println("共有商品"+total);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.hive.ql.io.parquet;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.hive.common.StringInternUtils;
import org.apache.hadoop.hive.ql.exec.SerializationUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.plan.TableScanDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr;
import org.apache.hadoop.hive.serde2.ColumnProjectionUtils;
import org.apache.hadoop.mapred.JobConf;

public class ProjectionPusher {

  private static final Logger LOG = LoggerFactory.getLogger(ProjectionPusher.class);

  private final Map<Path, PartitionDesc> pathToPartitionInfo = new LinkedHashMap<>();
  /**
   * MapWork is the Hive object which describes input files,
   * columns projections, and filters.
   */
  private MapWork mapWork;

  /**
   * Sets the mapWork variable based on the current JobConf in order to get all partitions.
   *
   * @param job
   */
  private void updateMrWork(final JobConf job) {
    final String plan = HiveConf.getVar(job, HiveConf.ConfVars.PLAN);
    if (mapWork == null && plan != null && plan.length() > 0) {
      mapWork = Utilities.getMapWork(job);
      pathToPartitionInfo.clear();
      for (final Map.Entry<Path, PartitionDesc> entry : mapWork.getPathToPartitionInfo().entrySet()) {
        // key contains scheme (such as pfile://) and we want only the path portion fix in HIVE-6366
        pathToPartitionInfo.put(StringInternUtils.internUriStringsInPath(
                Path.getPathWithoutSchemeAndAuthority(entry.getKey())), entry.getValue());
      }
    }
  }

  private void pushProjectionsAndFilters(final JobConf jobConf,
      final String splitPath,
      final String splitPathWithNoSchema) {

    if (mapWork == null) {
      return;
    } else if (mapWork.getPathToAliases() == null) {
      return;
    }

    final Set<String> aliases = new HashSet<String>();
    try {
      List<String> a = HiveFileFormatUtils.getFromPathRecursively(
          mapWork.getPathToAliases(), new Path(splitPath), null, false, true);
      if (a != null) {
        aliases.addAll(a);
      }
      if (a == null || a.isEmpty()) {
        // TODO: not having aliases for path usually means some bug. Should it give up?
        LOG.warn("Couldn't find aliases for " + splitPath);
      }
    } catch (IllegalArgumentException | IOException e) {
      throw new RuntimeException(e);
    }
    // Collect the needed columns from all the aliases and create ORed filter
    // expression for the table.
    boolean allColumnsNeeded = false;
    boolean noFilters = false;
    Set<Integer> neededColumnIDs = new HashSet<Integer>();
    // To support nested column pruning, we need to track the path from the top to the nested
    // fields
    Set<String> neededNestedColumnPaths = new HashSet<String>();
    List<ExprNodeGenericFuncDesc> filterExprs = new ArrayList<ExprNodeGenericFuncDesc>();
    RowSchema rowSchema = null;

    for(String alias : aliases) {
      final Operator<? extends Serializable> op =
          mapWork.getAliasToWork().get(alias);
      if (op != null && op instanceof TableScanOperator) {
        final TableScanOperator ts = (TableScanOperator) op;

        if (ts.getNeededColumnIDs() == null) {
          allColumnsNeeded = true;
        } else {
          neededColumnIDs.addAll(ts.getNeededColumnIDs());
          if (ts.getNeededNestedColumnPaths() != null) {
            neededNestedColumnPaths.addAll(ts.getNeededNestedColumnPaths());
          }
        }

        rowSchema = ts.getSchema();
        ExprNodeGenericFuncDesc filterExpr =
            ts.getConf() == null ? null : ts.getConf().getFilterExpr();
        noFilters = filterExpr == null; // No filter if any TS has no filter expression
        filterExprs.add(filterExpr);
      }
    }

    ExprNodeGenericFuncDesc tableFilterExpr = null;
    if (!noFilters) {
      try {
        for (ExprNodeGenericFuncDesc filterExpr : filterExprs) {
          if (tableFilterExpr == null ) {
            tableFilterExpr = filterExpr;
          } else {
            tableFilterExpr = ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPOr(),
                Arrays.<ExprNodeDesc>asList(tableFilterExpr, filterExpr));
          }
        }
      } catch(UDFArgumentException ex) {
        LOG.debug("Turn off filtering due to " + ex);
        tableFilterExpr = null;
      }
    }

    // push down projections
    if (!allColumnsNeeded) {
      if (!neededColumnIDs.isEmpty()) {
        ColumnProjectionUtils.appendReadColumns(jobConf, new ArrayList<Integer>(neededColumnIDs));
        ColumnProjectionUtils.appendNestedColumnPaths(jobConf,
          new ArrayList<String>(neededNestedColumnPaths));
      }
    } else {
      ColumnProjectionUtils.setReadAllColumns(jobConf);
    }

    pushFilters(jobConf, rowSchema, tableFilterExpr);
  }

  private void pushFilters(final JobConf jobConf, RowSchema rowSchema, ExprNodeGenericFuncDesc filterExpr) {
    // construct column name list for reference by filter push down
    Utilities.setColumnNameList(jobConf, rowSchema, true);

    // push down filters
    if (filterExpr == null) {
      LOG.debug("Not pushing filters because FilterExpr is null");
      return;
    }

    final String filterText = filterExpr.getExprString();
    final String filterExprSerialized = SerializationUtilities.serializeExpression(filterExpr);
    jobConf.set(
        TableScanDesc.FILTER_TEXT_CONF_STR,
        filterText);
    jobConf.set(
        TableScanDesc.FILTER_EXPR_CONF_STR,
        filterExprSerialized);
  }

  public JobConf pushProjectionsAndFilters(JobConf jobConf, Path path)
      throws IOException {
    updateMrWork(jobConf);  // TODO: refactor this in HIVE-6366
    final JobConf cloneJobConf = new JobConf(jobConf);
    final PartitionDesc part = HiveFileFormatUtils.getFromPathRecursively(
        pathToPartitionInfo, path, null, false, true);

    try {
      if ((part != null) && (part.getTableDesc() != null)) {
        Utilities.copyTableJobPropertiesToConf(part.getTableDesc(), cloneJobConf);
      }
    } catch (Exception e) {
      throw new IOException(e);
    }

    pushProjectionsAndFilters(cloneJobConf, path.toString(), path.toUri().getPath());
    return cloneJobConf;
  }
}


text:
using EzApp.Validation.Core.Validators.EntityValidators;
using System.Collections.Generic;

namespace EzApp.Validation.Core.Errors
{
    public interface IEzErrorSetter
        <TDto,
        TEntityFieldErrorCollection>
    {
        IEzEntityErrorCollection<TEntityFieldErrorCollection> SetErrors(TDto createDto, ICollection<IEzRuleValidator<TDto, TEntityFieldErrorCollection>> createRuleValidators);
    }
}


text:
require 'test_helper'

class UploadsTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Uploads
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetConsole.Core.Exceptions
{
    public class FailedUnregisterOperationException : CoreException
    {

        public FailedUnregisterOperationException(string name)
            : base(string.Format("Unable to unregister {0} object because is not presented in the factory", name))
        {

        }
    }
}


text:
package io.hops.metadata.yarn.dal.fair;

import io.hops.exception.StorageException;
import io.hops.metadata.common.EntityDataAccess;
import java.util.Collection;
import java.util.List;

public interface RunnableAppsDataAccess<T> extends EntityDataAccess {

  List<T> findById(String id) throws StorageException;

  void add(T modified) throws StorageException;

  void removeAll(Collection<T> removed) throws StorageException;
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Build.UnitTests;
using Xunit;

#nullable disable

namespace Microsoft.Build.Tasks.UnitTests
{
    public sealed class TelemetryTaskTests
    {
        [Fact]
        public void TelemetryTaskSendsEvents()
        {
            MockEngine engine = new MockEngine();

            Telemetry telemetryTask = new Telemetry
            {
                BuildEngine = engine,
                EventName = "My event name",
            };

            bool retVal = telemetryTask.Execute();

            Assert.True(retVal);

            Assert.Contains(telemetryTask.EventName, engine.Log);
        }

        [Fact]
        public void TelemetryTaskSendsEventsWithProperties()
        {
            const string propertyName = "9B7DA92A89914E2CA1D88DCEB9DAAD72";
            const string propertyValue = "68CB99868F2843B3B75230C1A0BFE358";

            MockEngine engine = new MockEngine();

            Telemetry telemetryTask = new Telemetry
            {
                BuildEngine = engine,
                EventName = "My event name",
                EventData = $"{propertyName}={propertyValue}",
            };

            bool retVal = telemetryTask.Execute();

            Assert.True(retVal);

            Assert.Contains(propertyName, engine.Log);

            Assert.Contains(propertyValue, engine.Log);
        }

        [Fact]
        public void TelemetryTaskInvalidEventData()
        {
            MockEngine engine = new MockEngine();

            Telemetry telemetryTask = new Telemetry
            {
                BuildEngine = engine,
                EventName = "My event name",
                EventData = $"Property1=Value1;Property2",
            };

            bool retVal = telemetryTask.Execute();

            Assert.False(retVal);
            Assert.Contains($"The property \"Property2\" in the telemetry event data property list \"{telemetryTask.EventData}\" is malformed.", engine.Log);
        }

        /// <summary>
        /// Verifies that when there are duplicate property names specified that the last one wins.
        /// </summary>
        [Fact]
        public void TelemetryTaskDuplicateEventDataProperty()
        {
            MockEngine engine = new MockEngine();

            Telemetry telemetryTask = new Telemetry
            {
                BuildEngine = engine,
                EventName = "My event name",
                EventData = $"Property1=EE2493A167D24F00996DE7C8E769EAE6;Property1=4ADE3D2622CA400B8B95A039DF540037",
            };

            bool retVal = telemetryTask.Execute();

            Assert.True(retVal);

            // Should not contain the first value
            //
            Assert.DoesNotContain("EE2493A167D24F00996DE7C8E769EAE6", engine.Log);

            // Should contain the second value
            //
            Assert.Contains("4ADE3D2622CA400B8B95A039DF540037", engine.Log);
        }
    }
}


text:
namespace utils = extension_function_test_utils;

namespace extensions {

ExtensionApiUnittest::ExtensionApiUnittest() : contents_(NULL) {
}

ExtensionApiUnittest::~ExtensionApiUnittest() {
}

void ExtensionApiUnittest::SetUp() {
  BrowserWithTestWindowTest::SetUp();
  extension_ = utils::CreateEmptyExtensionWithLocation(Manifest::UNPACKED);
}

void ExtensionApiUnittest::CreateBackgroundPage() {
  if (!contents_) {
    GURL url = BackgroundInfo::GetBackgroundURL(extension());
    if (url.is_empty())
      url = GURL(url::kAboutBlankURL);
    AddTab(browser(), url);
    contents_ = browser()->tab_strip_model()->GetActiveWebContents();
  }
}

scoped_ptr<base::Value> ExtensionApiUnittest::RunFunctionAndReturnValue(
    UIThreadExtensionFunction* function, const std::string& args) {
  function->set_extension(extension());
  if (contents_)
    function->SetRenderViewHost(contents_->GetRenderViewHost());
  return scoped_ptr<base::Value>(
      utils::RunFunctionAndReturnSingleResult(function, args, browser()));
}

scoped_ptr<base::DictionaryValue>
ExtensionApiUnittest::RunFunctionAndReturnDictionary(
    UIThreadExtensionFunction* function, const std::string& args) {
  base::Value* value = RunFunctionAndReturnValue(function, args).release();
  base::DictionaryValue* dict = NULL;

  if (value && !value->GetAsDictionary(&dict))
    delete value;

  // We expect to either have successfuly retrieved a dictionary from the value,
  // or the value to have been NULL.
  EXPECT_TRUE(dict || !value);
  return scoped_ptr<base::DictionaryValue>(dict);
}

scoped_ptr<base::ListValue> ExtensionApiUnittest::RunFunctionAndReturnList(
    UIThreadExtensionFunction* function, const std::string& args) {
  base::Value* value = RunFunctionAndReturnValue(function, args).release();
  base::ListValue* list = NULL;

  if (value && !value->GetAsList(&list))
    delete value;

  // We expect to either have successfuly retrieved a list from the value,
  // or the value to have been NULL.
  EXPECT_TRUE(list);
  return scoped_ptr<base::ListValue>(list);
}

std::string ExtensionApiUnittest::RunFunctionAndReturnError(
    UIThreadExtensionFunction* function, const std::string& args) {
  function->set_extension(extension());
  if (contents_)
    function->SetRenderViewHost(contents_->GetRenderViewHost());
  return utils::RunFunctionAndReturnError(function, args, browser());
}

void ExtensionApiUnittest::RunFunction(
    UIThreadExtensionFunction* function, const std::string& args) {
  RunFunctionAndReturnValue(function, args);
}

}  // namespace extensions


text:
package scuba.test.testcase.intra;

public class A {

}


text:
import math
import random

import pyglet
from pyglet import gl

WIDTH = 800
HEIGHT = 600
ROTATION_SPEED = 200
ACCELERATION = 300
SPACESHIP_RADIUS = 40
START_LIVES = 3
SHOOT_DELAY = 0.3
LASER_SPEED = 500
LASER_RADIUS = 5
COLLISION_SPEED_FACTOR = 0.2
ASTEROID_SPEED = 100
ASTEROID_ROTATION_SPEED = 3
ASTEROID_RADIUSES = {
    1: 8,
    2: 15,
    3: 20,
    4: 42,
}

def load_image(filename):
    image = pyglet.image.load(filename)
    image.anchor_x = image.width // 2
    image.anchor_y = image.height // 2
    return image

# Images from www.kenney.nl, thank you!
# Public Domain (Creative Commons CC-0)
spaceship_img = load_image('assets/PNG/playerShip2_red.png')
laser_img = load_image('assets/PNG/Lasers/laserBlue06.png')
space_img = load_image('assets/Backgrounds/blue.png')
life_img = load_image('assets/PNG/UI/playerLife2_red.png')
asteroid_images = {
    1: [load_image('assets/PNG/Meteors/meteorGrey_tiny1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_tiny2.png'),
       ],
    2: [load_image('assets/PNG/Meteors/meteorGrey_small1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_small2.png'),
       ],
    3: [load_image('assets/PNG/Meteors/meteorGrey_med1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_med2.png'),
       ],
    4: [load_image('assets/PNG/Meteors/meteorGrey_big1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_big3.png'),
        load_image('assets/PNG/Meteors/meteorGrey_big4.png'),
       ],
}

life_sprite = pyglet.sprite.Sprite(life_img)

exhaust_images = []
for i in range(25):
    name = 'assets2/PNG/White puff/whitePuff{:02}.png'.format(i)
    exhaust_images.append(load_image(name))

def circle(x, y, radius):
    iterations = 20
    s = math.sin(2*math.pi / iterations)
    c = math.cos(2*math.pi / iterations)

    dx, dy = radius, 0

    gl.glBegin(gl.GL_LINE_STRIP)
    for i in range(iterations+1):
        gl.glVertex2f(x+dx, y+dy)
        dx, dy = (dx*c - dy*s), (dy*c + dx*s)
    gl.glEnd()

pressed_keys = set()
objects = []
main_batch = pyglet.graphics.Batch()
exhaust_batch = pyglet.graphics.Batch()

pyglet.font.add_file('assets/Bonus/kenvector_future_thin.ttf')
level_label = pyglet.text.Label('Loading...', x=10, y=10,
                                font_name='Kenvector Future Thin',
                               )

class SpaceObject:
    kind = None

    def __init__(self, window, image, x, y, radius, rotation=0,
                 x_speed=0, y_speed=0, batch=main_batch):
        self.x = x
        self.y = y
        self.x_speed = x_speed
        self.y_speed = y_speed
        self.rotation = rotation
        self.radius = radius
        self.sprite = pyglet.sprite.Sprite(image, batch=batch)
        self.window = window

    def tick(self, dt):
        self.x += dt * self.x_speed
        self.y += dt * self.y_speed

        if self.x < 0:
            self.x += self.window.width
        if self.y < 0:
            self.y += self.window.height
        if self.x > self.window.width:
            self.x -= self.window.width
        if self.y > self.window.height:
            self.y -= self.window.height

        self.sprite.rotation = 90 - self.rotation
        self.sprite.x = self.x
        self.sprite.y = self.y

    def hit_by_spaceship(self, spaceship):
        return

    def hit_by_laser(self, laser):
        return

    def delete(self):
        if self in objects:
            objects.remove(self)
            self.sprite.delete()

class Spaceship(SpaceObject):
    def __init__(self, window, rotation=0):
        super().__init__(window=window,
                         image=spaceship_img,
                         x=window.width / 2,
                         y=window.height / 2,
                         rotation=rotation,
                         radius=SPACESHIP_RADIUS,
                        )
        self.shoot_timer = 0
        self.lives = START_LIVES - 1
        self.invincibility_timer = 0
        self.size = 5
        self.level = 0

    def tick(self, dt):
        if pyglet.window.key.LEFT in pressed_keys:
            self.rotation += dt * ROTATION_SPEED
            objects.append(make_exhaust(self, -1))
        if pyglet.window.key.RIGHT in pressed_keys:
            self.rotation -= dt * ROTATION_SPEED
            objects.append(make_exhaust(self, 1))
        if pyglet.window.key.UP in pressed_keys:
            rotation_radians = math.radians(self.rotation)
            self.x_speed += dt * ACCELERATION * math.cos(rotation_radians)
            self.y_speed += dt * ACCELERATION * math.sin(rotation_radians)
            objects.append(make_exhaust(self))
        if pyglet.window.key.SPACE in pressed_keys:
            if self.shoot_timer < 0:
                self.shoot()
                self.shoot_timer = SHOOT_DELAY

        super().tick(dt)

        self.shoot_timer -= dt

        self.invincibility_timer -= dt
        if self.invincibility_timer < 0:
            self.sprite.opacity = 255
            for obj in list(objects):
                if overlaps(self, obj):
                    obj.hit_by_spaceship(self)
        else:
            self.sprite.opacity = 255 * (
                abs(math.sin(self.invincibility_timer * 5)) *
                max(0, min(2.5 - self.invincibility_timer, 1))
            )

    def shoot(self):
        laser = Laser(self.window, rotation=self.rotation,
                      x=self.x, y=self.y,
                      ship_x_speed=self.x_speed, ship_y_speed=self.y_speed,
                     )
        objects.append(laser)

    def destroy(self, asteroid):
        for i in range(50):
            t = random.uniform(0, math.pi*2)
            rx = random.uniform(0, 100) * math.cos(t)
            ry = random.uniform(0, 100) * math.sin(t)
            debris = Debris(self.window, x=self.x, y=self.y,
                            x_speed=self.x_speed + rx * 3,
                            y_speed=self.y_speed + ry * 3,
                            time_to_live=4,
                           )
            objects.append(debris)
            explosion = Exhaust(self.window, x=self.x, y=self.y,
                                x_speed=self.x_speed + rx * 2,
                                y_speed=self.y_speed + ry * 2,
                                die_speed=1,
                               )
            objects.append(explosion)

        self.lives -= 1
        if self.lives < 0:
            self.delete()
            pyglet.text.Label('Game over', anchor_x='center',
                              x=window.width/2, y=window.height/2,
                              font_name='Kenvector Future Thin',
                              font_size=50,
                              batch=main_batch,
                             )
        else:
            self.invincibility_timer = 3
            self.x = self.window.width / 2
            self.y = self.window.height / 2
            self.x_speed = 0
            self.y_speed = 0
            pressed_keys.clear()

class Asteroid(SpaceObject):
    kind = 'asteroid'

    def __init__(self, window, size):
        # Asteroids start at edges of the screen, so they don't
        # initially collide with the ship
        edge = random.choice(['horizontal', 'vertical'])
        if edge == 'vertical':
            x = 0
            y = random.randrange(window.height)
        else:
            x = random.randrange(window.width)
            y = 0
        super().__init__(window=window,
                         image=random.choice(asteroid_images[size]),
                         x=x, y=y,
                         x_speed=random.uniform(-ASTEROID_SPEED, ASTEROID_SPEED),
                         y_speed=random.uniform(-ASTEROID_SPEED, ASTEROID_SPEED),
                         rotation=random.uniform(0, 360),
                         radius=ASTEROID_RADIUSES[size],
                        )
        self.size = size
        self.rotation_speed = random.uniform(-ASTEROID_ROTATION_SPEED,
                                             ASTEROID_ROTATION_SPEED)

    def tick(self, dt):
        self.rotation += self.rotation_speed
        super().tick(dt)

    def hit_by_spaceship(self, spaceship):
        spaceship.destroy(self)

    def hit_by_laser(self, laser):
        split_x_speed = -laser.y_speed * COLLISION_SPEED_FACTOR
        split_y_speed = laser.x_speed * COLLISION_SPEED_FACTOR

        for i in range(2):
            if self.size > 1:
                asteroid = Asteroid(self.window, self.size-1)
                asteroid.x = self.x
                asteroid.y = self.y
                asteroid.x_speed = self.x_speed + split_x_speed
                asteroid.y_speed = self.y_speed + split_y_speed
                objects.append(asteroid)

            for j in range(self.size):
                x_rand_speed = random.uniform(-40, 40)
                y_rand_speed = random.uniform(-40, 40)
                debris = Debris(self.window, x=self.x, y=self.y,
                                x_speed=self.x_speed - split_y_speed + x_rand_speed,
                                y_speed=self.y_speed + split_x_speed + y_rand_speed,
                                time_to_live=self.size,
                                )
                objects.append(debris)

            split_x_speed = -split_x_speed
            split_y_speed = -split_y_speed

        laser.delete()
        self.delete()

        for obj in objects:
            if obj.kind == 'asteroid':
                return

        # No asteroids!
        start_level()

class Laser(SpaceObject):
    def __init__(self, window, x, y, ship_x_speed, ship_y_speed, rotation):
        rotation_radians = math.radians(rotation)
        x_speed = ship_x_speed + LASER_SPEED * math.cos(rotation_radians)
        y_speed = ship_y_speed + LASER_SPEED * math.sin(rotation_radians)
        super().__init__(window,
                         x=x + math.cos(rotation_radians),
                         y=y + math.sin(rotation_radians),
                         x_speed=x_speed,
                         y_speed=y_speed,
                         rotation=rotation,
                         image=laser_img,
                         radius=LASER_RADIUS,
                        )
        self.time_to_live = max(window.width, window.height) / LASER_SPEED

    def tick(self, dt):
        super().tick(dt)

        for obj in list(objects):
            if overlaps(self, obj):
                obj.hit_by_laser(self)

        self.time_to_live -= dt
        if self.time_to_live < 0:
            self.delete()

def make_exhaust(spaceship, side=0):
    rotation_radians = math.radians(spaceship.rotation + side * 15)
    x_unit = -math.cos(rotation_radians)
    y_unit = -math.sin(rotation_radians)
    start_radians = math.radians(spaceship.rotation - side * 48)
    x_start = -math.cos(start_radians)
    y_start = -math.sin(start_radians)
    if side:
        speed = 100
        die_speed = 4
    else:
        speed = 200
        die_speed = 3
    x_rand_speed = random.uniform(-20,20)
    y_rand_speed = random.uniform(-20,20)
    return Exhaust(spaceship.window,
                    x=spaceship.x + x_start * 43,
                    y=spaceship.y + y_start * 43,
                    x_speed=spaceship.x_speed + x_unit*speed + x_rand_speed,
                    y_speed=spaceship.y_speed + y_unit*speed + y_rand_speed,
                    die_speed=die_speed,
                    small=side,
                   )

class Exhaust(SpaceObject):
    def __init__(self, window, x, y, x_speed, y_speed, die_speed, small=False):
        super().__init__(window,
                         x=x, y=y, x_speed=x_speed, y_speed=y_speed,
                         image=random.choice(exhaust_images),
                         radius=0,
                         batch=exhaust_batch,
                        )
        self.time_to_live = 2
        self.die_speed = die_speed
        if small:
            self.sprite.scale = 1/30
        else:
            self.sprite.scale = 1/10

    def tick(self, dt):
        super().tick(dt)

        self.time_to_live -= dt * self.die_speed
        if self.time_to_live > 1:
            t = self.time_to_live - 1
            self.sprite.color = (255, 255 * t, 0)
        elif self.time_to_live > 0:
            t = self.time_to_live
            self.sprite.color = (255 * t, 0, 0)
            self.sprite.opacity = 255 * t
        else:
            self.delete()

class Debris(SpaceObject):
    def __init__(self, window, x, y, x_speed, y_speed, time_to_live):
        super().__init__(window, x=x, y=y, x_speed=x_speed, y_speed=y_speed,
                         image=random.choice(asteroid_images[1]),
                         radius=0,
                         batch=exhaust_batch,
                        )
        self.time_to_live = time_to_live
        self.die_speed = 3
        self.sprite.color = 0, 0, 0
        self.sprite.scale = 1/2
        self.rotation_speed = random.uniform(-20, 20)

    def tick(self, dt):
        self.rotation += self.rotation_speed * dt
        super().tick(dt)

        self.time_to_live -= dt * self.die_speed
        if self.time_to_live > 1:
            self.sprite.opacity = 255
        elif self.time_to_live > 0:
            self.sprite.opacity = 255 * self.time_to_live
        else:
            self.delete()

def distance(a, b, wrap_size):
    result = abs(a - b)
    if result > wrap_size / 2:
        result = wrap_size - result
    return result

def overlaps(a, b):
    distance_squared = (distance(a.x, b.x, window.width) ** 2 +
                        distance(a.y, b.y, window.height) ** 2)
    max_distance_squared = (a.radius + b.radius) ** 2
    return distance_squared < max_distance_squared

def tick(dt):
    for obj in objects:
        obj.tick(dt)

def draw():
    window.clear()

    for x in range(0, window.width+space_img.width, space_img.width):
        for y in range(0, window.height+space_img.height, space_img.height):
            space_img.blit(x=x, y=y)

    exhaust_batch.draw()
    for x_offset in (-window.width, 0, window.width):
        for y_offset in (-window.height, 0, window.height):
            gl.glPushMatrix()
            gl.glTranslatef(x_offset, y_offset, 0)
            main_batch.draw()
            gl.glPopMatrix()

    for i in range(ship.lives):
        life_sprite.y = 40
        life_sprite.x = 30 + 40 * i
        life_sprite.draw()

    level_label.draw()

def key_pressed(key, mod):
    pressed_keys.add(key)

def key_released(key, mod):
    pressed_keys.discard(key)

def start_level():
    ship.level += 1
    ship.lives += 1
    for i in range(ship.level):
        objects.append(Asteroid(window, 4))
    level_label.text = 'Level {}'.format(ship.level)

window = pyglet.window.Window(width=WIDTH, height=HEIGHT)

window.push_handlers(
    on_draw=draw,
    on_key_press=key_pressed,
    on_key_release=key_released,
)

pyglet.clock.schedule(tick)

ship = Spaceship(window)
objects.append(ship)
start_level()

pyglet.app.run()


text:
<?php

namespace SUH\GestionBundle\Tests\Entity;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use SUH\GestionBundle\Entity\Etudiant;
use SUH\GestionBundle\Entity\Formation;

class FormationTest extends WebTestCase
{
    private $etudiantFormation;

    protected function setUp()
    {
        $this->etudiant = new Etudiant("AAAABBBBCCCC0000","17/10/1989");
        $this->formation = new Formation("DUT","IUT","Info",2,"UBP",3);

        $this->assertNotNull($this->formation);

    }

    public function testGetId()
    {
        $this->assertNull($this->formation->getId());
    }

    public function testGetDiplome()
    {
        $this->assertEquals("DUT", $this->formation->getDiplome());
    }

    public function testSetDiplome()
    {
        $this->formation->setDiplome("Licence");
        $this->assertEquals("Licence", $this->formation->getDiplome());
    }

   public function testGetComposante()
    {
        $this->assertEquals("IUT", $this->formation->getComposante());
    }

    public function testSetComposante()
    {
        $this->formation->setComposante("UFR");
        $this->assertEquals("UFR", $this->formation->getComposante());
    }

    public function testGetFiliere()
    {
        $this->assertEquals("Info", $this->formation->getFiliere());
    }

    public function testSetFiliere()
    {
        $this->formation->setFiliere("Bio");
        $this->assertEquals("Bio", $this->formation->getFiliere());
    }

    public function testGetCycle()
    {
        $this->assertEquals(2, $this->formation->getCycle());
    }

    public function testSetCycle()
    {
        $this->formation->setCycle(3);
        $this->assertEquals(3, $this->formation->getCycle());
    }

    public function testGetEtablissement()
    {
        $this->assertEquals("UBP", $this->formation->getEtablissement());
    }

    public function testSetEtablissement()
    {
        $this->formation->setEtablissement("UDA");
        $this->assertEquals("UDA", $this->formation->getEtablissement());
    }

    public function testGetAnneeEtude()
    {
        $this->assertEquals(3, $this->formation->getAnneeEtude());
    }

    public function testSetAnneeEtude()
    {
        $this->formation->setAnneeEtude(4);
        $this->assertEquals(4, $this->formation->getAnneeEtude());
    }

}


text:
module Pano
  module NumberHelper

    def clean_round(x, precision = 0)
      number_with_precision x, precision: precision, strip_insignificant_zeros: true
    end

    # shorthand for number_with_delimiter.
    def delimit(number, options = {})
      number_with_delimiter number, options
    end

    def delimited_pluralize(number, label)
      if number == 1
        "1 #{label}"
      else
        "#{delimit number} #{label.pluralize}"
      end
    end

    # Add a + before a positive integer
    def explicit_integer(integer)
      integer.positive? ? "+#{integer}" : integer.to_s
    end

    def not_zero(number)
      (number.nil? || number.zero?) ? '' : delimit(number)
    end

    def percent(numerator, denominator, decimal_digits = nil)
      return 0 if denominator == 0
      return ((numerator.to_f / denominator.to_f) * 100.0).round(decimal_digits) if decimal_digits
      ((numerator.to_f / denominator.to_f) * 100.0).round
    end
  end
end


text:
require 'rails_generator'
require 'rails_generator/scripts/generate'
Rails::Generator::Scripts::Generate.new.run(['footstool'], :destination => RAILS_ROOT)


text:
package cloudphoto

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// ListPhotoStores invokes the cloudphoto.ListPhotoStores API synchronously
// api document: https://help.aliyun.com/api/cloudphoto/listphotostores.html
func (client *Client) ListPhotoStores(request *ListPhotoStoresRequest) (response *ListPhotoStoresResponse, err error) {
	response = CreateListPhotoStoresResponse()
	err = client.DoAction(request, response)
	return
}

// ListPhotoStoresWithChan invokes the cloudphoto.ListPhotoStores API asynchronously
// api document: https://help.aliyun.com/api/cloudphoto/listphotostores.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListPhotoStoresWithChan(request *ListPhotoStoresRequest) (<-chan *ListPhotoStoresResponse, <-chan error) {
	responseChan := make(chan *ListPhotoStoresResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.ListPhotoStores(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// ListPhotoStoresWithCallback invokes the cloudphoto.ListPhotoStores API asynchronously
// api document: https://help.aliyun.com/api/cloudphoto/listphotostores.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListPhotoStoresWithCallback(request *ListPhotoStoresRequest, callback func(response *ListPhotoStoresResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *ListPhotoStoresResponse
		var err error
		defer close(result)
		response, err = client.ListPhotoStores(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// ListPhotoStoresRequest is the request struct for api ListPhotoStores
type ListPhotoStoresRequest struct {
	*requests.RpcRequest
}

// ListPhotoStoresResponse is the response struct for api ListPhotoStores
type ListPhotoStoresResponse struct {
	*responses.BaseResponse
	Code        string       `json:"Code" xml:"Code"`
	Message     string       `json:"Message" xml:"Message"`
	RequestId   string       `json:"RequestId" xml:"RequestId"`
	Action      string       `json:"Action" xml:"Action"`
	PhotoStores []PhotoStore `json:"PhotoStores" xml:"PhotoStores"`
}

// CreateListPhotoStoresRequest creates a request to invoke ListPhotoStores API
func CreateListPhotoStoresRequest() (request *ListPhotoStoresRequest) {
	request = &ListPhotoStoresRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("CloudPhoto", "2017-07-11", "ListPhotoStores", "cloudphoto", "openAPI")
	return
}

// CreateListPhotoStoresResponse creates a response to parse from ListPhotoStores response
func CreateListPhotoStoresResponse() (response *ListPhotoStoresResponse) {
	response = &ListPhotoStoresResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<!doctype html>

		<meta charset="utf-8" />
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<title>Smarty Admin</title>
		<meta name="description" content="" />
		<meta name="Author" content="Dorin Grigoras [www.stepofweb.com]" />

		<meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0" />

		<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800&subset=latin,latin-ext,cyrillic,cyrillic-ext" rel="stylesheet" type="text/css" />

		<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

		<link href="assets/css/essentials.css" rel="stylesheet" type="text/css" />
		<link href="assets/css/layout.css" rel="stylesheet" type="text/css" />
		<link href="assets/css/color_scheme/green.css" rel="stylesheet" type="text/css" id="color_scheme" />

				<form action="index.html" method="post" class="sky-form boxed ">
					 Forgot Password

					<fieldset>

						E-mail

							<input type="email">
							Type your Email

						Back to Login

					</fieldset>

						<button type="submit" class="btn btn-primary pull-right"> Reset Passsword</button>

				</form>

					The reset link will be sent to your email address. Click the link and reset your account password.

					Or sign up using:

					 Facebook
					 Twitter


text:
package org.jboss.arquillian.container.test.impl.enricher.resource;

import java.net.URL;
import org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * ArquillianTestEnricherTestCase
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@RunWith(MockitoJUnitRunner.class)
public class URLResourceProviderTestCase extends OperatesOnDeploymentAwareProviderBase {
    @Override
    protected ResourceProvider getResourceProvider() {
        return new URLResourceProvider();
    }

    @Test
    public void shouldBeAbleToInjectBaseContextURL() throws Exception {
        URLBaseContextClass test = execute(
            URLBaseContextClass.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST", 8080)));

        Assert.assertEquals("http://TEST:8080", test.url.toExternalForm());
    }

    @Test
    public void shouldBeAbleToInjectBaseContextURLQualified() throws Exception {
        URLBaseContextClassQualified test = execute(
            URLBaseContextClassQualified.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-Y", 8080)),
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-X", 8080)));

        Assert.assertEquals("http://TEST-X:8080", test.url.toExternalForm());
    }

    @Test
    public void shouldBeAbleToInjectServletContextURL() throws Exception {
        URLServletContextClass test = execute(
            URLServletContextClass.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test"))));

        Assert.assertEquals("http://TEST:8080/test/", test.url.toExternalForm());
    }

    @Test
    public void shouldBeAbleToInjectServletContextURLQualified() throws Exception {
        URLServletContextClassQualified test = execute(
            URLServletContextClassQualified.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y"))),
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X"))));

        Assert.assertEquals("http://TEST-X:8080/test-X/", test.url.toExternalForm());
    }

    @Test
    public void shouldBeAbleToInjectServletContextURLQualifiedAndTargeted() throws Exception {
        URLBaseContextClassQualifiedTargeted test = execute(
            URLBaseContextClassQualifiedTargeted.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("NAME-A", "TEST-A-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y")))
                .addContext(new HTTPContext("NAME-B", "TEST-B-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y"))),
            new ProtocolMetaData()
                .addContext(new HTTPContext("NAME-A", "TEST-A-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X")))
                .addContext(new HTTPContext("NAME-B", "TEST-B-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X"))));

        Assert.assertEquals("http://TEST-B-X:8080/test-X/", test.url.toExternalForm());
    }

    @Test
    public void shouldBeAbleToInjectServletContextURLQualifiedAndNoTarget() throws Exception {
        URLServletContextClassQualified test = execute(
            URLServletContextClassQualified.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("NAME-A", "TEST-A-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y")))
                .addContext(new HTTPContext("NAME-B", "TEST-B-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y"))),
            new ProtocolMetaData()
                .addContext(new HTTPContext("NAME-A", "TEST-A-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X")))
                .addContext(new HTTPContext("NAME-B", "TEST-B-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X"))));

        // Default on multiple Named contexts is the first one added
        Assert.assertEquals("http://TEST-A-X:8080/test-X/", test.url.toExternalForm());
    }

    @Test(expected = IllegalStateException.class)
    public void shouldThrowExceptionOnMissingContainerRegistry() throws Exception {
        execute(
            false,
            true,
            URLServletContextClassQualified.class,
            ProtocolMetaData.class,
            new ProtocolMetaData(),
            new ProtocolMetaData());
    }

    @Test(expected = IllegalStateException.class)
    public void shouldThrowExceptionOnMissingDeploymentScenario() throws Exception {
        execute(
            true,
            false,
            URLServletContextClassQualified.class,
            ProtocolMetaData.class,
            new ProtocolMetaData(),
            new ProtocolMetaData());
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionOnUnKnownDeployment() throws Exception {
        execute(
            URLBaseContextClassQualifiedMissing.class,
            ProtocolMetaData.class,
            new ProtocolMetaData(),
            new ProtocolMetaData());
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionOnUnKnownTargetInDeployment() throws Exception {
        execute(
            URLBaseContextClassQualifiedTargetedMissing.class,
            ProtocolMetaData.class,
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-Y", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-Y"))),
            new ProtocolMetaData()
                .addContext(new HTTPContext("TEST-X", 8080)
                    .add(new Servlet(URLServletContextClass.class.getSimpleName(), "/test-X"))));
    }

    public static class URLBaseContextClass {
        @ArquillianResource
        public URL url;
    }

    public static class URLServletContextClass {
        @ArquillianResource(URLServletContextClass.class)
        public URL url;
    }

    public static class URLBaseContextClassQualified {
        @ArquillianResource
        @OperateOnDeployment("X")
        public URL url;
    }

    public static class URLServletContextClassQualified {
        @ArquillianResource(URLServletContextClass.class)
        @OperateOnDeployment("X")
        public URL url;
    }

    public static class URLBaseContextClassQualifiedMissing {
        @ArquillianResource
        @OperateOnDeployment("MISSING")
        public URL url;
    }

    public static class URLBaseContextClassQualifiedTargeted {
        @ArquillianResource
        @OperateOnDeployment("X")
        @TargetsContainer("NAME-B")
        public URL url;
    }

    public static class URLBaseContextClassQualifiedTargetedMissing {
        @ArquillianResource
        @OperateOnDeployment("X")
        @TargetsContainer("MISSING")
        public URL url;
    }
}


text:
package org.apache.ignite.spi.discovery.tcp.internal;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.internal.processors.metric.MetricRegistry;
import org.apache.ignite.internal.processors.metric.impl.IntMetricImpl;
import org.apache.ignite.internal.util.GridBoundedLinkedHashMap;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage;

/**
 * Statistics for {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi}.
 */
public class TcpDiscoveryStatistics {
    /** Coordinator since timestamp. */
    private final AtomicLong crdSinceTs = new AtomicLong();

    /** Joined nodes count. */
    private final IntMetricImpl joinedNodesCnt;

    /** Failed nodes count. */
    private final IntMetricImpl failedNodesCnt;

    /** Left nodes count. */
    private final IntMetricImpl leftNodesCnt;

    /** Received messages. */
    @GridToStringInclude
    private final Map<String, Integer> rcvdMsgs = new HashMap<>();

    /** Processed messages. */
    @GridToStringInclude
    private final Map<String, Integer> procMsgs = new HashMap<>();

    /** Sent messages. */
    @GridToStringInclude
    private final Map<String, Integer> sentMsgs = new HashMap<>();

    /** Messages processing start timestamps. */
    private final Map<IgniteUuid, Long> msgsProcStartTs = new GridBoundedLinkedHashMap<>(1024);

    /** Average message processing time. */
    private long avgMsgProcTime;

    /** Max message processing time. */
    private long maxMsgProcTime;

    /** Pending messages registered count. */
    private final IntMetricImpl pendingMsgsRegistered;

    /** */
    public TcpDiscoveryStatistics() {
        joinedNodesCnt = new IntMetricImpl("JoinedNodes", "Joined nodes count");

        failedNodesCnt = new IntMetricImpl("FailedNodes", "Failed nodes count");

        leftNodesCnt = new IntMetricImpl("LeftNodes", "Left nodes count");

        pendingMsgsRegistered = new IntMetricImpl("PendingMessagesRegistered", "Pending messages registered count");
    }

    /**
     * @param discoReg Discovery metric registry.
     */
    public void registerMetrics(MetricRegistry discoReg) {
        discoReg.register("TotalProcessedMessages", this::totalProcessedMessages, "Total processed messages count");

        discoReg.register("TotalReceivedMessages", this::totalReceivedMessages, "Total received messages count");

        discoReg.register(joinedNodesCnt);
        discoReg.register(failedNodesCnt);
        discoReg.register(leftNodesCnt);
        discoReg.register(pendingMsgsRegistered);
    }

    /**
     * Increments joined nodes count.
     */
    public void onNodeJoined() {
        joinedNodesCnt.increment();
    }

    /**
     * Increments left nodes count.
     */
    public void onNodeLeft() {
        leftNodesCnt.increment();
    }

    /**
     * Increments failed nodes count.
     */
    public void onNodeFailed() {
        failedNodesCnt.increment();
    }

    /**
     * Initializes coordinator since date (if needed).
     */
    public void onBecomingCoordinator() {
        crdSinceTs.compareAndSet(0, U.currentTimeMillis());
    }

    /**
     * Collects necessary stats for message received by SPI.
     *
     * @param msg Received message.
     */
    public synchronized void onMessageReceived(TcpDiscoveryAbstractMessage msg) {
        assert msg != null;

        Integer cnt = F.addIfAbsent(rcvdMsgs, msg.getClass().getSimpleName(), 0);

        rcvdMsgs.put(msg.getClass().getSimpleName(), ++cnt);
    }

    /**
     * Collects necessary stats for message processed by SPI.
     *
     * @param msg Processed message.
     */
    public synchronized void onMessageProcessingStarted(TcpDiscoveryAbstractMessage msg) {
        assert msg != null;

        Integer cnt = F.addIfAbsent(procMsgs, msg.getClass().getSimpleName(), 0);

        procMsgs.put(msg.getClass().getSimpleName(), ++cnt);

        msgsProcStartTs.put(msg.id(), U.currentTimeMillis());
    }

    /**
     * Collects necessary stats for message processed by SPI.
     *
     * @param msg Processed message.
     */
    public synchronized void onMessageProcessingFinished(TcpDiscoveryAbstractMessage msg) {
        assert msg != null;

        Long startTs = msgsProcStartTs.remove(msg.id());

        if (startTs != null) {
            long duration = U.currentTimeMillis() - startTs;

            int totalProcMsgs = totalProcessedMessages();

            if (totalProcMsgs != 0)
                avgMsgProcTime = (avgMsgProcTime * (totalProcMsgs - 1) + duration) / totalProcMsgs;

            if (duration > maxMsgProcTime)
                maxMsgProcTime = duration;
        }
    }

    /**
     * Called by coordinator when ring message is sent.
     *  @param msg Sent message.
     * @param time Time taken to serialize message.
     */
    public synchronized void onMessageSent(TcpDiscoveryAbstractMessage msg, long time) {
        assert msg != null;
        assert time >= 0 : time;

        Integer cnt = F.addIfAbsent(sentMsgs, msg.getClass().getSimpleName(), 0);

        sentMsgs.put(msg.getClass().getSimpleName(), ++cnt);
    }

    /**
     * Increments pending messages registered count.
     */
    public void onPendingMessageRegistered() {
        pendingMsgsRegistered.increment();
    }

    /**
     * Gets processed messages counts (grouped by type).
     *
     * @return Map containing message types and respective counts.
     */
    public synchronized Map<String, Integer> processedMessages() {
        return new HashMap<>(procMsgs);
    }

    /**
     * Gets received messages counts (grouped by type).
     *
     * @return Map containing message types and respective counts.
     */
    public synchronized Map<String, Integer> receivedMessages() {
        return new HashMap<>(rcvdMsgs);
    }

    /**
     * @return Sent messages counts (grouped by type).
     */
    public synchronized Map<String, Integer> sentMessages() {
        return new HashMap<>(sentMsgs);
    }

    /**
     * Gets total received messages count.
     *
     * @return Total received messages count.
     */
    public synchronized int totalReceivedMessages() {
        return F.sumInt(rcvdMsgs.values());
    }

    /**
     * Gets total processed messages count.
     *
     * @return Total processed messages count.
     */
    public synchronized int totalProcessedMessages() {
        return F.sumInt(procMsgs.values());
    }

    /**
     * Gets max message processing time.
     *
     * @return Max message processing time.
     */
    public synchronized long maxMessageProcessingTime() {
        return maxMsgProcTime;
    }

    /**
     * Gets average message processing time.
     *
     * @return Average message processing time.
     */
    public synchronized long avgMessageProcessingTime() {
        return avgMsgProcTime;
    }

    /**
     * Gets pending messages registered count.
     *
     * @return Pending messages registered count.
     */
    public long pendingMessagesRegistered() {
        return pendingMsgsRegistered.value();
    }

    /**
     * Gets nodes joined count.
     *
     * @return Nodes joined count.
     */
    public int joinedNodesCount() {
        return joinedNodesCnt.value();
    }

    /**
     * Gets nodes left count.
     *
     * @return Nodes left count.
     */
    public int leftNodesCount() {
        return leftNodesCnt.value();
    }

    /**
     * Gets failed nodes count.
     *
     * @return Failed nodes count.
     */
    public int failedNodesCount() {
        return failedNodesCnt.value();
    }

    /**
     * Gets time local node has been coordinator since.
     *
     * @return Coordinator since timestamp.
     */
    public long coordinatorSinceTimestamp() {
        return crdSinceTs.get();
    }

    /**
     * Clears statistics.
     */
    public synchronized void clear() {
        avgMsgProcTime = 0;
        crdSinceTs.set(0);
        failedNodesCnt.reset();
        joinedNodesCnt.reset();
        leftNodesCnt.reset();
        maxMsgProcTime = 0;
        pendingMsgsRegistered.reset();
        procMsgs.clear();
        rcvdMsgs.clear();
        sentMsgs.clear();
    }

    /** {@inheritDoc} */
    @Override public synchronized String toString() {
        return S.toString(TcpDiscoveryStatistics.class, this);
    }
}


text:
exports.onRouteUpdate = ({ location }, pluginOptions = {}) => {
  if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) {
    return null
  }

  const pluginConfig = pluginOptions.pluginConfig || {}

  const pathIsExcluded =
    location &&
    typeof window.excludeGtagPaths !== `undefined` &&
    window.excludeGtagPaths.some(rx => rx.test(location.pathname))

  if (pathIsExcluded) return null

  // wrap inside a timeout to make sure react-helmet is done with its changes (https://github.com/gatsbyjs/gatsby/issues/11592)
  const sendPageView = () => {
    const pagePath = location
      ? location.pathname + location.search + location.hash
      : undefined
    window.gtag(`event`, `page_view`, { page_path: pagePath })
  }

  const { delayOnRouteUpdate = 0 } = pluginConfig

  if (`requestAnimationFrame` in window) {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => setTimeout(sendPageView, delayOnRouteUpdate))
    })
  } else {
    // Delay by 32ms to simulate 2 requestOnAnimationFrame calls
    setTimeout(sendPageView, 32 + delayOnRouteUpdate)
  }

  return null
}


text:
using SFA.DAS.EmployerAccounts.Models.Account;
using System.Collections.Generic;

namespace SFA.DAS.EmployerAccounts.Queries.GetEmployerAgreementsByAccountId
{
    public class GetEmployerAgreementsByAccountIdResponse
    {
        public List<EmployerAgreement> EmployerAgreements { get; set; }
    }
}


text:
using UnityEngine;
using UnityEngine.Rendering;

namespace Kino
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Camera))]
    [AddComponentMenu("Kino Image Effects/Obscurance")]
    public partial class Obscurance : MonoBehaviour
    {
        #region Public Properties

        /// Degree of darkness produced by the effect.
        public float intensity {
            get { return _intensity; }
            set { _intensity = value; }
        }

        [SerializeField, Range(0, 4), Tooltip(
            "Degree of darkness produced by the effect.")]
        float _intensity = 1;

        /// Radius of sample points, which affects extent of darkened areas.
        public float radius {
            get { return Mathf.Max(_radius, 1e-4f); }
            set { _radius = value; }
        }

        [SerializeField, Tooltip(
            "Radius of sample points, which affects extent of darkened areas.")]
        float _radius = 0.3f;

        /// Number of sample points, which affects quality and performance.
        public SampleCount sampleCount {
            get { return _sampleCount; }
            set { _sampleCount = value; }
        }

        public enum SampleCount { Lowest, Low, Medium, High, Variable }

        [SerializeField, Tooltip(
            "Number of sample points, which affects quality and performance.")]
        SampleCount _sampleCount = SampleCount.Medium;

        /// Determines the sample count when SampleCount.Variable is used.
        /// In other cases, it returns the preset value of the current setting.
        public int sampleCountValue {
            get {
                switch (_sampleCount) {
                    case SampleCount.Lowest: return 3;
                    case SampleCount.Low:    return 6;
                    case SampleCount.Medium: return 12;
                    case SampleCount.High:   return 20;
                }
                return Mathf.Clamp(_sampleCountValue, 1, 256);
            }
            set { _sampleCountValue = value; }
        }

        [SerializeField]
        int _sampleCountValue = 24;

        /// Halves the resolution of the effect to increase performance.
        public bool downsampling {
            get { return _downsampling; }
            set { _downsampling = value; }
        }

        [SerializeField, Tooltip(
            "Halves the resolution of the effect to increase performance.")]
        bool _downsampling = false;

        /// Source buffer used for obscurance estimation.
        public OcclusionSource occlusionSource {
            get {
                var isGBuffer = _occlusionSource == OcclusionSource.GBuffer;
                if (isGBuffer && !IsGBufferAvailable)
                    // An unavailable source was chosen:
                    // fallback to DepthNormalsTexture.
                    return OcclusionSource.DepthNormalsTexture;
                else
                    return _occlusionSource;
            }
            set { _occlusionSource = value; }
        }

        public enum OcclusionSource {
            DepthTexture, DepthNormalsTexture, GBuffer
        }

        [SerializeField, Tooltip(
            "Source buffer used for obscurance estimation")]
        OcclusionSource _occlusionSource = OcclusionSource.GBuffer;

        /// Enables the ambient-only mode in that the effect only affects
        /// ambient lighting. This mode is only available with G-buffer source
        /// and HDR rendering.
        public bool ambientOnly {
            get {
                return _ambientOnly && targetCamera.hdr &&
                    occlusionSource == OcclusionSource.GBuffer;
            }
            set { _ambientOnly = value; }
        }

        [SerializeField, Tooltip(
            "If checked, the effect only affects ambient lighting.")]
        bool _ambientOnly = false;

        #endregion

        #region Private Properties

        // Texture format used for storing AO
        RenderTextureFormat aoTextureFormat {
            get {
                if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.R8))
                    return RenderTextureFormat.R8;
                else
                    return RenderTextureFormat.Default;
            }
        }

        // AO shader material
        Material aoMaterial {
            get {
                if (_aoMaterial == null) {
                    var shader = Shader.Find("Hidden/Kino/Obscurance");
                    _aoMaterial = new Material(shader);
                    _aoMaterial.hideFlags = HideFlags.DontSave;
                }
                return _aoMaterial;
            }
        }

        [SerializeField] Shader _aoShader;
        Material _aoMaterial;

        // Command buffer for the AO pass
        CommandBuffer aoCommands {
            get {
                if (_aoCommands == null) {
                    _aoCommands = new CommandBuffer();
                    _aoCommands.name = "Kino.Obscurance";
                }
                return _aoCommands;
            }
        }

        CommandBuffer _aoCommands;

        // Target camera
        Camera targetCamera {
            get { return GetComponent<Camera>(); }
        }

        // Property observer
        PropertyObserver propertyObserver { get; set; }

        // Check if the G-buffer is available
        bool IsGBufferAvailable {
            get {
                var path = targetCamera.actualRenderingPath;
                return path == RenderingPath.DeferredShading;
            }
        }

        // Reference to the quad mesh in the built-in assets
        // (used in MRT blitting)
        [SerializeField] Mesh _quadMesh;

        #endregion

        #region Effect Passes

        // Build commands for the AO pass (used in the ambient-only mode).
        void BuildAOCommands()
        {
            var cb = aoCommands;

            var tw = targetCamera.pixelWidth;
            var th = targetCamera.pixelHeight;
            var ts = downsampling ? 2 : 1;
            var format = aoTextureFormat;
            var rwMode = RenderTextureReadWrite.Linear;
            var filter = FilterMode.Bilinear;

            // AO buffer
            var m = aoMaterial;
            var rtMask = Shader.PropertyToID("_ObscuranceTexture");
            cb.GetTemporaryRT(
                rtMask, tw / ts, th / ts, 0, filter, format, rwMode
            );

            // AO estimation
            cb.Blit(null, rtMask, m, 2);

            // Blur buffer
            var rtBlur = Shader.PropertyToID("_ObscuranceBlurTexture");

            // 1st blur iteration (large kernel)
            cb.GetTemporaryRT(rtBlur, tw, th, 0, filter, format, rwMode);
            cb.SetGlobalVector("_BlurVector", Vector2.right * 2);
            cb.Blit(rtMask, rtBlur, m, 4);
            cb.ReleaseTemporaryRT(rtMask);

            cb.GetTemporaryRT(rtMask, tw, th, 0, filter, format, rwMode);
            cb.SetGlobalVector("_BlurVector", Vector2.up * 2 * ts);
            cb.Blit(rtBlur, rtMask, m, 4);
            cb.ReleaseTemporaryRT(rtBlur);

            // 2nd blur iteration (small kernel)
            cb.GetTemporaryRT(rtBlur, tw, th, 0, filter, format, rwMode);
            cb.SetGlobalVector("_BlurVector", Vector2.right * ts);
            cb.Blit(rtMask, rtBlur, m, 6);
            cb.ReleaseTemporaryRT(rtMask);

            cb.GetTemporaryRT(rtMask, tw, th, 0, filter, format, rwMode);
            cb.SetGlobalVector("_BlurVector", Vector2.up * ts);
            cb.Blit(rtBlur, rtMask, m, 6);
            cb.ReleaseTemporaryRT(rtBlur);

            // Combine AO to the G-buffer.
            var mrt = new RenderTargetIdentifier[] {
                BuiltinRenderTextureType.GBuffer0,      // Albedo, Occ
                BuiltinRenderTextureType.CameraTarget   // Ambient
            };
            cb.SetRenderTarget(mrt, BuiltinRenderTextureType.CameraTarget);
            cb.DrawMesh(_quadMesh, Matrix4x4.identity, m, 0, 8);

            cb.ReleaseTemporaryRT(rtMask);
        }

        // Execute the AO pass immediately (used in the forward mode).
        void ExecuteAOPass(RenderTexture source, RenderTexture destination)
        {
            var tw = source.width;
            var th = source.height;
            var ts = downsampling ? 2 : 1;
            var format = aoTextureFormat;
            var rwMode = RenderTextureReadWrite.Linear;
            var useGBuffer = occlusionSource == OcclusionSource.GBuffer;

            // AO buffer
            var m = aoMaterial;
            var rtMask = RenderTexture.GetTemporary(
                tw / ts, th / ts, 0, format, rwMode
            );

            // AO estimation
            Graphics.Blit(source, rtMask, m, (int)occlusionSource);

            // 1st blur iteration (large kernel)
            var rtBlur = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
            m.SetVector("_BlurVector", Vector2.right * 2);
            Graphics.Blit(rtMask, rtBlur, m, useGBuffer ? 4 : 3);
            RenderTexture.ReleaseTemporary(rtMask);

            rtMask = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
            m.SetVector("_BlurVector", Vector2.up * 2 * ts);
            Graphics.Blit(rtBlur, rtMask, m, useGBuffer ? 4 : 3);
            RenderTexture.ReleaseTemporary(rtBlur);

            // 2nd blur iteration (small kernel)
            rtBlur = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
            m.SetVector("_BlurVector", Vector2.right * ts);
            Graphics.Blit(rtMask, rtBlur, m, useGBuffer ? 6 : 5);
            RenderTexture.ReleaseTemporary(rtMask);

            rtMask = RenderTexture.GetTemporary(tw, th, 0, format, rwMode);
            m.SetVector("_BlurVector", Vector2.up * ts);
            Graphics.Blit(rtBlur, rtMask, m, useGBuffer ? 6 : 5);
            RenderTexture.ReleaseTemporary(rtBlur);

            // Combine AO with the source.
            m.SetTexture("_ObscuranceTexture", rtMask);
            Graphics.Blit(source, destination, m, 7);

            RenderTexture.ReleaseTemporary(rtMask);
        }

        // Update the common material properties.
        void UpdateMaterialProperties()
        {
            var m = aoMaterial;
            m.SetFloat("_Intensity", intensity);
            m.SetFloat("_Radius", radius);
            m.SetFloat("_TargetScale", downsampling ? 0.5f : 1);
            m.SetInt("_SampleCount", sampleCountValue);
        }

        #endregion

        #region MonoBehaviour Functions

        void OnEnable()
        {
            // Register the command buffer if in the ambient-only mode.
            if (ambientOnly) targetCamera.AddCommandBuffer(
                CameraEvent.BeforeReflections, aoCommands
            );

            // Enable depth textures which the occlusion source requires.
            if (occlusionSource == OcclusionSource.DepthTexture)
                targetCamera.depthTextureMode |= DepthTextureMode.Depth;

            if (occlusionSource != OcclusionSource.GBuffer)
                targetCamera.depthTextureMode |= DepthTextureMode.DepthNormals;
        }

        void OnDisable()
        {
            // Destroy all the temporary resources.
            if (_aoMaterial != null) DestroyImmediate(_aoMaterial);
            _aoMaterial = null;

            if (_aoCommands != null) targetCamera.RemoveCommandBuffer(
                CameraEvent.BeforeReflections, _aoCommands
            );
            _aoCommands = null;
        }

        void Update()
        {
            if (propertyObserver.CheckNeedsReset(this, targetCamera))
            {
                // Reinitialize all the resources by disabling/enabling itself.
                // This is not very efficient way but just works...
                OnDisable();
                OnEnable();

                // Build the command buffer if in the ambient-only mode.
                if (ambientOnly)
                {
                    aoCommands.Clear();
                    BuildAOCommands();
                }

                propertyObserver.Update(this, targetCamera);
            }

            // Update the material properties (later used in the AO commands).
            if (ambientOnly) UpdateMaterialProperties();
        }

        [ImageEffectOpaque]
        void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (ambientOnly)
            {
                // Do nothing in the ambient-only mode.
                Graphics.Blit(source, destination);
            }
            else
            {
                // Execute the AO pass.
                UpdateMaterialProperties();
                ExecuteAOPass(source, destination);
            }
        }

        #endregion
    }
}