text:
<?php

/**
 * processing the uploaded files
 * @author Logan Cai (cailongqun [at] yahoo [dot] com [dot] cn)
 * @link www.phpletter.com
 * @since 22/May/2007
 *
 */
sleep(3);
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "inc" . DIRECTORY_SEPARATOR . "config.php");
echo "{";
$error = "";
$info = "";

include_once(CLASS_UPLOAD);
$upload = new Upload();

$upload->setInvalidFileExt(explode(",", CONFIG_UPLOAD_INVALID_EXTS));
if (CONFIG_SYS_VIEW_ONLY || !CONFIG_OPTIONS_UPLOAD) {
    $error = SYS_DISABLED;
} elseif (empty($_GET['folder']) || !isUnderRoot($_GET['folder'])) {
    $error = ERR_FOLDER_PATH_NOT_ALLOWED;
} else if (!$upload->isFileUploaded('file')) {
    $error = ERR_FILE_NOT_UPLOADED;
} else if (!$upload->moveUploadedFile($_GET['folder'])) {
    $error = ERR_FILE_MOVE_FAILED;
} elseif (!$upload->isPermittedFileExt(explode(",", CONFIG_UPLOAD_VALID_EXTS))) {
    $error = ERR_FILE_TYPE_NOT_ALLOWED;
} elseif (defined('CONFIG_UPLOAD_MAXSIZE') && CONFIG_UPLOAD_MAXSIZE && $upload->isSizeTooBig(CONFIG_UPLOAD_MAXSIZE)) {
    $error = sprintf(ERROR_FILE_TOO_BID, transformFileSize(CONFIG_UPLOAD_MAXSIZE));
} else {
    include_once(CLASS_FILE);
    $path = $upload->getFilePath();
    $obj = new file($path);
    $tem = $obj->getFileInfo();
    if (sizeof($tem)) {
        include_once(CLASS_MANAGER);

        $manager = new manager($upload->getFilePath(), false);

        $fileType = $manager->getFileType($upload->getFileName());

        foreach ($fileType as $k => $v) {
            $tem[$k] = $v;
        }

        $tem['path'] = backslashToSlash($path);
        $tem['type'] = "file";
        $tem['size'] = transformFileSize($tem['size']);
        $tem['ctime'] = date(DATE_TIME_FORMAT, $tem['ctime']);
        $tem['mtime'] = date(DATE_TIME_FORMAT, $tem['mtime']);
        $tem['short_name'] = shortenFileName($tem['name']);
        $tem['flag'] = 'noFlag';
        $obj->close();
        foreach ($tem as $k => $v) {
            $info .= sprintf(", %s:'%s'", $k, $v);
        }

        $info .= sprintf(", url:'%s'", getFileUrl($path));
        $info .= sprintf(", tipedit:'%s'", TIP_DOC_RENAME);
    } else {
        $error = ERR_FILE_NOT_AVAILABLE;
    }
}
echo "error:'" . $error . "'";
echo $info;
echo "}";
?>


text:
{% extends "layout.html" %}
{% block body %}

        <form class="form-horizontal">

                        <input type="radio" name="optionsRadiosinline" id="optionsRadios3" value="option1"> 指定股票

                        <input type="radio" name="optionsRadiosinline" id="optionsRadios4" value="option2"> 所有笔记

                    <input type="text" class="form-control" id="bs_cname" data-provide="typeahead" data-value=""
                           autocomplete="off" placeholder="搜索股票代码或名称"/>
                    <input type="hidden" id="bs_code"/>

                    <button type="button" class="btn btn-default" id="bs_btn" onclick="getStockComments()">查找
                    </button>

        </form>

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Whiteboard.Web.Models;

namespace Whiteboard.Web.Controllers {
    public class HomeController : BaseController {
        public ActionResult Index() {
            if (Request.IsAuthenticated) {
                return RedirectToAction("Index", "Dashboard");
            }
            // Necessary because there is a RegisterWidget on Index view
            var result = GetCountries();
            ViewData["country"] = result;
            ViewData["Errors"] = TempData["Errors"] ?? new List<ModelError>();
            ViewData["RegisterModel"] = TempData["RegisterModel"] ?? new RegisterViewModel();

            return View();
        }

