text:
<?php
/**
 * MediaFilesApi
 * PHP version 5
 *
 * @category Class
 * @package  Kinow\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Server API
 *
 * Reference for Server API (REST/Json)
 *
 * OpenAPI spec version: 1.4.39
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Kinow\Client\Api;

use \Kinow\Client\ApiClient;
use \Kinow\Client\ApiException;
use \Kinow\Client\Configuration;
use \Kinow\Client\ObjectSerializer;

/**
 * MediaFilesApi Class Doc Comment
 *
 * @category Class
 * @package  Kinow\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class MediaFilesApi
{
    /**
     * API Client
     *
     * @var \Kinow\Client\ApiClient instance of the ApiClient
     */
    protected $apiClient;

    /**
     * Constructor
     *
     * @param \Kinow\Client\ApiClient|null $apiClient The api client to use
     */
    public function __construct(\Kinow\Client\ApiClient $apiClient = null)
    {
        if ($apiClient === null) {
            $apiClient = new ApiClient();
            $apiClient->getConfig()->setHost('https://api.kinow.com/api');
        }

        $this->apiClient = $apiClient;
    }

    /**
     * Get API client
     *
     * @return \Kinow\Client\ApiClient get the API client
     */
    public function getApiClient()
    {
        return $this->apiClient;
    }

    /**
     * Set the API client
     *
     * @param \Kinow\Client\ApiClient $apiClient set the API client
     *
     * @return MediaFilesApi
     */
    public function setApiClient(\Kinow\Client\ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
        return $this;
    }

    /**
     * Operation getMediaFile
     *
     *
     *
     * @param int $media_file_id MediaFile ID to fetch (required)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return \Kinow\Client\Model\MediaFile
     */
    public function getMediaFile($media_file_id)
    {
        list($response) = $this->getMediaFileWithHttpInfo($media_file_id);
        return $response;
    }

    /**
     * Operation getMediaFileWithHttpInfo
     *
     *
     *
     * @param int $media_file_id MediaFile ID to fetch (required)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return array of \Kinow\Client\Model\MediaFile, HTTP status code, HTTP response headers (array of strings)
     */
    public function getMediaFileWithHttpInfo($media_file_id)
    {
        // verify the required parameter 'media_file_id' is set
        if ($media_file_id === null) {
            throw new \InvalidArgumentException('Missing the required parameter $media_file_id when calling getMediaFile');
        }
        // parse inputs
        $resourcePath = "/media-files/{media_file_id}";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $apiVersion = $this->apiClient->getConfig()->getApiVersion();
        $_header_accept = $this->apiClient->selectHeaderAccept(["application/vnd.kinowapi.v$apiVersion+json"]);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);

        // path params
        if ($media_file_id !== null) {
            $resourcePath = str_replace(
                "{" . "media_file_id" . "}",
                $this->apiClient->getSerializer()->toPathValue($media_file_id),
                $resourcePath
            );
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Id');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Id'] = $apiKey;
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Secret');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Secret'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'GET',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Kinow\Client\Model\MediaFile',
                '/media-files/{media_file_id}'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Kinow\Client\Model\MediaFile', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Kinow\Client\Model\MediaFile', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }

    /**
     * Operation getMediaSourceFiles
     *
     *
     *
     * @param int $source_id Media source ID to fetch (required)
     * @param int $page  (optional)
     * @param int $per_page  (optional)
     * @param string $filters ```      name[value]=string&name[operator]=contains&date_add[value]=string&date_add[operator]=lt      _______________        {      \"name\": {      \"value\": \"string\",      \"operator\": \"contains\"      },      \"date_add\": {      \"value\": \"string\",      \"operator\": \"lt\"      }      } ```Operator can be: strict, contains, between, in, gt (greater than), lt (lower than). (optional)
     * @param string $sort_by Sort by this attribute (id by default) (optional)
     * @param string $sort_direction Sorting direction (asc by default) (optional)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return \Kinow\Client\Model\MediaFiles
     */
    public function getMediaSourceFiles($source_id, $page = null, $per_page = null, $filters = null, $sort_by = null, $sort_direction = null)
    {
        list($response) = $this->getMediaSourceFilesWithHttpInfo($source_id, $page, $per_page, $filters, $sort_by, $sort_direction);
        return $response;
    }

    /**
     * Operation getMediaSourceFilesWithHttpInfo
     *
     *
     *
     * @param int $source_id Media source ID to fetch (required)
     * @param int $page  (optional)
     * @param int $per_page  (optional)
     * @param string $filters ```      name[value]=string&name[operator]=contains&date_add[value]=string&date_add[operator]=lt      _______________        {      \"name\": {      \"value\": \"string\",      \"operator\": \"contains\"      },      \"date_add\": {      \"value\": \"string\",      \"operator\": \"lt\"      }      } ```Operator can be: strict, contains, between, in, gt (greater than), lt (lower than). (optional)
     * @param string $sort_by Sort by this attribute (id by default) (optional)
     * @param string $sort_direction Sorting direction (asc by default) (optional)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return array of \Kinow\Client\Model\MediaFiles, HTTP status code, HTTP response headers (array of strings)
     */
    public function getMediaSourceFilesWithHttpInfo($source_id, $page = null, $per_page = null, $filters = null, $sort_by = null, $sort_direction = null)
    {
        // verify the required parameter 'source_id' is set
        if ($source_id === null) {
            throw new \InvalidArgumentException('Missing the required parameter $source_id when calling getMediaSourceFiles');
        }
        // parse inputs
        $resourcePath = "/media-sources/{source_id}/files";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $apiVersion = $this->apiClient->getConfig()->getApiVersion();
        $_header_accept = $this->apiClient->selectHeaderAccept(["application/vnd.kinowapi.v$apiVersion+json"]);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);

        // query params
        if ($page !== null) {
            $queryParams['page'] = $this->apiClient->getSerializer()->toQueryValue($page);
        }
        // query params
        if ($per_page !== null) {
            $queryParams['per_page'] = $this->apiClient->getSerializer()->toQueryValue($per_page);
        }
        // query params
        if ($filters !== null) {
            $queryParams['filters'] = $this->apiClient->getSerializer()->toQueryValue($filters);
        }
        // query params
        if ($sort_by !== null) {
            $queryParams['sort_by'] = $this->apiClient->getSerializer()->toQueryValue($sort_by);
        }
        // query params
        if ($sort_direction !== null) {
            $queryParams['sort_direction'] = $this->apiClient->getSerializer()->toQueryValue($sort_direction);
        }
        // path params
        if ($source_id !== null) {
            $resourcePath = str_replace(
                "{" . "source_id" . "}",
                $this->apiClient->getSerializer()->toPathValue($source_id),
                $resourcePath
            );
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Id');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Id'] = $apiKey;
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Secret');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Secret'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'GET',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Kinow\Client\Model\MediaFiles',
                '/media-sources/{source_id}/files'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Kinow\Client\Model\MediaFiles', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Kinow\Client\Model\MediaFiles', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }

    /**
     * Operation postMediaSourceFiles
     *
     *
     *
     * @param int $source_id Media source ID to fetch (required)
     * @param \Kinow\Client\Model\MediaFile $body Create MediaFile object (required)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return \Kinow\Client\Model\MediaFile
     */
    public function postMediaSourceFiles($source_id, $body)
    {
        list($response) = $this->postMediaSourceFilesWithHttpInfo($source_id, $body);
        return $response;
    }

    /**
     * Operation postMediaSourceFilesWithHttpInfo
     *
     *
     *
     * @param int $source_id Media source ID to fetch (required)
     * @param \Kinow\Client\Model\MediaFile $body Create MediaFile object (required)
     * @throws \Kinow\Client\ApiException on non-2xx response
     * @return array of \Kinow\Client\Model\MediaFile, HTTP status code, HTTP response headers (array of strings)
     */
    public function postMediaSourceFilesWithHttpInfo($source_id, $body)
    {
        // verify the required parameter 'source_id' is set
        if ($source_id === null) {
            throw new \InvalidArgumentException('Missing the required parameter $source_id when calling postMediaSourceFiles');
        }
        // verify the required parameter 'body' is set
        if ($body === null) {
            throw new \InvalidArgumentException('Missing the required parameter $body when calling postMediaSourceFiles');
        }
        // parse inputs
        $resourcePath = "/media-sources/{source_id}/files";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $apiVersion = $this->apiClient->getConfig()->getApiVersion();
        $_header_accept = $this->apiClient->selectHeaderAccept(["application/vnd.kinowapi.v$apiVersion+json"]);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);

        // path params
        if ($source_id !== null) {
            $resourcePath = str_replace(
                "{" . "source_id" . "}",
                $this->apiClient->getSerializer()->toPathValue($source_id),
                $resourcePath
            );
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // body params
        $_tempBody = null;
        if (isset($body)) {
            $_tempBody = $body;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Id');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Id'] = $apiKey;
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Client-Secret');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Client-Secret'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Kinow\Client\Model\MediaFile',
                '/media-sources/{source_id}/files'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Kinow\Client\Model\MediaFile', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Kinow\Client\Model\MediaFile', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }
}


