text:
package com.amazonaws.services.recyclebin.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateRuleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The unique ID of the retention rule.
     *

     */
    private String identifier;

    private RetentionPeriod retentionPeriod;
    /**
     *

     * The retention rule description.
     *

     */
    private String description;
    /**
     *

     * The resource type retained by the retention rule.
     *

     */
    private String resourceType;
    /**
     *

     * Information about the resource tags used to identify resources that are retained by the retention rule.
     *

     */
    private java.util.List<ResourceTag> resourceTags;
    /**
     *

     * The state of the retention rule. Only retention rules that are in the available state retain
     * resources.
     *

     */
    private String status;
    /**
     *

     * The lock state for the retention rule.
     *

     *

     *

     *

     * locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     * pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     * period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     * unlocked - The retention rule is unlocked and it can be modified or deleted by any user with the
     * required permissions.
     *

     *

     *

     *

     * null - The retention rule has never been locked. Once a retention rule has been locked, it can
     * transition between the locked and unlocked states only; it can never transition back to
     * null.
     *

     *

     *

     */
    private String lockState;
    /**
     *

     * The date and time at which the unlock delay is set to expire. Only returned for retention rules that have been
     * unlocked and that are still within the unlock delay period.
     *

     */
    private java.util.Date lockEndTime;

    /**
     *

     * The unique ID of the retention rule.
     *

     *
     * @param identifier
     *        The unique ID of the retention rule.
     */

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    /**
     *

     * The unique ID of the retention rule.
     *

     *
     * @return The unique ID of the retention rule.
     */

    public String getIdentifier() {
        return this.identifier;
    }

    /**
     *

     * The unique ID of the retention rule.
     *

     *
     * @param identifier
     *        The unique ID of the retention rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withIdentifier(String identifier) {
        setIdentifier(identifier);
        return this;
    }

    /**
     * @param retentionPeriod
     */

    public void setRetentionPeriod(RetentionPeriod retentionPeriod) {
        this.retentionPeriod = retentionPeriod;
    }

    /**
     * @return
     */

    public RetentionPeriod getRetentionPeriod() {
        return this.retentionPeriod;
    }

    /**
     * @param retentionPeriod
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withRetentionPeriod(RetentionPeriod retentionPeriod) {
        setRetentionPeriod(retentionPeriod);
        return this;
    }

    /**
     *

     * The retention rule description.
     *

     *
     * @param description
     *        The retention rule description.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * The retention rule description.
     *

     *
     * @return The retention rule description.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * The retention rule description.
     *

     *
     * @param description
     *        The retention rule description.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * The resource type retained by the retention rule.
     *

     *
     * @param resourceType
     *        The resource type retained by the retention rule.
     * @see ResourceType
     */

    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
    }

    /**
     *

     * The resource type retained by the retention rule.
     *

     *
     * @return The resource type retained by the retention rule.
     * @see ResourceType
     */

    public String getResourceType() {
        return this.resourceType;
    }

    /**
     *

     * The resource type retained by the retention rule.
     *

     *
     * @param resourceType
     *        The resource type retained by the retention rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ResourceType
     */

    public UpdateRuleResult withResourceType(String resourceType) {
        setResourceType(resourceType);
        return this;
    }

    /**
     *

     * The resource type retained by the retention rule.
     *

     *
     * @param resourceType
     *        The resource type retained by the retention rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ResourceType
     */

    public UpdateRuleResult withResourceType(ResourceType resourceType) {
        this.resourceType = resourceType.toString();
        return this;
    }

    /**
     *

     * Information about the resource tags used to identify resources that are retained by the retention rule.
     *

     *
     * @return Information about the resource tags used to identify resources that are retained by the retention rule.
     */

    public java.util.List<ResourceTag> getResourceTags() {
        return resourceTags;
    }

    /**
     *

     * Information about the resource tags used to identify resources that are retained by the retention rule.
     *

     *
     * @param resourceTags
     *        Information about the resource tags used to identify resources that are retained by the retention rule.
     */

    public void setResourceTags(java.util.Collection<ResourceTag> resourceTags) {
        if (resourceTags == null) {
            this.resourceTags = null;
            return;
        }

        this.resourceTags = new java.util.ArrayList<ResourceTag>(resourceTags);
    }

    /**
     *

     * Information about the resource tags used to identify resources that are retained by the retention rule.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setResourceTags(java.util.Collection)} or {@link #withResourceTags(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param resourceTags
     *        Information about the resource tags used to identify resources that are retained by the retention rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withResourceTags(ResourceTag... resourceTags) {
        if (this.resourceTags == null) {
            setResourceTags(new java.util.ArrayList<ResourceTag>(resourceTags.length));
        }
        for (ResourceTag ele : resourceTags) {
            this.resourceTags.add(ele);
        }
        return this;
    }

    /**
     *

     * Information about the resource tags used to identify resources that are retained by the retention rule.
     *

     *
     * @param resourceTags
     *        Information about the resource tags used to identify resources that are retained by the retention rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withResourceTags(java.util.Collection<ResourceTag> resourceTags) {
        setResourceTags(resourceTags);
        return this;
    }

    /**
     *

     * The state of the retention rule. Only retention rules that are in the available state retain
     * resources.
     *

     *
     * @param status
     *        The state of the retention rule. Only retention rules that are in the available state retain
     *        resources.
     * @see RuleStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The state of the retention rule. Only retention rules that are in the available state retain
     * resources.
     *

     *
     * @return The state of the retention rule. Only retention rules that are in the available state retain
     *         resources.
     * @see RuleStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The state of the retention rule. Only retention rules that are in the available state retain
     * resources.
     *

     *
     * @param status
     *        The state of the retention rule. Only retention rules that are in the available state retain
     *        resources.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see RuleStatus
     */

    public UpdateRuleResult withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The state of the retention rule. Only retention rules that are in the available state retain
     * resources.
     *

     *
     * @param status
     *        The state of the retention rule. Only retention rules that are in the available state retain
     *        resources.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see RuleStatus
     */

    public UpdateRuleResult withStatus(RuleStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     *

     * The lock state for the retention rule.
     *

     *

     *

     *

     * locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     * pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     * period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     * unlocked - The retention rule is unlocked and it can be modified or deleted by any user with the
     * required permissions.
     *

     *

     *

     *

     * null - The retention rule has never been locked. Once a retention rule has been locked, it can
     * transition between the locked and unlocked states only; it can never transition back to
     * null.
     *

     *

     *

     *
     * @param lockState
     *        The lock state for the retention rule.

     *

     *

     *

     *        locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     *        pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     *        period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     *        unlocked - The retention rule is unlocked and it can be modified or deleted by any user with
     *        the required permissions.
     *

     *

     *

     *

     *        null - The retention rule has never been locked. Once a retention rule has been locked, it
     *        can transition between the locked and unlocked states only; it can never
     *        transition back to null.
     *

     *

     * @see LockState
     */

    public void setLockState(String lockState) {
        this.lockState = lockState;
    }

    /**
     *

     * The lock state for the retention rule.
     *

     *

     *

     *

     * locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     * pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     * period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     * unlocked - The retention rule is unlocked and it can be modified or deleted by any user with the
     * required permissions.
     *

     *

     *

     *

     * null - The retention rule has never been locked. Once a retention rule has been locked, it can
     * transition between the locked and unlocked states only; it can never transition back to
     * null.
     *

     *

     *

     *
     * @return The lock state for the retention rule.

     *

     *

     *

     *         locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     *         pending_unlock - The retention rule has been unlocked but it is still within the unlock
     *         delay period. The retention rule can be modified or deleted only after the unlock delay period has
     *         expired.
     *

     *

     *

     *

     *         unlocked - The retention rule is unlocked and it can be modified or deleted by any user with
     *         the required permissions.
     *

     *

     *

     *

     *         null - The retention rule has never been locked. Once a retention rule has been locked, it
     *         can transition between the locked and unlocked states only; it can never
     *         transition back to null.
     *

     *

     * @see LockState
     */

    public String getLockState() {
        return this.lockState;
    }

    /**
     *

     * The lock state for the retention rule.
     *

     *

     *

     *

     * locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     * pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     * period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     * unlocked - The retention rule is unlocked and it can be modified or deleted by any user with the
     * required permissions.
     *

     *

     *

     *

     * null - The retention rule has never been locked. Once a retention rule has been locked, it can
     * transition between the locked and unlocked states only; it can never transition back to
     * null.
     *

     *

     *

     *
     * @param lockState
     *        The lock state for the retention rule.

     *

     *

     *

     *        locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     *        pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     *        period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     *        unlocked - The retention rule is unlocked and it can be modified or deleted by any user with
     *        the required permissions.
     *

     *

     *

     *

     *        null - The retention rule has never been locked. Once a retention rule has been locked, it
     *        can transition between the locked and unlocked states only; it can never
     *        transition back to null.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see LockState
     */

    public UpdateRuleResult withLockState(String lockState) {
        setLockState(lockState);
        return this;
    }

    /**
     *

     * The lock state for the retention rule.
     *

     *

     *

     *

     * locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     * pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     * period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     * unlocked - The retention rule is unlocked and it can be modified or deleted by any user with the
     * required permissions.
     *

     *

     *

     *

     * null - The retention rule has never been locked. Once a retention rule has been locked, it can
     * transition between the locked and unlocked states only; it can never transition back to
     * null.
     *

     *

     *

     *
     * @param lockState
     *        The lock state for the retention rule.

     *

     *

     *

     *        locked - The retention rule is locked and can't be modified or deleted.
     *

     *

     *

     *

     *        pending_unlock - The retention rule has been unlocked but it is still within the unlock delay
     *        period. The retention rule can be modified or deleted only after the unlock delay period has expired.
     *

     *

     *

     *

     *        unlocked - The retention rule is unlocked and it can be modified or deleted by any user with
     *        the required permissions.
     *

     *

     *

     *

     *        null - The retention rule has never been locked. Once a retention rule has been locked, it
     *        can transition between the locked and unlocked states only; it can never
     *        transition back to null.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see LockState
     */

    public UpdateRuleResult withLockState(LockState lockState) {
        this.lockState = lockState.toString();
        return this;
    }

    /**
     *

     * The date and time at which the unlock delay is set to expire. Only returned for retention rules that have been
     * unlocked and that are still within the unlock delay period.
     *

     *
     * @param lockEndTime
     *        The date and time at which the unlock delay is set to expire. Only returned for retention rules that have
     *        been unlocked and that are still within the unlock delay period.
     */

    public void setLockEndTime(java.util.Date lockEndTime) {
        this.lockEndTime = lockEndTime;
    }

    /**
     *

     * The date and time at which the unlock delay is set to expire. Only returned for retention rules that have been
     * unlocked and that are still within the unlock delay period.
     *

     *
     * @return The date and time at which the unlock delay is set to expire. Only returned for retention rules that have
     *         been unlocked and that are still within the unlock delay period.
     */

    public java.util.Date getLockEndTime() {
        return this.lockEndTime;
    }

    /**
     *

     * The date and time at which the unlock delay is set to expire. Only returned for retention rules that have been
     * unlocked and that are still within the unlock delay period.
     *

     *
     * @param lockEndTime
     *        The date and time at which the unlock delay is set to expire. Only returned for retention rules that have
     *        been unlocked and that are still within the unlock delay period.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateRuleResult withLockEndTime(java.util.Date lockEndTime) {
        setLockEndTime(lockEndTime);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getIdentifier() != null)
            sb.append("Identifier: ").append(getIdentifier()).append(",");
        if (getRetentionPeriod() != null)
            sb.append("RetentionPeriod: ").append(getRetentionPeriod()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getResourceType() != null)
            sb.append("ResourceType: ").append(getResourceType()).append(",");
        if (getResourceTags() != null)
            sb.append("ResourceTags: ").append(getResourceTags()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus()).append(",");
        if (getLockState() != null)
            sb.append("LockState: ").append(getLockState()).append(",");
        if (getLockEndTime() != null)
            sb.append("LockEndTime: ").append(getLockEndTime());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof UpdateRuleResult == false)
            return false;
        UpdateRuleResult other = (UpdateRuleResult) obj;
        if (other.getIdentifier() == null ^ this.getIdentifier() == null)
            return false;
        if (other.getIdentifier() != null && other.getIdentifier().equals(this.getIdentifier()) == false)
            return false;
        if (other.getRetentionPeriod() == null ^ this.getRetentionPeriod() == null)
            return false;
        if (other.getRetentionPeriod() != null && other.getRetentionPeriod().equals(this.getRetentionPeriod()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getResourceType() == null ^ this.getResourceType() == null)
            return false;
        if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false)
            return false;
        if (other.getResourceTags() == null ^ this.getResourceTags() == null)
            return false;
        if (other.getResourceTags() != null && other.getResourceTags().equals(this.getResourceTags()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getLockState() == null ^ this.getLockState() == null)
            return false;
        if (other.getLockState() != null && other.getLockState().equals(this.getLockState()) == false)
            return false;
        if (other.getLockEndTime() == null ^ this.getLockEndTime() == null)
            return false;
        if (other.getLockEndTime() != null && other.getLockEndTime().equals(this.getLockEndTime()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getIdentifier() == null) ? 0 : getIdentifier().hashCode());
        hashCode = prime * hashCode + ((getRetentionPeriod() == null) ? 0 : getRetentionPeriod().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode());
        hashCode = prime * hashCode + ((getResourceTags() == null) ? 0 : getResourceTags().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode + ((getLockState() == null) ? 0 : getLockState().hashCode());
        hashCode = prime * hashCode + ((getLockEndTime() == null) ? 0 : getLockEndTime().hashCode());
        return hashCode;
    }

    @Override
    public UpdateRuleResult clone() {
        try {
            return (UpdateRuleResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<?php

class Connect_Controller extends OneAuth\Auth\Controller {

public function action_error($provider = null, $e = '') {
        dd($e);
}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
	$writeup_no = $argv[2];

	# check exist writeup
	is_writeup_no($writeup_no) or error(404);
	$p = $pdo->prepare("
		SELECT
			`problem_no`
		FROM
			`{$db_prefix}_writeup`
		WHERE
			`no`=:no
		LIMIT
			1
	");
	$p->bindParam(':no', $writeup_no);
	$p->execute();
	$writeup = $p->fetch(PDO::FETCH_ASSOC) or error(404);

	# check permission
	if(!is_admin()){
		$p = $pdo->prepare("
			SELECT
				1
			FROM
				`{$db_prefix}_authlog`
			WHERE
				`problem_no`=:problem_no AND
				`username`=:username
			LIMIT
				1
		");
		$p->bindParam(':problem_no', $writeup['problem_no']);
		$p->bindParam(':username', $_SESSION['username']);
		$p->execute();
		$p->fetch(PDO::FETCH_ASSOC) or error(403);
	}

	# common header
	$title = __SITE__['title'].' » Writeup';
	$need_login = true;
	$js_files = [
		'/assets/js/writeup.js'
	];
	$show_category = true;
	require __DIR__.'/header.php';

	# get writeup
	$p = $pdo->prepare("
		SELECT
			`no`,
			(SELECT COUNT(*) FROM `{$db_prefix}_writeup` WHERE `problem_no`=`w`.`problem_no` AND `no` <= `w`.`no`) AS `idx`,
			(SELECT `title` FROM `{$db_prefix}_problem` WHERE `no`=`w`.`problem_no` LIMIT 1) AS `problem_title`,
			`contents`,
			`author`,
			(SELECT `comment` FROM `{$db_prefix}_user` WHERE `username`=`w`.`author` LIMIT 1) AS `author_comment`,
			`register_time`,
			EXISTS(SELECT 1 FROM `{$db_prefix}_authlog` WHERE `username`=:username AND `problem_no`=`w`.`problem_no` LIMIT 1) AS `is_solved`
		FROM
			`{$db_prefix}_writeup` AS `w`
		WHERE
			`no`=:no
		LIMIT
			1
	");
	$p->bindParam(':no', $writeup_no);
	$p->bindParam(':username', $_SESSION['username']);
	$p->execute();
	$writeup_info = $p->fetch(PDO::FETCH_ASSOC);

	# get author's info
	$p = $pdo->prepare("
		SELECT
			`email`,
			`comment`
		FROM
			`{$db_prefix}_user`
		WHERE
			`username`=:username
		LIMIT
			1
	");
	$p->bindParam(':username', $writeup_info['author']);
	$p->execute();
	$author_info = $p->fetch(PDO::FETCH_ASSOC);

?>

								<?php echo secure_escape($writeup_info['problem_title']); ?> — #<?php echo $writeup_info['idx']; ?>

									Written by <a href="/profile/<?php echo secure_escape(strtolower($writeup_info['author'])); ?>"><?php echo secure_escape($writeup_info['author']); ?> at <time><?php echo date('Y-m-d H:i:s',strtotime($writeup_info['register_time'])); ?></time>, and origin is <a href="/chall/<?php echo secure_escape(get_chall_link($writeup_info['problem_title'])); ?>"><?php echo secure_escape($writeup_info['problem_title']); ?>

								<?php echo secure_escape($writeup_info['contents'], true); ?>

								About writer

										<img class="media-object p-0" src="<?php echo get_gravatar_link($author_info['email'], 85); ?>" style="width:85px">

<?php echo secure_escape($writeup_info['author']); ?>

											<?php echo filter_var($author_info['comment'], FILTER_VALIDATE_URL) ? secure_escape('[url]'.$author_info['comment'].'[/url]', true) : secure_escape($author_info['comment']); ?>

							<?php
								if($writeup_info['author'] === $_SESSION['username']){
									?><button class="btn btn-dark mr-5" data-toggle="modal" data-target="#delete-writeup-modal">Delete</button><?php
								}
							?><button class="btn btn-default go-back" data-href="/writeup">List</button>

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

Delete a writeup

										Are you sure you want to delete this writeup?

										<button type="button" class="btn btn-danger delete-writeup" data-no="<?php echo $writeup_no; ?>" data-dismiss="modal">Delete</button>
										<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

<?php
	# common footer
	require __DIR__.'/footer.php';


text:
/*jshint node:true */
"use strict";

var express = require('express');
var reddit = require('../lib/api/reddit');
var redditAnalyzer = require('../lib/analytics/reddit-analyzer');
var db = require('../lib/models/db');
var router = express.Router();

function getId(subreddit, currentTime) {
  return subreddit +
    "-" + currentTime.getUTCFullYear() +
    "-" + (currentTime.getUTCMonth() + 1) +
    "-" + currentTime.getUTCDate() +
    "-" + currentTime.getUTCHours();
}

function handleError(res, err) {
  console.log("Error encountered somewhere within the API Router.");
  console.log(err);
  res.status(500);
  res.json({"message": err.message});
}

// Query for the latest subreddit data from the database.
// If it doesn't exist - fetch it from reddit, process it, and store in the database.
function pullRequestHandler(req, res) {
  var subreddit = req.params.subreddit || "all";
  var currentTime = new Date();
  var id = getId(subreddit, currentTime);

  // Query the database for the latest subreddit data.
  db.queryById(id, function (err, queryResults) {
    if(err) {
      handleError(res, err);
    } else {
      if (queryResults) {
        // If it exists - place the results in the response.
        res.json(queryResults);
      } else {
        // Otherwise - fetch it directly from reddit.
        reddit.getTop(subreddit, currentTime, function (err, redditData) {
          if (err) {
            handleError(res, err);
          } else {
            // Process the results from reddit.
            redditData.id = id;
            redditAnalyzer.generateStats(redditData, function (err, processedData) {
              if (err) {
                handleError(res, err);
              } else {
                // Place the results in the response and store it in the database.
                res.json(processedData);
                db.store(processedData);
              }
            });
          }
        });
      }
    }
  });
}

router.all('/pull', function (req, res) {
  pullRequestHandler(req, res);
});

router.all('/pull/:subreddit', function (req, res) {
  pullRequestHandler(req, res);
});

module.exports = router;


text:
FreeCodeCamp

Request Header Parser Microservice

Objective: Build a full stack JavaScript app that is functionally similar to this: https://cryptic-ridge-9197.herokuapp.com/api/whoami/ and deploy it to Heroku.

Note that for each project, you should create a new GitHub repository and a new Heroku project. If you can't remember how to do this, revisit http://freecodecamp.com/challenges/get-set-for-our-back-end-development-projects.

Here's the specific user story you should implement for this project:

User Story: I can get the IP address, language and operating system for my browser.

Once you've finished implementing these user stories, click the "I've completed this challenge" button and enter the URLs for both your GitHub repository and your live app running on Heroku.

You can get feedback on your project from fellow campers by sharing it in our Code Review Chatroom. You can also share it on Twitter and your city's Campsite (on Facebook).


text:
CREATE DATABASE  IF NOT EXISTS `llmm_main` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `llmm_main`;
-- MySQL dump 10.13  Distrib 5.6.17, for Win32 (x86)
--
-- Host: localhost    Database: llmm_main
-- ------------------------------------------------------
-- Server version	5.6.20

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `userpermissioneditpropertyattributeaccesslistcustom`
--

DROP TABLE IF EXISTS `userpermissioneditpropertyattributeaccesslistcustom`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userpermissioneditpropertyattributeaccesslistcustom` (
  `paID` int(10) unsigned NOT NULL DEFAULT '0',
  `peID` int(10) unsigned NOT NULL DEFAULT '0',
  `akID` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`paID`,`peID`,`akID`),
  KEY `peID` (`peID`),
  KEY `akID` (`akID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `userpermissioneditpropertyattributeaccesslistcustom`
--

LOCK TABLES `userpermissioneditpropertyattributeaccesslistcustom` WRITE;
/*!40000 ALTER TABLE `userpermissioneditpropertyattributeaccesslistcustom` DISABLE KEYS */;
/*!40000 ALTER TABLE `userpermissioneditpropertyattributeaccesslistcustom` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-09-27 17:02:54


text:
@interface DCXOREncryptUtility : NSObject

+ (BOOL)encryptFile:(NSString *)source toPath:(NSString *)dest withBlockLength:(NSUInteger)len;
+ (BOOL)decryptFile:(NSString *)source toPath:(NSString *)dest withBlockLength:(NSUInteger)len;

@end


text:
using System;
using System.Windows;
using MapUtils.Structs;

namespace NUI4Map.Handler
{
    public interface IMapHandler
    {
        event Action MapInitialized;
        UIElement CreateMap();
        void ShowClickedFlag(MapCoord coord, Uri imageUri);
        void ShowTargetFlag(MapCoord coord, Uri imageUri);
        void ClearFlags();
    }
}


text:
<?php

namespace Webuni\Bundle\CommonMarkBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class CommonMarkExtensionPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $extensions = [];
        foreach ($container->findTaggedServiceIds('webuni_commonmark.extension') as $id => $tag) {
            $alias = isset($tag[0]['alias']) ? $tag[0]['alias'] : $id;
            $extensions[$alias] = $id;
        }

        if ($container->hasDefinition('webuni_commonmark.default_environment')) {
            $definition = $container->getDefinition('webuni_commonmark.default_environment');
            foreach ($extensions as $alias => $id) {
                $definition->addMethodCall('addExtension', [new Reference($id)]);
            }
        }

        foreach ($container->findTaggedServiceIds('webuni_commonmark.environment.extensions') as $id => $tag) {
            // todo
        }
    }
}


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0" is_locked="false">
    <option name="myName" value="Project Default" />
    <option name="myLocal" value="false" />
    <inspection_tool class="Fix shebang" enabled="true" level="WARNING" enabled_by_default="true">/bin/sh#/bin/bash</inspection_tool>
    <inspection_tool class="JSUnusedGlobalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="JSUnusedLocalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="LessUnresolvedVariable" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="ReplaceAssignmentWithOperatorAssignmentJS" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="SassUnresolvedMixin" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SassUnresolvedVariable" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SillyAssignmentJS" enabled="false" level="WARNING" enabled_by_default="false" />
    <inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
      <option name="processCode" value="true" />
      <option name="processLiterals" value="true" />
      <option name="processComments" value="true" />
    </inspection_tool>
  </profile>
</component>


text:
package io.kuzzle.test.core.KuzzleDataCollection;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.net.URISyntaxException;

import io.kuzzle.sdk.core.Collection;
import io.kuzzle.sdk.core.Kuzzle;
import io.kuzzle.sdk.core.Options;
import io.kuzzle.sdk.enums.Mode;
import io.kuzzle.sdk.listeners.ResponseListener;
import io.kuzzle.sdk.listeners.OnQueryDoneListener;
import io.kuzzle.sdk.state.States;
import io.kuzzle.test.testUtils.KuzzleExtend;
import tech.gusavila92.websocketclient.WebSocketClient;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class fetchDocument {
  private Kuzzle kuzzle;
  private Collection collection;
  private ResponseListener listener;

  @Before
  public void setUp() throws URISyntaxException {
    Options opts = new Options();
    opts.setConnect(Mode.MANUAL);
    KuzzleExtend extended = new KuzzleExtend("localhost", opts, null);
    extended.setSocket(mock(WebSocketClient.class));
    extended.setState(States.CONNECTED);

    kuzzle = spy(extended);
    when(kuzzle.getHeaders()).thenReturn(new JSONObject());

    collection = new Collection(kuzzle, "test", "index");
    listener = mock(ResponseListener.class);
  }

  @Test
  public void checkSignaturesVariants() {
    collection = spy(collection);
    collection.fetchDocument("foo", listener);
    verify(collection).fetchDocument(eq("foo"), eq((Options)null), eq(listener));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testFetchDocumentIllegalDocumentId() {
    collection.fetchDocument(null, listener);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testFetchDocumentIllegalListener() {
    collection.fetchDocument("id", null);
  }

  @Test(expected = RuntimeException.class)
  public void testFetchDocumentQueryException() throws JSONException {
    doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class));
    collection.fetchDocument("id", listener);
  }

  @Test(expected = RuntimeException.class)
  public void testFetchDocumentException() throws JSONException {
    doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
        ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject()));
        return null;
      }
    }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class));
    doThrow(JSONException.class).when(listener).onSuccess(any(String.class));
    collection.fetchDocument("id", listener);
  }

  @Test
  public void testFetchDocument() throws JSONException {
    doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
        ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(
          new JSONObject()
            .put("result", new JSONObject()
                .put("_id", "foo")
                .put("_version", 42)
                .put("_source", new JSONObject())
            )
        );
        ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class));
        return null;
      }
    }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class));
    collection.fetchDocument("42", mock(ResponseListener.class));
    collection.fetchDocument("42", new Options(), mock(ResponseListener.class));
    ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class);
    verify(kuzzle, times(2)).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class));
    assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "document");
    assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "get");
  }

}


text:
import sys, base64, json, os.path, os, argparse, errno
from binascii import b2a_hex
import nghttp2

def testsuite(testdata, filename, outdir, table_size, deflate_table_size,
              simulate_table_size_change):
    res = {
        'description': '''\
Encoded by nghttp2. The basic encoding strategy is described in \
http://lists.w3.org/Archives/Public/ietf-http-wg/2013JulSep/1135.html \
We use huffman encoding only if it produces strictly shorter byte string than \
original. We make some headers not indexing at all, but this does not always \
result in less bits on the wire.'''
    }
    cases = []
    deflater = nghttp2.HDDeflater(deflate_table_size)

    if table_size != nghttp2.DEFAULT_HEADER_TABLE_SIZE:
        deflater.change_table_size(table_size)

    num_item = len(testdata['cases'])

    change_points = {}
    if simulate_table_size_change and num_item > 1:
        change_points[num_item * 2 // 3] = table_size * 2 // 3
        change_points[num_item // 3] = table_size // 3

    for casenum, item  in enumerate(testdata['cases']):
        outitem = {
            'seqno': casenum,
            'headers': item['headers']
        }

        if casenum in change_points:
            new_table_size = change_points[casenum]
            deflater.change_table_size(new_table_size)
            outitem['header_table_size'] = new_table_size

        casenum += 1
        hdrs = [(list(x.keys())[0].encode('utf-8'),
                 list(x.values())[0].encode('utf-8')) \
                for x in item['headers']]
        outitem['wire'] = b2a_hex(deflater.deflate(hdrs)).decode('utf-8')
        cases.append(outitem)

    if cases and table_size != nghttp2.DEFAULT_HEADER_TABLE_SIZE:
        cases[0]['header_table_size'] = table_size

    res['cases'] = cases
    jsonstr = json.dumps(res, indent=2)
    with open(os.path.join(outdir, filename), 'w') as f:
        f.write(jsonstr)

if __name__ == '__main__':
    ap = argparse.ArgumentParser(description='HPACK test case generator')
    ap.add_argument('-d', '--dir', help='output directory', default='out')
    ap.add_argument('-s', '--table-size', help='max header table size',
                    type=int, default=nghttp2.DEFAULT_HEADER_TABLE_SIZE)
    ap.add_argument('-S', '--deflate-table-size',
                    help='max header table size for deflater',
                    type=int, default=nghttp2.DEFLATE_MAX_HEADER_TABLE_SIZE)
    ap.add_argument('-c', '--simulate-table-size-change',
                    help='simulate table size change scenario',
                    action='store_true')

    ap.add_argument('file', nargs='*', help='input file')
    args = ap.parse_args()
    try:
        os.mkdir(args.dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e
    for filename in args.file:
        sys.stderr.write('{}\n'.format(filename))
        with open(filename) as f:
            input = f.read()
        testsuite(json.loads(input), os.path.basename(filename),
                  args.dir, args.table_size, args.deflate_table_size,
                  args.simulate_table_size_change)


text:
package cache

import (
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

var testAuthEntry = AuthEntry{
	AuthorizationToken: "testToken",
	RequestedAt:        time.Now().Add(-5 * time.Hour),
	ExpiresAt:          time.Now().Add(7 * time.Hour),
	ProxyEndpoint:      "testEndpoint",
}

var testRegistryName = "testRegistry"

var testCachePrefixKey = "prefix-"
var testPath = os.TempDir()
var testFilename = "test.json"
var testFullFillename = filepath.Join(testPath, testFilename)

func TestAuthEntryValid(t *testing.T) {
	assert.True(t, testAuthEntry.IsValid(time.Now()))
}

func TestAuthEntryInValid(t *testing.T) {
	assert.True(t, testAuthEntry.IsValid(time.Now().Add(time.Second)))
}

func TestCredentials(t *testing.T) {
	credentialCache := NewFileCredentialsCache(testPath, testFilename, testCachePrefixKey)

	credentialCache.Set(testRegistryName, &testAuthEntry)

	entry := credentialCache.Get(testRegistryName)
	assert.Equal(t, testAuthEntry.AuthorizationToken, entry.AuthorizationToken)
	assert.Equal(t, testAuthEntry.ProxyEndpoint, entry.ProxyEndpoint)
	assert.WithinDuration(t, testAuthEntry.RequestedAt, entry.RequestedAt, 1*time.Second)
	assert.WithinDuration(t, testAuthEntry.ExpiresAt, entry.ExpiresAt, 1*time.Second)

	credentialCache.Clear()

	entry = credentialCache.Get(testRegistryName)
	assert.Nil(t, entry)
}

func TestPreviousVersionCache(t *testing.T) {
	credentialCache := NewFileCredentialsCache(testPath, testFilename, testCachePrefixKey)

	registryCache := newRegistryCache()
	registryCache.Version = "0.1"
	registryCache.Registries[testRegistryName] = &testAuthEntry
	credentialCache.(*fileCredentialCache).save(registryCache)

	entry := credentialCache.Get(testRegistryName)
	assert.Nil(t, entry)

	credentialCache.Clear()
}

const testBadJson = "{nope not good json at all."

func TestInvalidCache(t *testing.T) {
	credentialCache := NewFileCredentialsCache(testPath, testFilename, testCachePrefixKey)

	file, err := os.Create(testFullFillename)
	assert.NoError(t, err)

	file.WriteString(testBadJson)
	err = file.Close()
	assert.NoError(t, err)

	entry := credentialCache.Get(testRegistryName)
	assert.Nil(t, entry)

	credentialCache.Clear()
}


text:
<?php

Class Homeworkmodel extends CI_Model
{

  public function __construct()
  {
      parent::__construct();

  }

  public function getYear()
    {
      $sqlYear = "SELECT * FROM edu_academic_year WHERE NOW() >= from_month AND NOW() <= to_month AND status = 'Active'";
      $year_result = $this->db->query($sqlYear);
      $ress_year = $year_result->result();

      if($year_result->num_rows()==1)
      {
        foreach ($year_result->result() as $rows)
        {
            $year_id = $rows->year_id;
        }
        return $year_id;
      }
    }
//GET ALL SECTION get_subject($classid,$user_id,$user_type)

//---------------New--------------------------------
	function get_teacher_class_sec($user_id,$user_type)
	{
		$query="SELECT user_id,user_type,user_master_id,teacher_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type'";
		$resultset=$this->db->query($query);
		$row=$resultset->result();
		 foreach($row as $rows){}
		 $teacher_id=$rows->user_master_id;
		 //echo  $teacher_id;exit;

		 $sql="SELECT ts.id,ts.subject_id,ts.teacher_id,ts.class_master_id,ts.status,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name FROM edu_teacher_handling_subject AS ts,edu_classmaster AS cm,edu_class AS c,edu_sections AS s WHERE ts.teacher_id='$teacher_id'  AND ts.class_master_id=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id  AND ts.status='Active' GROUP BY ts.class_master_id ";
		 $resultset=$this->db->query($sql);
         $res1=$resultset->result();
         return $res1;
	}

	function get_cls_tutor($user_id,$user_type)
	{
		$query="SELECT user_id,user_type,user_master_id,teacher_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type'";
		$resultset=$this->db->query($query);
		$row=$resultset->result();
		 foreach($row as $rows){}
		 $teacher_id=$rows->user_master_id;

		 $cls_tutor="SELECT t.teacher_id,t.class_teacher,t.status,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name FROM edu_teachers AS t,edu_classmaster AS cm,edu_class AS c,edu_sections AS s WHERE t.teacher_id='$teacher_id' AND t.class_teacher=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id";
		 $resultset1=$this->db->query($cls_tutor);
         $res2=$resultset1->result();
         return $res2;
	}

	function get_subject($classid,$user_id,$user_type)
	{
		$query="SELECT user_id,user_type,user_master_id,teacher_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type'";
		$resultset=$this->db->query($query);
		$row=$resultset->result();
		foreach($row as $rows){}
		$teacher_id=$rows->user_master_id;

		$sql="SELECT ts.id,ts.subject_id,ts.teacher_id,ts.class_master_id,ts.status,su.subject_id,su.subject_name FROM edu_teacher_handling_subject AS ts,edu_subject AS su WHERE ts.teacher_id='$teacher_id' AND ts.class_master_id='$classid' AND ts.subject_id=su.subject_id AND ts.status='Active' ";
        $resultset1=$this->db->query($sql);
        //$res=$resultset1->result();
        //return $res;
		if($resultset1->num_rows()==0){
           $data= array("status" => "nodata");
           return $data;
         }else{
             $res1=$resultset1->result();
             $data=array("status"=>"success","res2"=>$res1);
             return $data;
		 }

	}
//--------------------------------------------------
		 function get_teacher_id($user_id)
		 {
			$query="SELECT teacher_id FROM edu_users WHERE user_id='$user_id'";
			$resultset=$this->db->query($query);
			$row=$resultset->result();
			 foreach($row as $rows){}
			 $teacher_id=$rows->teacher_id;
			 $get_classes="SELECT class_name FROM edu_teachers WHERE teacher_id='$teacher_id'";
			 $resultset1=$this->db->query($get_classes);
			 $teacher_row=$resultset1->result();
			  foreach($teacher_row as $teacher_rows){}
			$teach_id=$teacher_rows->class_name;

			$sQuery = "SELECT c.class_name,s.sec_name,cm.class_sec_id,cm.class FROM edu_class AS c,edu_sections AS s ,edu_classmaster AS cm WHERE cm.class = c.class_id AND cm.section = s.sec_id ORDER BY c.class_name";
			$objRs=$this->db->query($sQuery);
			$row=$objRs->result();
			foreach ($row as $rows1)
			{
			$s= $rows1->class_sec_id;
			$sec=$rows1->class;
			$clas=$rows1->class_name;
			$sec_name=$rows1->sec_name;
			$arryPlatform = explode(",", $teach_id);
		   $sPlatform_id  = trim($s);
		   $sPlatform_name  = trim($sec);
				 if(in_array($sPlatform_id, $arryPlatform )) {
					 $class_id[]=$s;
			 $class_name[]=$clas;
			 $sec_n[]=$sec_name;
 			 }
 			 }
      // print_r($sec_n);exit
      if(empty($class_id)){
        $data= array("status" =>"No Record Found");
        return $data;
      }else{

        $data= array("class_id" => $class_id,"class_name"=>$class_name,"sec_name"=>$sec_n,"status"=>"Record Found");
        return $data;
      }
        //print_r($data);exit;
       }

	    function create_test($year_id,$class_id,$user_id,$user_type,$test_type,$title,$subject_name,$formatted_date,$format_date,$details)
	   {
		     /*  $check_test_date="SELECT * FROM edu_homework WHERE class_id='$class_id' AND test_date='$formatted_date' AND subject_id='$subject_name'";
			  $result=$this->db->query($check_test_date);
			  if($result->num_rows()==0)
			  { */
			  $query="SELECT teacher_id,user_master_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type' ";
			  $resultset=$this->db->query($query);
			  $row=$resultset->result();
			  //foreach($row as $rows){}
			  $teacher_id=$row[0]->user_master_id;

			  $query="INSERT INTO edu_homework(year_id,class_id,teacher_id,hw_type,subject_id,title,test_date,due_date,hw_details,status,	created_by,created_at)VALUES('$year_id','$class_id','$teacher_id','$test_type','$subject_name','$title','$formatted_date','$format_date','$details','Active','$user_id',NOW())";
			  $resultset=$this->db->query($query);
			  $data= array("status"=>"success");
			  return $data;
			  /* }else{
					$data= array("status"=>"Already Exist");
					return $data;
				  } */

	   }

	   function getall_details($user_id,$user_type)
	   {
		    $query="SELECT teacher_id,user_master_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type' ";
			$resultset=$this->db->query($query);
			$row=$resultset->result();
			//foreach($row as $rows){}
			$id=$row[0]->user_master_id;

		  //$query="SELECT * FROM edu_homework ";
		    $query="SELECT eh.*,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name,su.subject_id,su.subject_name FROM edu_homework as eh,edu_classmaster AS cm,edu_subject AS su,edu_class AS c,edu_sections AS s WHERE eh.teacher_id='$id' AND eh.class_id=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id AND eh.subject_id=su.subject_id ORDER BY eh.hw_id DESC";
          $result=$this->db->query($query);
          return $result->result();
	   }
	  function get_stu_details($hw_id,$user_id,$user_type)
	  {
		    $query="SELECT eh.*,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name,su.subject_id,su.subject_name,ed.enroll_id,ed.admission_id,ed.admit_year,ed.admisn_no,ed.name,ed.class_id,ed.status,a.admission_id,a.admisn_no,a.name,a.sex FROM edu_homework as eh,edu_classmaster AS cm,edu_subject AS su,edu_class AS c,edu_sections AS s,edu_enrollment AS ed,edu_admission AS a WHERE ed.class_id=eh.class_id AND eh.class_id=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id AND eh.subject_id=su.subject_id And eh.hw_id='$hw_id' AND ed.status='Active' AND ed.admission_id=a.admission_id AND ed.name=a.name ORDER BY a.sex DESC,ed.name ASC ";
		  $result=$this->db->query($query);
          return $result->result();

	  }

	  function enter_marks($enroll,$hwid,$marks,$remarks,$user_id,$user_type)
	  {
		   $count_name = count($marks);
		  //echo $count_name; exit;
           for($i=0;$i<$count_name;$i++)
		   {
			$enroll1=$enroll[$i];
			//print_r($enroll);
			$hwid1=$hwid;
			$marks1=$marks[$i];
			$remarks1=$remarks[$i];
		  $query="INSERT INTO edu_class_marks(enroll_mas_id,hw_mas_id,marks,remarks,status,created_by,created_at) VALUES ('$enroll1','$hwid1','$marks1','$remarks1','Active','$user_id',NOW())";
		  $result=$this->db->query($query);

		  $sql="UPDATE edu_homework SET mark_status='1' WHERE hw_id='$hwid1'";
		  $result1=$this->db->query($sql);

          //return $result->result();
		  }
		  $data= array("status"=>"success");
		  return $data;

	  }

	  function edit_details($hw_id,$user_id,$user_type)
	  {
		  $query="SELECT teacher_id,user_master_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type' ";
		  $resultset=$this->db->query($query);
		  $row=$resultset->result();
		  //foreach($row as $rows){}
		  $teacher_id=$row[0]->user_master_id;

		    $query="SELECT eh.hw_id,eh.year_id,eh.class_id,eh.teacher_id,eh.	hw_type,eh.subject_id,su.subject_id,su.subject_name,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name,em.mark_id,em.enroll_mas_id,em.hw_mas_id,em.marks,em.remarks,ed.enroll_id,ed.admission_id,ed.admit_year,ed.admisn_no,ed.name,ed.class_id,ed.status,a.admission_id,a.admisn_no,a.name,a.sex FROM edu_homework AS eh,edu_classmaster AS cm,edu_subject AS su,edu_class AS c,edu_sections AS s,edu_class_marks AS em,edu_enrollment AS ed,edu_admission AS a WHERE eh.hw_id='$hw_id' AND em.hw_mas_id='$hw_id' AND eh.teacher_id='$teacher_id' AND eh.subject_id=su.subject_id AND eh.class_id=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id AND ed.enroll_id=em.enroll_mas_id AND ed.admission_id=a.admission_id AND ed.name=a.name ORDER BY a.sex DESC,ed.name ASC ";
		 $result=$this->db->query($query);
         return $result->result();
	  }

	  function update_marks($enroll,$hwid,$marks,$remarks,$user_id,$user_type)
	  {

		  $count_name = count($marks);
				//echo $count_name; exit;
           for($i=0;$i<$count_name;$i++)
		   {
			$enroll1=$enroll[$i];
			//print_r($enroll);
			$hwid1=$hwid;
			$marks1=$marks[$i];
			$remarks1=$remarks[$i];
		  $query="UPDATE edu_class_marks SET enroll_mas_id='$enroll1',hw_mas_id='$hwid1',marks='$marks1',remarks='$remarks1',updated_by='$user_id',updated_at=NOW() WHERE hw_mas_id='$hwid1' AND enroll_mas_id='$enroll1'";
		  $result=$this->db->query($query);

          //return $result->result();
		  }
		  $data= array("status"=>"success");
		  return $data;

	  }
	  function edit_test_details($hw_id,$user_id,$user_type)
	  {
		  $query="SELECT teacher_id,user_master_id FROM edu_users WHERE user_id='$user_id' AND user_type='$user_type' ";
		  $resultset=$this->db->query($query);
		  $row=$resultset->result();
		  //foreach($row as $rows){}
		  $teacher_id=$row[0]->user_master_id;

		   $query="SELECT eh.*,su.subject_id,su.subject_name,cm.class_sec_id,cm.class,cm.section,c.class_id,c.class_name,s.sec_id,s.sec_name FROM edu_homework AS eh,edu_classmaster AS cm,edu_subject AS su,edu_class AS c,edu_sections AS s WHERE eh.hw_id='$hw_id' AND eh.teacher_id='$teacher_id' AND eh.subject_id=su.subject_id AND eh.class_id=cm.class_sec_id AND cm.class=c.class_id AND cm.section=s.sec_id";
		 $result=$this->db->query($query);
         return $result->result();
	  }

	   function update_test_details($id,$hw_type,$title,$formatted_date,$format_date,$test_details,$status,$user_id,$user_type)
	   {
		   $query1="UPDATE edu_homework SET hw_type='$hw_type',title='$title',test_date='$formatted_date',due_date='$format_date',hw_details='$test_details',status='$status',updated_by='$user_id',updated_at=NOW() WHERE hw_id='$id'";
		   $result1=$this->db->query($query1);
           $data= array("status"=>"success");
		   return $data;
	   }

	  function get_acdaemicyear()
		{
		  $get_year="SELECT * FROM edu_academic_year WHERE NOW()>=from_month AND NOW()<=to_month";
		  $result1=$this->db->query($get_year);
		  $all_year= $result1->result();
		  return $all_year;
		}

		///SMS

		function get_all_ctutor_homework($user_id,$cls_tutor_id)
		{
			$year_id=$this->getYear();

		  $hmw="SELECT h.*,s.subject_id,s.subject_name FROM edu_homework AS h,edu_subject AS s WHERE class_id='$cls_tutor_id' AND h.year_id='$year_id' AND h.subject_id=s.subject_id GROUP BY DATE_FORMAT(h.created_at, '%Y-%m-%d')  DESC";
		  $hmw1=$this->db->query($hmw);
		  $hmw2= $hmw1->result();
		  return $hmw2;
		}

		function send_homework_status($user_id,$createdate,$clssid)
		{
			$send="UPDATE edu_homework SET send_option_status='1',updated_by='$user_id',updated_at=NOW() WHERE class_id='$clssid' AND DATE_FORMAT(created_at, '%Y-%m-%d')='$createdate'";
			$send1=$this->db->query($send);
            $data= array("status"=>"success");
		    return $data;
		}

		function view_send_homework_all($user_id,$tdate,$cid)
		{
		  $year_id=$this->getYear();
		   $ahmw="SELECT h.hw_id,h.hw_type,h.title,h.created_at,h.test_date,h.due_date,h.hw_details,h.send_option_status,s.subject_id,s.subject_name,t.name FROM edu_homework AS h,edu_subject AS s,edu_teachers AS t WHERE class_id='$cid' AND h.year_id='$year_id' AND h.subject_id=s.subject_id AND DATE_FORMAT(h.created_at,'%Y-%m-%d')='$tdate'  AND h.teacher_id=t.teacher_id";
		  $ahmw1=$this->db->query($ahmw);
		  $ahmw2= $ahmw1->result();
		  return $ahmw2;
		}

}
?>


