text:
package rest

import (
	"net"
	"net/http"
	"net/url"
	"strings"

	"github.com/gorilla/mux"
	"github.com/inconshreveable/log15"

	"github.com/nsec/askgod/internal/config"
	"github.com/nsec/askgod/internal/database"
)

var clusterPeers []string

// AttachFunctions attaches all the REST API functions to the provided router
func AttachFunctions(config *config.Config, router *mux.Router, db *database.DB, logger log15.Logger) error {
	r := rest{
		config: config,
		db:     db,
		logger: logger,
		router: router,
	}

	// Update the list of hidden teams
	err := r.configHiddenTeams()
	if err != nil {
		return err
	}

	// Guest API
	r.registerEndpoint("/", "guest", r.getRoot, nil, nil, nil)
	r.registerEndpoint("/1.0", "guest", r.getStatus, nil, nil, nil)

	r.registerEndpoint("/1.0/events", "guest", r.getEvents, r.injectEvents, nil, nil)

	r.registerEndpoint("/1.0/scoreboard", "guest", r.getScoreboard, nil, nil, nil)
	r.registerEndpoint("/1.0/timeline", "guest", r.getTimeline, nil, nil, nil)

	// Team API
	r.registerEndpoint("/1.0/team", "team", r.getTeam, nil, r.updateTeam, nil)
	r.registerEndpoint("/1.0/team/flags", "team", r.getTeamFlags, r.submitTeamFlag, nil, nil)
	r.registerEndpoint("/1.0/team/flags/{id}", "team", r.getTeamFlag, nil, r.updateTeamFlag, nil)

	// Admin API
	r.registerEndpoint("/1.0/config", "admin", r.getConfig, nil, r.updateConfig, nil)

	r.registerEndpoint("/1.0/flags", "admin", r.adminGetFlags, r.adminCreateFlag, nil, r.adminClearFlags)
	r.registerEndpoint("/1.0/flags/{id}", "admin", r.adminGetFlag, nil, r.adminUpdateFlag, r.adminDeleteFlag)

	r.registerEndpoint("/1.0/scores", "admin", r.adminGetScores, r.adminCreateScore, nil, r.adminClearScores)
	r.registerEndpoint("/1.0/scores/{id}", "admin", r.adminGetScore, nil, r.adminUpdateScore, r.adminDeleteScore)

	r.registerEndpoint("/1.0/teams", "admin", r.adminGetTeams, r.adminCreateTeam, nil, r.adminClearTeams)
	r.registerEndpoint("/1.0/teams/{id}", "admin", r.adminGetTeam, nil, r.adminUpdateTeam, r.adminDeleteTeam)

	// Setup forwarder
	for _, peer := range config.Daemon.ClusterPeers {
		u, err := url.ParseRequestURI(peer)
		if err != nil {
			r.logger.Error("Unable to parse peer address", log15.Ctx{"peer": peer, "error": err})
			return err
		}

		host, _, err := net.SplitHostPort(u.Host)
		if err != nil {
			r.logger.Error("Unable to parse peer host", log15.Ctx{"peer": peer, "error": err})
			return err
		}

		peerIP := net.ParseIP(strings.Trim(host, "[]"))
		if peerIP != nil {
			clusterPeers = append(clusterPeers, peerIP.String())
		} else {
			addr, err := net.LookupHost(host)
			if err != nil {
				r.logger.Error("Unable to resolve peer to addr", log15.Ctx{"peer": peer, "error": err})
				return err
			}
			clusterPeers = append(clusterPeers, addr...)
		}

		go r.forwardEvents(peer)
	}

	return nil
}

func (r *rest) registerEndpoint(url string, access string, funcGet, funcPost, funcPut, funcDelete func(writer http.ResponseWriter, request *http.Request, logger log15.Logger)) {
	r.router.HandleFunc(url, func(writer http.ResponseWriter, request *http.Request) {
		metricRequests.Inc()

		if !r.hasAccess(access, request) {
			r.errorResponse(403, "Forbidden", writer, request)
			return
		}

		r.logger.Debug("Request received", log15.Ctx{"method": request.Method, "url": request.URL, "client": request.RemoteAddr})
		logger := r.logger.New("method", request.Method, "url", request.URL, "client", request.RemoteAddr)

		// Process the Origin header
		r.processOrigin(writer, request)

		// Process OPTIONS
		if request.Method == "OPTIONS" {
			return
		}

		switch request.Method {
		case "GET":
			if funcGet != nil {
				funcGet(writer, request, logger)
				return
			}
		case "POST":
			if funcPost != nil {
				funcPost(writer, request, logger)
				return
			}
		case "PUT":
			if funcPut != nil {
				funcPut(writer, request, logger)
				return
			}
		case "DELETE":
			if funcDelete != nil {
				funcDelete(writer, request, logger)
				return
			}
		}

		r.logger.Info("Bad request (not implemented)", log15.Ctx{"method": request.Method, "url": request.URL, "client": request.RemoteAddr})
		r.errorResponse(501, "Not Implemented", writer, request)
		return
	})
}


text:
/**
 * @file
 * @author  Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
 * @brief   Execute utils
 */

#include "config.hpp"

#include "cargo-utils/exception.hpp"
#include "cargo-utils/execute.hpp"
#include "cargo-logger/logger.hpp"

#include <iostream>

#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

namespace utils {

namespace {

const uid_t UNSPEC_UID = static_cast<uid_t>(-1);

__attribute__((unused)) std::ostream& operator<< (std::ostream& out, const char* const* argv)
{
    if (*argv) {
        argv++; //skip
    }
    while (*argv) {
        out << " '" << *argv++ << "'";
    }
    return out;
}

bool isExecutionSuccessful(int status)
{
    if (!WIFEXITED(status)) {
        if (WIFSIGNALED(status)) {
            LOGE("Child terminated by signal, signal: " << WTERMSIG(status));
        } else if (WIFSTOPPED(status)) {
            LOGW("Child was stopped by signal " << WSTOPSIG(status));
        } else {
            LOGE("Child exited abnormally, status: " << status);
        }
        return false;
    }
    if (WEXITSTATUS(status) != EXIT_SUCCESS) {
        LOGE("Child exit status: " << WEXITSTATUS(status));
        return false;
    }
    return true;
}

} // namespace

bool executeAndWait(const std::function<void()>& func, int& status)
{
    LOGD("Execute child process");

    pid_t pid = ::fork();
    if (pid == -1) {
        LOGE("Fork failed: " << getSystemErrorMessage());
        return false;
    }
    if (pid == 0) {
        func();
        ::_exit(EXIT_SUCCESS);
    }
    return waitPid(pid, status);
}

bool executeAndWait(const std::function<void()>& func)
{
    int status;
    if (!executeAndWait(func, status)) {
        return false;
    }
    return isExecutionSuccessful(status);
}

bool executeAndWait(const uid_t uid, const char* fname, const char* const* argv, int& status)
{
    LOGD("Execute " << (uid == UNSPEC_UID ? "" : "as " + std::to_string(uid) + " ") << fname << argv);

    pid_t pid = ::fork();
    if (pid == -1) {
        LOGE("Fork failed: " << getSystemErrorMessage());
        return false;
    }

    if (pid == 0) {
        if (uid != UNSPEC_UID && ::setuid(uid) < 0) {
            LOGW("Failed to become uid(" << uid << "): " << getSystemErrorMessage());
            ::_exit(EXIT_FAILURE);
        }
        ::execv(fname, const_cast<char* const*>(argv));
        LOGE("execv(" << fname << ") failed: " << getSystemErrorMessage());
        ::_exit(EXIT_FAILURE);
    }
    return waitPid(pid, status);
}

bool executeAndWait(const char* fname, const char* const* argv, int& status)
{
    return executeAndWait(UNSPEC_UID, fname, argv, status);
}

bool executeAndWait(const char* fname, const char* const* argv)
{
    int status;
    if (!executeAndWait(UNSPEC_UID, fname, argv, status)) {
        return false;
    }
    return isExecutionSuccessful(status);
}

bool waitPid(pid_t pid, int& status)
{
    LOGD("Wait pid " << pid);

    while (::waitpid(pid, &status, 0) == -1) {
        if (errno != EINTR) {
            LOGE("waitpid() failed: " << getSystemErrorMessage());
            return false;
        }
    }
    return true;
}

bool executeAndWait(const uid_t uid, const std::vector<std::string>& argv, int& status)
{
    std::vector<const char *> args;
    args.reserve(argv.size() + 1);

    for (const auto& arg : argv) {
        args.push_back(arg.c_str());
    }
    args.push_back(nullptr);

    return executeAndWait(uid, args[0], args.data(), status);
}

bool executeAndWait(const uid_t uid, const std::vector<std::string>& argv)
{
    int status;
    if (!executeAndWait(uid, argv, status)) {
        return false;
    }
    return isExecutionSuccessful(status);
}

bool executeAndWait(const std::vector<std::string>& argv)
{
    return executeAndWait(UNSPEC_UID, argv);
}

} // namespace utils

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <title>flowbased-polymer demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">

<flow-repeat >

Use flow-repeat to repeat Arrays

    <demo-snippet>
        <template>
            <flow-bind id="elem">
                <template>

                    <data-maker @-data="--newData"></data-maker>

                        <flow-repeat  ƒ-inject-items="--newData"
                                     internal-wire="--itemInjected">
                            <template>

                                    neu
                                    <rep-item ƒ-raw="--itemInjected" @-click="--xx"></rep-item>
                                    <rep-item ƒ-index="--itemInjected(*.index)" ƒ-yy="--xx" ></rep-item>

                                    <flow-repeat ƒ-inject-items="--itemInjected(*.item.arr)" internal-wire="--item">
                                        <template>

                                        </template>
                                    </flow-repeat>

                            </template>
                        </flow-repeat>

                </template>
            </flow-bind>
        </template>

    </demo-snippet>