text:
class SessionController < ApplicationController

  # ---------------------------------------------------------------------------
  # GET:/auth/github/callback
  # ---------------------------------------------------------------------------

  def create
    if account = Account.github(env["omniauth.auth"])
      then session[:id] = account.id
      redirect_to :root, {
        :success => "Hello, nice to see you!"
      }
    else
      redirect_to :root, {
        :error => "There was a serious error making your account."
      }
    end
  end

  # ---------------------------------------------------------------------------
  # GET,DELETE:/auth/logout
  # ---------------------------------------------------------------------------

  def delete
    reset_session
    redirect_to :root, {
      :success => "You have been logged out."
    }
  end
end

redpajama_set_name: RedPajamaGithub


text: Cartridge config scripts can be used for creating base or fully configured cartridge images.


text:
@interface PodsDummy_TTZoomTransition : NSObject
@end
@implementation PodsDummy_TTZoomTransition
@end


text:
/*
 * #TODO hook css auto loading into lively-container
 lively.loadCSSThroughDOM("LivelyCSS", "https://lively-kernel.org/lively4/lively4-jens/src/client/lively.css")
 */

html, body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  text-align: left!;
  /* Needed for PDF selection */
  user-select: auto;
}

@font-face {
  font-family: Virgil;
  src: url(../../src/external/fonts/Virgil.woff2);
}

.sketchy {
  font-family: Virgil;
}

.virgil {
  font-family: Virgil
}

.lively-file  {
  user-select: none;
}

lively-menu, lively-navbar  {
  user-select: none;
}

/*
body {
  user-select: none;
}

lively-container > * {
  user-select: text;
}

lively-pdf, lively-markdown {
  user-select: text;
}

lively-halo  {
  user-select: none;
}

div.lively-content  {
  user-select: text;
}
 */
h1, h2, h3, h4 {
  color: rgb(0, 78, 151);
}

/*
::-webkit-scrollbar {
  display: none;
}
*/

lively-list li.selected {
  background-color: lightgray;
}

lively-table table, lively-table tr, lively-table  th, lively-table  td {
  border: 1px solid gray;
  border-collapse: collapse;
}

lively-table td {
  white-space: nowrap;
}

lively-table td.number {
  text-align: right;
}

lively-table.active .table-selected {
  margin: -1px;
  border-collapse: collapse;
  background-color: rgba(190,190,190,0.3);
  border: 1px solid gray;

}

lively-table.active .start-selection:not(.editing) {
  outline: 2px solid gray;
  background-color: rgba(100,100,200,0.1);
}

lively-table .editing {
  background-color: white;
  outline: 2px solid blue;
}

lively-container img {
  max-width: 800px;
}

.lively-preferences {
  display: none;
}

.lively-text:empty:before {
  content: "<insert text here>";
  color: lightgray;
  border: none;
}

.lively-text:empty {
  border: 1px solid lightgray;
  content: "haha";
}

.lively-text {
  background-color: none;
}

.CodeMirror-Tern-tooltip {
/*   position: fixed;
  top: 0px !important;
  left: 0px !important;
  background-color: lightgray;
  font-size: 14px; */
  z-index: 100000 !important;
}

.CodeMirror-lint-tooltip {
  z-index: 100000 !important;
}

.task-list-item {
  list-style-type: none;
}

#croquet_spinnerOverlay {
  width: 200px;
  height: 200px;
}

pre:has(.snippet) {
  background-color: lightgray;
  padding: 20px;
}


text:
/*
    Document   : schedule
    Created on : 30 Jul 2013, 6:53:34 PM
    Author     : OpenCollan
    Description:
        Schedule tool specific style
*/

.fc-event {
    border: 1px solid #BBBBBB;
    background-color: #FFFFCC;
    color: black;
    font-size: 1em;
    cursor: default;
    text-align: left;
    position: relative;
    left: 20px
}

a.fc-event {
    text-decoration: none;
    cursor: pointer;
}

.fc-event-inner {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
    z-index: 2;
    padding-left: 20px;
}

.fc-event{
    border-style: none;
}

.fc-day-number{
    position: relative;
}

.fc-day-content{
    font-size: 9px;
    top: 0px;
    right: 0px;
}

.activity {
    background: url(../../../unipoole/image/activity.gif) no-repeat left top;
}

.deadline {
    background: url(../../../unipoole/image/deadline.gif) no-repeat left top;
}

#calendar {
    padding-top: 10px;
}

/* Table headers and rows */

table.dataTable td {
    padding: 0;
}

table.dataTable tr.odd {
    background-color: white;
}

table.dataTable tr.even {
    background-color: white;
}

table.dataTable tr.even td.sorting_1 {
    background-color: white;
}

table.dataTable tr.odd td.sorting_1 {
    background-color: white;
}

table.dataTable thead th {
    text-align: left;
    padding: 3px 18px 3px 13px !important;

}

.sorting_asc {
    background: url('../../../unipoole/image/sortascending.gif') no-repeat center left, #eeeeee !important;

}

.sorting_desc {
    background: url('../../../unipoole/image/sortdescending.gif') no-repeat center left, #eeeeee !important;
}

.fc-event-time {
    display:none;
}


text:
require "sorrow/version"
require 'rack'

module Sorrow
  # Your code goes here...
  def call(env)
    [200, {"Content-Type" => "text/html"}, ["Hello Rack!"]]
  end
end


text:
from jip import *

####################################################
# Implementation as single functions either as tools
# that return a script or as (interpreter, script)
# tuple. You can also decorate a function with
# @pytool and implement the tool execution in python
# directly.
####################################################
@tool()
def fun_hello_world():
    return "echo 'Hello World'"

@tool()
def fun_hello_world_perl():
    return 'perl', "print('Hello World\n');"

@pytool()
def fun_hello_world_py():
    """Prints hello world in a python module"""
    print "Hello python"

####################################################
# Implementation as python classes. For a simple
# hello world, that might seem overhead, but class
# base implementation allow you to customize the
# initialization, setup, and validation
####################################################
@tool()
class cls_hello_world(object):
    def get_command(self):
        return "echo 'Hello World'"

@tool()
class cls_hello_world_perl(object):
    def get_command(self):
        return 'perl', "print('Hello World\n');"

@pytool()
class cls_hello_world_py(object):
    def run(self):
        print "Hello World"


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Konva GIF Demo</title>


text:
"""Wrapper for interacting with the Stackdriver Trace API."""

from google.api_core.gapic_v1 import client_info
from google.cloud.trace import __version__
from google.cloud.trace_v1.gapic import trace_service_client
from google.cloud.trace_v1.proto import trace_pb2
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict

_CLIENT_INFO = client_info.ClientInfo(client_library_version=__version__)