text:
import os, sys, json
from backupcommon import scriptpath, Configuration, BackupLogger, BackupTemplate, info, error, debug, exception, create_snapshot_class
from tempfile import mkstemp
from oraexec import OracleExec

def printhelp():
    print "Usage: report.py [comma separated list of databases]"
    sys.exit(2)

if len(sys.argv) not in [1,2]:
    printhelp()

# Directory where the executable script is located
scriptpath = scriptpath()

# Read configuration
logf = mkstemp(prefix='backupreport-', suffix='.log')
os.close(logf[0])
Configuration.init('generic')
BackupLogger.init(logf[1], 'reporting')
Configuration.substitutions.update( {'logfile': BackupLogger.logfile, 'autorestorecatalog': Configuration.get('autorestorecatalog', 'autorestore')} )
reporttemplate = BackupTemplate('reporttemplate.cfg')

def exec_sqlplus(oraexec, script, header = 'sqlplusheader'):
    finalscript = "%s\n%s\n%s" % (reporttemplate.get(header), script, reporttemplate.get('sqlplusfooter'))
    output = oraexec.sqlplus(finalscript, silent=True)
    for line in output.splitlines():
        if line.startswith('OUTLOG: '):
            yield(line.strip()[8:])

def process_database(dbname):
    Configuration.defaultsection = dbname
    Configuration.substitutions.update({'dbname': dbname})
    oraexec = OracleExec(oraclehome=Configuration.get('oraclehome', 'generic'), tnspath=os.path.join(scriptpath, Configuration.get('tnsadmin', 'generic')))
    # Read job status information from the database
    jobinfo = {}
    for line in exec_sqlplus(oraexec, reporttemplate.get('jobstatus')):
        j = json.loads(line)
        if j["type"] == "job":
            if j["job_name"] == "ARCHLOGBACKUP_JOB":
                jobinfo["archlog"] = j
            elif j["job_name"] == "IMAGECOPY_JOB":
                jobinfo["imagecopy"] = j
        elif j["type"] == "exec":
            if j["job_name"] == "ARCHLOGBACKUP_JOB":
                jobinfo["archlogexec"] = j
            elif j["job_name"] == "IMAGECOPY_JOB":
                jobinfo["imagecopyexec"] = j
    # Read snapshot information
    zfs = create_snapshot_class(dbname)
    snaps = zfs.listsnapshots(True, True)
    # Autorestore information
    autorestoreinfo = None
    try:
        for line in exec_sqlplus(oraexec, reporttemplate.get('autorestorestatus'), 'sqlplusautorestoreheader'):
            autorestoreinfo = json.loads(line)
    except:
        pass
    # Print output
    print "%s:" % dbname
    try:
        print "  Backup job: %s, last: %s, duration: %s, last failure: %s" % (jobinfo['imagecopy']['state'], jobinfo['imagecopy']['last_start_date'], jobinfo['imagecopy']['last_run_duration'], jobinfo['imagecopyexec']['last_failed'])
        print "  Archivelog job: %s, last: %s, duration: %s, last failure: %s" % (jobinfo['archlog']['state'], jobinfo['archlog']['last_start_date'], jobinfo['archlog']['last_run_duration'], jobinfo['archlogexec']['last_failed'])
        if len(snaps) > 0:
            firstsnap = zfs.getsnapinfo(snaps[0])
            lastsnap = zfs.getsnapinfo(snaps[-1])
            print "  Snapshots: %d, latest: %s, oldest: %s" % (len(snaps), firstsnap["creation"], lastsnap["creation"])
        else:
            print "  Snapshots: none"
        if autorestoreinfo is not None:
            print "  Last successful restore: %s, last restore failure: %s, last successful validation: %s, avg difference from target (s): %d, avg restore time (min): %d" % (autorestoreinfo["last_success"], autorestoreinfo["last_fail"], autorestoreinfo["last_validated"], autorestoreinfo["avgdiff"], autorestoreinfo["avgrestoremin"])
    except:
        print "  Error getting information."