<template is="flow-repeat" >

Use flow-repeat to repeat Arrays

    <demo-snippet>
        <template>
            <flow-bind id="elem">
                <template>

                    <data-maker @-data="--newData"></data-maker>
                    <data-maker @-data="--newData" data="[3,5,7,2]"></data-maker>

                                <template is="flow-repeat" ƒ-inject-items="--newData" internal-wire="--itemInjected">

                                        <rep-item ƒ-raw="--itemInjected" @-click="--xx"></rep-item>
                                        <rep-item ƒ-index="--itemInjected(*.index)" ƒ-yy="--xx"></rep-item>
                                        <flow-repeat ƒ-inject-items="--itemInjected(*.item.arr)" internal-wire="--item">
                                            <template>

                                            </template>
                                        </flow-repeat>

                                </template>

                </template>
            </flow-bind>
        </template>

    </demo-snippet>


text:
require('./angular-locale_nus-sd');
module.exports = 'ngLocale';


text:
<?php
namespace App\Views\Components\Heads;
use Pure\Utils\DynamicHtml;
use Pure\Utils\Res;
?>

<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
	<?= DynamicHtml::link_favicon('favicon.ico'); ?>
	<title> <?= Res::str('app_title') ?> </title>

	<!-- Bootstrap -->
	<?= DynamicHtml::link_css('bootstrap.min.css'); ?>

	<?php if(PURE_ENV === 'production'): ?>
		<?= DynamicHtml::link_css('minimal.min.css') ?>
		<?= DynamicHtml::link_css('ufrgs.min.css') ?>
	<?php else: ?>
		<?= DynamicHtml::link_css('minimal.css') ?>
		<?= DynamicHtml::link_css('ufrgs.css') ?>
	<?php endif; ?>

	<meta property="creator.productor" content="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/200000" />
</head>


text:
%w(mysql-client libmysqlclient-dev).each do |p|
  package p do
    action :install
  end
end


text:
.. djmail documentation master file, created by
   sphinx-quickstart on Sat Apr 20 22:16:45 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

djmail
======

Release v\ |version|.

djmail is a :ref:`BSD LIcensed <license>`, simple, powerful and nonobstructive django email
middleware.

Introduction
------------

djmail involves these features:

* Can send emails asynchronously (it integrates very well with celery)
* Can retry send failed email messages (with crond or celery periodic tasks)
* Can assign deliver priority to a email message.
* Provides a simple way to build email messages from templates.
* Works transparently for your or third party code.

User guide
----------

.. toctree::
   :maxdepth: 2

   quickstart.rst
   usage.rst
   settings.rst


text:
Ember.Handlebars.helper('x-log', function(value) {

	console.log(value);
	return '';
});

Ember.Handlebars.helper('format-date', function(value) {

	return moment(value).fromNow();
});


text:
//
//  GTLCalendarEvent.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Calendar API (calendar/v3)
// Description:
//   Manipulates events and other calendar data.
// Documentation:
//   https://developers.google.com/google-apps/calendar/firstapp
// Classes:
//   GTLCalendarEvent (0 custom class methods, 37 custom properties)
//   GTLCalendarEventCreator (0 custom class methods, 4 custom properties)
//   GTLCalendarEventExtendedProperties (0 custom class methods, 2 custom properties)
//   GTLCalendarEventGadget (0 custom class methods, 8 custom properties)
//   GTLCalendarEventOrganizer (0 custom class methods, 4 custom properties)
//   GTLCalendarEventReminders (0 custom class methods, 2 custom properties)
//   GTLCalendarEventSource (0 custom class methods, 2 custom properties)
//   GTLCalendarEventExtendedPropertiesPrivate (0 custom class methods, 0 custom properties)
//   GTLCalendarEventExtendedPropertiesShared (0 custom class methods, 0 custom properties)
//   GTLCalendarEventGadgetPreferences (0 custom class methods, 0 custom properties)

#import "GTLCalendarEvent.h"

#import "GTLCalendarEventAttachment.h"
#import "GTLCalendarEventAttendee.h"
#import "GTLCalendarEventDateTime.h"
#import "GTLCalendarEventReminder.h"

// ----------------------------------------------------------------------------
//
//   GTLCalendarEvent
//

@implementation GTLCalendarEvent
@dynamic anyoneCanAddSelf, attachments, attendees, attendeesOmitted, colorId,
         created, creator, descriptionProperty, end, endTimeUnspecified, ETag,
         extendedProperties, gadget, guestsCanInviteOthers, guestsCanModify,
         guestsCanSeeOtherGuests, hangoutLink, htmlLink, iCalUID, identifier,
         kind, location, locked, organizer, originalStartTime, privateCopy,
         recurrence, recurringEventId, reminders, sequence, source, start,
         status, summary, transparency, updated, visibility;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map = @{
    @"descriptionProperty" : @"description",
    @"ETag" : @"etag",
    @"identifier" : @"id"
  };
  return map;
}

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"attachments" : [GTLCalendarEventAttachment class],
    @"attendees" : [GTLCalendarEventAttendee class],
    @"recurrence" : [NSString class]
  };
  return map;
}