class _TraceAPI(object):
    """
    Wrapper to help mapping trace-related APIs.

    See
    https://cloud.google.com/trace/docs/reference/v1/rpc/google.devtools.
    cloudtrace.v1

    Args:
        gapic_api (~google.cloud.trace_v1.gapic.trace_service_client.
            TraceServiceClient): Required. API object used to make RPCs.
        client (~google.cloud.trace.client.Client): The client that owns this
            API object.
    """

    def __init__(self, gapic_api, client):
        self._gapic_api = gapic_api
        self.client = client

    def patch_traces(self, project_id, traces):
        """
        Sends new traces to Stackdriver Trace or updates existing traces.

        Args:
            project_id (Optional[str]): ID of the Cloud project where the trace
                data is stored.
            traces (dict): Required. The traces to be patched in the API call.
        """
        traces_pb = _traces_mapping_to_pb(traces)
        self._gapic_api.patch_traces(project_id, traces_pb)

    def get_trace(self, project_id, trace_id):
        """
        Gets a single trace by its ID.

        Args:
            trace_id (str): ID of the trace to return.
            project_id (str): Required. ID of the Cloud project where the trace
                data is stored.

        Returns:
            A Trace dict.
        """
        trace_pb = self._gapic_api.get_trace(project_id, trace_id)
        trace_mapping = _parse_trace_pb(trace_pb)
        return trace_mapping

    def list_traces(
        self,
        project_id,
        view=None,
        page_size=None,
        start_time=None,
        end_time=None,
        filter_=None,
        order_by=None,
        page_token=None,
    ):
        """
        Returns of a list of traces that match the filter conditions.

        Args:
            project_id (Optional[str]): ID of the Cloud project where the trace
                data is stored.

            view (Optional[~google.cloud.trace_v1.gapic.enums.
                ListTracesRequest.ViewType]): Type of data returned for traces
                in the list. Default is ``MINIMAL``.

            page_size (Optional[int]): Maximum number of traces to return. If
                not specified or <= 0, the implementation selects a reasonable
                value. The implementation may return fewer traces than the
                requested page size.

            start_time (Optional[~datetime.datetime]): Start of the time
                interval (inclusive) during which the trace data was collected
                from the application.

            end_time (Optional[~datetime.datetime]): End of the time interval
                (inclusive) during which the trace data was collected from the
                application.

            filter_ (Optional[str]): An optional filter for the request.

            order_by (Optional[str]): Field used to sort the returned traces.

            page_token (Optional[str]): opaque marker for the next "page" of
                entries. If not passed, the API will return the first page of
                entries.

        Returns:
            A  :class:`~google.api_core.page_iterator.Iterator` of traces that
            match the specified filter conditions.
        """
        page_iter = self._gapic_api.list_traces(
            project_id=project_id,
            view=view,
            page_size=page_size,
            start_time=start_time,
            end_time=end_time,
            filter_=filter_,
            order_by=order_by,
        )
        page_iter.item_to_value = _item_to_mapping
        page_iter.next_page_token = page_token
        return page_iter

def _parse_trace_pb(trace_pb):
    """
    Parse a ``Trace`` protobuf to a dictionary.

    Args:
        trace_pb (~google.cloud.trace_v1.proto.trace_pb2.Trace): A trace
            protobuf instance.

    Returns:
        The converted trace dict.
    """
    try:
        return MessageToDict(trace_pb)
    except TypeError:
        raise

def _item_to_mapping(iterator, trace_pb):
    """
    Helper callable function for the page iterator

    Args:
        iterator(~google.api_core.page_iterator.Iterator): The iterator that is
            currently in use.

        trace_pb(~google.cloud.trace_v1.proto.trace_pb2.Trace): A trace
            protobuf instance.
    """
    mapping = _parse_trace_pb(trace_pb)
    return mapping

def make_trace_api(client):
    """
    Create an instance of the gapic Trace API.

    Args:
        client (~google.cloud.trace.client.Client): The client that holds
            configuration details.

    Returns:
        A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
        proper configurations.
    """
    generated = trace_service_client.TraceServiceClient(
        credentials=client._credentials,
        client_info=client._client_info,
        client_options=client._client_options,
    )
    return _TraceAPI(generated, client)

def _traces_mapping_to_pb(traces_mapping):
    """
    Convert a trace dict to protobuf.

    Args:
        traces_mapping (dict): A trace mapping.

    Returns:
        The converted protobuf type traces.
    """
    traces_pb = trace_pb2.Traces()
    ParseDict(traces_mapping, traces_pb)
    return traces_pb


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IOpenStackApiKeyPairController.cs" company="">
//
// </copyright>
// <summary>
//   Interface for open stack API key pair controller.
//   GET/v2/{tenant_id}/os-keypairs List keypairs
//   Lists keypairs that are associated with the account.
//   detail
//   POST/v2/{tenant_id}/os-keypairs Create or import keypair
//   Generates or imports a keypair.
//   detail
//   DELETE/v2/{tenant_id}/os-keypairs/{keypair_name}Delete keypair
//   Deletes a keypair.
//   detail
//   GET/v2/{tenant_id}/os-keypairs/{keypair_name}Show keypair information
//   Shows a keypair associated with the account.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Threading.Tasks;
using Caas.OpenStack.API.Models.keypair;

namespace Caas.OpenStack.API.Interfaces
{
	/// <summary>	Interface for open stack API key pair controller.
	/// 			GET/v2/{tenant_id}/os-keypairs List keypairs
	/// Lists keypairs that are associated with the account.
	///
	///  detail
	/// POST/v2/{tenant_id}/os-keypairs Create or import keypair
	/// Generates or imports a keypair.
	///
	///  detail
	/// DELETE/v2/{tenant_id}/os-keypairs/{keypair_name}Delete keypair
	/// Deletes a keypair.
	///
	///  detail
	/// GET/v2/{tenant_id}/os-keypairs/{keypair_name}Show keypair information
	/// Shows a keypair associated with the account. </summary>
	/// <remarks>	Anthony, 4/15/2015. </remarks>
	public interface IOpenStackApiKeyPairController
	{
		/// <summary>
		/// 	Gets key pairs
		/// 			GET/v2/{tenant_id}/os-keypairs.
		/// </summary>
		/// <param name="tenantId">
		/// The tenant Id.
		/// </param>
		/// <returns>
		/// 	The key pairs.
		/// </returns>
		Task<KeyPairCollectionResponse> GetKeyPairs(string tenantId);

		/// <summary>
		/// 	Creates key pair.
		/// 			POST/v2/{tenant_id}/os-keypairs
		/// </summary>
		/// <param name="tenantId">
		/// The tenant Id.
		/// </param>
		/// <param name="request">
		/// 	The request.
		/// </param>
		/// <returns>
		/// 	The new key pair.
		/// </returns>
		Task<KeyPairDetailResponse> CreateKeyPair(string tenantId, KeyPairCreateRequest request);

		/// <summary>
		/// 	Deletes the key pair described by keypairName
		/// 			DELETE/v2/{tenant_id}/os-keypairs/{keypair_name}.
		/// </summary>
		/// <param name="tenantId">
		/// The tenant Id.
		/// </param>
		/// <param name="keypairName">
		/// 	Name of the key pair.
		/// </param>
		/// <returns>
		/// 	A Task.
		/// </returns>
		Task DeleteKeyPair(string tenantId, string keypairName);

		/// <summary>
		/// 	Updates the key pair described by keypairName
		/// 			GET/v2/{tenant_id}/os-keypairs/{keypair_name}.
		/// </summary>
		/// <param name="tenantId">
		/// The tenant Id.
		/// </param>
		/// <param name="keypairName">
		/// 	Name of the key pair.
		/// </param>
		/// <returns>
		/// 	A KeyPairDetailResponse;
		/// </returns>
		Task<KeyPairDetailResponse> GetKeyPair(string tenantId, string keypairName);
	}
}


text:
/**
 */
package org_eclipse_smarthome_schemas_thing_description_v1__0Simplified.tests;

import junit.framework.TestCase;

import junit.textui.TestRunner;

import org_eclipse_smarthome_schemas_thing_description_v1__0Simplified.Tags;
import org_eclipse_smarthome_schemas_thing_description_v1__0Simplified.org_eclipse_smarthome_schemas_thing_description_v1__0SimplifiedFactory;

/**
 *
 * A test case for the model object 'Tags'.
 *
 * @generated
 */
public class TagsTest extends TestCase {

	/**
	 * The fixture for this Tags test case.
	 *
	 *
	 * @generated
	 */
	protected Tags fixture = null;

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(TagsTest.class);
	}

	/**
	 * Constructs a new Tags test case with the given name.
	 *
	 *
	 * @generated
	 */
	public TagsTest(String name) {
		super(name);
	}

	/**
	 * Sets the fixture for this Tags test case.
	 *
	 *
	 * @generated
	 */
	protected void setFixture(Tags fixture) {
		this.fixture = fixture;
	}

	/**
	 * Returns the fixture for this Tags test case.
	 *
	 *
	 * @generated
	 */
	protected Tags getFixture() {
		return fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(org_eclipse_smarthome_schemas_thing_description_v1__0SimplifiedFactory.eINSTANCE.createTags());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

} //TagsTest


text:
var Adapter = require('..').Adapter;
var tests = require('../lib/adapter-tests');