excludelist = ['generic','rman','zfssa','autorestore']
includelist = []
if len(sys.argv) == 2:
    includelist = sys.argv[1].split(",")

# Loop through all sections
for dbname in Configuration.sections():
    if dbname not in excludelist and (len(includelist) == 0 or dbname in includelist):
        process_database(dbname)


text:
require "spec_helper"

describe Chef::Application::Solo do

  let(:app) { Chef::Application::Solo.new }

  before do
    allow(Kernel).to receive(:trap).and_return(:ok)
    allow(app).to receive(:configure_opt_parser).and_return(true)
    allow(app).to receive(:configure_chef).and_return(true)
    allow(app).to receive(:configure_logging).and_return(true)
    allow(app).to receive(:trap)

    Chef::Config[:json_attribs] = false
    Chef::Config[:solo] = true

    # protect the unit tests against accidental --delete-entire-chef-repo from firing
    # for real during tests.  DO NOT delete this line.
    expect(FileUtils).not_to receive(:rm_rf)
  end

  describe "configuring the application" do
    it "should call set_specific_recipes" do
      expect(app).to receive(:set_specific_recipes)
      app.reconfigure
    end

    it "should set solo mode to true" do
      app.reconfigure
      expect(Chef::Config[:solo]).to be_truthy
    end

    it "should set audit-mode to :disabled" do
      app.reconfigure
      expect(Chef::Config[:audit_mode]).to be :disabled
    end

    describe "when configured to not fork the client process" do
      before do
        Chef::Config[:client_fork] = false
        Chef::Config[:daemonize] = false
        Chef::Config[:interval] = nil
        Chef::Config[:splay] = nil
      end

      context "when interval is given" do
        before do
          Chef::Config[:interval] = 600
        end

        it "should terminate with message" do
          expect(Chef::Application).to receive(:fatal!).with(
"Unforked chef-client interval runs are disabled in Chef 12.
Configuration settings:
  interval  = 600 seconds
Enable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options."
          )
          app.reconfigure
        end
      end
    end

    describe "when in daemonized mode and no interval has been set" do
      before do
        Chef::Config[:daemonize] = true
      end

      it "should set the interval to 1800" do
        Chef::Config[:interval] = nil
        app.reconfigure
        expect(Chef::Config[:interval]).to eq(1800)
      end
    end

    describe "when the json_attribs configuration option is specified" do
      let(:json_attribs) { { "a" => "b" } }
      let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) }
      let(:json_source) { "https://foo.com/foo.json" }

      before do
        Chef::Config[:json_attribs] = json_source
        expect(Chef::ConfigFetcher).to receive(:new).with(json_source).
          and_return(config_fetcher)
      end

      it "reads the JSON attributes from the specified source" do
        app.reconfigure
        expect(app.chef_client_json).to eq(json_attribs)
      end
    end

    it "downloads a tarball when the recipe_url configuration option is specified" do
      Chef::Config[:cookbook_path] = "#{Dir.tmpdir}/chef-solo/cookbooks"
      Chef::Config[:recipe_url] = "http://junglist.gen.nz/recipes.tgz"

      expect(FileUtils).to receive(:mkdir_p).with("#{Dir.tmpdir}/chef-solo").and_return(true)

      tarfile = StringIO.new("remote_tarball_content")
      target_file = StringIO.new

      expect(app).to receive(:open).with("http://junglist.gen.nz/recipes.tgz").and_yield(tarfile)
      expect(File).to receive(:open).with("#{Dir.tmpdir}/chef-solo/recipes.tgz", "wb").and_yield(target_file)

      shellout = instance_double("Mixlib::ShellOut", run_command: nil, error!: nil, stdout: "")

      expect(app).to receive(:shell_out!).with("tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo").and_return(shellout)
      app.reconfigure
      expect(target_file.string).to eq("remote_tarball_content")
    end

    it "fetches the recipe_url first when both json_attribs and recipe_url are specified" do
      json_attribs = { "a" => "b" }
      config_fetcher = instance_double("Chef::ConfigFetcher", :fetch_json => json_attribs)

      Chef::Config[:json_attribs] = "https://foo.com/foo.json"
      Chef::Config[:recipe_url] = "http://icanhas.cheezburger.com/lolcats"
      Chef::Config[:cookbook_path] = "#{Dir.tmpdir}/chef-solo/cookbooks"
      expect(FileUtils).to receive(:mkdir_p).with("#{Dir.tmpdir}/chef-solo").and_return(true)

      allow(Chef::Mixin::Command).to receive(:run_command).and_return(true)

      shellout = instance_double("Mixlib::ShellOut", run_command: nil, error!: nil, stdout: "")

      expect(app).to receive(:shell_out!).with("tar zxvf #{Dir.tmpdir}/chef-solo/recipes.tgz -C #{Dir.tmpdir}/chef-solo").and_return(shellout)
      expect(app).to receive(:fetch_recipe_tarball).ordered
      expect(Chef::ConfigFetcher).to receive(:new).ordered.and_return(config_fetcher)
      app.reconfigure
    end
  end

  describe "after the application has been configured" do
    before do
      Chef::Config[:solo] = true

      allow(Chef::Daemon).to receive(:change_privilege)
      chef_client = double("Chef::Client")
      allow(Chef::Client).to receive(:new).and_return(chef_client)
      # this is all stuff the reconfigure method needs
      allow(app).to receive(:configure_opt_parser).and_return(true)
      allow(app).to receive(:configure_chef).and_return(true)
      allow(app).to receive(:configure_logging).and_return(true)
    end

    it "should change privileges" do
      expect(Chef::Daemon).to receive(:change_privilege).and_return(true)
      app.setup_application
    end
  end