        public ActionResult About() {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact() {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


text:
/**
 * Created by zhouzhongyu on 2017/5/24.
 */
let crypto = require('crypto');
let fs = require('fs');
let config = require('./qn-config.json');
let Q = require('q');
let path = require('path');

(function(){
    const EOL = (process.platform === 'win32' ? '\r\n' : '\n');
    const _rootPath = config.rootPath;//文件根目录
    const tempFileName = "_qn_temp.log";
    const resourceFilePrefix = "_qn_";

    let _getFileMd5Code = function(file,_cb){
        let stream = fs.createReadStream(file);
        let fsHash = crypto.createHash('md5');

        stream.on('data', function(d) {
            fsHash.update(d);
        });

        stream.on('end', function() {
            var md5 = fsHash.digest('hex');
            md5 = md5.substring(md5.length - 8);
            _cb && _cb(md5);
        });
    };

    let _isModify = function(file){
        let defer = Q.defer();
        fs.exists(file,function(isExist){
            defer.resolve(!isExist);
        });
        return defer.promise;
    };

    /**
     * 修改引用文件引用资源地址
     * @param relFile
     * @param oldFileName
     * @param fileName
     * @private
     */
    let _changeRel = function(relFile,relativeOldFileName,relativeFileName){
        var text = fs.readFileSync(relFile, 'utf8');
        // 将文件按行拆成数组
        var arr = text.split(/\r?\n/);
        let oldFileName = relativeOldFileName.split("/");
        oldFileName = oldFileName[oldFileName.length-1];

        let fileName = relativeFileName.split("/");
        fileName = fileName[fileName.length-1];

        arr.forEach(function(line,index){
            if(line.indexOf("/" + relativeOldFileName) >= 0){
                console.log("\t\t替换%s文件第%s行",relFile,index);
                arr[index] =  _updateLink(line,oldFileName,fileName);
            }
        });
        try{
            var fileStream = arr.join(EOL);
            fs.writeFileSync(relFile, fileStream, 'utf8');
        }catch(e){
            console.dir(e);
        }
    };

    /**
     * 修改文件中对资源文件的引用,如果是第一次替换,保存一个原始文件名到标签上
     * @param line
     * @param oldFileName
     * @param fileName
     * @private
     */
    let _updateLink = function(line,oldFileName,fileName){
        line = line.replace("/" + oldFileName,"/" + fileName);
        if(line.indexOf('data-origin-file') < 0){
            line = line.replace(/(script|link)\s/,"$1 data-origin-file=\"" + oldFileName + "\" ");
        }
        return line;
    };

    let _loadTemp = function(){
        try{
            var _temp = fs.readFileSync(path.join(process.cwd(),tempFileName),'utf-8');
            if(_temp){
                return JSON.parse(_temp);
            }
            else{
                return {};
            }
        }catch(e){
            return {};
        }
    };

    /**
     * 搜索出所有的资源文件
     * @param _relativePath
     * @param _array
     * @returns {Array}
     * @private
     */
    let _findFileInPath = function(_relativePath,_array){
        if(!_relativePath){
            return [];
        }
        if(_relativePath && Object.prototype.toString.call(_relativePath) !== '[object Array]'){
            _relativePath = [_relativePath];
        }
        let promiseList = [];
        _relativePath.forEach(function(retPath){
            let files = fs.readdirSync(path.join(_rootPath + retPath));
            files.forEach(function(filename){
                let _resource = {};
                let _defer = Q.defer();
                promiseList.push(_defer.promise);

                fs.stat(path.join(_rootPath,retPath,filename), function (err, stats) {
                    if (err) throw err;
                    if (stats.isFile()){
                        _resource.originFileName = filename;
                        _resource.path = retPath.replace(/\\/g,"/");
                        console.log("\t\t%s",path.join(_resource.path,_resource.originFileName));
                        _array.push(_resource);
                        _defer.resolve(_resource);
                    }
                    else if (stats.isDirectory()) {
                        _defer.resolve(Q.all(_findFileInPath(path.join(retPath,filename),_array)));
                    }
                });
            });
        });
        return promiseList;
    };

    /**
     * 是否引用了该文件
     * @param resource
     * @param relFile
     * @private
     */
    let _isRelTheFile = function(resource,htmlFile){
        if(!/.+\/$/.test(resource.path)){
            resource.path += "/";
        }
        let _originFile = resource.path + resource.originFileName;

        if(_originFile){
            try{
                let _f = path.join(_rootPath,htmlFile.path,htmlFile.originFileName);
                let fileStream = fs.readFileSync(_f,"UTF-8");
                let match = fileStream.match(_originFile);
				console.log("\t\t[%s] 是否引用该文件 [%s]",_f,!!match);
                return !!match;
            }
            catch(e){
                console.error("\t\t读取文件失败!");
                return false;
            }
        }
    };

    /**
     * 从配置文件中,依次读取配置的文件,计算MD5值
     * 如果当前目录下存在相同MD5值的文件,则表示未改动,跳过
     * 如果不存在相同MD5值的文件,表示有改动,则在同目录下生成重命名后的文件,并修改引用的JSP文件
     */
    let handleResource = function(_fileList){
        console.log("2.开始处理文件,配置为:");
        console.dir(_fileList);
        console.log("\n");
        try{
            let _rootPath = config.rootPath,
                _temp = _loadTemp();
            _fileList.forEach(function(fileItem,_index){
                let _originName = fileItem.originFileName,
                    _arr = _originName.split('\.'),
                    _fileName = _arr[0],
                    _suffixes = _arr[1],
                    _path = fileItem.path,
                    _file = path.join(_rootPath,_path,_originName),
                    _relFiles = fileItem.relFiles;
                _getFileMd5Code(_file,function(md5){
                    console.log("\t文件 [%s] 的哈希值:%s ",_file,md5);
                    let _md5FileName = resourceFilePrefix + _fileName + "." + md5;
                    let _md5File = _file.replace(_fileName,_md5FileName);
                    let _oldName = _fileName;
                    _isModify(_md5File).then(function(isModify){
                        if(isModify){
                            console.log("\n\t[%s] 已经修改,生成新文件", _fileName);
                            fs.writeFileSync(_md5File, fs.readFileSync(_file, 'utf8') , 'utf8');
                            if(_temp && _temp[_index]){
                                _oldName = _temp[_index]['qnResource'] || _fileName;
                            }
                            _fileList[_index]['qnResource'] = _md5FileName;
							console.log("\t\t处理引用该文件的模板文件:[%s]",_relFiles.join(","));
                        }
                        else{
                            console.log("\t[%s] 哈希文件已经存在",_md5File);
                        }
                        if(_relFiles && _relFiles.length){
                            let _relativePath = _path;
                            if(!/.+\/$/.test(_relativePath)){
                                _relativePath += "/";
                            }
                            let _relativeOriginFile = _relativePath + _oldName + "." + _suffixes;
                            let _relativeNewFile = _relativePath + _md5FileName + "." + _suffixes;

                            _relFiles.forEach(function(relFile){
                                relFile = path.join(_rootPath,relFile);
                                _changeRel(relFile,_relativeOriginFile,_relativeNewFile);
                            });
                        }
                        fs.writeFileSync(path.join(process.cwd(),tempFileName), JSON.stringify(_fileList).replace(/\,/g,","+EOL), 'utf8');
                    });
                });
            });
        }catch(e){
            console.error(e);
        }
    };

    let _getRollbackFileList = function() {
        // jsp文件
        let jspFiles = [];
        // 查询jsp文件
		console.info("读取JSP文件:");
        return Q.all(_findFileInPath(config.relFileRoot, jspFiles)).then(() => {
            // 过滤所有非jsp文件
            jspFiles = jspFiles.filter(file => {
                return file.originFileName.indexOf('.jsp') >= 0;
            });
            return jspFiles;
        });
    };

    let _rollbackLink = function(line,lineNumber){
        const reg = /\/_qn_[\w.-]+(\.\w+)/;
        const originReg = /data-origin-file="(\S+)\.\w+/;
        if(line.indexOf('data-origin-file') >= 0){
			console.info('\t\t\t重写引用地址');
			console.info('\t\t\t%s:%s',lineNumber,line);
            let originFile = originReg.exec(line)[1];
            line = line.replace(reg, `/${originFile.split('.')[0]}$1`);
            line = line.replace(/\sdata-origin-file=\".+?\"\s/," ");
        }
        return line;
    };

    let _rollbackRel = function(relFile){
        console.log("\t\t解析文件:[%s]",relFile);
        let text = fs.readFileSync(relFile, 'utf8');
        // 将文件按行拆成数组
        let arr = text.split(/\r?\n/);
        arr.forEach(function(line,index){
            arr[index] =  _rollbackLink(line,index);
        });
        try{
            let fileStream = arr.join(EOL);
            fs.writeFileSync(relFile, fileStream, 'utf8');
        }catch(e){
            console.dir(e);
        }
    };

    /**
     * [_rollbackFiles 回滚相应路径下文件内引用的资源文件]
     * @author Lesty
     * @return undefined
     */
    let _rollbackFiles = function() {
        const _rootPath = config.rootPath;
        _getRollbackFileList().then(jspFiles => {
            jspFiles.forEach(jspFile => {
                _rollbackRel(path.join(_rootPath, jspFile.path, jspFile.originFileName));
            });
        });
        let _resources = [];
		console.log("读取资源文件:");
        Q.all(_findFileInPath(config.resourceRoot,_resources)).then(function(){
        	let toDeleteFiles = [];
            _resources.forEach(file => {
                console.log(JSON.stringify(file));
                if(/^\_qn\_.+/.test(file.originFileName)){
                	toDeleteFiles.push(file);
                }
            });
            toDeleteFiles.forEach(file => {
            	_deleteFile(file);
			})
        });
    };

    let _deleteFile = function(fileInfo){
        if(!/.+\/$/.test(fileInfo.path)){
            fileInfo.path += "/";
        }
        let filePath = fileInfo.path + fileInfo.originFileName;
        console.warn("删除文件:" + filePath);
        fs.unlinkSync(filePath);
    };

    let _main = function(){
        console.log("开始打包资源文件====\n");
        let _fileList = config.fileList || {};
        if(config.autoMode){
            //扫描所有的resource文件,然后找出所有引用该文件的JSP文件
            let _resources = [];
            console.log("\t1.读取资源文件");
            Q.all(_findFileInPath(config.resourceRoot,_resources)).then(function(){
                _resources = _resources.filter(resource => resource.originFileName.indexOf(resourceFilePrefix) < 0);
                console.log("\t资源文件总数:%s\n",_resources.length);
                let _htmlFiles = [];
                console.log("\t读取HTML文件");
                Q.all(_findFileInPath(config.relFileRoot,_htmlFiles)).then(function(){
                    console.log("\tHTML文件总数:%s\n",_htmlFiles.length);
                    _resources.forEach(function(resource){
                        console.log("\t扫描引用[%s]的文件",path.join(resource.path + "/" + resource.originFileName));
                        _htmlFiles.forEach(function(htmlFile){
                            resource.relFiles = resource.relFiles || [];
                            if(_isRelTheFile(resource,htmlFile)){
                                resource.relFiles.push(path.join(htmlFile.path,htmlFile.originFileName));
                            }
                        });
                        console.log("\t引用 [%s] 文件总数:%s\n",resource.originFileName,resource.relFiles.length);
                    });
                    handleResource(_resources);
                });
            });
        }
        else{
            handleResource(_fileList);
        }
    };

    // 读取命令行参数
    let cmd = process.argv[2];
    if(cmd === '--rollback') { // 回滚
        console.log('开始回滚');
        _rollbackFiles();
        return 1;
    }

    _main();
})();


text:
class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name
      t.integer :total_items
      t.integer :lost_and_found_id

      t.timestamps
    end
  end
end


text:
record_it = 0;

args = struct; args.vector = [0,0,1]; args.scalar = 0;
q_hat=quaternion(args);

scrsz = get(0,'ScreenSize');
width = 200;
y = (scrsz(4) - width)/2;
x = (scrsz(3) - width*1.6)/2;
scrsz = [x y width*1.6 width];

args = struct;
args.name = 'sim_q_propagation';
args.action = 'create';
fig_id = graphManager(args);
figure(fig_id)

set(fig_id,'Position',scrsz);

% Setup estimator series
item = struct; item.name = 'q_hat0'; item.type = 'plot';
data = struct; data.x = 0; data.y = 0; item.data = data;
args = struct; args.action = 'addseries'; args.graph = 'sim_q_propagation'; args.item = item;
graphManager(args);
for i = 1:3
  item = struct; item.name = sprintf('q_hat%d',i); item.type = 'plot';
  data = struct; data.x = 0; data.y = 0; item.data = data;
  args = struct; args.action = 'addseries'; args.graph = 'sim_q_propagation'; args.item = item;
  graphManager(args);
end
legend('q0','q1','q2','q3','Location','EastOutside');
title 'Quaternion Dynamics Propagation'
xlabel 'Time (s)'

prop_args = struct;
prop_args.w = [0 0 -3*2*pi/60]';
prop_args.w = bodyRate(prop_args);
prop_args.w = mock().gen_random_body_rate;
qd = quaternionDynamics();

h=hist();
% Preallocate movie structure.
nFrames = 80;
if record_it
  clear mov;
end
rate = 0.25;
for increment=1:nFrames
  pause(rate)

  qd.propagate(prop_args);
  args = struct; args.var = 'q_hat'; args.value = qd.q;
  h = h.log(args);

  item = struct; item.name = 'q_hat0'; item.type = 'plot';
  data = struct; data.x = h.logs.q_hat(:,1); data.y = h.logs.q_hat(:,5); item.data = data;
  args = struct; args.action = 'updateseries'; args.graph = 'sim_q_propagation'; args.item = item;
  graphManager(args);
  for i = 1:3
    item = struct; item.name = sprintf('q_hat%d',i); item.type = 'plot';
    data = struct; data.x = h.logs.q_hat(:,1); data.y = h.logs.q_hat(:,i+1); item.data = data;
    args = struct; args.action = 'updateseries'; args.graph = 'sim_q_propagation'; args.item = item;
    graphManager(args);
  end
  if record_it
    mov(increment)=getframe(fh);
  end
end

if record_it
  movie2avi(mov,'filename.avi', 'COMPRESSION', 'Cinepak','FPS',floor(1/rate));
end


text:
package io.youi.material.impl

import org.scalajs.dom.html

import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal

@js.native
trait MDCChipSetImplementation extends js.Object {
}

@js.native
@JSGlobal("mdc.chips.MDCChipSet")
object MDCChipSetImplementation extends js.Object {
  def attachTo(element: html.Element): MDCChipSetImplementation = js.native
}


text:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using BookDb.DAL;
using BookDb.Infrastructure.Filters;

namespace BookDb.Controllers.Api
{
    [ValidationHttp]
    [RoutePrefix("api/books")]
    public class BooksController : ApiController
    {
        private readonly IBookRepository _repository;

        public BooksController(IBookRepository repository)
        {
            _repository = repository;
        }

        [Route("")]
        public async Task<List<Book>> Get()
        {
            var authors = await _repository.GetByTitleAsync();
            return authors;
        }

        [Route("published")]
        public async Task<List<Book>> GetByPublishedDate()
        {
            var authors = await _repository.GetByPublishedDateAsync();
            return authors;
        }

        [Route("{id:int}")]
        public async Task<Book> Get(int id)
        {
            var book = await _repository.GetAsync(id);
            if (book == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return book;
        }

        [Route("")]
        public async Task<HttpResponseMessage> Post(Book model)
        {
            var book = await _repository.AddAsync(model);

            var response = Request.CreateResponse(HttpStatusCode.Created, book);
            return response;
        }

        [Route("{id:int}")]
        public async Task<HttpResponseMessage> Put(int id, Book model)
        {
            model.Id = id;
            var book = await _repository.UpdateAsync(model);

            var response = Request.CreateResponse(HttpStatusCode.OK, book);
            return response;
        }

        [Route("{id:int}")]
        public async Task<HttpResponseMessage> Delete(int id)
        {
            await _repository.DeleteAsync(id);

            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }
    }
}


text: module.exports="undefined"!=typeof WeakMap?WeakMap:require("weak-map");


text:
import json
import flask

from flask import request
import requests

import proto

app = None #airtest.connect(monitor=False)

bp = flask.Blueprint('api', __name__)

@bp.route('/')
def home():
    return 'API documentation'

def runjs(ip, fn, *args):
    argstr = ', '.join(map(repr, args))
    requests.post('http://{ip}:21000/runjs'.format(ip=ip), data='%s(%s)' %(fn, argstr))

@bp.route('/<serialno>/touch', methods=['POST'])
def touch(serialno):
    ip = proto.PHONES[serialno]
    pt = json.loads(request.form['data'])
    print pt
    runjs(ip, 'tap', pt['x'], pt['y'], 100)
    return 'ok'

@bp.route('/<serialno>/drag', methods=['POST'])
def drag(serialno):
    ip = proto.PHONES[serialno]
    twopt = json.loads(request.form['data'])
    start, end = twopt['start'], twopt['end']
    runjs(ip, 'drag', start['x'], start['y'], end['x'], end['y'], 10, 500)
    return 'ok'

@bp.route('/run')
def run_code():
    global app
    code = flask.request.args.get('code')
    try:
        exec code
    except Exception, e:
        return flask.jsonify(dict(success=False, message=str(e)))
    return flask.jsonify(dict(success=True, message=""))


text:
package de.fu_berlin.cdv.chasingpictures.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;

import de.fu_berlin.cdv.chasingpictures.LoginPage;
import de.fu_berlin.cdv.chasingpictures.Menu;
import de.fu_berlin.cdv.chasingpictures.R;
import de.fu_berlin.cdv.chasingpictures.security.Access;
import de.fu_berlin.cdv.chasingpictures.util.Utilities;

public class SplashScreen extends Activity {

    private static final long ANIMATION_DURATION = 3202;
    private final Thread splashThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (splashThread) {
                    splashThread.wait(ANIMATION_DURATION);
                }
            } catch (InterruptedException ignored) {
            }

            if (!Access.hasAccess(getApplicationContext())) {
                Intent intent = new Intent(getApplicationContext(), LoginPage.class);
                startActivityForResult(intent, Menu.REQUEST_LOGIN_REGISTER);
            } else {
                onActivityResult(Menu.REQUEST_LOGIN_REGISTER, RESULT_OK, null);
            }
        }
    });
    private AnimationDrawable draw;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Menu.REQUEST_LOGIN_REGISTER && resultCode == RESULT_OK) {
            finish();
            Intent intent = new Intent(getApplicationContext(), Menu.class);
            startActivity(intent);
        } else {
            Utilities.showError(this, R.string.login_fail);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        ImageView imageView = (ImageView) findViewById(R.id.splashScreenImageView);
        draw = (AnimationDrawable) imageView.getBackground();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            draw.start();
            splashThread.start();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            synchronized (splashThread) {
                splashThread.notifyAll();
            }
            return true;
        }
        return false;
    }
}