var TestModel = function(props) {
  this.props = props;
};

var TestAdapter = function() {
  this.db = [];
};
TestAdapter.prototype = new Adapter();
TestAdapter.prototype.save = function(doc, Model, cb) {
  this.db.push(doc);
  process.nextTick(function() {
    cb(null, doc);
  });
};
TestAdapter.prototype.destroy = function(doc, Model, cb) {
  var db = this.db;
  var i = db.indexOf(doc);
  if (i != -1) this.db = db.slice(0, i).concat(db.slice(i + 1));
  process.nextTick(cb);
};

describe('test adapter', function() {
  var adapter = new TestAdapter();
  tests(adapter, TestModel, countModels);
  function countModels(cb) {
    process.nextTick(function() {
      cb(null, adapter.db.length);
    });
  }
});


text:
"""Nice small extensions that maybe will it make to Blocks at some point."""
from __future__ import print_function
import subprocess
import pkgutil
import math
import logging
import copy
import re

import theano
from theano import tensor
from theano.gof.graph import io_toposort
from theano.scan_module.scan_op import Scan

from blocks.extensions import TrainingExtension, SimpleExtension,\
    FinishAfter
from blocks.graph import ComputationGraph
from blocks.filter import VariableFilter
from blocks.utils import shared_floatx_zeros
from blocks.select import Selector
from blocks.utils import shared_like

logger = logging.getLogger(__name__)

class CGStatistics(SimpleExtension):

    def __init__(self, **kwargs):
        kwargs.setdefault('before_first_epoch', True)
        kwargs.setdefault('on_resumption', True)
        super(CGStatistics, self).__init__(**kwargs)

    def do(self, *args, **kwargs):
        logger.info("Computation graph statistics:")
        cost_cg = ComputationGraph(self.main_loop.algorithm.cost)
        updates_cg = ComputationGraph(
            [u[1] for u in self.main_loop.algorithm.updates
             if isinstance(u[1], theano.Variable)])
        cost_nodes = io_toposort(cost_cg.inputs, cost_cg.outputs)
        updates_nodes = io_toposort(updates_cg.inputs, updates_cg.outputs)

        cost_scan_nodes = [
            node for node in cost_nodes
            if isinstance(node.op, Scan)]
        updates_scan_nodes = [
            node for node in updates_nodes
            if isinstance(node.op, Scan)]
        final_scan_nodes = [
            node for node in self.main_loop.algorithm._function.maker.fgraph.apply_nodes
            if isinstance(node.op, Scan)]

        logger.info("SCAN NODES IN THE COST GRAPH:")
        for n in cost_scan_nodes:
            logger.info(n.op.name)
        logger.info("SCAN NODES IN THE UPDATES GRAPH:")
        for n in updates_scan_nodes:
            logger.info(n.op.name)
        logger.info("SCAN NODES IN THE FINAL GRAPH:")
        for n in final_scan_nodes:
            logger.info(n.op.name)

class CodeVersion(SimpleExtension):

    def __init__(self, packages, **kwargs):
        self.packages = packages
        kwargs.setdefault('before_training', True)
        super(CodeVersion, self).__init__(**kwargs)

    def do(self, *args, **kwargs):
        package_paths = {name: loader.path
                         for loader, name, _ in pkgutil.iter_modules()
                         # skipping .eggs imported with zipimporter
                         if isinstance(loader, pkgutil.ImpImporter)}
        for package in self.packages:
            path = package_paths[package]
            last_commit_record = "_{}_last_commit".format(package)
            git_diff_record = "_{}_git_diff".format(package)
            self.main_loop.log.status[last_commit_record] = (
                subprocess.check_output("git --no-pager log -1",
                                        cwd=path, shell=True))
            self.main_loop.log.status[git_diff_record] = (
                subprocess.check_output("git diff",
                                        cwd=path, shell=True))

class IPDB(SimpleExtension):

    def do(self, *args, **kwargs):
        import ipdb; ipdb.set_trace()

class AdaptiveClipping(TrainingExtension):

    def __init__(self, gradient_norm, clipping_rule,
                 initial_threshold, burnin_period=100, decay_rate=0.99):
        self.gradient_norm = gradient_norm
        self.clipping_rule = clipping_rule
        self.initial_threshold = initial_threshold
        self.burnin_period = burnin_period
        self.decay_rate = decay_rate

        self.mean_gradient_norm = self.mean_gradient_norm2 = .0
        self._gradient_norm_receiver = shared_like(self.gradient_norm)

    def before_training(self):
        self.main_loop.algorithm.add_updates([
            (self._gradient_norm_receiver, self.gradient_norm)])

    def after_batch(self, batch):
        gradient_norm = math.log(self._gradient_norm_receiver.get_value())
        self.mean_gradient_norm = (self.decay_rate * self.mean_gradient_norm
                                   + (1 - self.decay_rate) * gradient_norm)
        self.mean_gradient_norm2 = (self.decay_rate * self.mean_gradient_norm2
                                    + (1 - self.decay_rate) * gradient_norm ** 2)
        self.std_gradient_norm = (
            (self.mean_gradient_norm2 - self.mean_gradient_norm ** 2) ** .5)
        threshold = math.exp(self.mean_gradient_norm + 1 * self.std_gradient_norm)
        confidence = (min(
            self.burnin_period, self.main_loop.status['iterations_done']) /
            float(self.burnin_period))
        threshold = (confidence * threshold +
                     (1 - confidence) * self.initial_threshold)
        threshold = min(threshold, 5 * self.initial_threshold)
        self.clipping_rule.threshold.set_value(threshold)

class GeneratePredictions(SimpleExtension):

    def __init__(self, extra_generation_steps,
                 compute_targets, compute_policy,
                 force_generate_groundtruth,
                 catching_up_coof, catching_up_freq,
                **kwargs):
        self.extra_generation_steps = extra_generation_steps
        self.compute_targets = compute_targets
        self.compute_policy = compute_policy
        self.force_generate_groundtruth = force_generate_groundtruth
        self.catching_up_coof = catching_up_coof
        self.catching_up_freq = catching_up_freq
        kwargs.setdefault('before_training', True)
        kwargs.setdefault('before_batch', True)
        kwargs.setdefault('after_batch', True)
        super(GeneratePredictions, self).__init__(**kwargs)

    def do(self, which_callback, *args):
        if which_callback == 'before_training':
            logger.info("Compiling prediction generator...")
            recognizer, = self.main_loop.model.get_top_bricks()
            self.trained_recognizer = recognizer
            self.recognizer = copy.deepcopy(recognizer)

            # A bit of defensive programming, because why not :)
            assert self.recognizer.generator.readout.compute_targets
            assert self.recognizer.generator.readout.trpo_coef == 0.0
            assert self.recognizer.generator.readout.solve_bellman
            assert self.recognizer.generator.readout.epsilon == 0.0

            groundtruth = self.recognizer.labels
            groundtruth_mask = self.recognizer.labels_mask
            generated = self.recognizer.get_generate_graph(
                n_steps=self.recognizer.labels.shape[0]
                    + self.extra_generation_steps,
                return_initial_states=True,
                use_softmax_t=True)
            generation_method = self.recognizer.generator.generate

            if not self.force_generate_groundtruth:
                prediction = generated.pop('samples')
                prediction_mask = self.recognizer.mask_for_prediction(
                    prediction, groundtruth_mask, self.extra_generation_steps)
            else:
                prediction = groundtruth.copy()
                prediction_mask = groundtruth_mask.copy()
            prediction.name = 'predicted_labels'
            prediction_mask.name = 'predicted_mask'

            cg = ComputationGraph(generated.values())
            attended, = VariableFilter(
                applications=[generation_method], name='attended')(cg)
            attended_mask, = VariableFilter(
                applications=[generation_method], name='attended_mask')(cg)
            generated = {key: value[:-1] for key, value in generated.items()}
            costs = self.recognizer.generator.readout.costs(
                prediction=prediction, prediction_mask=prediction_mask,
                groundtruth=groundtruth, groundtruth_mask=groundtruth_mask,
                attended=attended, attended_mask=attended_mask,
                **generated)
            cost_cg = ComputationGraph(costs)
            value_targets, = VariableFilter(name='value_targets')(cost_cg)
            value_targets.name = 'value_targets'
            probs, = VariableFilter(name='probs')(cost_cg)
            probs.name = 'probs'
            rewards, = VariableFilter(name='rewards')(cost_cg)

            variables_to_compute = [prediction, prediction_mask]
            if self.compute_targets:
                logger.debug("Also compute the targets")
                variables_to_compute += [value_targets]
            if self.compute_policy:
                variables_to_compute += [probs]
            self.extended_cg = ComputationGraph(variables_to_compute)
            self._generate = self.extended_cg.get_theano_function()
            logger.info("Prediction generator compiled")

            params = Selector(self.recognizer).get_parameters()
            trained_params = Selector(self.trained_recognizer).get_parameters()
            if self.catching_up_freq:
                def get_coof(name):
                    if isinstance(self.catching_up_coof, float):
                        return self.catching_up_coof
                    elif isinstance(self.catching_up_coof, list):
                        result = None
                        for pattern, coof in self.catching_up_coof:
                            if re.match(pattern, name):
                                result = coof
                        return result
                    else:
                        raise ValueError
                updates = []
                for name in params:
                    coof = get_coof(name)
                    logging.debug("Catching up coefficient for {} is {}".format(
                        name, coof))
                    updates.append((params[name], params[name] * (1 - coof)
                                                  + trained_params[name] * coof))
                # This is needed when parameters are shared between brick
                # and occur more than once in the list of updates.
                updates = dict(updates).items()
                self._catch_up = theano.function([], [], updates=updates)
        elif which_callback == 'before_batch':
            batch, = args
            generated = self._generate(
                *[batch[variable.name] for variable in self.extended_cg.inputs])
            for variable, value in zip(self.extended_cg.outputs, generated):
                batch[variable.name] = value
        elif which_callback == 'after_batch':
            if (self.catching_up_freq
                    and self.main_loop.status['iterations_done'] % self.catching_up_freq == 0):
                self._catch_up()
        else:
            raise ValueError("can't be called on " + which_callback)