end


text:
package org.apache.kafka.common.record;

import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.utils.Utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Compressor {

    static private final float COMPRESSION_RATE_DAMPING_FACTOR = 0.9f;
    static private final float COMPRESSION_RATE_ESTIMATION_FACTOR = 1.05f;
    static private final int COMPRESSION_DEFAULT_BUFFER_SIZE = 1024;

    private static float[] typeToRate;
    private static int MAX_TYPE_ID = -1;

    static {
        for (CompressionType type : CompressionType.values()) {
            MAX_TYPE_ID = Math.max(MAX_TYPE_ID, type.id);
        }
        typeToRate = new float[MAX_TYPE_ID+1];
        for (CompressionType type : CompressionType.values()) {
            typeToRate[type.id] = type.rate;
        }
    }

    private final CompressionType type;
    private final DataOutputStream appendStream;
    private final ByteBufferOutputStream bufferStream;
    private final int initPos;

    public long writtenUncompressed;
    public long numRecords;

    public Compressor(ByteBuffer buffer, CompressionType type, int blockSize) {
        this.type = type;
        this.initPos = buffer.position();

        this.numRecords = 0;
        this.writtenUncompressed = 0;

        if (type != CompressionType.NONE) {
            // for compressed records, leave space for the header and the shallow message metadata
            // and move the starting position to the value payload offset
            buffer.position(initPos + Records.LOG_OVERHEAD + Record.RECORD_OVERHEAD);
        }

        // create the stream
        bufferStream = new ByteBufferOutputStream(buffer);
        appendStream = wrapForOutput(bufferStream, type, blockSize);
    }

    public Compressor(ByteBuffer buffer, CompressionType type) {
        this(buffer, type, COMPRESSION_DEFAULT_BUFFER_SIZE);
    }

    public ByteBuffer buffer() {
        return bufferStream.buffer();
    }

    public double compressionRate() {
        ByteBuffer buffer = bufferStream.buffer();
        if (this.writtenUncompressed == 0)
            return 1.0;
        else
            return (double) buffer.position() / this.writtenUncompressed;
    }

    public void close() {
        try {
            appendStream.close();
        } catch (IOException e) {
            throw new KafkaException(e);
        }

        if (type != CompressionType.NONE) {
            ByteBuffer buffer = bufferStream.buffer();
            int pos = buffer.position();
            // write the header, for the end offset write as number of records - 1
            buffer.position(initPos);
            buffer.putLong(numRecords - 1);
            buffer.putInt(pos - initPos - Records.LOG_OVERHEAD);
            // write the shallow message (the crc and value size are not correct yet)
            Record.write(buffer, null, null, type, 0, -1);
            // compute the fill the value size
            int valueSize = pos - initPos - Records.LOG_OVERHEAD - Record.RECORD_OVERHEAD;
            buffer.putInt(initPos + Records.LOG_OVERHEAD + Record.KEY_OFFSET, valueSize);
            // compute and fill the crc at the beginning of the message
            long crc = Record.computeChecksum(buffer,
                initPos + Records.LOG_OVERHEAD + Record.MAGIC_OFFSET,
                pos - initPos - Records.LOG_OVERHEAD - Record.MAGIC_OFFSET);
            Utils.writeUnsignedInt(buffer, initPos + Records.LOG_OVERHEAD + Record.CRC_OFFSET, crc);
            // reset the position
            buffer.position(pos);

            // update the compression ratio
            float compressionRate = (float) buffer.position() / this.writtenUncompressed;
            typeToRate[type.id] = typeToRate[type.id] * COMPRESSION_RATE_DAMPING_FACTOR +
                compressionRate * (1 - COMPRESSION_RATE_DAMPING_FACTOR);
        }
    }

    // Note that for all the write operations below, IO exceptions should
    // never be thrown since the underlying ByteBufferOutputStream does not throw IOException;
    // therefore upon encountering this issue we just close the append stream.

    public void putLong(final long value) {
        try {
            appendStream.writeLong(value);
        } catch (IOException e) {
            throw new KafkaException("I/O exception when writing to the append stream, closing", e);
        }
    }

    public void putInt(final int value) {
        try {
            appendStream.writeInt(value);
        } catch (IOException e) {
            throw new KafkaException("I/O exception when writing to the append stream, closing", e);
        }
    }

    public void put(final ByteBuffer buffer) {
        try {
            appendStream.write(buffer.array(), buffer.arrayOffset(), buffer.limit());
        } catch (IOException e) {
            throw new KafkaException("I/O exception when writing to the append stream, closing", e);
        }
    }

    public void putByte(final byte value) {
        try {
            appendStream.write(value);
        } catch (IOException e) {
            throw new KafkaException("I/O exception when writing to the append stream, closing", e);
        }
    }

    public void put(final byte[] bytes, final int offset, final int len) {
        try {
            appendStream.write(bytes, offset, len);
        } catch (IOException e) {
            throw new KafkaException("I/O exception when writing to the append stream, closing", e);
        }
    }

    public void putRecord(byte[] key, byte[] value, CompressionType type, int valueOffset, int valueSize) {
        // put a record as un-compressed into the underlying stream
        long crc = Record.computeChecksum(key, value, type, valueOffset, valueSize);
        byte attributes = Record.computeAttributes(type);
        putRecord(crc, attributes, key, value, valueOffset, valueSize);
    }

    public void putRecord(byte[] key, byte[] value) {
        putRecord(key, value, CompressionType.NONE, 0, -1);
    }

    private void putRecord(final long crc, final byte attributes, final byte[] key, final byte[] value, final int valueOffset, final int valueSize) {
        Record.write(this, crc, attributes, key, value, valueOffset, valueSize);
    }

    public void recordWritten(int size) {
        numRecords += 1;
        writtenUncompressed += size;
    }

    public long estimatedBytesWritten() {
        if (type == CompressionType.NONE) {
            return bufferStream.buffer().position();
        } else {
            // estimate the written bytes to the underlying byte buffer based on uncompressed written bytes
            return (long) (writtenUncompressed * typeToRate[type.id] * COMPRESSION_RATE_ESTIMATION_FACTOR);
        }
    }

    // the following two functions also need to be public since they are used in MemoryRecords.iteration

    static public DataOutputStream wrapForOutput(ByteBufferOutputStream buffer, CompressionType type, int bufferSize) {
        try {
            switch (type) {
                case NONE:
                    return new DataOutputStream(buffer);
                case GZIP:
                    return new DataOutputStream(new GZIPOutputStream(buffer, bufferSize));
                case SNAPPY:
                    // dynamically load the snappy class to avoid runtime dependency
                    // on snappy if we are not using it
                    try {
                        Class SnappyOutputStream = Class.forName("org.xerial.snappy.SnappyOutputStream");
                        OutputStream stream = (OutputStream) SnappyOutputStream.getConstructor(OutputStream.class, Integer.TYPE)
                            .newInstance(buffer, bufferSize);
                        return new DataOutputStream(stream);
                    } catch (Exception e) {
                        throw new KafkaException(e);
                    }
                case LZ4:
                    try {
                        Class LZ4BlockOutputStream = Class.forName("net.jpountz.lz4.LZ4BlockOutputStream");
                        OutputStream stream = (OutputStream) LZ4BlockOutputStream.getConstructor(OutputStream.class)
                            .newInstance(buffer);
                        return new DataOutputStream(stream);
                    } catch (Exception e) {
                        throw new KafkaException(e);
                    }
                case LZ4HC:
                    try {
                        Class<?> factoryClass = Class.forName("net.jpountz.lz4.LZ4Factory");
                        Class<?> compressorClass = Class.forName("net.jpountz.lz4.LZ4Compressor");
                        Class<?> lz4BlockOutputStream = Class.forName("net.jpountz.lz4.LZ4BlockOutputStream");
                        Object factory = factoryClass.getMethod("fastestInstance").invoke(null);
                        Object compressor = factoryClass.getMethod("highCompressor").invoke(factory);
                        OutputStream stream = (OutputStream) lz4BlockOutputStream
                            .getConstructor(OutputStream.class, Integer.TYPE, compressorClass)
                            .newInstance(buffer, 1 << 16, compressor);
                        return new DataOutputStream(stream);
                    } catch (Exception e) {
                        throw new KafkaException(e);
                    }
                default:
                    throw new IllegalArgumentException("Unknown compression type: " + type);
            }
        } catch (IOException e) {
            throw new KafkaException(e);
        }
    }

    static public DataInputStream wrapForInput(ByteBufferInputStream buffer, CompressionType type) {
        try {
            switch (type) {
                case NONE:
                    return new DataInputStream(buffer);
                case GZIP:
                    return new DataInputStream(new GZIPInputStream(buffer));
                case SNAPPY:
                    // dynamically load the snappy class to avoid runtime dependency
                    // on snappy if we are not using it
                    try {
                        Class SnappyInputStream = Class.forName("org.xerial.snappy.SnappyInputStream");
                        InputStream stream = (InputStream) SnappyInputStream.getConstructor(InputStream.class)
                            .newInstance(buffer);
                        return new DataInputStream(stream);
                    } catch (Exception e) {
                        throw new KafkaException(e);
                    }
                case LZ4:
                case LZ4HC:
                    // dynamically load LZ4 class to avoid runtime dependency
                    try {
                        Class inputStreamClass = Class.forName("net.jpountz.lz4.LZ4BlockInputStream");
                        InputStream stream = (InputStream) inputStreamClass.getConstructor(InputStream.class)
                            .newInstance(buffer);
                        return new DataInputStream(stream);
                    } catch (Exception e) {
                        throw new KafkaException(e);
                    }
                default:
                    throw new IllegalArgumentException("Unknown compression type: " + type);
            }
        } catch (IOException e) {
            throw new KafkaException(e);
        }
    }
}