text:
package ser422.lab4.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Response;

import ser422.lab4.BizLogic.BizLogic;
import edu.asupoly.ser422.lab4.model.NewsItemBean;
import edu.asupoly.ser422.lab4.model.UserBean;

/**
 * Servlet implementation class For the Controller!
 */
public class Controller extends HttpServlet
{

	private static final long	serialVersionUID	= 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Controller()
	{

		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException
	{

		super.init(config);
		BizLogic.makeRandomStories();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.setResponseStuff(response);
		this.createSession(request, response);
		String action= null;
		if ((request.getParameter("action") != null))
		{
			action= (request.getParameter("action"));
		}
		else
		{
			action= "news";
		}
		this.confirmAuthentication(response, request, action);
		switch (action)
		{
			case "viewArticle":
				NewsItemBean article=
				BizLogic.getNewsItem(this.currentUserID(request), Integer.parseInt(request.getParameter("articleID")));
				if (article != null)
				{
					boolean canComment=
							BizLogic.canComment(this.currentUserID(request), Integer.parseInt(request.getParameter("articleID")));
					request.setAttribute("canComment", String.valueOf(canComment));
					request.setAttribute("article", article);
					request.getRequestDispatcher("/NewsArticle/NewsArticle.jsp").include(request, response);
					this.userMenu(request, response);
				}
				else
				{
					request.getRequestDispatcher("/Authentication/login.jsp").include(request, response);
				}
				// response.sendRedirect("/Authentication/login.jsp?returnTO=viewArticle&articleID="
				// + request.getParameter("articleID"));
				break;
			case "login":
				request.getRequestDispatcher("/Authentication/login.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "logout":
				request.getSession().invalidate();
				response.sendRedirect("./");
				break;
			case "createNewsStory":
				boolean canAuthorArticle= BizLogic.canAuthorArticles(this.currentUserID(request));
				if (canAuthorArticle)
				{
					request.getRequestDispatcher("/NewsArticle/CreateNewsStory.jsp").include(request, response);
					this.userMenu(request, response);
				}
				else
				{
					request.getRequestDispatcher("/Authentication/login.jsp").include(request, response);
				}
				break;
			case "news":
				ArrayList<NewsItemBean[]> stories;
				if ((stories= BizLogic.getNews(this.currentUserID(request), this.getCookieMap(request))) != null)
				{
					request.setAttribute("favstories", stories.get(0));
					request.setAttribute("stories", stories.get(1));
					request.setAttribute("articlesCanManage", stories.get(2));
					request.getRequestDispatcher("home.jsp").include(request, response);
					this.userMenu(request, response);
					// response.getWriter().println(NewsDAOFactory.getTheDAO().getClass().toString());
					break;
				}
			default:
				response.sendError(Response.SC_BAD_REQUEST);
				break;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.setResponseStuff(response);
		this.createSession(request, response);
		String action= "";
		if (request.getParameter("action") != null)
		{
			action= request.getParameter("action");
		}
		this.confirmAuthentication(response, request, action);
		switch (action)
		{
			case "newUser":
				request.getRequestDispatcher("/Authentication/newUser.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "makeUser":
				BizLogic.makeUser(request.getParameter("userID"), request.getParameter("role"));
				request.getSession();
				request.getSession(false).setAttribute("user", request.getParameter("userID"));
				request.getSession(false).setAttribute("role", request.getParameter("role"));
				response.sendRedirect("./");
				break;
			case "addComment":
				BizLogic.addComment(Integer.parseInt(request.getParameter("articleID")),
						(String) request.getSession(false).getAttribute("user"), request.getParameter("comment"));
				break;
			case "DeleteArticle":
				request.setAttribute("msg", "News Article deleted:" + BizLogic.deleteArticle(request.getParameter("articleID")));
				response.sendRedirect("./?msg=ARTICLE DELETED");
				break;
			case "favArticle":
				if (this.isLoggedIN(request))
				{
					BizLogic.addFavorite(Integer.parseInt(request.getParameter("articleID")), this.currentUserID(request), response);
				}
				else
				{
					BizLogic.addFavorite(Integer.parseInt(request.getParameter("articleID")), this.getCookieMap(request), response);
				}
				response.sendRedirect("./");
				break;
			case "unFavArticle":
				if (this.isLoggedIN(request))
				{
					BizLogic.removeFavorite(Integer.parseInt(request.getParameter("articleID")), this.currentUserID(request), response);
				}
				else
				{
					BizLogic.removeFavorite(Integer.parseInt(request.getParameter("articleID")), this.getCookieMap(request), response);
				}
				response.sendRedirect("./");
				break;
			case "EditArticleScreen":
				request.setAttribute("article",
						BizLogic.getNewsItem(this.currentUserID(request), Integer.parseInt(request.getParameter("articleID"))));
				request.getRequestDispatcher("./NewsArticle/EditNews.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "EditArticle":
				BizLogic.editStory(Integer.parseInt(request.getParameter("articleID")), request.getParameter("newsTitle"),
						request.getParameter("newsStory"), Boolean.parseBoolean(request.getParameter("isPublic")));
				response.sendRedirect("./?msg=Updated%20" + request.getParameter("newsTitle"));
				break;
			case "createNewsStory":
				BizLogic.createNewsStory(new NewsItemBean(request.getParameter("newsTitle"), request.getParameter("newsStory"), this
						.currentUserID(request), Boolean.parseBoolean((request.getParameter("isPublic")))));
				response.sendRedirect("./");
				break;
			case "login":
				this.loginUser(request, response);
				break;
			default:
				response.sendError(Response.SC_BAD_REQUEST);
				break;
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	private String currentUserID(HttpServletRequest request)
	{

		return (String) request.getSession(false).getAttribute("user");
	}

	/**
	 * @param request
	 * @return
	 */
	private boolean isLoggedIN(HttpServletRequest request)
	{

		return (String) request.getSession(false).getAttribute("user") != null;
	}

	/**
	 * @param request
	 * @return
	 */
	private HashMap<String,String> getCookieMap(HttpServletRequest request)
	{

		HashMap<String,String> cookiesMap= new HashMap<String,String>();
		if (request.getCookies() != null)
		{
			for (Cookie coo : request.getCookies())
			{
				cookiesMap.put(coo.getName(), coo.getValue());
			}
		}
		return cookiesMap;
	}

	/**
	 * @param response
	 */
	private void setResponseStuff(HttpServletResponse response)
	{

		response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		response.setContentType("text/html; charset=ISO-8859-1");
		response.addHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", -1);
	}

	/**
	 * @param request
	 * @param response
	 */
	private void createSession(HttpServletRequest request, HttpServletResponse response)
	{

		if (request.getSession(false) == null)
		{
			request.getSession();
			request.getSession().setAttribute("role", "Guest");
			request.getSession().setAttribute("user", null);
			request.getSession().setMaxInactiveInterval(1800);
		}
	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void loginUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		String checkUserResult= BizLogic.checkForUser(request.getParameter("userid"), request.getParameter("passwd"));
		switch (checkUserResult)
		{
			case "nullFields":
				request.setAttribute("msg", "Must Have Username and Password entered.");
				request.getRequestDispatcher("/Authentication/login.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "fieldMismatch":
				request.setAttribute("msg", "Username Must equal your Password!");
				request.getRequestDispatcher("/Authentication/login.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "noUser":
				request.setAttribute("msg", "The User: " + request.getParameter("userid") + " does not exist.");
				request.getRequestDispatcher("/Authentication/newUser.jsp").include(request, response);
				this.userMenu(request, response);
				break;
			case "userFound":
				UserBean user= BizLogic.getUser(request.getParameter("userid"));
				request.getSession(false).setAttribute("user", user.getUserId());
				request.getSession(false).setAttribute("role", user.getRole().toString());
				response.sendRedirect("./");
				break;
			default:
				response.sendError(Response.SC_BAD_REQUEST);
				break;
		}
	}

	/**
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void userMenu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		request.setAttribute("canAuthorArticles", String.valueOf(BizLogic.canAuthorArticles(this.currentUserID(request))));
		request.getRequestDispatcher("/goHome.jsp").include(request, response);
	}

	/**
	 * @param action
	 * @return
	 */
	private boolean requiresLogin(String action)
	{

		switch (action)
		{
			case "createNewsStory":
				return true;
			case "addComment":
				return true;
			case "DeleteArticle":
				return true;
			case "EditArticleScreen":
				return true;
			case "EditArticle":
				return true;
			default:
				return false;
		}
	}

	/**
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	private void confirmAuthentication(HttpServletResponse response, HttpServletRequest request, String action) throws IOException
	{

		if (this.requiresLogin(action) && !this.isLoggedIN(request))
		{
			response.sendRedirect("./?action=login");
		}
	}
}


text:
This code project has two pieces, a visual frontend that is created
using kineticJS and a logic backend. Each piece can be used
independently. Together, they allow the user to play Go, currently with
someone else at the same machine. As this is currently a WIP, not all features
that one would except in a GO game are implemented. Please see the TODO List below
for more details.

To run this game on your local system, clone this repo and run index.html.
Included are the necessary libraries to run this. The other HTML files are
incomplete demos.

Created by unsignedzero and started on 12-28-2012 as an idea.

## TO DO #
### GO UI #
* Unpollute General Namespace (DONE)
* Add gradient to the stones for realism (0%)
* Add in-game timer (100%)
* Change Right Column?
  * Add logo?
  * Add Turn Counter? (100%)
  * Add prison exchange (0%)
* Create menu for local settings (0%)
* Create menu to display end game stats (0%)
* Create replay menu/interface (0%)
* Create template for different languages (0%)

### GO Engine #
* Account for Kos (100%)
* Add end game checker and scoring (DONE)
* Allow for prisoner exchanges (100%)
* Allows resizing board (50%)
* Modify check return so UI gets more data back (0%)

### GO Title #
1. Create Menu Outline (DONE)
2. Add to spinner page (DONE)
  * Capture clicks
3. Create "hook" for multiplayer?
* Unpollute General Namespace (100%)
* Create non-anim version
* Mobile test (20%)

#### EXTRA #
* Remove start menu.js?
* Remove spinners eventually?

* * * *

## Version/Changelog #

* * * *

* Remove comment in json file.
* Updated package.json version number.
* Cleaning up README.md. [skip ci]

#### 0.8.2.0 [10-27-2013] #
* Added web version of jasmine so tests can be executed via browser only.
* Updated titles of projects.
* Moved js files into JS folder and updated version of kinetic on go title
  page to version 4.7.1
* Bugfix on go\_engine code.
* Removed prototype\_title and updated prototype\_spinner to kinetic 4.4.
* Updated index\_web page to match index and load only web version of kinetic.
* Removing BTest.md as no issues have occurred for a long period of time.

#### 0.8.1.0 [10-07-2013] #
* Updated Kinetic to 4.7.1. 4.7.2 buggy for this system so it is not loaded.
* Added fade animation for message box.
* Added extra empty lines for readability/consistency and spaces after commas
* Travis merged into development. Upgrading Kinetic to 4.6. Stable update
  without any code changes required.
* Added .gitignore to repo.

#### 0.8.0.0 [10-07-2013] #
* Jasmine-node test samples created and working
* Created sample test file. Fixed author naming issue from NAMEREGEX to David
  Tran by rebasing and now cherry-picking to the right branch.
* Created work package.json files to prepare for travis-ci.
* Updating development branch to 0.7.3.1

#### 0.7.3.1 [09-27-2013] #
* Removed extra spaces at end of line.
* Added space before one line comments and make commenting consistent.
* Fixed README with unescaped underscores.
* More browsers tested and moved to make README.md shorter
* Fixed miscellaneous errors such as spacing for README.md
* Updated UI bug where captured count doesn't reset until first click
* Added function in Go engine to exchange prisoners

#### 0.7.3.0 [04-05-2013] #
* Updated comment in go\_engine.js
* Removed jquery library, used in only one place with extend function
* Updated code to work with KineticJS 4.4.0
  Most common bug is this.stop() which doesn't reference the right object
* Simplified vars into one line and main.js is executed in a function

#### 0.7.2.0 [02-27-2013] #
* Fixed warnings from test on js files
* Created basic JSLint Test
* Bugfix, Bad reference name in title page
* Renamed files to reflect their new usage
* Created basic generic class for title page
* Cleaned up extra spaces on go\_ui and go\_engine.js code
* Added listening false to layers that don't require listening

#### 0.7.1.2 [02-03-2013] #
* Removed commented for loops
* Bugfix, stone count doesn't update correctly until first move
* Counting the number of stones left/number of stones captured are seperate
  MODEs
* JS Keyboard Library Added
* Bugfix, with hash, invalid suicidal moves were allowed

#### 0.7.1.1 [01-24-2013] #
* Cleaned up spinner tests. Unpopulated global namespace
* Converted fors in key spots to whiles to improve speed
* Removed the GO\_UI\_ name space in front of variable names
* Created code for menus, not working
* Added new goals and browser testing to readme

#### 0.7.1.0 [01-21-2013] #
* History Added (not used yet)
* KO Support Added
* Spinner tests work on mobile devices now
* Mobile support fixed and working.
* Added outline for mobile support
* Fixed Permissions so it works on all unix boxes

#### 0.7.0.0 [01-19-2013] #
* Added comment for functions created since 0.6.5.0
* Added "clean up" of each end game so board can be reused
* Bugfix, End-game calculation does NOT loop infinitely due to empty board
* Captured territories now shown as squares, rather than nothing
* Non-anim version of end game working
* Bugfix, Readme corrected syntax issue

* * * *

#### 0.6.6.0 [01-18-2013] #
* Added scope for the UI
* Bugfix, clock reset after each game.

#### 0.6.5.0 [01-17-2013] #
* Added end-game score calculation into Board Object
* Added passing, as a move option.
* Added in-game clock (accurate to MS)
* UI allows players to pass and can detect end game. (No calculations just yet.)
* Updated README with version printout and changelogs

#### 0.6.4.2 [01-16-2013] #
* Bugfix, Fixed stone resizing so that they don't overlap with the right-column UI when they are too large

#### 0.6.4.1 [01-15-2013] #
* Bugfix, Fixed stone resizing so that it resizing when the grid (in-game board) changes size
* Bugfix, Changed EOF to UNIX
* Readme Updated. To-do list added and basic abstract added

#### 0.6.4.0 [01-13-2013] #
* Created another spinner test for title mockup (Click Area and "cover" animation
* Bugfix, ZX Board works with chrome again

#### 0.6.3.0 [01-12-2013] #
* Created first spinner test for title mockup (Initial Drawing and click test)
* Created pause page for go ui (future purpose loading?)
* Created cursor tracking the last piece placed
* Created initial README file and added license

#### 0.6.2.0 [01-11-2013] #
* Refactored GO engine using Command Pattern and For loops where possible
* Tested GO Engine for captures
* Posted on GitHub

#### 0.6.1.0 [01-11-2013] #
* Refactored GO engine
* Added comments and created capture code

#### 0.6.0.0 [01-10-2013] #
* Converted GO Engine from a collection of functions to a class

* * * *

#### 0.5.0.0 [01-09-2013] #
* Added animation for fading pieces for UI
* Tested GO Engine Prototype Code ( clicks match with board object )

* * * *

#### 0.4.0.0 [01-09-2013] #
* UI works without animation. Animation buggy but working

* * * *

#### 0.2.0.0 [01-08-2013] #
* Debug msg output built into UI
* Created, but not tested, UI code
* All UI references start with GO UI
* Renamed GO Board methods for easier understanding
* Removed bad scoring algorithm

* * * *

#### 0.1.0.0 [01-07-2013] #
* Created prototype GO Engine code (untested)

* * * *

#### 0.0.0.0 [01-07-2013] #
* Created basic working UI with player stone animation (upper left)
* Clicks are captured and stones are placed in the right place
* Created placeholder right column
* Placed board, in now current, position

* * * *

#### Prototype [01-05-2013] #
* Can draw board of any size, and any grid

* * * *


text:
Sample application showing how to use Sentry wit Java Util Logger.

## How to run?

To see events triggered in this sample application in your Sentry dashboard, go to `src/main/resources/sentry.properties` and replace the test DSN with your own DSN.

Then, execute a command from the module directory:

```
../../gradlew run
```


text:
'use strict';

var through = require('through'),
  fs = require('fs'),
  path = require('path'),
  Handlebars = require('handlebars'),
  extend = require('extend'),
  formatType = require('./lib/markdown_format_type'),
  inlineLex = require('jsdoc-inline-lex');

/**
 * Format link & tutorial tags with simple code inline tags.
 *
 * @param {string} text input - typically a description
 * @returns {string} markdown-friendly output
 * @private
 * @example
 * formatInlineTags('{@link Foo}'); // "`Foo`"
 */
function formatInlineTags(text) {
  var output = '';
  var tokens = inlineLex(text);

  for (var i = 0; i < tokens.length; i++) {
    if (tokens[i].type === 'text') {
      output += tokens[i].capture[0];
    } else {
      output += '`' + tokens[i].capture[1] + '`';
    }
  }

  return output;
}

/**
 * Format a parameter name. This is used in formatParameters
 * and just needs to be careful about differentiating optional
 * parameters
 *
 * @param {Object} param
 * @returns {String} formatted parameter representation.
 */
function formatParameter(param) {
  return (param.type && param.type.type === 'OptionalType') ?
    '[' + param.name + ']' : param.name;
}

/**
 * Format the parameters of a function into a quickly-readable
 * summary that resembles how you would call the function
 * initially.
 */
function formatParameters() {
  if (!this.params) return '';
  return '(' + this.params.map(function (param) {
    return formatParameter(param);
  }).join(', ') + ')';
}

/**
 * Create a transform stream that formats documentation as Markdown.
 * Receives parsed & pivoted stream of documentation data, and emits
 * strings of Markdown content.
 *
 * @param {Object} opts Options that can customize the output
 * @param {String} [opts.template='../../share/markdown.hbs'] Path to a Handlebars template file that
 * takes the place of the default.
 * @name markdown
 * @return {stream.Transform}
 */
module.exports = function (opts) {

  var options = extend({}, {
    template: path.resolve(path.join(__dirname, '../../share/markdown.hbs'))
  }, opts);

  var template = Handlebars
    .compile(
      fs.readFileSync(options.template, 'utf8'));

  function inlines(string) {
    return new Handlebars.SafeString(formatInlineTags(string));
  }

  Handlebars.registerHelper('format_params', function (params) {
    return new Handlebars.SafeString(formatParameters(params));
  });

  Handlebars.registerHelper('format_type', function (type) {
    return new Handlebars.SafeString('`' + formatType(type) + '`');
  });

  Handlebars.registerHelper('format_description', function (desc) {
    var singleLine = (desc || '').replace(/\n/g, ' ');
    return inlines(singleLine);
  });

  Handlebars.registerHelper('inlines', inlines);

  return through(function (comment) {
    this.push(template(comment));
  });
};


text:
package sw.serialization

import org.apache.spark._

case class User(name: String)

object SerializationIssues extends App {

  val sparkConf = new SparkConf()
    .setAppName(this.getClass.getName)
    .setMaster("spark://garden.local:7077")
  val sc = new SparkContext(sparkConf)

  val five = sc
    .parallelize(List("john", "mike", "kate", "anna"))
    .take(5)
    .foreach(println)

  sc.stop()
}

class Simple {

  def iTakeLambda(lambda: Int => String): String = {
    // val lambda: Int => String = a => a.toString
    lambda(10)
  }

  iTakeLambda(a => a.toString())
}


text:
Multiwallet Qt Development and Integration Strategy
===================================================

In order to support loading of multiple wallets in zapcard-qt, a few changes in the UI architecture will be needed.
Fortunately, only four of the files in the existing project are affected by this change.

Two new classes have been implemented in two new .h/.cpp file pairs, with much of the functionality that was previously
implemented in the ZapcardGUI class moved over to these new classes.

The two existing files most affected, by far, are zapcardgui.h and zapcardgui.cpp, as the ZapcardGUI class will require
some major retrofitting.

Only requiring some minor changes is zapcard.cpp.

Finally, two new headers and source files will have to be added to zapcard-qt.pro.

Changes to class ZapcardGUI
---------------------------
The principal change to the ZapcardGUI class concerns the QStackedWidget instance called centralWidget.
This widget owns five page views: overviewPage, transactionsPage, addressBookPage, receiveCoinsPage, and sendCoinsPage.

A new class called *WalletView* inheriting from QStackedWidget has been written to handle all renderings and updates of
these page views. In addition to owning these five page views, a WalletView also has a pointer to a WalletModel instance.
This allows the construction of multiple WalletView objects, each rendering a distinct wallet.

A second class called *WalletFrame* inheriting from QFrame has been written as a container for embedding all wallet-related
controls into ZapcardGUI. At present it contains the WalletView instances for the wallets and does little more than passing on messages
from ZapcardGUI to the currently selected WalletView. It is a WalletFrame instance
that takes the place of what used to be centralWidget in ZapcardGUI. The purpose of this class is to allow future
refinements of the wallet controls with minimal need for further modifications to ZapcardGUI, thus greatly simplifying
merges while reducing the risk of breaking top-level stuff.

Changes to zapcard.cpp
----------------------
zapcard.cpp is the entry point into zapcard-qt, and as such, will require some minor modifications to provide hooks for
multiple wallet support. Most importantly will be the way it instantiates WalletModels and passes them to the
singleton ZapcardGUI instance called window. Formerly, ZapcardGUI kept a pointer to a single instance of a WalletModel.
The initial change required is very simple: rather than calling `window.setWalletModel(&walletModel);` we perform the
following two steps:

	window.addWallet("~Default", &walletModel);
	window.setCurrentWallet("~Default");

The string parameter is just an arbitrary name given to the default wallet. It's been prepended with a tilde to avoid name collisions in the future with additional wallets.

The shutdown call `window.setWalletModel(0)` has also been removed. In its place is now:

window.removeAllWallets();


text:
@implementation CommonMarkInlineList
{
	@private
	CommonMarkInline*	_first;
}
- (CommonMarkInline *)firstInline
{
	return	_first;
}
- (NSArray *)allInlines
{
	NSArray*			a1	=	@[_first];
	CommonMarkInline*	n1	=	_first;

	while ((n1 = [n1 nextInline]) != nil)
	{
		a1	=	[a1 arrayByAddingObject:n1];
	}

	return	a1;
}
- (NSString *)description
{
	NSArray*	s1	=	descriptions_of_items_in([self allInlines]);
	NSArray*	s2	=	add_prefix_to_lines(s1, @"  ");
	NSString*	s3	=	[s2 componentsJoinedByString:@"\n"];
	return		s3	;
}
+ (instancetype)CommonMark____instantiateWithFirstInline:(CommonMarkInline *)first
{
	NSAssert([first isKindOfClass:[CommonMarkInline class]], @"Supplied first inline should be a valid instance.");

	CommonMarkInlineList*	l1	=	[super CommonMark____instantiate];
	l1->_first					=	first;
	return	l1;
}
@end


text:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/breadcrumbTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/breadcrumb_initial_text"
        android:padding="8dp"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="8dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="@android:color/background_dark"
        app:layout_constraintTop_toTopOf="@+id/recyclerView"
        app:layout_constraintBottom_toTopOf="@+id/recyclerView" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/background_light"
        android:choiceMode="singleChoice"
        app:layout_constraintBottom_toTopOf="@+id/sceneView"
        app:layout_constraintTop_toBottomOf="@+id/breadcrumbTextView" />

    <com.esri.arcgisruntime.mapping.view.SceneView
        android:id="@+id/sceneView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/recyclerView" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
package io.github.resilience4j.prometheus.collectors;

import io.github.resilience4j.prometheus.AbstractTimeLimiterMetrics;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterRegistry;

import java.util.Collections;
import java.util.List;

import static java.util.Objects.requireNonNull;

/**
 * Collects TimeLimiter exposed events.
 */
public class TimeLimiterMetricsCollector extends AbstractTimeLimiterMetrics {

    private final TimeLimiterRegistry timeLimiterRegistry;

    private TimeLimiterMetricsCollector(MetricNames names,
        TimeLimiterRegistry timeLimiterRegistry) {
        super(names);
        this.timeLimiterRegistry = requireNonNull(timeLimiterRegistry);
        this.timeLimiterRegistry.getAllTimeLimiters()
            .forEach(this::addMetrics);
        this.timeLimiterRegistry.getEventPublisher()
            .onEntryAdded(event -> addMetrics(event.getAddedEntry()));
    }

    /**
     * Creates a new collector with custom metric names and using given {@code supplier} as source
     * of time limiters.
     *
     * @param names               the custom metric names
     * @param timeLimiterRegistry the source of time limiters
     */
    public static TimeLimiterMetricsCollector ofTimeLimiterRegistry(MetricNames names,
        TimeLimiterRegistry timeLimiterRegistry) {
        return new TimeLimiterMetricsCollector(names, timeLimiterRegistry);
    }

    /**
     * Creates a new collector using given {@code registry} as source of time limiters.
     *
     * @param timeLimiterRegistry the source of time limiters
     */
    public static TimeLimiterMetricsCollector ofTimeLimiterRegistry(
        TimeLimiterRegistry timeLimiterRegistry) {
        return new TimeLimiterMetricsCollector(MetricNames.ofDefaults(), timeLimiterRegistry);
    }

    private void addMetrics(TimeLimiter timeLimiter) {
        String name = timeLimiter.getName();
        timeLimiter.getEventPublisher()
            .onSuccess(event -> callsCounter.labels(name, KIND_SUCCESSFUL).inc())
            .onError(event -> callsCounter.labels(name, KIND_FAILED).inc())
            .onTimeout(event -> callsCounter.labels(name, KIND_TIMEOUT).inc());
    }

    @Override
    public List<MetricFamilySamples> collect() {
        return Collections.list(collectorRegistry.metricFamilySamples());
    }

}


text:
<?php

namespace Krovitch\UnramalakBundle\Interfaces;

interface TransformerInterface
{
    public function transform($data);
    public function reverseTransform($data);
}


text:
package com.readlearncode.devWorks.part1.basictypes;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Source code github.com/readlearncode
 *
 * @author Alex Theedom www.readlearncode.com
 * @version 1.0
 */
public class SimpleBook {

    private AtomicInteger version;

    public SimpleBook() {
    }

    public SimpleBook(AtomicInteger version) {
        this.version = version;
    }

    public AtomicInteger getVersion() {
        return version;
    }

    public void setVersion(AtomicInteger version) {
        this.version = version;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SimpleBook that = (SimpleBook) o;
        return
                Objects.equals(version, that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(version);
    }

    @Override
    public String toString() {
        return "OptionalExample{" +
                ", version=" + version +
                '}';
    }
}


text:
.. _zendservice.rackspace.files:

Zend\\Service\\Rackspace\\Files
===============================

.. _zendservice.rackspace.files.intro:

Overview
--------

The ``ZendService\Rackspace\Files`` is a class that provides a simple *API* to manage the `Rackspace Cloud
Files`_.

.. _zendservice.rackspace.files.quick-start:

Quick Start
-----------

To use this class you have to pass the username and the API's key of Rackspace in the construction of the class.

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user,$key);

A container is a storage compartment for your data and provides a way for you to organize your data. You can think
of a container as a folder in Windows® or a directory in UNIX®. The primary difference between a container and
these other file system concepts is that containers cannot be nested. You can, however, create an unlimited number
of containers within your account. Data must be stored in a container so you must have at least one container
defined in your account prior to uploading data.

The only restrictions on container names is that they cannot contain a forward slash (/) and must be less than 256
bytes in length (please note that the length restriction applies to the name using the URL encoded format).

The containers are managed using the class ``ZendService\Rackspace\Files\Container``.

An object (file) is the basic storage entity and any optional metadata that represents the files you store in the
Cloud Files system. When you upload data to Cloud Files, the data is stored as-is (no compression or encryption)
and consists of a location (container), the object's name, and any metadata consisting of key/value pairs. For
instance, you may chose to store a backup of your digital photos and organize them into albums. In this case, each
object could be tagged with metadata such as Album : Caribbean Cruise or Album : Aspen Ski Trip.

The only restriction on object names is that they must be less than 1024 bytes in length after URL encoding. Cloud
Files has a limit on the size of a single uploaded object; by default this is 5 GB. For metadata, you should not
exceed 90 individual key/value pairs for any one object and the total byte length of all key/value pairs should not
exceed 4KB (4096 bytes).

The objects are managed using the class ``ZendService\Rackspace\Files\Object``.

To create a new container you can use the **createContainer** method.

.. code-block:: php
   :linenos:

   $container= $rackspace->createContainer('test');

   if (!$rackspace->isSuccessful()) {
       die('ERROR: '.$rackspace->getErrorMsg());
   }

   printf("Name: %s",$container->getName());

This example create a container with name **test**. The result of **createContainer** is a new instance of
``ZendService\Rackspace\Files\Container``.

To store an object (file) in a container you can use the **storeObject** method.

.. code-block:: php
   :linenos:

   $name= 'example.jpg';
   $file= file_get_contents($name);

   $metadata= array (
       'foo' => 'bar'
   );

   $rackspace->storeObject('test',$name,$file,$metadata);

   if ($rackspace->isSuccessful()) {
       echo 'Object stored successfully';
   } else {
       printf("ERROR: %s",$rackspace->getErrorMsg());
   }

This example store a file image **example.jpg** in the container **test** with the metadata specified in the array
**$metadata**.

To delete an object (file) you can use the **deleteObject** method.

.. code-block:: php
   :linenos:

   $rackspace->deleteObject('test','example.jpg');

   if ($rackspace->isSuccessful()) {
       echo 'Object deleted successfully';
   } else {
       printf("ERROR: %s",$rackspace->getErrorMsg());
   }

This example delete the object **example.jpg** in the container **test**.

To publish a container as *CDN* (Content Delivery Network) you can use the **enableCdnContainer** method.

.. code-block:: php
   :linenos:

   $cdnInfo= $rackspace->enableCdnContainer('test');

   if ($rackspace->isSuccessful()) {
       print_r($cdnInfo);
   } else {
       printf("ERROR: %s",$rackspace->getErrorMsg());
   }

This example publish the container **test** as *CDN*. If the operation is successfull returns an associative arrays
with the following values:

- **cdn_uri**, the url of the CDN container;

- **cdn_uri_ssl**, the ssl url of the CDN container;

.. _zendservice.rackspace.files.methods:

Available Methods
-----------------

.. _zendservice.rackspace.files.methods.copy-object:

**copyObject**
   ``copyObject(string $container_source,string $obj_source,string $container_dest,string $obj_dest,$metadata=array(),string $content_type=null)``

   Copy an object from a container to another. The return is **true** in case of success and **false** in case of
   error.

   The **$container_source** is the name of the source container.

   The **$obj_source** is the name of the source object.

   The **$container_dest** is the name of the destination container.

   The **$obj_dest** is the name of the destination object.

   The **$metadata** array contains the metadata information related to the destination object.

   The **$content_type** is the optional content type of the destination object (file).

.. _zendservice.rackspace.files.methods.create-container:

**createContainer**
   ``createContainer(string $container, $metadata=array())``

   Create a container. The return is an instance of ``ZendService\Rackspace\Files\Container``. In case of error
   the return is **false**.

   The **$container** is the name of the container to create.

   The **$metadata** array contains the metadata information related to the container.

.. _zendservice.rackspace.files.methods.delete-container:

**deleteContainer**
   ``deleteContainer(string $container)``

   Delete a container. The return is **true** in case of success and **false** in case of error.

   The **$container** is the name of the container to delete.

.. _zendservice.rackspace.files.methods.delete-object:

**deleteObject**
   ``deleteObject(string $container,string $object)``

   Delete an object in a specific container. Return **true** in case of success, **false** in case of error.

   The **$container** is the name of the container.

   The **$object** is the name of the object to delete.

.. _zendservice.rackspace.files.methods.enable-cdn-container:

**enableCdnContainer**
   ``enableCdnContainer(string $container,integer $ttl=900)``

   Publish a container as *CDN* (Content Delivery Network). Return an associative array contains the CDN url and
   SSL url. In case of error the return is **false**.

   The **$container** is the name of the container.

   The **$ttl** is the time to live for the CDN cache content. The default value is 15 minutes (900 seconds). The
   minimum TTL that can be set is 15 minutes (900 seconds); the maximum TTL is 50 years (range of 900 to 1577836800
   seconds).

.. _zendservice.rackspace.files.methods.get-cdn-containers:

**getCdnContainers**
   ``getCdnContainers($options=array())``

   Returns all the CDN containers available. The return is an instance of
   ``ZendService\Rackspace\Files\ContainerList``. In case of error the return is **false**.

   The **$options** contains the following optional parameters:

      - **limit**, for an integer value n, limits the number of results to at most n values.

      - **marker**, given a string value x, return object names greater in value than the specified marker.

.. _zendservice.rackspace.files.methods.get-containers:

**getContainers**
   ``getContainers($options=array())``

   Returns all the containers available. The return is an instance of
   ``ZendService\Rackspace\Files\ContainerList`` In case of error the return is **false**.

   The **$options** contains the following optional parameters:

      - **limit**, for an integer value n, limits the number of results to at most n values.

      - **marker**, given a string value x, return object names greater in value than the specified marker.

.. _zendservice.rackspace.files.methods.get-container:

**getContainer**
   ``getContainer(string $container)``

   Returns the container specified as instance of ``ZendService\Rackspace\Files\Container`` In case of error the
   return is **false**.

   The **$container** is the name of the container.

.. _zendservice.rackspace.files.methods.get-count-containers:

**getCountContainers**
   ``getCountContainers()``

   Return the total count of containers.

.. _zendservice.rackspace.files.methods.get-count-objects:

**getCountObjects**
   ``getCountObjects()``

   Return the count of objects contained in all the containers.

.. _zendservice.rackspace.files.methods.get-info-cdn-container:

**getInfoCdnContainer**
   ``getInfoCdnContainer(string $container)``

   Get the information of a CDN container. The result is an associative array with all the CDN information. In case
   of error the return is **false**.

   The **$container** is the name of the container.

.. _zendservice.rackspace.files.methods.get-info-containers:

**getInfoContainers**
   ``getInfoContainers()``

   Get the information about all the containers available. Return an associative array with the following values:

      - **tot_containers**, the total number of containers stored

      - **size_containers**, the total size, in byte, of all the containers.

      - **tot_objects**, the total number of objects (file) stored in all the containers.

   In case of error the return is **false**.

.. _zendservice.rackspace.files.methods.get-metadata-container:

**getMetadataContainer**
   ``getMetadataContainer(string $container)``

   Get the metadata information of a container. The result is an associative array with all the metadata
   keys/values. In case of error the return is **false**.

   The **$container** is the name of the container.

.. _zendservice.rackspace.files.methods.get-metadata-object:

**getMetadataObject**
   ``getMetadataObject(string $container, string $object)``

   Get the metadata information of an object. The result is an associative array with all the metadata keys/values.
   In case of error the return is **false**.

   The **$container** is the name of the container.

   The **$object** is the name of the object.

.. _zendservice.rackspace.files.methods.get-objects:

**getObjects**
   ``getObjects(string $container, $options=array())``

   Returns all the objects of a container. The return is an instance of ``ZendService\Rackspace\Files\ObjectList``
   In case of error the return is **false**.

   The **$container** is the name of the container.

   The **$options** contains the following optional parameters:

      - **limit**, for an integer value n, limits the number of results to at most n values.

      - **marker**, given a string value x, return object names greater in value than the specified marker.

      - **prefix**, for a string value x, causes the results to be limited to object names beginning with the
        substring x.

      - **path**, for a string value x, return the object names nested in the pseudo path.

      - **delimiter**, for a character c, return all the object names nested in the container (without the need for
        the directory marker objects).

.. _zendservice.rackspace.files.methods.get-object:

**getObject**
   ``getObject(string $container, string $object, $headers=array())``

   Returns an object of a container. The return is an instance of ``ZendService\Rackspace\Files\Object`` In case
   of error the return is **false**.

   The **$container** is the name of the container.

   The **$object** is the name of the object.

   The **$headers** contains the following optional parameters (See the `RFC-2616`_ for more info):

      - **If-Match**, a client that has one or more entities previously obtained from the resource can verify that
        one of those entities is current by including a list of their associated entity tags in the If-Match header
        field.

      - **If-None-Match**, a client that has one or more entities previously obtained from the resource can verify
        that none of those entities is current by including a list of their associated entity tags in the
        If-None-Match header field.

      - **If-Modified-Since**, if the requested variant has not been modified since the time specified in this
        field, an entity will not be returned from the server.

      - **If-Unmodified-Since**, if the requested resource has not been modified since the time specified in this
        field, the server SHOULD perform the requested operation as if the If-Unmodified-Since header were not
        present.

      - **Range**, Rackspace supports a sub-set of Range and do not adhere to the full RFC-2616 specification. We
        support specifying OFFSET-LENGTH where either OFFSET or LENGTH can be optional (not both at the same time).
        The following are supported forms of the header:

           - **Range: bytes=-5**, last five bytes of the object

           - **Range: bytes=10-15**, the five bytes after a 10-byte offset

           - **Range: bytes=32-**, all data after the first 32 bytes of the object

.. _zendservice.rackspace.files.methods.get-size-containers:

**getSizeContainers**
   ``getSizeContainers()``

   Return the size, in bytes, of all the containers.

.. _zendservice.rackspace.files.methods.set-metadata-object:

**setMetadataObject**
   ``setMetadataObject(string $container,string $object, array $metadata)``

   Update metadata information to the object (all the previous metadata will be deleted). Return **true** in case
   of success, **false** in case of error.

   The **$container** is the name of the container.

   The **$object** is the name of the object to store.

   The **$metadata** array contains the metadata information related to the object.

.. _zendservice.rackspace.files.methods.store-object:

**storeObject**
   ``storeObject(string $container,string $object,string $file,$metadata=array())``

   Store an object in a specific container. Return **true** in case of success, **false** in case of error.

   The **$container** is the name of the container.

   The **$object** is the name of the object to store.

   The **$file** is the content of the object to store.

   The **$metadata** array contains the metadata information related to the object to store.

.. _zendservice.rackspace.files.methods.update-cdn-container:

**updateCdnContainer**
   ``updateCdnContainer(string $container,integer $ttl=null,$cdn_enabled=null,$log=null)``

   Update the attribute of a *CDN* container. Return an associative array contains the CDN url and SSL url. In case
   of error the return is **false**.

   The **$container** is the name of the container.

   The **$ttl** is the time to live for the CDN cache content. The default value is 15 minutes (900 seconds). The
   minimum TTL that can be set is 15 minutes (900 seconds); the maximum TTL is 50 years (range of 900 to 1577836800
   seconds).

   The **$cdn_enabled** is the flag to swith on/off the CDN. **True** switch on, **false** switch off.

   The **$log** enable or disable the log retention. **True** switch on, **false** switch off.

.. _zendservice.rackspace.files.examples:

Examples
--------

.. _zendservice.rackspace.files.examples.authenticate:

.. rubric:: Authenticate

Check if the username and the key are valid for the Rackspace authentication.

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user,$key);

   if ($rackspace->authenticate()) {
       printf("Authenticated with token: %s",$rackspace->getToken());
   } else {
       printf("ERROR: %s",$rackspace->getErrorMsg());
   }

.. _zendservice.rackspace.files.examples.get-object:

.. rubric:: Get an object

Get an image file (**example.gif**) from the cloud and render it in the browser

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user,$key);

   $object= $rackspace->getObject('test','example.gif');

   if (!$rackspace->isSuccessful()) {
       die('ERROR: '.$rackspace->getErrorMsg());
   }

   header('Content-type: image/gif');
   echo $object->getFile();

.. _zendservice.rackspace.files.examples.create-container:

.. rubric:: Create a container with metadata

Create a container (**test**) with some metadata information (**$metadata**)

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user,$key);

   $metadata= array (
       'foo'  => 'bar',
       'foo2' => 'bar2',
   );

   $container= $rackspace->createContainer('test',$metadata);

   if ($rackspace->isSuccessful()) {
       echo 'Container created successfully';
   }

.. _zendservice.rackspace.files.examples.get-metadata-container:

.. rubric:: Get the metadata of a container

Get the metadata of the container **test**

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user, $key);

   $container= $rackspace->getContainer('test');

   if (!$rackspace->isSuccessful()) {
       die('ERROR: ' . $rackspace->getErrorMsg());
   }

   $metadata= $container->getMetadata();
   print_r($metadata);

.. _zendservice.rackspace.files.examples.store-object-container:

.. rubric:: Store an object in a container

Store an object using a ``ZendService\Rackspace\Files\Container`` instance

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user, $key);

   $container= $rackspace->getContainer('test');

   if (!$rackspace->isSuccessful()) {
       die('ERROR: ' . $rackspace->getErrorMsg());
   }

   $file     = file_get_contents('test.jpg');
   $metadata = array (
       'foo' => 'bar',
   );

   if ($container->addObject('test.jpg', $file, $metadata)) {
       echo 'Object stored successfully';
   }

.. _zendservice.rackspace.files.examples.check-cdn-enabled:

.. rubric:: Check if a container is CDN enabled

Check if the **test** container is CDN enabled. If it is not we enable it.

.. code-block:: php
   :linenos:

   $user = 'username';
   $key  = 'secret key';

   $rackspace = new ZendService\Rackspace\Files($user, $key);

   $container= $rackspace->getContainer('test');

   if (!$rackspace->isSuccessful()) {
       die('ERROR: ' . $rackspace->getErrorMsg());
   }

   if (!$container->isCdnEnabled()) {
       if (!$container->enableCdn()) {
           die('ERROR: ' . $rackspace->getErrorMsg());
       }
   }
   printf(
       "The container is CDN enabled with the following URLs:\n %s\n %s\n",
       $container->getCdnUri(),
       $container->getCdnUriSsl()
   );

.. _`Rackspace Cloud Files`: http://www.rackspace.com/cloud/cloud_hosting_products/files/
.. _`RFC-2616`: http://www.ietf.org/rfc/rfc2616.txt


text:
@interface SVViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation SVViewController
@synthesize tableView = tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupDataSource];

    __weak SVViewController *weakSelf = self;

    // setup pull-to-refresh
    [self.tableView addRefreshControlWithActionHandler:^{
        NSLog(@"refresh top");
        [weakSelf insertRowAtTop];
    }];

    // setup infinite scrolling
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        NSLog(@"refresh bottom");
        [weakSelf insertRowAtBottom];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
//    [tableView triggerPullToRefresh];
}

#pragma mark - Actions

- (void)setupDataSource {
    self.dataSource = [NSMutableArray array];
    for(int i=0; i<4; i++)
        [self.dataSource addObject:[NSDate dateWithTimeIntervalSinceNow:-(i*90)]];
}

- (void)insertRowAtTop {
    __weak SVViewController *weakSelf = self;

    int64_t delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [weakSelf.tableView beginUpdates];
        [weakSelf.dataSource insertObject:[NSDate date] atIndex:0];
        [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
        [weakSelf.tableView endUpdates];

        [weakSelf.tableView.refreshControlOD endRefreshing];
    });
}

- (void)insertRowAtBottom {
    __weak SVViewController *weakSelf = self;

    int64_t delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [weakSelf.tableView beginUpdates];
        [weakSelf.dataSource addObject:[weakSelf.dataSource.lastObject dateByAddingTimeInterval:-90]];
        [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:weakSelf.dataSource.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        [weakSelf.tableView endUpdates];

        [weakSelf.tableView.infiniteScrollingView stopAnimating];
    });
}
#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

    NSDate *date = [self.dataSource objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterMediumStyle];
    return cell;
}

@end