class Patience(FinishAfter):
    """Stop after improvements have ceased for a given period.

    Parameters
    ----------
    notification_names : list of str
        The names of the log record to look for which indicate that a new
        best performer has been found.  Note that the value of this
        record is not inspected.
    min_iterations : int, optional
        The minimum number of iterations to perform. Exactly one of
        `iterations` or `epochs` must be not `None` (default).
    min_epochs : int, optional
        The minimum number of epochs to perform. Exactly one of
        `iterations` or `epochs` must be not `None` (default).
    patience_factor : float
        The factor by which to expand the number of iterations to do after
        after an improvement.
    patience_log_record : str, optional
        The name under which to record the number of iterations we
        are currently willing to wait for a new best performer.
        Defaults to `notification_name + '_patience_epochs'` or
        `notification_name + '_patience_iterations'`, depending
        which measure is being used.

    Notes
    -----
    By default, runs after each epoch. This can be manipulated via
    keyword arguments (see :class:`blocks.extensions.SimpleExtension`).

    """
    def __init__(self, notification_names, min_iterations=None,
                 min_epochs=None, patience_factor=1.5,
                 patience_log_record=None, **kwargs):
        if (min_epochs is None) == (min_iterations is None):
            raise ValueError("Need exactly one of epochs or iterations "
                             "to be specified")
        self.notification_names = notification_names
        self.min_iterations = min_iterations
        self.min_epochs = min_epochs
        self.patience_factor = patience_factor
        kwargs.setdefault('after_epoch', True)
        kwargs.setdefault('before_first_epoch', True)
        self.last_best_iter = self.last_best_epoch = 0
        if patience_log_record is None:
            self.patience_log_record = ('patience' +
                                        ('_epochs' if self.min_epochs is not None
                                         else '_iterations'))
        else:
            self.patience_log_record = patience_log_record
        super(Patience, self).__init__(**kwargs)

    def update_best(self):
        # Here mainly so we can easily subclass different criteria.
        matched = False
        for not_name in self.notification_names:
            if not_name in self.main_loop.log.current_row:
                matched = True
                break

        if matched:
            self.last_best_iter = self.main_loop.log.status['iterations_done']
            self.last_best_epoch = self.main_loop.log.status['epochs_done']

    def do(self, which_callback, *args):
        self.update_best()
        if self.min_epochs is not None:
            to_do = max(self.min_epochs,
                        int(self.patience_factor * self.last_best_epoch+0.5))
            self.main_loop.log.status[self.patience_log_record] = to_do
            if to_do <= self.main_loop.log.status['epochs_done']:
                super(Patience, self).do(which_callback, *args)
        else:
            to_do = max(self.min_iterations,
                        int(self.patience_factor * self.last_best_iter+0.5))
            self.main_loop.log.status[self.patience_log_record] = to_do
            if to_do <= self.main_loop.log.status['iterations_done']:
                super(Patience, self).do(which_callback, *args)