text:
package be.arndep.commons.patterns;

/**
 * Created by Arnaud on 12-08-14.
 *
 * {@inheritDoc}
 */
@FunctionalInterface
public interface Factory<E, R> extends ThrowableFactory<E, R, RuntimeException> {
}


text:
<?php

namespace soleil\DonBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class soleilDonBundle extends Bundle
{
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>ORKSignatureView Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				ResearchKit

				ResearchKit

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/lineWidthVariation">lineWidthVariation</option>

	</optgroup>

</select>

ORKSignatureView Class Reference

	Inherits from
	UIView

	Declared in
	ORKSignatureView.h
ORKSignatureView.m

  lineWidthVariation

lineWidthVariation defines the max amount by which the line
width can vary (default 3pts).

@property (nonatomic) CGFloat lineWidthVariation

Discussion

The exact amount of the variation is determined by the amount
of force applied on 3D touch capable devices or by the speed
of the stroke if 3D touch is not available.

If the user is signing with an Apple Pencil, its force will be used.

Declared In

ORKSignatureView.h

Copyright © 2018 ResearchKit. All rights reserved. Updated: 2018-07-23

Generated by appledoc 2.2.1 (build 1334).


text:
#ifndef BLOCK_H
#define BLOCK_H

#include <QString>
#include <QHash>
#include <QSet>
#include <QPointF>
#include "blockpin.h"
#include <QJsonValue>

/**
 * The Block class represents a specific instance of a block type in a flow
 * chart.
 *
 * In addition to the name of its block type, a Block stores its position,
 * input and output connections, and the values of any set options.
 */
class Block {
public:
    /**
     * Construct an invalid Block.
     *
     * A Block is invalid if its typename is empty.
     */
    Block();