+ (void)load {
  [self registerObjectClassForKind:@"calendar#event"];
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventCreator
//

@implementation GTLCalendarEventCreator
@dynamic displayName, email, identifier, selfProperty;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map = @{
    @"identifier" : @"id",
    @"selfProperty" : @"self"
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventExtendedProperties
//

@implementation GTLCalendarEventExtendedProperties
@dynamic privateProperty, shared;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map = @{
    @"privateProperty" : @"private"
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventGadget
//

@implementation GTLCalendarEventGadget
@dynamic display, height, iconLink, link, preferences, title, type, width;
@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventOrganizer
//

@implementation GTLCalendarEventOrganizer
@dynamic displayName, email, identifier, selfProperty;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map = @{
    @"identifier" : @"id",
    @"selfProperty" : @"self"
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventReminders
//

@implementation GTLCalendarEventReminders
@dynamic overrides, useDefault;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"overrides" : [GTLCalendarEventReminder class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventSource
//

@implementation GTLCalendarEventSource
@dynamic title, url;
@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventExtendedPropertiesPrivate
//

@implementation GTLCalendarEventExtendedPropertiesPrivate

+ (Class)classForAdditionalProperties {
  return [NSString class];
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventExtendedPropertiesShared
//

@implementation GTLCalendarEventExtendedPropertiesShared

+ (Class)classForAdditionalProperties {
  return [NSString class];
}

@end

// ----------------------------------------------------------------------------
//
//   GTLCalendarEventGadgetPreferences
//

@implementation GTLCalendarEventGadgetPreferences

+ (Class)classForAdditionalProperties {
  return [NSString class];
}

@end


text:
### [Espresso Framework](http://espresso.github.com)

### Scalable Web Framework aimed at Speed and Simplicity

## Install

```bash
$ [sudo] gem install e
```

or update `Gemfile` by adding:

```ruby
gem 'e'
```

## Quick Start

**One-file App:**

```ruby
require 'e' # or Bundler.require

class App < E
  map '/'

  def index
    "Hello Espresso World!"
  end
end

App.run
```

**Full-fledged application using [Enginery](https://github.com/espresso/enginery)**

```bash
$ enginery g
$ ruby app.rb # or rackup
```

## Tutorial

### Intro

[Actions](https://github.com/espresso/espresso/blob/master/docs/Intro.md#actions) |
[Controllers](https://github.com/espresso/espresso/blob/master/docs/Intro.md#controllers) |
[Slices](https://github.com/espresso/espresso/blob/master/docs/Intro.md#slices) |
[MVC?](https://github.com/espresso/espresso/blob/master/docs/Intro.md#mvc) |
[Models?](https://github.com/espresso/espresso/blob/master/docs/Intro.md#models)

### Routing

[Base URL](https://github.com/espresso/espresso/blob/master/docs/Routing.md#base-url) |
[Canonicals](https://github.com/espresso/espresso/blob/master/docs/Routing.md#canonicals) |
[Actions](https://github.com/espresso/espresso/blob/master/docs/Routing.md#actions) |
[Action Mapping](https://github.com/espresso/espresso/blob/master/docs/Routing.md#action-mapping) |
[Action Aliases](https://github.com/espresso/espresso/blob/master/docs/Routing.md#action-aliases) |
[Shared Actions](https://github.com/espresso/espresso/blob/master/docs/Routing.md#shared-actions)

[Parametrization](https://github.com/espresso/espresso/blob/master/docs/Routing.md#parametrization) |
[Format](https://github.com/espresso/espresso/blob/master/docs/Routing.md#format) |
[RESTful Actions](https://github.com/espresso/espresso/blob/master/docs/Routing.md#restful-actions) |
[Hosts](https://github.com/espresso/espresso/blob/master/docs/Routing.md#hosts) |
[Rewriter](https://github.com/espresso/espresso/blob/master/docs/Routing.md#rewriter)

### Setup

[Global Setup](https://github.com/espresso/espresso/blob/master/docs/Setup.md#global-setup) |
[Setup by Name](https://github.com/espresso/espresso/blob/master/docs/Setup.md#setup-by-name) |
[Setup by Format](https://github.com/espresso/espresso/blob/master/docs/Setup.md#setup-by-format) |
[Remote Setup](https://github.com/espresso/espresso/blob/master/docs/Setup.md#remote-setup)

### Workflow

[Route](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#route) |
[Params](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#params) |
[Passing Control](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#passing-control) |
[Fetching Body](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#fetching-body) |
[Halt](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#halt) |
[Redirect](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#redirect) |
[Reload](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#reload) |
[Error Handlers](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#error-handlers) |
[Hooks](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#hooks) |
[Authorization](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#authorization) |
[Sessions](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#sessions) |
[Flash](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#flash) |
[Cookies](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#cookies) |
[Content Type](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#content-type) |
[Charset](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#charset) |
[Cache Control](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#cache-control) |
[Expires](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#expires) |
[Last Modified](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#last-modified) |
[Accepted Content Type](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#accepted-content-type) |
[Send File](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#send-file) |
[Send Files](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#send-files) |
[Attachment](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#attachment) |
[Headers](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#headers) |
[Helpers](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#helpers) |

### View API

[Engine](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#engine) |
[Extension](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#extension) |
[Templates Path](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#templates-path) |
[Layouts Path](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#layouts-path) |
[Layout](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#layout)

[Rendering Templates](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#rendering-templates) |
[Rendering Layouts](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#rendering-layouts) |
[Ad hoc Rendering](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#ad-hoc-rendering) |
[Path Resolver](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#path-resolver) |
[Templates Compilation](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#templates-compilation)

### Streaming

[Server-Sent Events](https://github.com/espresso/espresso/blob/master/docs/Streaming.md#server-sent-events) |
[WebSockets](https://github.com/espresso/espresso/blob/master/docs/Streaming.md#websockets) |
[Chunked Responses](https://github.com/espresso/espresso/blob/master/docs/Streaming.md#chunked-responses)

### Espresso Lungo

Extending Espresso functionality via [`Espresso Lungo`](https://github.com/espresso/espresso-lungo#espresso-lungo) gem:

Install:
```bash
$ gem install el
```

Load:
```ruby
require 'el'
```

Or simply add `gem 'el'` to Gemfile.

Functionality added by `Espresso Lungo`:

  CRUD |

  Assets |

  Content Helpers |

  Tag Factory |

  Cache Manager

### Deploy

[Controllers](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#controllers) |
[Slices](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#slices) |
[Roots](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#roots) |
[Arbitrary Applications](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#arbitrary-applications) |
[Run](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#run) |
[config.ru](https://github.com/espresso/espresso/blob/master/docs/Deploy.md#configru)

# Highlights / Motivation

Performance
---

In terms of performance, the only really important thing for any framework it is to add as low overhead as possible.

The overhead are the time consumed by framework to accept the request then prepare and send response.

The tests that follows will allow to disclose the overhead added by various frameworks.

The overhead are calculated by dividing 1000 milliseconds to **framework's standard speed**.

The **framework's standard speed** are the speed of a "HelloWorld" app running on top of given framework.

The **framework's standard speed** means nothing by itself. It is only used to calculate the framework's overhead.

Tested apps will run on `Thin` web server and will return a trivial "Hello World!" response.

Hardware used:

    Processor Name: Intel Core i5
    Processor Speed: 3.31 GHz
    Number of Processors: 1
    Total Number of Cores: 4
    Memory: 8 GB

To run tests on your hardware, clone Espresso Framework repository and execute `rake overhead` inside it.

Test results:

    ---
             Speed    Overhead   1ms-app  5ms-app   10ms-app  20ms-app  50ms-app  100ms-app
    espresso  5518      0.18ms   847      193       98        49        19        9
     sinatra  3629      0.28ms   783      189       97        49        19        9
       rails   792      1.26ms   442      159       88        47        19        9
    ---

**1ms-app** shows your app speed when your actions takes **1ms** to run.

**10ms-app** shows your app speed when your actions takes **10ms** to run.

etc.

The app speed are calculated as follow:

    1000 / (time taken by action + time taken by framework)

So, if your actions takes about 1ms and you use a framework with overhead of 0.18ms, the app speed will be:

    1000 / ( 1 + 0.18 ) = 847 requests per second

However, if framework's overhead is of **1ms** or more, the app speed will decrease dramatically:

    1000 / ( 1 + 1.26 ) = 442 requests per second

**Conclusions?**

The framework speed matter only if your code matter.

If you develop a site aimed to serve a serious amount of requests,
you should write actions that takes  insignificant amount of time.

Only after that it make sense to think about framework speed.

**Worth to Note** - Espresso has built-in [cache manager](https://github.com/espresso/espresso/blob/master/docs/Workflow.md#cache-manager)
as well as [views compiler](https://github.com/espresso/espresso/blob/master/docs/ViewAPI.md#templates-compilation).

These tools may help you to dramatically reduce the time consumed by your actions.

Natural Action/Routes/Params
---

I never understood why should i create actions in some file,
then open another file and directing requests to created action.

Even worse! To use params inside action, i have to remember how i named them in another file.
And when i want to change a param name i have to change it in both files?

What about consistency?

A good tradeoff would be to use some DSL.

```ruby
get '/book/:id' do
  params[:id]
end
```

Looks much better.

But! Strings/Regexps as action names? No, thanks.

What if i need to remount a bunch of actions to a new root?
Say from /news to /headlines? Refactoring? Using vars/constants in names? No, Thanks.

How do i setup multiple actions?

How do i find out the currently running action?

What if i do a request like "/book/100/?id=200"? What? Should i use unique param names? No, thanks.

etc. etc.

And why should i remember so many non-natural stuff?

Is not Ruby powerful enough? I guess it is:

```ruby
def book id

end
```

That's a regular **Ruby method** and it's regular **Espresso action**.

That's also an Espresso route. Yes, the app will respond to **"/book/100"**

And of course action params are used naturally, through method arguments(`id` rather than `params[:id]`).

All this offered by Ruby for free! Why to reinvent the wheel?

Expressive Setup
---

Usually you do not want to instruct each action about how it should behave.

It would take eras to define inside each action what content type should it return or what layout should it render.

Instead, you will use few lines of code at class level to write instructions that will be followed by all actions.

**Example:** Instruct **all** actions under `App` controller to return JSON Content-Type

```ruby
class App < E
  content_type '.json'
  # ...
end
```

But what if you need to setup only specific actions?

Simple! Put your setup, well, inside `setup` block and pass action names as parameters.

**Example:** Instruct **only** `rss` and `feed` actions to return XML Content-Type

```ruby
class App < E

  setup :rss, :feed do
    content_type :xml
  end
  # ...
end
```

Well, what if i need to setup for some 10 actions and another setup for another 20 actions?
Should i pass 30 arguments to `setup`? I do not want to buy a new keyboard every month...

That's simple too. Use regular expressions.

Ex: setup **only** news related actions:

```ruby
class App < E

  setup /news/ do
    # some setup
  end
  # ...
end
```

Slices
---

Portability and DRY done right and easy.

With Espresso, any controller can be mounted under any app.

Even more, any set of controllers - a.k.a. **slices** - can be mounted under any app.

To create a slice simply put your controllers under some module.

Then you can mount that module under any Espresso app.

Even more, when mounting you can easily setup all controllers(or some) at once.

And of course when mounting, you can give a mount point.

```ruby
require 'e'
require 'e-ext' # needed for `Cms.run` and `Cms.mount` to work

module Cms

  class Articles < E
    # ...
  end

  class News < E
    # ...
  end

  class Pages < E
    # ...
  end
end

app = Cms.mount do
  # some setup that will run inside each controller
end

# or
app = Cms.mount do |ctrl|
  # some setup that will run inside controllers that match `ctrl` param
end

app.run
```

RESTful Actions
---

By default, verbless actions will respond to any request type.

To make some action to respond only to some request type,
simply prepend the corresponding verb to the action name.

```ruby
# will respond to any request type
def book
  # ...
end

# GET
def get_book
  # ...
end

# POST
def post_book
  # ...
end

# PUT
def put_book
  # ...
end

# etc.
```

Flexible Rewriter
---

With Espresso built-in rewriter you can redirect any requests to new URL.

Beside trivial redirects rewriter can also pass the control to an arbitrary controller#action or simply halt the request and send the response.

Views Compiler
---

For most web sites, most time are spent at templates rendering. When rendering templates, most time are spent at reading and compiling.

Espresso allow to easily skip these expensive operations by keeping compiled templates in memory and just render them on consequent requests.

## Contributing

  - Fork Espresso repository
  - make your changes
  - submit a pull request

  Issues/Bugs:

    github.com/espresso/espresso/issues

  Mailing List:
  groups.google.com/.../espresso-framework

  IRC channel: #espressorb on irc.freenode.net

### Author - [Silviu Rusu](https://github.com/slivu).  License - [MIT](https://github.com/espresso/espresso/blob/master/LICENSE).


text:
package com.telrikk.archivist.storage

import java.lang.{Boolean, Long}

case class ScrollResult (
                          _scroll_id: String,
                          took: Long,
                          timed_out: Boolean,
                          _shards: ShardStatus,
                          hits: Hits)


text:
/*
 * SpectrumCircleTransformer.cpp
 *
 * Created on: Jul 30, 2015
 *     Author: dpayne
 */

#include "Domain/VisConstants.h"
#include "Utils/Logger.h"
#include "Utils/NcursesUtils.h"
#include "Transformer/SpectrumCircleTransformer.h"

namespace
{
}

vis::SpectrumCircleTransformer::SpectrumCircleTransformer(
    const Settings *const settings)
    : SpectrumTransformer(settings), m_settings{settings}
{
}

vis::SpectrumCircleTransformer::~SpectrumCircleTransformer()
{
}

void vis::SpectrumCircleTransformer::draw_bars(
    const std::vector<double> &bars, const std::vector<double> &bars_falloff,
    int32_t win_height, const bool flipped, const std::wstring &bar_row_msg,
    vis::NcursesWriter *writer)
{
    const auto half_height = win_height / 2.0;
    const auto half_width = NcursesUtils::get_window_width() / 2.0;

    // TODO(dpayne): add const everywhere and use min of half height or half
    // width
    const auto max_distance =
        std::sqrt(std::pow(half_height, 2) + std::pow(half_height, 2));

    for (auto i = 0u; i < bars.size(); ++i)
    {
        auto rad =
            (static_cast<double>(i) / static_cast<double>(win_height)) * 360.0;

        auto bar_height = std::max(bars_falloff[i], (half_height / 2.0));
        for (auto row_index = 0u; row_index < bar_height; ++row_index)
        {
            auto x = static_cast<int32_t>(std::cos(rad) * row_index);

            auto y = static_cast<int32_t>(std::sin(rad) * row_index);

            const auto distance = std::sqrt(std::pow(x, 2) + std::pow(y, 2));

            // TODO(dpayne): precompute colors
            const ColorIndex color_distance =
                writer->to_color_pair(static_cast<int32_t>(distance),
                                      static_cast<int32_t>(max_distance));

            x += half_height;
            y += half_width;

            // TODO(dpayne): if stereo just use 180 degrees
            if (flipped)
            {
                writer->write(x, y, color_distance, bar_row_msg,
                              m_settings->get_spectrum_character());
            }
            else
            {
                writer->write(y, x, color_distance, bar_row_msg,
                              m_settings->get_spectrum_character());
            }
        }
    }
}


text:
import React from "react";
import Collapsible from "react-collapsible";

const success = <Collapsible trigger="Click me">
Children
</Collapsible>;

// $FlowExpectedError
const error = <Collapsible>
I don't have a trigger prop
</Collapsible>;


text:
namespace webkit {
namespace npapi {
  class QtPluginContainerManager;
}
}

static const int kMaxWindowWidth = 4000;
static const int kMaxWindowHeight = 4000;
static const char* kRenderWidgetHostViewKey = "__RENDER_WIDGET_HOST_VIEW__";

class RenderWidgetHost;
struct NativeWebKeyboardEvent;

class VideoRendererWidget;
class PluginRendererWidget;

// -----------------------------------------------------------------------------
// See comments in render_widget_host_view.h about this class and its members.
// -----------------------------------------------------------------------------
class RenderWidgetHostViewQt : public RenderWidgetHostView,
                               public webkit::npapi::QtPluginContainerManagerHostDelegate {
 public:

  explicit RenderWidgetHostViewQt(RenderWidgetHost* widget);
  ~RenderWidgetHostViewQt();

  // Initialize this object for use as a drawing area.
  void InitAsChild();

  // RenderWidgetHostView implementation.
  virtual void InitAsPopup(RenderWidgetHostView* parent_host_view,
                           const gfx::Rect& pos);
  virtual void InitAsFullscreen() {DNOTIMPLEMENTED();}
  virtual RenderWidgetHost* GetRenderWidgetHost() const {return host_; }
  virtual void DidBecomeSelected();
  virtual void WasHidden();
  virtual void SetSize(const gfx::Size& size);
  virtual void SetPreferredSize(const gfx::Size& size);
  virtual gfx::NativeView GetNativeView();
  virtual void MovePluginWindows(
  const std::vector<webkit::npapi::WebPluginGeometry>& moves);
  virtual void Focus();
  virtual void Blur();
  virtual bool HasFocus();
  virtual void Show();
  virtual void Hide();
  virtual bool IsShowing();
  virtual gfx::Rect GetViewBounds() const;
  virtual void SetScrollPosition(const gfx::Point& pos);
  virtual void UpdateCursor(const WebCursor& cursor);
  virtual void SetIsLoading(bool is_loading);
  virtual void DidUpdateBackingStore(
      const gfx::Rect& scroll_rect, int scroll_dx, int scroll_dy,
      const std::vector<gfx::Rect>& copy_rects);
  virtual void RenderViewGone(base::TerminationStatus status,
                              int error_code);
  virtual void Destroy();
  virtual void WillDestroyRenderWidget(RenderWidgetHost* rwh) {};
  virtual void SetTooltipText(const std::wstring& tooltip_text);
  virtual void SelectionChanged(const std::string& text);
  virtual void ShowingContextMenu(bool showing);
  virtual BackingStore* AllocBackingStore(const gfx::Size& size);
  virtual void SetBackground(const SkBitmap& background);
  virtual void CreatePluginContainer(gfx::PluginWindowHandle id);
  virtual void DestroyPluginContainer(gfx::PluginWindowHandle id);
  virtual void SetVisuallyDeemphasized(const SkColor* color, bool animate);
  virtual bool ContainsNativeView(gfx::NativeView native_view) const;
  virtual void AcceleratedCompositingActivated(bool activated) {DNOTIMPLEMENTED();};
  virtual gfx::PluginWindowHandle GetCompositingSurface() {DNOTIMPLEMENTED();};
  virtual void ReleaseCompositingSurface(gfx::PluginWindowHandle surface) {DNOTIMPLEMENTED();};
  virtual void ImeUpdateTextInputState(WebKit::WebTextInputType, const gfx::Rect&);
  virtual void ImeCancelComposition();

#if defined(TOOLKIT_MEEGOTOUCH)
  virtual void SetBounds(const gfx::Rect& rect);
  virtual void SetScaleFactor(double factor);

  // this one is derived from QtPluginContainerManagerHostDelegate
  virtual void OnCloseFSPluginWindow(gfx::PluginWindowHandle id);

  virtual void UpdateWebKitNodeInfo(unsigned int node_info);
  virtual void UpdateSelectionRange(gfx::Point start, gfx::Point end, int height, bool set);

  ////////////////////////////////////////////////////////////
  // for tiled backing store
  virtual void UpdateContentsSize(const gfx::Size& size);
  virtual gfx::Size GetContentsSize();
  virtual gfx::Rect GetVisibleRect();

  virtual void DidBackingStoreScale();
  virtual void DidBackingStorePaint(const gfx::Rect& rect);

  virtual void PaintTileAck(unsigned int seq, unsigned int tag, const gfx::Rect& rect, const gfx::Rect& pixmap_rect);

  virtual void ScenePosChanged();

  gfx::Size CalPluginWindowSize();
  gfx::Size CalFSWinSize();

  virtual gfx::Size GetFSPluginWindowSize();

  void SetPluginWindowSize();
 ////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////

  //// for HW accelerated HTML5 video
  virtual void CreateVideoWidget(unsigned int id, const gfx::Size& size);
  virtual void UpdateVideoWidget(unsigned int id, unsigned int pixmap, const gfx::Rect& rect);
  virtual void EnableVideoWidget(unsigned int id, bool enabled);
  virtual void DestroyVideoWidgetPixmap(unsigned int id, unsigned int pixmap);
  virtual void DestroyVideoWidget(unsigned int id);

  // For compose flash embeded window
  virtual void ComposeEmbededFlashWindow(const gfx::Rect& rect);
  virtual void ReShowEmbededFlashWindow();

#if defined(PLUGIN_DIRECT_RENDERING)
  virtual void UpdatePluginWidget(unsigned int id,
                                  unsigned int pixmap,
                                  const gfx::Rect& rect,
                                  unsigned int seq);
  virtual void DestroyPluginWidget(unsigned int id);
#endif
  void DidPaintPluginWidget(unsigned int id, unsigned int ack);

#endif

  gfx::NativeView native_view() const {return view_;}

  void Paint(const gfx::Rect&);

  // Called by GtkIMContextWrapper to forward a keyboard event to renderer.
  // Before calling RenderWidgetHost::ForwardKeyboardEvent(), this method
  // calls GtkKeyBindingsHandler::Match() against the event and send matched
  // edit commands to renderer by calling
  // RenderWidgetHost::ForwardEditCommandsForNextKeyEvent().
  void ForwardKeyboardEvent(const NativeWebKeyboardEvent& event);

 private:
  friend class RWHVQtWidget;
  friend class RWHVQtWidgetView;

  // Returns whether the widget needs an input grab (GTK+ and X) to work
  // properly.
  bool NeedsInputGrab();

  // Returns whether this render view is a popup (<select> dropdown or
  // autocomplete window).
  bool IsPopup();

  // Update the display cursor for the render view.
  void ShowCurrentCursor();

  // The model object.
  RenderWidgetHost* host_;

  // The native UI widget.
  QGraphicsWidget* view_;
  QGraphicsWidget* parent_;

  // This is true when we are currently painting and thus should handle extra
  // paint requests by expanding the invalid rect rather than actually
  // painting.
  bool about_to_validate_and_paint_;

  // This is the rectangle which we'll paint.
  gfx::Rect invalid_rect_;

  // Whether or not this widget is hidden.
  bool is_hidden_;

  // Whether we are currently loading.
  bool is_loading_;
  // The cursor for the page. This is passed up from the renderer.
  WebCursor current_cursor_;

  // Whether we are showing a context menu.
  bool is_showing_context_menu_;

  // The time at which this view started displaying white pixels as a result of
  // not having anything to paint (empty backing store from renderer). This
  // value returns true for is_null() if we are not recording whiteout times.
  base::TimeTicks whiteout_start_time_;

  // The time it took after this view was selected for it to be fully painted.
  base::TimeTicks tab_switch_paint_time_;

  // If true, fade the render widget when painting it.
  bool visually_deemphasized_;

  // Variables used only for popups --------------------------------------------
  // Our parent widget.
  RenderWidgetHostView* parent_host_view_;
  // We ignore the first mouse release on popups.  This allows the popup to
  // stay open.
  bool is_popup_first_mouse_release_;

  // Whether or not this widget was focused before shadowed by another widget.
  // Used in OnGrabNotify() handler to track the focused state correctly.
  bool was_focused_before_grab_;

  // True if we are responsible for creating an X grab. This will only be used
  // for <select> dropdowns. It should be true for most such cases, but false
  // for extension popups.
  bool do_x_grab_;

  // The size that we want the renderer to be.  We keep this in a separate
  // variable because resizing in GTK+ is async.
  gfx::Size requested_size_;

  gfx::Size contents_size_;

  webkit::npapi::QtPluginContainerManager* plugin_container_manager_;

  gfx::Point scene_pos_;

  unsigned int webkit_node_info_;

  QMap<unsigned int, VideoRendererWidget* > video_widgets_map_;

#if defined(PLUGIN_DIRECT_RENDERING)
  QMap<unsigned int, PluginRendererWidget*> plugin_widgets_map_;
#endif
};

#endif  // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_QT_H_


text:
//
//  ArticleSectionController.m
//  AMSlideMenu
//
//  Created by dampier on 14-1-22.
//  Copyright (c) 2014年 Artur Mkrtchyan. All rights reserved.
//

#import "ArticleSectionController.h"
#import "AppDelegate.h"
#import "POSection.h"
#import "FCMapController.h"
#import "DaoArticle.h"
#import "POArticle.h"
#import <Social/Social.h>
#import <FacebookSDK/FacebookSDK.h>
#import "FCSettingVC.h"
#import <MediaPlayer/MediaPlayer.h>
#import "FSBasicImage.h"
#import "FSBasicImageSource.h"
#import "ShopCardVC.h"

@interface ArticleSectionController ()

@end

@implementation ArticleSectionController
{
    FCMapController *mapController;
    //播放模式,如果为yes,则动态滚动显示内容
    BOOL isPlayMode;
    AVAudioPlayer * _audioPlayer;
    NSTimer *_timer;
    //当前播放行号
    int index;
    int oldIndex;
    UIImage *mainImage;
    UIBarButtonItem *_shareButton;
    UIBarButtonItem *_mapButton;
    SLComposeViewController *slComposerSheet;
    NSArray * articles;
    //缓存Cell
    NSMutableDictionary *_cellCache;
    int CELL_CONTENT_WIDTH;
    MPMoviePlayerViewController *moviePlayer;
}
@synthesize masterkeyid, articleTitle, link_, caption_, picture_;
#define imageIdentifier  @"image"
#define textIdentifier  @"text"
#define positionIdentifier  @"position"
#define titleIdentifier  @"title"
#define relatedIdentifier  @"related"
#define videoIdentifier  @"video"
#define photoIdentifier  @"photos"
#define phoneIdentifier  @"phone"
#define emailIdentifier  @"email"
#define discountIdentifier  @"discount"

#define KeyVoiceType @"voicetype"

#define TITLEFONT_SIZE 17.0f
#define FONT_SIZE 16.0f
#define CELL_CONTENT_MARGIN 10.0f
#define RGB(r, g, b) [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:1.0]

#define TableTypeFC   @"fc"
#define Description @"iGuid, make your travel smart"

#pragma mark - LifeCycle

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initData];
    [self initView];
}

- (void) dealloc
{
    mapController = nil;
    masterkeyid = nil;
    articles = nil;
    _cellCache = nil;
    _timer = nil;
    _audioPlayer = nil;
    _shareButton = nil;
    slComposerSheet = nil;
    articleTitle = nil;
    link_= nil;
    caption_= nil;
    picture_ = nil;
    mainImage = nil;
    moviePlayer = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    //设置监控 每秒刷新一次时间
    if (isPlayMode) {
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.5f
                                                      target:self
                                                    selector:@selector(updateTime)
                                                    userInfo:nil
                                                     repeats:YES];
        }
//        [_timer setFireDate:[NSDate distantPast]];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
//    [_timer setFireDate:[NSDate distantFuture]];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [articles count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //获取缓存的Cell
    UITableViewCell *cell = [self getCellFromIndexPath:indexPath tableview:tableView];
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */
- (UITableViewCell *)getCellFromIndexPath:(NSIndexPath*)indexPath tableview:(UITableView *) tableView
{
    int row = indexPath.row;
//    UITableViewCell *cachedCell = [_cellCache objectForKey:@(row)];
//    if (cachedCell)
//    {
//        return cachedCell;
//    }

    UITableViewCell *cell;

    POSection *articleSection = articles[row];
    if ([articleSection.type isEqualToString:imageIdentifier]) {

        cell = [tableView dequeueReusableCellWithIdentifier:imageIdentifier];
        UIImageView *imageview = (UIImageView *)[cell viewWithTag:1];
        if (!mainImage) {
            mainImage = [UIImage imageNamed:articleSection.imagename];
        }
//        CGFloat height = CELL_CONTENT_WIDTH * mainImage.size.height /mainImage.size.width;
//        [imageview setFrame:CGRectMake(0, 0, CELL_CONTENT_WIDTH, height)];
//        [imageview setContentMode:UIViewContentModeScaleAspectFill];
        imageview.image = [UIImage imageNamed:articleSection.imagename];

    }
    if ([articleSection.type isEqualToString:textIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:textIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];

//        textview.font = [UIFont systemFontOfSize:FONT_SIZE];
//        [textview sizeToFit];

        [textview setLineBreakMode: NSLineBreakByWordWrapping];
//        [textview setMinimumFontSize:FONT_SIZE];
        [textview setNumberOfLines:0];
        [textview setFont:[UIFont systemFontOfSize:FONT_SIZE]];
//        [textview setTag:1];

//        [[textview layer] setBorderWidth:2.0f];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        NSString *text = articleSection.textcontent;
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        [textview setText: text];
        [textview setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height+ (CELL_CONTENT_MARGIN * 2), 33.0f))];
        [textview sizeToFit];
    }
    if ([articleSection.type isEqualToString:positionIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:positionIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];
        textview.text = articleSection.textcontent;
    }
    if ([articleSection.type isEqualToString:videoIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:videoIdentifier];
        UILabel *videoLabel = (UILabel *)[cell viewWithTag:1];
        [videoLabel setText:articleSection.textcontent];
    }
    if ([articleSection.type isEqualToString:titleIdentifier]) {
        cell = [tableView dequeueReusableCellWithIdentifier:titleIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];

        [textview setLineBreakMode: NSLineBreakByWordWrapping];
        [textview setMinimumFontSize:TITLEFONT_SIZE];
        [textview setNumberOfLines:0];
        [textview setFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE]];
//        [textview setTextColor:[UIColor whiteColor]];
        //        [textview setTag:1];

        //        [[textview layer] setBorderWidth:2.0f];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        NSString *text;
        if (articleSection.textcontent) {
            text = articleSection.textcontent;
        } else {
            text = articleTitle;
        };
        CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        [textview setText: text];
        [textview setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height+ (CELL_CONTENT_MARGIN * 2), 33.0f))];
        [textview sizeToFit];

        //添加渐变色
        CAGradientLayer *gradient = [CAGradientLayer layer];
        float ft = MAX(size.height+ (CELL_CONTENT_MARGIN * 2), 33.0f);
        [gradient setFrame: CGRectMake(0, 0, self.view.bounds.size.width, ft)];
        gradient.startPoint = CGPointMake(0, 0.5);
        gradient.endPoint = CGPointMake(1, 0.5);
        gradient.colors = [NSArray arrayWithObjects:
                           (id)RGB(236, 98, 51).CGColor,
                           (id)RGB(128, 0, 0).CGColor,
                           nil];

        UIView *tableBackgroundView = [[UIView alloc] init];
        [tableBackgroundView.layer insertSublayer:gradient atIndex:0];
        [cell setBackgroundView:tableBackgroundView];

//        if (cell.layer.sublayers.count <= 2) {
//            [cell.layer insertSublayer:gradient atIndex:0];
//            NSLog([NSString stringWithFormat:@"%@ %d", text, cell.layer.sublayers.count]);
//        }
    }
    if ([articleSection.type isEqualToString:relatedIdentifier]) {
        cell = [tableView dequeueReusableCellWithIdentifier:relatedIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];

        [textview setLineBreakMode: NSLineBreakByWordWrapping];
        [textview setMinimumFontSize:TITLEFONT_SIZE];
        [textview setNumberOfLines:0];
        [textview setFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE]];
//        [textview setTextColor:[UIColor whiteColor]];
        //        [textview setTag:1];

        //        [[textview layer] setBorderWidth:2.0f];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        NSString *text;
        if (articleSection.textcontent) {
            text = articleSection.textcontent;
        };
        CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        [textview setText: text];
        [textview setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 3), MAX(size.height+ (CELL_CONTENT_MARGIN * 2), 33.0f))];
        [textview sizeToFit];
    }
    if ([articleSection.type isEqualToString:phoneIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:phoneIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];
        textview.text = articleSection.textcontent;
    }
    if ([articleSection.type isEqualToString:emailIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:emailIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];
        textview.text = articleSection.textcontent;
    }
    if ([articleSection.type isEqualToString:photoIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:photoIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];
        textview.text = articleSection.textcontent;
    }
    if ([articleSection.type isEqualToString:discountIdentifier]){
        cell = [tableView dequeueReusableCellWithIdentifier:discountIdentifier];
        UILabel *textview = (UILabel *)[cell viewWithTag:1];
        textview.text = articleSection.textcontent;
    }
    //缓存Cell
//    [_cellCache setObject:cell forKey:@(row)];
    if (!cell) {
        NSLog(@"not have articleSection type '%@'", articleSection.type);
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = indexPath.row;
    POSection *articleSection = articles[row];
    CGSize size;

    if ([articleSection.type isEqualToString:textIdentifier]) {
//        POSection *articleSection = [articles objectAtIndex:[indexPath row]];
        NSString *text = articleSection.textcontent;

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        CGFloat height = size.height + (CELL_CONTENT_MARGIN * 2);

        text = nil;
        return MAX(height, 33.0f);
    }
    if ([articleSection.type isEqualToString:imageIdentifier]) {
        POSection *articleSection = [articles objectAtIndex:[indexPath row]];
        UIImage *image = [UIImage imageNamed:articleSection.imagename];
        if (image) {
            CGFloat height = CELL_CONTENT_WIDTH * image.size.height /image.size.width;
            return height;
        }
    }
    if ([articleSection.type isEqualToString:positionIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:positionIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:videoIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:videoIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:photoIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:videoIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:phoneIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:videoIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:emailIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:videoIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:discountIdentifier]) {
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:discountIdentifier];
        return tableViewCell.frame.size.height;
    }
    if ([articleSection.type isEqualToString:titleIdentifier]) {
        NSString *text;
        if (articleSection.textcontent) {
            text = articleSection.textcontent;
        } else {
            text = articleTitle;
        };

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        CGFloat height = size.height + (CELL_CONTENT_MARGIN * 2);

        text = nil;
        return MAX(height, 33.0f);
    }
    if ([articleSection.type isEqualToString:relatedIdentifier]) {
        NSString *text;
        if (articleSection.textcontent) {
            text = articleSection.textcontent;
        };

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 3), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Arial" size:TITLEFONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

        CGFloat height = size.height + (CELL_CONTENT_MARGIN * 2);

        text = nil;
        return MAX(height, 33.0f);
    }

    articleSection = nil;

    // 這裏返回需要的高度
    return size.height;
}

//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    POSection *poa = articles[indexPath.row];

    if ([poa.type isEqualToString:positionIdentifier]) {
//        if (!mapController) {
//            mapController = [self.storyboard instantiateViewControllerWithIdentifier:@"mapview"];
//        }
//        mapController.x = poa.positionx;
//        mapController.y = poa.positiony;

//        [self.navigationController pushViewController: mapController animated:(true)];
        if ([[UIApplication sharedApplication] canOpenURL:
             [NSURL URLWithString:@"comgooglemaps://"]]) {
            [[UIApplication sharedApplication] openURL:
             [NSURL URLWithString:[NSString stringWithFormat:@"comgooglemaps://?q=donghuamen&center=%f,%f", poa.positionx, poa.positiony]]];
        } else {
            NSString *path = [NSString stringWithFormat:@"http://maps.apple.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", poa.positionx, poa.positiony];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:path]];
        }
//        } else {
//                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                                 message:@"Sorry, you haven't installed Google Map"
//                                                                delegate:self
//                                                       cancelButtonTitle:@"OK"
//                                                       otherButtonTitles:nil];
//                 [alert show];
//
//                 NSLog(@"Can't use comgooglemaps://");
//        }
    }
    if ([poa.type isEqualToString:relatedIdentifier]) {
        ArticleSectionController *childController = [self.storyboard instantiateViewControllerWithIdentifier:@"articleSectionView"];
        DaoArticle *dao = [DaoArticle alloc];
        NSArray *section = [dao getArticleByID:poa.imagename];
        POArticle * relatedPO = [section objectAtIndex:0];

        childController.title = @"Mysteries Article";
        childController.articleTitle = relatedPO.title;
        childController.link_ = relatedPO.link;
        childController.picture_ = relatedPO.picture;
        childController.caption_ = relatedPO.caption;

        //SEL selector;
        childController.masterkeyid = relatedPO.primaryid;
        [self.navigationController pushViewController: childController animated:(true)];
    }

    if ([poa.type isEqualToString:videoIdentifier]) {
        NSString *filepath   =   [[NSBundle mainBundle] pathForResource:poa.imagename ofType:nil];
        NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];
//        moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
        MPMoviePlayerViewController *moviePlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
        moviePlayerView.moviePlayer.view.transform = CGAffineTransformConcat(moviePlayerView.moviePlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));
        moviePlayerView.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
        [self presentViewController:moviePlayerView animated:YES completion:^{}];
    }
    if ([poa.type isEqualToString:emailIdentifier]) {
        [self showEmail:poa.textcontent];
    }

    if ([poa.type isEqualToString:phoneIdentifier]) {
        UIDevice *device = [UIDevice currentDevice];
        if ([[device model] isEqualToString:@"iPhone"] ) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", poa.textcontent]]];
        }
    }
    if ([poa.type isEqualToString:discountIdentifier]) {
        ShopCardVC *childController = [self.storyboard instantiateViewControllerWithIdentifier:@"shopCard"];
        [self.navigationController pushViewController: childController animated:(true)];
    }
    if ([poa.type isEqualToString:photoIdentifier]) {
        NSMutableArray *images = [NSMutableArray array];
        NSArray *stringArray = [poa.imagename componentsSeparatedByString:@"."];
        int count = [stringArray[1] integerValue];
        for (int i = 1; i<=count; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d.jpg", stringArray[0], i]];
            if (img) {
                FSBasicImage *image = [[FSBasicImage alloc] initWithImage:img  name:@""];
                [images addObject:image];
            }
        }
        if ([images count] > 0) {
            FSBasicImageSource *photoSource = [[FSBasicImageSource alloc] initWithImages:images];
            FSImageViewerViewController *imageViewController = [[FSImageViewerViewController alloc] initWithImageSource:photoSource imageIndex: 0];

            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                [self.navigationController pushViewController:imageViewController animated:YES];
                //            [self.navigationController presentViewController:imageViewController animated:YES completion:nil];
            }
            else {
                [self.navigationController pushViewController:imageViewController animated:YES];
            }
        }
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
}

#pragma mark - set Play Mode
- (void) playMode:(AVAudioPlayer *) audioPlayer
{
    isPlayMode = YES;
    _audioPlayer =audioPlayer;
}

#pragma mark - Private Method

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - Private Method

-(void)initView
{
    //设置导航栏颜色
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:(float)128 / 255.0 green:(float)0 / 255.0 blue:(float)0/ 255.0 alpha:1.0]];
    }
    _shareButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareAction:)];
    self.navigationItem.rightBarButtonItem = _shareButton;

//    _mapButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(mapAction:)];
//    [_mapButton setTitle:@"Map"];
//    self.navigationItem.rightBarButtonItem = _mapButton;
}
-(void)mapAction:(id)sender
{

}

- (void)showEmail:(NSString *) emailAdress{

    NSString *emailTitle = @"";
    NSString *messageBody = @"";
    NSArray *toRecipents = [NSArray arrayWithObject:emailAdress];

    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    if (mc) {
        mc.mailComposeDelegate = self;
//        [mc setSubject:emailTitle];
//        [mc setMessageBody:messageBody isHTML:NO];
        [mc setToRecipients:toRecipents];

        // Present mail view controller on screen
        [self presentViewController:mc animated:YES completion:NULL];
    } else {
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alart"
        //                                                        message:@"You havn't login your Email, please add your email accounts in Settings."
        //                                                       delegate:self
        //                                              cancelButtonTitle:@"OK"
        //                                              otherButtonTitles:nil];
        //        [alert show];
    }

}
-(void)shareAction:(id)sender
{
    FBShareDialogParams *params = [[FBShareDialogParams alloc] init];
    params.link = [NSURL URLWithString:link_];
    params.name = articleTitle;
    params.caption = caption_;
    params.picture = [NSURL URLWithString:picture_];
    params.description = Description;

    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:params]) {

        // Present share dialog
        [FBDialogs presentShareDialogWithLink:params.link
                                         name:params.name
                                      caption:params.caption
                                  description:params.description
                                      picture:params.picture
                                  clientState:nil
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              NSLog(@"Error publishing story: %@", error.description);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                          }
                                      }];

        // If the Facebook app is NOT installed and we can't present the share dialog
    } else {
        // FALLBACK: publish just a link using the Feed dialog

        // Put together the dialog parameters
        NSMutableDictionary *params1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       articleTitle, @"name",
                                       caption_, @"caption",
                                       Description, @"description",
                                       link_, @"link",
                                       picture_, @"picture",
                                       nil];

        // Show the feed dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params1
                                                  handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See: https://developers.facebook.com/docs/ios/errors
                                                          NSLog(@"Error publishing story: %@", error.description);
                                                      } else {
                                                          if (result == FBWebDialogResultDialogNotCompleted) {
                                                              // User canceled.
                                                              NSLog(@"User cancelled.");
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [self parseURLParams:[resultURL query]];

                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");

                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                              }
                                                          }
                                                      }
                                                  }];
    }

    /*
     // If the Facebook app is installed and we can present the share dialog
     if([FBDialogs canPresentShareDialogWithPhotos]) {
         /// Package the image inside a dictionary
         UIImage *img = mainImage;
         FBShareDialogPhotoParams *params = [[FBShareDialogPhotoParams alloc] init];
         params.photos = @[img];

         [FBDialogs presentShareDialogWithPhotoParams:params
                                          clientState:nil
                                              handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"Error: %@", error.description);
                                                  } else {
                                                      NSLog(@"Success!");
                                                  }
                                              }];

//         if (!appCall) {
//             [self performPublishAction:^{
//                 FBRequestConnection *connection = [[FBRequestConnection alloc] init];
//                 connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
//                 | FBRequestConnectionErrorBehaviorAlertUser
//                 | FBRequestConnectionErrorBehaviorRetry;
//
//                 [connection addRequest:[FBRequest requestForUploadPhoto:img]
//                      completionHandler:^(FBRequestConnection *innerConnection, id result, NSError *error) {
//                          [self showAlert:@"Photo Post" result:result error:error];
//                          if (FBSession.activeSession.isOpen) {
//                              _shareButton.enabled = YES;
//                          }
//                      }];
//                 [connection start];
//
//                 _shareButton.enabled = NO;
////             }];
//         }

     } else {
     //The user doesn't have the Facebook for iOS app installed, so we can't present the Share Dialog
         UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"Note" message:@"It seems you don't have Facebook installed, You need to have Facebook to share the photo" delegate:self  cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [alter show];
     }
    */
}
// Convenience method to perform some action that requires the "publish_actions" permissions.
- (void)performPublishAction:(void(^)(void))action {
    // we defer request for permission to post to the moment of post, then we check for the permission
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        // if we don't already have the permission, then we request it now
        [FBSession.activeSession requestNewPublishPermissions:@[@"publish_actions"]
                                              defaultAudience:FBSessionDefaultAudienceFriends
                                            completionHandler:^(FBSession *session, NSError *error) {
                                                if (!error) {
                                                    action();
                                                } else if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
                                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Permission denied"
                                                                                message:@"Unable to get permission to post"
                                                                                delegate:nil
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
                                                    [alertView show];
                                                }
                                            }];
    } else {
        action();
    }

}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message
           result:(id)result
            error:(NSError *)error {

    NSString *alertMsg;
    NSString *alertTitle;
    if (error) {
        alertTitle = @"Error";
        // Since we use FBRequestConnectionErrorBehaviorAlertUser,
        // we do not need to surface our own alert view if there is an
        // an fberrorUserMessage unless the session is closed.
        if (error.fberrorUserMessage && FBSession.activeSession.isOpen) {
            alertTitle = nil;

        } else {
            // Otherwise, use a general "connection problem" message.
            alertMsg = @"Operation failed due to a connection problem, retry later.";
        }
    } else {
        NSDictionary *resultDict = (NSDictionary *)result;
        alertMsg = [NSString stringWithFormat:@"Successfully posted '%@'.", message];
        NSString *postId = [resultDict valueForKey:@"id"];
        if (!postId) {
            postId = [resultDict valueForKey:@"postId"];
        }
        if (postId) {
            alertMsg = [NSString stringWithFormat:@"%@\nPost ID: %@", alertMsg, postId];
        }
        alertTitle = @"Success";
    }

    if (alertTitle) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                            message:alertMsg
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
}
- (void)initData
{
    CELL_CONTENT_WIDTH = self.view.frame.size.width;

    link_ = @"http://www.forbiddencitywizdavid.com/fc.html";
    picture_ = @"http://www.forbiddencitywizdavid.com/images/pic_fc01.jpg";
    caption_ = @"comes from iGuide Forbidden City";
    if (!articleTitle) {
        articleTitle = @"The Forbedden City";
    }
    //如果为空,则默认为Tips的
    if (!masterkeyid) {
        POArticle * spot = (POArticle *)[[[DaoArticle alloc] getAllTips] objectAtIndex:0];
        masterkeyid = spot.primaryid;
        self.title = spot.title;
        spot = nil;
    }
    DaoArticle *dao = [DaoArticle alloc];
    articles = [dao findAllArticleSectionsByID:masterkeyid];
    _cellCache = [NSMutableDictionary dictionary];

    index = -1;
    oldIndex = -1;
}
// A function for parsing URL parameters returned by the Feed Dialog.
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val =
        [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        params[kv[0]] = val;
    }
    return params;
}

#pragma mark - 动态显示播放内容
- (void)updateTime {
    if (isPlayMode && _audioPlayer.currentTime > 0) {
        float female = [FCSettingVC getfloatByKey:KeyVoiceType];
        int i = 0;
        for (POSection *section in articles) {
            if (female) {
                if (section.starttime1 && !(section.endtime1)) {
                    if (_audioPlayer.currentTime > [section.starttime1 doubleValue]) {
                        index = i;
                    }
                } else if (section.starttime1 && section.endtime1) {
                    if (_audioPlayer.currentTime > [section.starttime1 doubleValue] && _audioPlayer.currentTime < [section.endtime1 doubleValue]) {
                        index = i;
                    }
                }
            } else {
                if (section.starttime && !(section.endtime)) {
                    if (_audioPlayer.currentTime > [section.starttime doubleValue]) {
                        index = i;
                    }
                } else if (section.starttime && section.endtime) {
                    if (_audioPlayer.currentTime > [section.starttime doubleValue] && _audioPlayer.currentTime < [section.endtime doubleValue]) {
                        index = i;
                    }
                }
            }

            i++;
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        if (oldIndex != index) {
            //当播放下一段时,选中并移动到屏幕中心UITableViewScrollPositionMiddle
            [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            oldIndex = index;
        } else {
            //当播放当前段落时,选中直选中但不移动
            [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }

}

@end


text:
import logging
import urllib

from agro.sources import utils

NEARBY_ADDRESS_GEONAMES_URL = "http://ws5.geonames.org/findNearestAddressJSON?"
log = logging.getLogger('agro.geo')

def reverse_geocode(lat, lng):
    """
    Geonames response
    -----------------
            {'address':
                {'distance': '0.03',
                'countryCode': 'US',
                'placename': 'Lawrence',
                'lat': '38.946397849397954',
                'street': 'W 21st St',
                'streetNumber': '1446',
                'postalcode': '66046',
                'lng': '-95.25217028671905',
                'adminName2': 'Douglas',
                'adminCode1': 'KS',
                'adminCode2': '045',
                'adminName1': 'Kansas'
                }
            }
    -----------------

    """
    kwargs = {'lat':lat, 'lng':lng}

    res = utils.get_remote_data(NEARBY_ADDRESS_GEONAMES_URL + urllib.urlencode(kwargs), rformat='json')

    if not res:
        log.error("geonames failed.")
        return False, False, False, False, False

    address = "%s %s" % (res['address']['streetNumber'], res['address']['street'])
    zip = res['address']['postalcode']
    city = res['address']['placename']
    state = res['address']['adminCode1']
    country = res['address']['countryCode']
    return address, zip, city, state, country


text:
// SimpleHashSet.java, created Wed Mar  5  0:26:27 2003 by joewhaley
// Copyright (C) 2001-3 John Whaley <jwhaley@alum.mit.edu>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
package jwutil.collections;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import jwutil.util.Assert;

/**
 * A simple implementation of a hash map.
 *
 * @author  John Whaley <jwhaley@alum.mit.edu>
 * @version $Id: SimpleHashSet.java,v 1.4 2005/05/05 19:38:49 joewhaley Exp $
 */
public class SimpleHashSet extends AbstractMap {

    public static final boolean TRACE = false;

    public static final int STARTING_TABLE_SIZE = 1024;
    public static final int STARTING_HASH_SIZE = 666;
    public static final int STARTING_CHAIN_SIZE = 4;

    public Object[] table = new Object[STARTING_TABLE_SIZE];
    public int size = -1;
    public int[][] chains = new int[STARTING_HASH_SIZE][]; // for hashing

    public Iterator iterator() {
        return Arrays.asList(table).subList(0, size+1).iterator();
    }

    public int size() { return size+1; }

    public boolean add(Object o) {
        int oldSize = this.size;
        o = getOrAdd(o);
        return size != oldSize;
    }

    public Set getMatchingHashcode(int hash) {
        return new ChainSet(this, hash);
    }

    public static class ChainSet extends AbstractSet {
        SimpleHashSet shs;
        int[] chain;
        int hash;
        public ChainSet(SimpleHashSet shs, int hash) {
            this.shs = shs;
            int chain_index = Math.abs(hash) % shs.chains.length;
            chain = shs.chains[chain_index];
            this.hash = hash;
            if (TRACE) System.out.println("Initialized chain set: hash="+hash+" index="+chain_index+" length="+(chain==null?-1:chain.length));
        }
        public Iterator iterator() {
            return new Itr();
        }
        public int size() {
            int s = 0, i = 0;
            for (;;) {
                if (i == chain.length)
                    return s;
                int loc = chain[i]-1;
                if (loc == -1)
                    return s;
                if (shs.table[loc].hashCode() == hash)
                    ++s;
                ++i;
            }
        }
        public class Itr extends UnmodifiableIterator {
            int i;
            public Itr() {
                i = -1;
                findNext();
            }
            private int findNext() {
                if (chain == null) return -1;
                for (;;) {
                    ++i;
                    if (i == chain.length)
                        return -1;
                    int loc = chain[i]-1;
                    if (loc == -1)
                        return -1;
                    if (shs.table[loc].hashCode() == hash) {
                        if (TRACE) System.out.println("next matching hash is chain["+i+"]="+loc);
                        return loc;
                    }
                }
            }
            public Object next() {
                if (chain == null || i == chain.length || chain[i]-1 == -1)
                    throw new NoSuchElementException();
                Object o = shs.table[chain[i]-1];
                findNext();
                return o;
            }
            public boolean hasNext() {
                return chain != null && i != chain.length && chain[i]-1 != -1;
            }
            public void addToEnd(Object o) {
                Assert._assert(o.hashCode() == hash);
                if (chain == null) {
                    int chain_index = Math.abs(hash) % shs.chains.length;
                    Assert._assert(shs.chains[chain_index] == null);
                    shs.chains[chain_index] = chain = new int[STARTING_CHAIN_SIZE];
                    i = 0;
                } else if (i == chain.length) {
                    int[] newchain = new int[chain.length<<1];
                    System.arraycopy(chain, 0, newchain, 0, chain.length);
                    int chain_index = Math.abs(hash) % shs.chains.length;
                    Assert._assert(shs.chains[chain_index] == (Object)chain);
                    shs.chains[chain_index] = newchain;
                    chain = newchain;
                } else if (chain[i]-1 != -1) {
                    throw new UnsupportedOperationException("not at end");
                }
                shs.addToTable_helper(o, chain, i);
            }
        }

    }

    public Object getOrAdd(Object o) {
        int id = getOrAddID(o);
        return table[id];
    }

    public Object get(Object o) {
        int id = getID(o);
        if (id == -1) return null;
        return table[id];
    }

    public int getID(Object b) {
        int hash = b.hashCode();
        int chain_index = Math.abs(hash) % chains.length;
        int[] chain = chains[chain_index];
        if (chain == null) return -1;
        for (int i=0; i<chain.length; ++i) {
            int id = chain[i]-1;
            if (id == -1) return -1;
            Object that = table[id];
            // ??? check hash before calling equals ???
            if (that.equals(b)) {
                // ??? swap first one and this one ???
                return id;
            }
        }
        return -1;
    }

    public int getOrAddID(Object b) {
        int hash = b.hashCode();
        int chain_index = Math.abs(hash) % chains.length;
        int[] chain = chains[chain_index];
        if (chain == null) {
            chains[chain_index] = chain = new int[STARTING_CHAIN_SIZE];
            return addToTable_helper(b, chain, 0);
        }
        for (int i=0; i<chain.length; ++i) {
            int id = chain[i]-1;
            if (id == -1) {
                return addToTable_helper(b, chain, i);
            }
            if (TRACE) System.out.println("Id="+id);
            Object that = table[id];
            // ??? check hash before calling equals ???
            if (that.equals(b)) {
                // ??? swap first one and this one ???
                return id;
            }
        }
        int[] newchain = new int[chain.length<<1];
        System.arraycopy(chain, 0, newchain, 0, chain.length);
        chains[chain_index] = newchain;
        return addToTable_helper(b, newchain, chain.length);
        // free(chain)

        // todo: rehash when the table gets too full...
    }

    // Helper function.
    private int addToTable_helper(Object b, int[] chain, int index) {
        if (++size == table.length) growTable_helper();
        table[size] = b;
        chain[index] = size+1;
        if (TRACE) System.out.println("added to table["+size+"]: "+table[size]);
        return size;
    }

    // Helper function.
    private void growTable_helper() {
        Object[] newtable = new Object[size<<1];
        System.arraycopy(table, 0, newtable, 0, size);
        table = newtable;
    }

    public boolean contains(Object arg0) {
        return getID(arg0) != -1;
    }

    /**
     * @see java.util.Map#containsKey(Object)
     */
    public boolean containsKey(Object arg0) {
        return contains(arg0);
    }

    /**
     * @see java.util.Map#containsValue(Object)
     */
    public boolean containsValue(Object arg0) {
        return contains(arg0);
    }

    /**
     * @see java.util.Map#entrySet()
     */
    public Set entrySet() {
        return new EntrySet();
    }

    public static class Entry extends AbstractMapEntry {
        Object o;
        public Entry(Object o) { this.o = o; }
        public Object getKey() { return o; }
        public Object getValue() { return o; }
        public Object setValue(Object o) { throw new UnsupportedOperationException(); }
    }

    public class EntrySet extends AbstractSet {
        public Iterator iterator() {
            return new Itr();
        }
        public int size() {
            return SimpleHashSet.this.size();
        }
        public class Itr extends UnmodifiableIterator {
            Iterator itr = SimpleHashSet.this.iterator();
            public Itr() { }
            public Object next() { return new Entry(itr.next()); }
            public boolean hasNext() { return itr.hasNext(); }
        }
    }

    public class SetView implements Set {
        public Iterator iterator() {
            return SimpleHashSet.this.iterator();
        }
        public int size() {
            return SimpleHashSet.this.size();
        }

        /**
         * @see java.util.Collection#add(Object)
         */
        public boolean add(Object arg0) {
            return SimpleHashSet.this.add(arg0);
        }

        /**
         * @see java.util.Collection#addAll(Collection)
         */
        public boolean addAll(Collection arg0) {
            boolean change = false;
            for (Iterator i=arg0.iterator(); i.hasNext(); ) {
                if (add(i.next()))
                    change = true;
            }
            return change;
        }

        /**
         * @see java.util.Collection#clear()
         */
        public void clear() {
            throw new UnsupportedOperationException();
        }

        /**
         * @see java.util.Collection#contains(Object)
         */
        public boolean contains(Object arg0) {
            return SimpleHashSet.this.contains(arg0);
        }

        /**
         * @see java.util.Collection#containsAll(Collection)
         */
        public boolean containsAll(Collection arg0) {
            return SimpleHashSet.this.containsAll(arg0);
        }

        /**
         * @see java.util.Collection#isEmpty()
         */
        public boolean isEmpty() {
            return SimpleHashSet.this.isEmpty();
        }

        /**
         * @see java.util.Collection#remove(Object)
         */
        public boolean remove(Object arg0) {
            throw new UnsupportedOperationException();
        }

        /**
         * @see java.util.Collection#removeAll(Collection)
         */
        public boolean removeAll(Collection arg0) {
            throw new UnsupportedOperationException();
        }

        /**
         * @see java.util.Collection#retainAll(Collection)
         */
        public boolean retainAll(Collection arg0) {
            throw new UnsupportedOperationException();
        }

        /**
         * @see java.util.Collection#toArray()
         */
        public Object[] toArray() {
            return SimpleHashSet.this.toArray();
        }

        /**
         * @see java.util.Collection#toArray(Object[])
         */
        public Object[] toArray(Object[] arg0) {
            return SimpleHashSet.this.toArray(arg0);
        }

    }

    public boolean containsAll(Collection c) {
        Iterator e = c.iterator();
        while (e.hasNext())
            if (!contains(e.next()))
                return false;
        return true;
    }

    public Object[] toArray() {
        Object[] o = new Object[size()];
        int j = -1;
        for (Iterator i=iterator(); i.hasNext(); ) {
            o[++j] = i.next();
        }
        Assert._assert(j+1 == o.length);
        return o;
    }

    public Object[] toArray(Object[] a) {
        int this_size = size();
        if (this_size > a.length) {
            a = (Object[])java.lang.reflect.Array.newInstance(
                                  a.getClass().getComponentType(), this_size);
        }
        int j = -1;
        for (Iterator i = iterator(); i.hasNext(); ) {
            a[++j] = i.next();
        }
        if (++j < a.length)
            a[j] = null;
        return a;
    }

    public Set getAsSet() {
        return new SetView();
    }

    /**
     * @see java.util.Map#keySet()
     */
    public Set keySet() {
        return this.getAsSet();
    }

    /**
     * @see java.util.Map#put(Object, Object)
     */
    public Object put(Object arg0, Object arg1) {
        Assert._assert(arg0 == arg1);
        arg1 = getOrAdd(arg0);
        // we are supposed to return the old one...
        return null;
    }

    /**
     * @see java.util.Map#putAll(Map)
     */
    public void putAll(Map arg0) {
        Iterator i = arg0.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry e = (Map.Entry) i.next();
            Assert._assert(e.getKey() == e.getValue());
            add(e.getKey());
        }
    }

    /**
     * @see java.util.Map#values()
     */
    public Collection values() {
        return this.getAsSet();
    }

}


text:
package org.knowm.xchange.hitbtc.v2.dto;

import java.math.BigDecimal;

import com.fasterxml.jackson.annotation.JsonProperty;

public class HitbtcOrderLimit {

  private final BigDecimal price;
  private final BigDecimal size;

  public HitbtcOrderLimit(@JsonProperty("price") BigDecimal price, @JsonProperty("size") BigDecimal size) {
    this.price = price;
    this.size = size;
  }

  public BigDecimal getPrice() {
    return price;
  }

  public BigDecimal getSize() {
    return size;
  }

  @Override
  public String toString() {
    return "HitbtcOrderLimit{" +
        "price=" + price +
        ", size=" + size +
        '}';
  }
}


text:
var strings = {
  'report_to_text': 'Report to text',
  'report_to_text2': 'Text to report'
};

function restoreFieldSetInline(elem) {
  var fieldset = $(elem);
  var parent_tr = fieldset.parents('tr').first();

  fieldset.css({
    display: 'block',
    width: 'auto'
  })
  fieldset.find('br').remove();
  parent_tr.css('line-height', 0);

  //console.log(fieldset.find(':input').length);
  if (fieldset.find(':input').length < 1) {
    //console.log('ukryj parent_tr');
    parent_tr.css('display', 'none');
  }
  else {
    parent_tr.css('display', 'table-row');
  }
}

///////////////////////
function report_to_text_func(report_id, report_id2) {
  var report = $(report_id);

  report.append('

Raport do textu: 	'+strings.report_to_text+'

')

  report.find('.report_to_text').click(report_to_text).data('report_id', report_id2);

  $(report_id2).data('report_to_text', true);

//  console.log('ustawilem mode na '+$(report_id2).data('report_to_text'))

}

function report_to_text(){

  var report_id = $(this).data('report_id');

  /*
    mode == true | false | null, true == null == ukryj
    04 - column heading text
    05 - aligment
    06 - heading
    07 - show
    08 - sum
    09 - sort
    10 - sort seq
    11 - column width
  */
  var report = $(report_id);

  var mode = report.data('report_to_text') ? true : false;
  //console.log(mode);

  var items = '[name=f04], [name=f05], [name=f06], [name=f07], [name=f08], [name=f09], [name=f10], [name=f11]';
  var span_temp = '#TEXT#';

  report.find(items).each(function(){
    var self = $(this);
    var parent = self.parents('td').first();

    if (mode) {
      self.hide();

      if ( self.is(':checkbox') )
        parent.append( span_temp.replace('#TEXT#',  self.is(':checked') ? 1 : 0));
      else
        parent.append( span_temp.replace('#TEXT#',  self.val() ));

    }
    else {
      self.show();
      parent.find('.to_text').remove();
    }
  });

  if (mode) {
    report_container.find('.report_to_text').text(strings.report_to_text2);
    report.find('[headers="ID"], th[id=ID]').hide();
    report.find('td:has(img)').hide()

  }
  else {
    report_container.find('.report_to_text').text(strings.report_to_text);
    report.find('[headers="ID"], th[id=ID]').show();
    report.find('td:has(img)').show()

  }

  report.data('report_to_text', !mode);
}