text:
{-# LANGUAGE MagicHash                 #-}
{-# LANGUAGE UnboxedTuples             #-}
{-# LANGUAGE ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  GHC.StaticPtr
-- Copyright   :  (C) 2014 I/O Tweag
-- License     :  see libraries/base/LICENSE
--
-- Maintainer  :  cvs-ghc@haskell.org
-- Stability   :  internal
-- Portability :  non-portable (GHC Extensions)
--
-- Symbolic references to values.
--
-- References to values are usually implemented with memory addresses, and this
-- is practical when communicating values between the different pieces of a
-- single process.
--
-- When values are communicated across different processes running in possibly
-- different machines, though, addresses are no longer useful since each
-- process may use different addresses to store a given value.
--
-- To solve such concern, the references provided by this module offer a key
-- that can be used to locate the values on each process. Each process maintains
-- a global table of references which can be looked up with a given key. This
-- table is known as the Static Pointer Table. The reference can then be
-- dereferenced to obtain the value.
--
-----------------------------------------------------------------------------

module GHC.StaticPtr
  ( StaticPtr
  , deRefStaticPtr
  , StaticKey
  , staticKey
  , unsafeLookupStaticPtr
  , StaticPtrInfo(..)
  , staticPtrInfo
  , staticPtrKeys
  ) where

import Foreign.C.Types     (CInt(..))
import Foreign.Marshal     (allocaArray, peekArray, withArray)
import Foreign.Ptr         (castPtr)
import GHC.Exts            (addrToAny#)
import GHC.Ptr             (Ptr(..), nullPtr)
import GHC.Fingerprint     (Fingerprint(..))

-- | A reference to a value of type 'a'.
data StaticPtr a = StaticPtr StaticKey StaticPtrInfo a

-- | Dereferences a static pointer.
deRefStaticPtr :: StaticPtr a -> a
deRefStaticPtr (StaticPtr _ _ v) = v

-- | A key for `StaticPtrs` that can be serialized and used with
-- 'unsafeLookupStaticPtr'.
type StaticKey = Fingerprint

-- | The 'StaticKey' that can be used to look up the given 'StaticPtr'.
staticKey :: StaticPtr a -> StaticKey
staticKey (StaticPtr k _ _) = k

-- | Looks up a 'StaticPtr' by its 'StaticKey'.
--
-- If the 'StaticPtr' is not found returns @Nothing@.
--
-- This function is unsafe because the program behavior is undefined if the type
-- of the returned 'StaticPtr' does not match the expected one.
--
unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a))
unsafeLookupStaticPtr (Fingerprint w1 w2) = do
    ptr@(Ptr addr) <- withArray [w1,w2] (hs_spt_lookup . castPtr)
    if (ptr == nullPtr)
    then return Nothing
    else case addrToAny# addr of
           (# spe #) -> return (Just spe)

foreign import ccall unsafe hs_spt_lookup :: Ptr () -> IO (Ptr a)

-- | Miscelaneous information available for debugging purposes.
data StaticPtrInfo = StaticPtrInfo
    { -- | Package key of the package where the static pointer is defined
      spInfoPackageKey  :: String
      -- | Name of the module where the static pointer is defined
    , spInfoModuleName :: String
      -- | An internal name that is distinct for every static pointer defined in
      -- a given module.
    , spInfoName       :: String
      -- | Source location of the definition of the static pointer as a
      -- @(Line, Column)@ pair.
    , spInfoSrcLoc     :: (Int, Int)
    }
  deriving (Show)

-- | 'StaticPtrInfo' of the given 'StaticPtr'.
staticPtrInfo :: StaticPtr a -> StaticPtrInfo
staticPtrInfo (StaticPtr _ n _) = n

-- | A list of all known keys.
staticPtrKeys :: IO [StaticKey]
staticPtrKeys = do
    keyCount <- hs_spt_key_count
    allocaArray (fromIntegral keyCount) $ \p -> do
      count <- hs_spt_keys p keyCount
      peekArray (fromIntegral count) p >>=
        mapM (\pa -> peekArray 2 pa >>= \[w1, w2] -> return $ Fingerprint w1 w2)
{-# NOINLINE staticPtrKeys #-}

foreign import ccall unsafe hs_spt_key_count :: IO CInt

foreign import ccall unsafe hs_spt_keys :: Ptr a -> CInt -> IO CInt


text:
package com.marasm.cm_romhelper.activities;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.marasm.cm_romhelper.fragments.AbstractFragmentWithCallback;
import com.marasm.cm_romhelper.fragments.HomeFragment;
import com.marasm.cm_romhelper.fragments.LedNotificationsFragment;
import com.marasm.cm_romhelper.fragments.WallpaperFragment;
import com.marasm.cm_romhelper.R;

public class HomePage extends AppCompatActivity implements HomeFragment.OnHomeFragmentActionListener,
        WallpaperFragment.OnWallpaperFragmentActionListener, LedNotificationsFragment.OnLedNotificationAcionListener
{

  private boolean rootAvailable = false;
  private DrawerLayout drawerLayout;
  private Toolbar toolbar;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null)
    {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setHomeButtonEnabled(true);
      actionBar.setHomeAsUpIndicator(R.drawable.ic_action_menu);
    }

    drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
    // Setup drawer view
    setupDrawerContent(navView);

    MenuItem homeMI = navView.getMenu().getItem(0);
    selectDrawerItem(homeMI);

    Log.d(this.getClass().getName(), "Root is available=" + rootAvailable);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the HomeFragment/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    switch (item.getItemId()) {
      case android.R.id.home:
        drawerLayout.openDrawer(GravityCompat.START);
        return true;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override
  protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
  }

  private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
              @Override
              public boolean onNavigationItemSelected(MenuItem menuItem) {
                selectDrawerItem(menuItem);
                return true;
              }
            });
  }

  public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    AbstractFragmentWithCallback fragment = null;
    Class fragmentClass;
    switch(menuItem.getItemId()) {
      case R.id.nav_home_fragment:
        fragmentClass = HomeFragment.class;
        break;
      case R.id.nav_wallppr_fragment:
        fragmentClass = WallpaperFragment.class;
        break;
      case R.id.led_notifications_fragment:
        fragmentClass = LedNotificationsFragment.class;
        break;
      default:
        fragmentClass = HomeFragment.class;
    }

    try {
      fragment = (AbstractFragmentWithCallback) fragmentClass.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    //Check if the fragment needs root
    if(!fragment.getNeedsRoot() || (fragment.getNeedsRoot() && rootAvailable))
    {
      // Insert the fragment by replacing any existing fragment
      FragmentManager fragmentManager = getSupportFragmentManager();
      fragmentManager.beginTransaction().replace(R.id.fragment_content, fragment).commit();

      // Highlight the selected item has been done by NavigationView
      menuItem.setChecked(true);
      // Set action bar title
      setTitle(menuItem.getTitle());
      // Close the navigation drawer
      drawerLayout.closeDrawers();
    }
    else
    {
      Toast.makeText(this, menuItem.getTitle() + getString(R.string.toast_mi_needs_root), Toast.LENGTH_SHORT).show();
    }

  }

  @Override
  public void onRootCheckComplete(boolean inRootAvailable)
  {
    rootAvailable = inRootAvailable;
  }

  @Override
  public void onWallpaperFragmentAction()
  {
    //nothing so far
  }

  @Override
  public void onLedNotificationFragmentAction(Uri uri)
  {
    //nothing so far

  }
}


text:
package samples.powermockito.junit4.agent;

import org.junit.Rule;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases;
import samples.privatemocking.PrivateMethodDemo;

@PrepareForTest( { PrivateMethodDemo.class })
public class PrivateInstanceMockingTest extends PrivateInstanceMockingCases {
    @Rule
    public PowerMockRule powerMockRule = new PowerMockRule();
}


text:
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const OptimizeJsPlugin = require('optimize-js-plugin')
const WebpackMd5Hash = require('webpack-md5-hash')
const webpack = require('webpack')
const config = require('c0nfig')
const chalk = require('chalk')
const path = require('path')

///////////////////////////////////////////////////////////
// Silence deprecation warnings
// (caused by deprecated API used by webpack loaders)
//
///////////////////////////////////////////////////////////
//process.traceDeprecation = true
process.noDeprecation = true