    /**
     * Construct a block with no connections.
     * @param blockTypeName the block's type name
     * @param pos the block's position
     */
    Block(QString blockTypeName, QPointF pos);

    /**
     * Construct a block with the given connections.
     * @param blockTypeName the block's type name
     * @param pos the block's position
     * @param inputConnections a mapping from input pin names to the BlockPin that drives that input pin
     * @param outputConnections a mapping from output pin names to the set of BlockPins driven by that output pin
     */
    Block(QString blockTypeName, QPointF pos, QHash<QString, BlockPin> inputConnections, QHash< QString, QSet< BlockPin > > outputConnections);

    /**
     * Determine whether or not this Block is valid.
     * A Block is valid if its blockTypeName is not empty.
     * @return true if this is a valid Block, false otherwise
     */
    bool isValid() const;

    /**
     * Connect the given output pin to the given BlockPin.
     * @param outputPinName the name of the output pin
     * @param inputPin the BlockPin to connect to
     */
    void connectOutput(QString outputPinName, BlockPin inputPin);

    /**
     * Disconnect the given output pin from the given BlockPin.
     * @param outputPinName the name of the output pin
     * @param inputPin the BlockPin to disconnect from
     */
    void disconnectOutput(QString outputPinName, BlockPin inputPin);

    /**
     * Connect the given input pin to the given BlockPin.
     * @param inputPinName the name of the input pin
     * @param outputPin the BlockPin to connect to
     */
    void connectInput(QString inputPinName, BlockPin outputPin);