///////////////////////////////////////////////////////////
// Webpack config production
//
///////////////////////////////////////////////////////////
module.exports = {

  // no dev tool, we are in Prod!
  devtool: false,

  // it's good to specify context
  context: path.join(__dirname, '..'),

  entry: {
    bundle: [
      path.resolve('./src/client/index.js')
    ]
  },

  // output arguments
  // it will append the [chunkhash] to each chunck
  // in order to perform long-term caching:
  // https://webpack.js.org/guides/caching/#components/sidebar/sidebar.jsx
  output: {
    path: path.resolve(__dirname, '../dist'),
    chunkFilename: "[name].[chunkhash].min.js",
    filename: "[name].[chunkhash].min.js",
    publicPath: '/'
  },

  // settings that control webpack compiler stats when building the app
  // see description for each setting below
  // straight from the doc:
  // https://webpack.js.org/configuration/stats/#components/sidebar/sidebar.jsx
  stats: {
    // Add asset Information
    assets: true,
    // Sort assets by a field
    assetsSort: "field",
    // Add information about cached (not built) modules
    cached: true,
    // Add children information
    children: true,
    // Add chunk information (setting this to `false` allows for a less verbose output)
    chunks: false,
    // Add built modules information to chunk information
    chunkModules: true,
    // Add the origins of chunks and chunk merging info
    chunkOrigins: false,
    // Sort the chunks by a field
    chunksSort: "field",
    // Context directory for request shortening
    context: path.resolve("../src/"),
    // `webpack --colors` equivalent
    colors: true,
    // Add errors
    errors: true,
    // Add details to errors (like resolving log)
    errorDetails: true,
    // Add the hash of the compilation
    hash: false,
    // Add built modules information
    modules: false,
    // Sort the modules by a field
    modulesSort: "field",
    // Add public path information
    publicPath: false,
    // Add information about the reasons why modules are included
    reasons: false,
    // Add the source code of modules
    source: false,
    // Add timing information
    timings: true,
    // Add webpack version information
    version: true,
    // Add warnings
    warnings: false
  },

  // webpack pluging: perform code splitting, optiomization
  // and html generation template from .ejs template
  plugins: [

    // default options
    new webpack.LoaderOptionsPlugin({
      minify: true,
      debug: false
    }),

    // enabled by default
    new webpack.optimize.OccurrenceOrderPlugin(),

    // generates chucks from all bundles
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
      minChunks: Infinity
    }),

    // MD5 hash, see long-term caching for more details
    // https://webpack.js.org/guides/caching/#components/sidebar/sidebar.jsx
    new WebpackMd5Hash(),

    // generate webpack file manifest on disk
    new ManifestPlugin(),

    // this will automatically embbed the chunck manifest in
    // generated html output from HtmlWebpackPlugin
    new InlineManifestWebpackPlugin({
      name: 'webpackManifest'
    }),

    // mangle and compress generated code
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        conditionals: true,
        comparisons:  true,
        screw_ie8:    true,
        sequences:    true,
        dead_code:    true,
        if_return:    true,
        join_vars:    true,
        warnings:     false,
        evaluate:     false,
        unused:       true
      },
      output: {
        comments: false
      }
    }),

    // provides some globals
    new webpack.ProvidePlugin({
      'window.jQuery': 'jquery',
      jQuery: 'jquery',
      _: 'lodash',
      $: 'jquery'
    }),

    new OptimizeJsPlugin({
      sourceMap: false
    }),

    // define env variables during the build
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        WEBPACK: true
      }
    }),

    // outputs html from .ejs template
    new HtmlWebpackPlugin({

      viewer3D: config.forge.viewer.viewer3D,
      threeJS: config.forge.viewer.threeJS,
      style: config.forge.viewer.style,

      template: path.resolve(__dirname, '../src/client/layouts/index.ejs'),
      title: 'Forge | DM',
      filename: 'index.html',
      bundle: 'bundle.min.js',
      minify: {
        removeStyleLinkTypeAttributes: true,
        removeAttributeQuotes: true,
        collapseWhitespace: true,
        removeComments: true,
        minifyCSS: true
      },
      inject: 'head'
    }),

    // just a progress bar to make compilation less boring
    new ProgressBarPlugin({
      format: '  build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)',
      clear: false
    })
  ],

  // directories used by webpack to resolve dependencies
  resolve: {
    modules: [
      path.resolve('./src/client/Viewer/Viewing.Extensions'),
      path.resolve('./src/client/components'),
      path.resolve('./src/client/services'),
      path.resolve('./src/client/Viewer'),
      path.resolve('./src/client/styles'),
      path.resolve('./src/client/utils'),
      path.resolve('./node_modules'),
      path.resolve('./src/client')
    ],
    extensions : ['.js', '.jsx', '.json']
  },

  resolveLoader: {
    modules: ['node_modules']
  },

  // compilation rules: i.e. loaders
  module: {

    rules: [

      // all .js and .jsx code from the project goes through babel transpiler
      // also enable stage-0 features for async/await support
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            plugins: ['transform-runtime'],
            presets: ['env']
          }
        }]
      },

      // plain .css
      {
        test: /\.css$/,
        use: [{
          loader: 'style-loader'
        }, {
          loader: 'css-loader'
        }, {
          loader: 'postcss-loader',
          options: {
            plugins: function () {
              return [
                require('precss'),
                require('autoprefixer')
              ]
            }
          }
        }]
      },

      //.sass and .scss
      {
        test: /\.(sass|scss)$/,
        use: [{
          loader:'style-loader'
        },  {
          loader: 'css-loader'
        }, {
          loader: 'postcss-loader',
          options: {
            plugins: function () {
              return [
                require('precss'),
                require('autoprefixer')
              ]
            }
          }
        }, {
          loader:'sass-loader'
        }]
      },

      // bootstrap and font-awesome resources
      { test: /\.ttf(\?.*)?$/,   loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
      { test: /\.woff2(\?.*)?$/, loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
      { test: /\.woff(\?.*)?$/,  loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
      { test: /\.otf(\?.*)?$/,   loader: 'file-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
      { test: /\.svg(\?.*)?$/,   loader: 'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
      { test: /\.eot(\?.*)?$/,   loader: 'file-loader?prefix=fonts/&name=[path][name].[ext]' },
      { test: /\.(png|jpg)$/,    loader: 'url-loader?limit=8192' }
    ]
  }
}


text:
package org.grobid.trainer.sax;

import org.grobid.core.utilities.TextUtilities;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * SAX parser for author sequences encoded in the TEI format data.
 * Segmentation of tokens must be identical as the one from pdf2xml files to that
 * training and online input tokens are identical.
 *
 * @author Patrice Lopez
 */
public class TEIAuthorSaxParser extends DefaultHandler {

    private StringBuffer accumulator = new StringBuffer(); // Accumulate parsed text

    private String output = null;
    private String currentTag = null;

    private ArrayList<String> labeled = null; // store line by line the labeled data

    private String title = null;
    private String affiliation = null;
    private String address = null;
    private String note = null;
    private String keywords = null;

    public int n = 0;

    public TEIAuthorSaxParser() {
        labeled = new ArrayList<String>();
    }

    public void characters(char[] buffer, int start, int length) {
        accumulator.append(buffer, start, length);
    }

    public String getText() {
        return accumulator.toString().trim();
    }

    public ArrayList<String> getLabeledResult() {
        return labeled;
    }

    public void endElement(java.lang.String uri,
                           java.lang.String localName,
                           java.lang.String qName) throws SAXException {
        if ((
                (qName.equals("forename")) | (qName.equals("middlename")) | (qName.equals("title")) |
                        (qName.equals("suffix")) |
                        (qName.equals("surname")) | (qName.equals("lastname")) | (qName.equals("marker")) |
                        (qName.equals("roleName"))
        ) & (currentTag != null)) {
            String text = getText();
            writeField(text);
        } else if (qName.equals("lb")) {
            // we note a line break
            accumulator.append(" +L+ ");
        } else if (qName.equals("pb")) {
            accumulator.append(" +PAGE+ ");
        } else if (qName.equals("author")) {
            String text = getText();
            if (text.length() > 0) {
                currentTag = "<other>";
                writeField(text);
            }
            labeled.add("\n \n");
            n++;
        }
        accumulator.setLength(0);
    }

    public void startElement(String namespaceURI,
                             String localName,
                             String qName,
                             Attributes atts)
            throws SAXException {

        String text = getText();
        if (text.length() > 0) {
            currentTag = "<other>";
            writeField(text);
        }
        accumulator.setLength(0);

        if (qName.equals("title") | qName.equals("roleName")) {
            currentTag = "<title>";
        } else if (qName.equals("marker")) {
            currentTag = "<marker>";
        } else if ((qName.equals("surname")) | (qName.equals("lastname"))) {
            currentTag = "<surname>";
        } else if (qName.equals("middlename")) {
            currentTag = "<middlename>";
        } else if (qName.equals("forename")) {
            currentTag = "<forename>";
        } else if (qName.equals("suffix")) {
            currentTag = "<suffix>";
        }
        /*else if (qName.equals("author")) {
              int length = atts.getLength();

              // Process each attribute
              for (int i=0; i<length; i++) {
                  // Get names and values for each attribute
                  String name = atts.getQName(i);
                  String value = atts.getValue(i);

                  if (name != null) {
                      if (name.equals("file")) {
                             System.out.println(value);
                         }
                  }
              }

          }*/
    }

    private void writeField(String text) {
        // we segment the text
        //StringTokenizer st = new StringTokenizer(text, " \n\t");
        List<String> tokens = TextUtilities.segment(text, TextUtilities.punctuations);

        boolean begin = true;
        //while(st.hasMoreTokens()) {
        for (String tok : tokens) {
            //String tok = st.nextToken().trim();
            tok = tok.trim();
            if (tok.length() == 0) continue;
            boolean punct1 = false;

            if (tok.equals("+L+")) {
                labeled.add("@newline\n");
            } else if (tok.equals("+PAGE+")) {
                // page break not relevant for authors
                labeled.add("@newline\n");
            } else {
                String content = tok;
                int i = 0;
                for (; i < TextUtilities.punctuations.length(); i++) {
                    if (tok.length() > 0) {
                        if (tok.charAt(tok.length() - 1) == TextUtilities.punctuations.charAt(i)) {
                            punct1 = true;
                            content = tok.substring(0, tok.length() - 1);
                            break;
                        }
                    }
                }
                if (tok.length() > 0) {
                    if ((tok.startsWith("(")) & (tok.length() > 1)) {
                        if (punct1)
                            content = tok.substring(1, tok.length() - 1);
                        else
                            content = tok.substring(1, tok.length());
                        if (begin) {
                            labeled.add("(" + " I-" + currentTag + "\n");
                            begin = false;
                        } else {
                            labeled.add("(" + " " + currentTag + "\n");
                        }
                    } else if ((tok.startsWith("[")) & (tok.length() > 1)) {
                        if (punct1)
                            content = tok.substring(1, tok.length() - 1);
                        else
                            content = tok.substring(1, tok.length());
                        if (begin) {
                            labeled.add("[" + " I-" + currentTag + "\n");
                            begin = false;
                        } else {
                            labeled.add("[" + " " + currentTag + "\n");
                        }
                    } else if ((tok.startsWith("\"")) & (tok.length() > 1)) {
                        if (punct1)
                            content = tok.substring(1, tok.length() - 1);
                        else
                            content = tok.substring(1, tok.length());
                        if (begin) {
                            labeled.add("\"" + " I-" + currentTag + "\n");
                            begin = false;
                        } else {
                            labeled.add("\"" + " " + currentTag + "\n");
                        }
                    }
                }

                if (content.length() > 0) {
                    if (begin) {
                        labeled.add(content + " I-" + currentTag + "\n");
                        begin = false;
                    } else {
                        labeled.add(content + " " + currentTag + "\n");
                    }
                }

                if (punct1) {
                    if (begin) {
                        labeled.add(tok.charAt(tok.length() - 1) + " I-" + currentTag + "\n");
                        begin = false;
                    } else {
                        labeled.add(tok.charAt(tok.length() - 1) + " " + currentTag + "\n");
                    }
                }
            }

            begin = false;
        }
    }

}


text:
package com.emc.documentum.rest.client.sample.cases;

import com.emc.documentum.rest.client.sample.client.DCTMRestClient;
import com.emc.documentum.rest.client.sample.client.DCTMRestClientBuilder;
import com.emc.documentum.rest.client.sample.client.annotation.RestServiceSample;
import com.emc.documentum.rest.client.sample.model.Feed;
import com.emc.documentum.rest.client.sample.model.FutureModel;
import com.emc.documentum.rest.client.sample.model.RestObject;
import com.emc.documentum.rest.client.sample.model.RestType;
import com.emc.documentum.rest.client.sample.model.SearchFeed;
import com.emc.documentum.rest.client.sample.model.batch.Capabilities;

import static com.emc.documentum.rest.client.sample.client.util.Debug.printStep;

@RestServiceSample("Simple async client")
public class SimpleAsyncClientSample extends Sample {
    @SuppressWarnings("unused")
    public void asyncCall() {
        printStep("build up async client based on the sync client");
        DCTMRestClient asyncClinet = DCTMRestClientBuilder.buildAsyncClient(client);

        printStep("execute operations of DCTMRestClient like a normal sync clinet");
        Feed<RestObject> groups = asyncClinet.getGroups();

        printStep("continue executing other operations without blocking");
        Feed<RestObject> cabinets = asyncClinet.getCabinets();
        Capabilities capabilities = asyncClinet.getBatchCapabilities();
        RestObject currentUser = asyncClinet.getCurrentUser();
        Feed<RestObject> users = asyncClinet.getUsers();

        printStep("use the result as the normal DCTMRestClient response, but the operations on the result will be blocked until the async execution finished");
        System.out.println("there are " + groups.getEntries().size() + " gruops");

        printStep("cast the response to the FutureModel, if wants to know more information");
        if(users instanceof FutureModel) {
            FutureModel futureUsers = (FutureModel)users;

            printStep("check whether the execution finished");
            while(true) {
                boolean ready = futureUsers.isModelReady();
                System.out.println("isModelReady: " + ready);
                if(ready) {
                    break;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
            }

            printStep("or get the async call status and headers");
            System.out.println(futureUsers.getStatus());
            System.out.println(futureUsers.getHeaders());
        }

        printStep("get the status and headers from the async client, will only return the latest operation's info, here is getUsers");
        System.out.println(asyncClinet.getStatus());
        System.out.println(asyncClinet.getHeaders());
    }

    public void compareWithSync() {
        printStep("warm up");
        Feed<RestObject> cabinets = client.getCabinets();
        Feed<RestObject> users = client.getUsers();
        Feed<RestType> types = client.getTypes();
        Feed<RestObject> formats = client.getFormats();
        SearchFeed<RestObject> searches = client.search("test");

        printStep("execute some requests syncly");
        long start = System.currentTimeMillis();
        cabinets = client.getCabinets();
        users = client.getUsers();
        types = client.getTypes();
        formats = client.getFormats();
        searches = client.search("test");
        long end = System.currentTimeMillis();
        System.out.println("sync execution costs " + (end - start) + " milliseconds");
        System.out.println("cabinets: " + cabinets.getEntries().size() +
                           ", users: " + users.getEntries().size() +
                           ", types: " + types.getEntries().size() +
                           ", formats: " + formats.getEntries().size() +
                           ", searches: " + searches.getEntries().size());

        printStep("execute some requests asyncly");
        DCTMRestClient asyncClinet = DCTMRestClientBuilder.buildAsyncClient(client);
        start = System.currentTimeMillis();
        cabinets = asyncClinet.getCabinets();
        users = asyncClinet.getUsers();
        types = asyncClinet.getTypes();
        formats = asyncClinet.getFormats();
        searches = asyncClinet.search("test");
        end = System.currentTimeMillis();
        System.out.println("async execution costs " + (end - start) + " milliseconds");
        System.out.println("cabinets: " + cabinets.getEntries().size() +
                ", users: " + users.getEntries().size() +
                ", types: " + types.getEntries().size() +
                ", formats: " + formats.getEntries().size() +
                ", searches: " + searches.getEntries().size());
    }
}


text:
static NSString *identifier = @"cellID";

@interface XKCalendarView ()<UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *monthArray;

@property (nonatomic, strong) NSArray *weekdayArray;

@property (nonatomic, strong) NSDictionary *dayDict;

@end

@implementation XKCalendarView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self initUserInterface];
    }
    return self;
}