    /**
     * Disconnect the given input pin from its associated BlockPin.
     * @param inputPinName the name of the input pin
     */
    void disconnectInput(QString inputPinName);

    /**
     * Set this block's position.
     * @param pos the new position
     */
    void setPos(QPointF pos);

    /**
     * Set the value of one of this block's options.
     * @param optionName the name of the option to set
     * @param value the value to set the option to
     */
    void setOptionValue(QString optionName, QString value);

    /**
     * Reset this block's option values to the defaults.
     */
    void resetOptionValues();

    /**
     * @return this block's position
     */
    QPointF pos() const;

    /**
     * @return this block's type name
     */
    QString blockTypeName() const;

    /**
     * @return true if this block has connected inputs, false if not
     */
    bool hasInputConnections() const;

    /**
     * Query the BlockPin that the named input pin is connected to.
     *
     * @param inputPinName the name of the input pin to query
     * @return the BlockPin that the given input pin connects to, or an invalid
     * BlockPin if it is not connected
     */
    BlockPin inputConnection(QString inputPinName) const;

    /**
     * Query the set of BlockPins that the named output pin is connected to.
     *
     * @param otuputPinName the name of the output pin to query
     * @return the set of BlockPins that the given output pin connects to
     */
    QSet<BlockPin> outputConnection(QString outputPinName) const;