- (void)initUserInterface {

    [self addSubview:self.collectionView];

    [self setNeedsUpdateConstraints];
}

- (void)updateConstraints {

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self).offset(0);

        make.right.equalTo(self).offset(0);

        make.top.equalTo(self).offset(0);

        make.bottom.equalTo(self).offset(0);

    }];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];

        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];

    });

    [super updateConstraints];
}

#pragma mark -- delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return 3;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    XKCalendarViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    cell.dateDict = self.dayDict;

    return cell;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {

    CGPoint translation = [self.collectionView.panGestureRecognizer translationInView:self.collectionView];

    if (translation.x > self.collectionView.bounds.size.width / 2 || translation.x < - self.collectionView.bounds.size.width / 2) {

        if (translation.x > self.collectionView.bounds.size.width / 2) {

            self.dayDict = [NSDate getDayDicAfterDays:-1 fromDate:self.dayDict[MYDIARYDATE]];

        } else {

            self.dayDict = [NSDate getDayDicAfterDays:1 fromDate:self.dayDict[MYDIARYDATE]];
        }

        [self.collectionView reloadData];
    }

    if (self.delegate && [self.delegate respondsToSelector:@selector(calendarViewscrollToFrontOrLater:)]) {

        [self.delegate calendarViewscrollToFrontOrLater:self.dayDict];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width;

    if (offset == 0 || offset == 2) {

        if (offset == 0) {

            offset = 2;

        } else {

            offset = 1;
        }
        scrollView.contentOffset = CGPointMake(offset * scrollView.bounds.size.width, 0);
    }
}

- (void)calenderOfToday {

    self.dayDict = nil;

    [self.collectionView reloadData];
}

- (UICollectionView *)collectionView {

    if (!_collectionView) {

        AnimatedCollectionViewLayout *layout = [[AnimatedCollectionViewLayout alloc] initWithAnimationType:NSClassFromString(@"RotateInOutAttributesAnimator")];

        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

        layout.minimumLineSpacing = 0;

        layout.minimumInteritemSpacing = 0;

        layout.itemSize = CGSizeMake(self.frame.size.width, self.frame.size.height);

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];

        _collectionView.dataSource = self;

        _collectionView.delegate = self;

        _collectionView.pagingEnabled = YES;

        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.showsHorizontalScrollIndicator = NO;

        _collectionView.backgroundColor = [UIColor clearColor];

        [_collectionView registerClass:[XKCalendarViewCell class] forCellWithReuseIdentifier:identifier];

    }
    return _collectionView;
}

- (NSArray *)monthArray {

    if (!_monthArray) {
        _monthArray = @[@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月",@"8月",@"9月",@"10月",@"11月",@"12月"];
    }
    return _monthArray;
}

- (NSArray *)weekdayArray {

    if (!_weekdayArray) {
        _weekdayArray = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
    }
    return _weekdayArray;
}

- (NSDictionary *)dayDict {

    if (!_dayDict) {

        _dayDict = @{}.mutableCopy;

        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

        NSArray *monthArray = self.monthArray;

        NSArray *weekdayArray = self.weekdayArray;

        NSDateComponents *addingDateComponents = [[NSDateComponents alloc] init];

        [addingDateComponents setDay:0];

        NSDate *date = [calendar dateByAddingComponents:addingDateComponents toDate:[NSDate date] options:0];

        NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:date];

        _dayDict = @{MYDIARYYEAR:[NSString stringWithFormat:@"%ld年", (long)components.year],
                     MYDIARYMONTH:monthArray[components.month - 1],
                     MYDIARYDAY:[NSString stringWithFormat:@"%ld", (long)components.day],
                     MYDIARYWEEK:weekdayArray[components.weekday - 1],
                     MYDIARYDATE:date};
    }
    return _dayDict;
}

@end