    /**
     * Query the set value of one of this block's options.
     *
     * @param optionName the name of the option to query.
     * @return the set value of this option, or an empty string if no value has been set.
     */
    QString optionValue(QString optionName) const;

    /**
     * Query the set value of one of this block's options.
     *
     * @param optionName the name of the option to query.
     * @param defaultValue the option's default value
     * @return the set value of this option, or the default value if no value has been set.
     */
    QString optionValue(QString optionName, QString defaultValue = "") const;

    /**
     * @return the JSON representation of this block
     */
    QJsonValue toJson() const;

private:
    QPointF m_pos;
    QString m_blockTypeName;
    QHash<QString, BlockPin> m_inputConnections;
    QHash< QString, QSet< BlockPin > > m_outputConnections;
    QHash<QString, QString> m_optionValues;
};

QJsonValue Block_toJson(Block obj);
Block Block_fromJson(QJsonValue node, bool *ok = NULL);

QJsonValue QHash_int_Block_toJson(QHash<int, Block> obj);
QHash<int, Block> QHash_int_Block_fromJson(QJsonValue node, bool *ok = NULL);

QJsonValue QMap_int_Block_toJson(QMap<int, Block> obj);
QMap<int, Block> QMap_int_Block_fromJson(QJsonValue node, bool *ok = NULL);

#endif // BLOCK_H