text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>NullMainModel</title>
<meta name="date" content="2013-03-26">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

emr_vis_nlp.model

Class NullMainModel

java.lang.Object

emr_vis_nlp.model.NullMainModel

All Implemented Interfaces:

MainModel

public class NullMainModel
extends java.lang.Object
implements MainModel

Empty model for use when no dataset is loaded.

Field Summary

Fields

Modifier and Type
Field and Description

private MainController
controller

this MainModel's governing MainController

Constructor Summary

Constructors

Constructor and Description

NullMainModel()

Method Summary

Methods

Modifier and Type
Method and Description

java.util.List<java.lang.String>
getAllAttributes()

java.util.List<Document>
getAllDocuments()

java.util.Map<java.lang.String,java.lang.Integer>
getAttributeValueCountMap(java.lang.String attrName)

java.util.List<java.lang.Boolean>
getIsAttributeEnabledList()

java.util.List<java.lang.Boolean>
getIsDocumentEnabledList()

java.lang.String
getManAnn(int globalDocId,
         java.lang.String attrName)

Provides the manual annotation for the given document for the given attribute.

boolean
hasManAnn(int globalDocId,
         java.lang.String attrName)

Returns whether a manual annotation exists in the given document for the given attribute.

void
setEnabledAttributes(java.util.List<java.lang.Boolean> selectedAttributes)

void
setIsAttributeEnabled(int globalAttrID,
                     boolean isEnabled)

void
setIsAttributeEnabled(java.lang.String attrName,
                     boolean isEnabled)

void
setIsDocumentEnabled(int globalDocID,
                    boolean isEnabled)

boolean
updateDocumentAttr(int docID,
                  java.lang.String docAttr,
                  java.lang.String docAttrVal)

Updates target document's target attribute with the designated value.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

controller

private MainController controller

this MainModel's governing MainController

Constructor Detail

NullMainModel

public NullMainModel()

Method Detail

setEnabledAttributes

public void setEnabledAttributes(java.util.List<java.lang.Boolean> selectedAttributes)

Specified by:

setEnabledAttributes in interface MainModel

Parameters:

selectedAttributes - List of flags as to which attributes should be enabled

getAllDocuments

public java.util.List<Document> getAllDocuments()

Specified by:

getAllDocuments in interface MainModel

Returns:

List containing all Documents from this data source

getIsDocumentEnabledList

public java.util.List<java.lang.Boolean> getIsDocumentEnabledList()

Specified by:

getIsDocumentEnabledList in interface MainModel

Returns:

List of boolean indicators as to which documents (as returned by getAllDocuments()) are currently enabled.

getAllAttributes

public java.util.List<java.lang.String> getAllAttributes()

Specified by:

getAllAttributes in interface MainModel

Returns:

List of names for all attributes in model

getIsAttributeEnabledList

public java.util.List<java.lang.Boolean> getIsAttributeEnabledList()

Specified by:

getIsAttributeEnabledList in interface MainModel

Returns:

List of flags as to which attributes in model are currently "enabled" (disabled attributes should not be displayed in the visualization)

getAttributeValueCountMap

public java.util.Map<java.lang.String,java.lang.Integer> getAttributeValueCountMap(java.lang.String attrName)

Specified by:

getAttributeValueCountMap in interface MainModel

Parameters:

attrName - String name of an attribute from this model

Returns:

map of all possible values & their counts for a given attribute in the model

updateDocumentAttr

public boolean updateDocumentAttr(int docID,
                         java.lang.String docAttr,
                         java.lang.String docAttrVal)

Description copied from interface: MainModel

Updates target document's target attribute with the designated value.

Specified by:

updateDocumentAttr in interface MainModel

Parameters:

docID - global integer identifier for document (index into getAllDocuments())

docAttr - name of an attribute used in this model

docAttrVal - the manually-annotated value which this should have for this document

Returns:

true if update was completed successfully, false otherwise

hasManAnn

public boolean hasManAnn(int globalDocId,
                java.lang.String attrName)

Description copied from interface: MainModel

Returns whether a manual annotation exists in the given document for the given attribute.

Specified by:

hasManAnn in interface MainModel

Parameters:

globalDocId - global integer identifier for document (index into getAllDocuments())

attrName - name of an attribute used in this model

Returns:

true if a manual annotation exists in the document for the given attribute, false otherwise

getManAnn

public java.lang.String getManAnn(int globalDocId,
                         java.lang.String attrName)

Description copied from interface: MainModel

Provides the manual annotation for the given document for the given attribute.

Specified by:

getManAnn in interface MainModel

Parameters:

globalDocId - global integer identifier for document (index into getAllDocuments())

attrName - name of an attribute used in this model

Returns:

the value of the manual annotation in the document for the given attribute if it exists, null otherwise

setIsAttributeEnabled

public void setIsAttributeEnabled(int globalAttrID,
                         boolean isEnabled)

Specified by:

setIsAttributeEnabled in interface MainModel

Parameters:

globalAttrID - integer identifier (index into getAllAttributes()) of an attribute used in this model

isEnabled - boolean indicator as to whether or not this attribute should be enabled

setIsAttributeEnabled

public void setIsAttributeEnabled(java.lang.String attrName,
                         boolean isEnabled)

Specified by:

setIsAttributeEnabled in interface MainModel

Parameters:

attrName - name of an attribute used in this model

isEnabled - boolean indicator as to whether or not this attribute should be enabled

setIsDocumentEnabled

public void setIsDocumentEnabled(int globalDocID,
                        boolean isEnabled)

Specified by:

setIsDocumentEnabled in interface MainModel

Parameters:

globalDocID - global integer identifier for document (index into getAllDocuments())

isEnabled - boolean flag as to whether or not this document should be enabled

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
RSpec.describe RuboCop::Cop::Lint::EachWithObjectArgument do
  subject(:cop) { described_class.new }

  it 'registers an offense for fixnum argument' do
    expect_offense(<<-RUBY.strip_indent)
      collection.each_with_object(0) { |e, a| a + e }
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object can not be immutable.
    RUBY
  end

  it 'registers an offense for float argument' do
    expect_offense(<<-RUBY.strip_indent)
      collection.each_with_object(0.1) { |e, a| a + e }
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object can not be immutable.
    RUBY
  end

  it 'registers an offense for bignum argument' do
    expect_offense(<<-RUBY.strip_indent)
      c.each_with_object(100000000000000000000) { |e, o| o + e }
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object can not be immutable.
    RUBY
  end

  it 'accepts a variable argument' do
    expect_no_offenses('collection.each_with_object(x) { |e, a| a.add(e) }')
  end

  it 'accepts two arguments' do
    # Two arguments would indicate that this is not Enumerable#each_with_object.
    expect_no_offenses('collection.each_with_object(1, 2) { |e, a| a.add(e) }')
  end

  it 'accepts a string argument' do
    expect_no_offenses("collection.each_with_object('') { |e, a| a << e.to_s }")
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace WingtipToys.Logic
{
    // Create our own utility for exceptions
    public sealed class ExceptionUtility
    {
        // All methods are static, so this can be private
        private ExceptionUtility()
        { }

        // Log an Exception
        public static void LogException(Exception exc, string source)
        {
            // Include logic for logging exceptions
            // Get the absolute path to the log file
            string logFile = "App_Data/ErrorLog.txt";
            logFile = HttpContext.Current.Server.MapPath(logFile);

            // Open the log file for append and write the log
            StreamWriter sw = new StreamWriter(logFile, true);
            sw.WriteLine("********** {0} **********", DateTime.Now);
            if (exc.InnerException != null)
            {
                sw.Write("Inner Exception Type: ");
                sw.WriteLine(exc.InnerException.GetType().ToString());
                sw.Write("Inner Exception: ");
                sw.WriteLine(exc.InnerException.Message);
                sw.Write("Inner Source: ");
                sw.WriteLine(exc.InnerException.Source);
                if (exc.InnerException.StackTrace != null)
                {
                    sw.WriteLine("Inner Stack Trace: ");
                    sw.WriteLine(exc.InnerException.StackTrace);
                }
            }
            sw.Write("Exception Type: ");
            sw.WriteLine(exc.GetType().ToString());
            sw.WriteLine("Exception: " + exc.Message);
            sw.WriteLine("Source: " + source);
            sw.WriteLine("Stack Trace: ");
            if (exc.StackTrace != null)
            {
                sw.WriteLine(exc.StackTrace);
                sw.WriteLine();
            }
            sw.Close();
        }
    }
}


text:
'use strict';

import createTester from './internal/createTester';
import eachOfLimit from './eachOfLimit';
import identity from 'lodash/identity';

/**
 * The same as `some` but runs a maximum of `limit` async operations at a time.
 *
 * @name someLimit
 * @static
 * @memberOf async
 * @see async.some
 * @alias anyLimit
 * @category Collection
 * @param {Array|Object} coll - A collection to iterate over.
 * @param {number} limit - The maximum number of async operations at a time.
 * @param {Function} iteratee - A truth test to apply to each item in the array
 * in parallel. The iteratee is passed a `callback(err, truthValue)` which must
 * be called with a boolean argument once it has completed. Invoked with
 * (item, callback).
 * @param {Function} [callback] - A callback which is called as soon as any
 * iteratee returns `true`, or after all the iteratee functions have finished.
 * Result will be either `true` or `false` depending on the values of the async
 * tests. Invoked with (err, result).
 */
export default createTester(eachOfLimit, Boolean, identity);


text:
<form style="display: none;" id="{{ form_id }}" class="connect-button" name="login" method="post" action="{% if request.user.is_authenticated %}{% url facebook_connect %}{% else %}{% url facebook_login %}{% endif %}">
    {% csrf_token %}
    {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
    {% endif %}
</form>


text:
package org.jasig.portal.rendering;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jasig.portal.character.stream.CharacterEventReader;
import org.jasig.portal.character.stream.FilteringCharacterEventReader;
import org.jasig.portal.character.stream.events.CharacterEvent;
import org.jasig.portal.utils.cache.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logs the Character events
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
public class LoggingCharacterComponent extends CharacterPipelineComponentWrapper {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public void setLoggerName(String loggerName) {
        logger = LoggerFactory.getLogger(loggerName);
    }

    @Override
    public CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response) {
        return this.wrappedComponent.getCacheKey(request, response);
    }

    /* (non-Javadoc)
     * @see org.jasig.portal.rendering.PipelineComponent#getEventReader(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public PipelineEventReader<CharacterEventReader, CharacterEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {
        final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response);

        final CharacterEventReader eventReader = pipelineEventReader.getEventReader();

        final LoggingCharacterEventReader loggingEventReader = new LoggingCharacterEventReader(eventReader);

        final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
        return new PipelineEventReaderImpl<CharacterEventReader, CharacterEvent>(loggingEventReader, outputProperties);
    }

    private class LoggingCharacterEventReader extends FilteringCharacterEventReader {

        public LoggingCharacterEventReader(CharacterEventReader delegate) {
            super(delegate);
        }

        /* (non-Javadoc)
         * @see org.jasig.portal.character.stream.FilteringCharacterEventReader#filterEvent(org.jasig.portal.character.stream.events.CharacterEvent, boolean)
         */
        @Override
        protected CharacterEvent filterEvent(CharacterEvent event, boolean peek) {
            if (logger.isDebugEnabled()) {
                logger.debug(event.toString());
            }

            return event;
        }
    }
}


text:
[![(a histogram of downloads)](https://nodei.co/npm-dl/phido.png?height=3)](https://npmjs.org/package/phido)

![PhiDo](icon/PhiDo-32x32.png)

**PhiDo** (aka **φ道**) is a Fidonet browser with a GUI.

* Its name means "the Golden Path", where "φ" represents [the golden ratio](http://en.wikipedia.org/wiki/Golden_ratio) and "道" means "path".

* Its name sounds like the Russian "Фидо" that means "Fido" (as in "Fidonet").

## Features

[![(Fidonet Unicode substrings)](https://img.shields.io/badge/Fidonet-Unicode%20substrings-57ab1e.svg?style=plastic)](https://github.com/Mithgol/fiunis)
[![(Fidonet avatars)](https://img.shields.io/badge/Fidonet-avatars-57ab1e.svg?style=plastic)](https://github.com/Mithgol/node-fidonet-jam/blob/master/avatar.txt)
[![(FGHI URL)](https://img.shields.io/badge/FGHI-URL-57ab1e.svg?style=plastic)](https://github.com/Mithgol/FGHI-URL)
[![(Fidonet Runes)](https://img.shields.io/badge/Fidonet-Runes-57ab1e.svg?style=plastic)](https://github.com/Mithgol/node-fidonet-fidohtml/blob/master/runes.txt)

The application is currently in an early phase of its development and thus does not have the desired level of feature completeness.

However, it already supports the following features:

* [Fidonet Unicode substrings](https://github.com/Mithgol/fiunis)

* pictures displayed instead of their [UUE codes](http://en.wikipedia.org/wiki/Uuencoding)

* some [Fidonet avatars](https://github.com/Mithgol/node-fidonet-jam/blob/master/avatar.txt)

* some [FGHI URLs](https://github.com/Mithgol/FGHI-URL)

* [IPFS](https://ipfs.io/) URLs (both `fs:` and `ipfs:`), using the [`ipfs.io`](https://ipfs.io/) web gate

* some Fidonet Runes (Markdown-alike declarations of hyperlinks and images)

## Requirements

* PhiDo is written in HTML5 + CSS + JavaScript and uses the latest [nw.js](https://github.com/nwjs/nw.js) engine to run. A system supported by nw.js (such as Windows, or Linux, or Mac OS X) is required.

* Have 2 Gb RAM (or more). When PhiDo renders large Fidonet echomail areas (thousands of messages) and some other browser (such as Firefox) is running in background, if the system has only 1 Gb RAM (or less), swapping occurs inevitably.

* PhiDo currently requires **Node.js** and **npm** to be present (installed) on your system; the version of **npm** must be 3.0.0 or greater. (Usually [Node.js installers](https://nodejs.org/en/download/) install both Node.js and npm.)

* PhiDo currently supports only the JAM [(Joaquim-Andrew-Mats)](https://github.com/Mithgol/node-fidonet-jam/blob/master/JAM.txt) type of Fidonet message bases.

* PhiDo currently uses [HPT](http://husky.sourceforge.net/hpt.html)'s area configuration file as the description of echomail areas.

* PhiDo does not currently create any lock files, not does it lock files in use. Users themselves have to prevent their echoprocessors (tossers) or mail editors from running when PhiDo is active.

* PhiDo currently uses ParaType's fonts of three font families: PT Sans, PT Serif, PT Mono. These families were released by ParaType with an open user license; use the corresponding ParaType's web page ([in English](http://www.paratype.com/public/) or [in Russian](http://www.paratype.ru/public/)) to download these fonts and install them on your system.

## Installing PhiDo

[![(npm package version)](https://nodei.co/npm/phido.png?downloads=true&downloadRank=true)](https://npmjs.org/package/phido)

### Global installation

* Latest packaged version: `npm install -g phido`

* Latest githubbed version: `npm install -g https://github.com/Mithgol/phido/tarball/master`

The application becomes installed globally (for example, in `node_modules/phido` subdirectory in your Node's directory) and appears in your `PATH`.

You may use `phido` command to run the application.

You should create a configuration file for the installed PhiDo (in its directory) before you launch it.

### Local installation

Instead of the above, download the [ZIP-packed](https://github.com/Mithgol/phido/archive/master.zip) source code of PhiDo and unpack it to some directory. Then run `npm install --production` in that directory.

Unlike the global installation (`npm -g`), the application does not appear in the `PATH`, and thus you'll have to run it directly from the application's directory. You'll also have to run `node phido` instead of `phido`. (On Windows you may use `start.bat` as the launcher.)

You should create a configuration file for the installed PhiDo (in its directory) before you launch it.

#### Portability of a local installation

If you install PhiDo in a directory on a portable drive (such as [a USB flash drive](https://en.wikipedia.org/wiki/USB_flash_drive)), you may move it to a different system and run PhiDo there if the following requirements are met:

* The platform has to be the same (i.e. move from Linux to Linux, or from Windows to Windows, or from Mac OS X to Max OS X).

* The architecture has to be the same (i.e. move from a 32-bit system to 32-bit or from 64-bit system to 64-bit).

* It is also possible to run PhiDo on a 64-bit Windows if PhiDo was originally installed on a 32-bit Windows, but not vice versa.

* Node.js has to be installed on the target system.

#### Be patient

More than 200 megabytes of dependencies are installed. Most of them contain dozens of small files with source code and metadata. An installation on a low-speed (USB 2.0) flash drive may take, for example, **half an hour** on a system with a limited Internet connection.

## Configuration options

PhiDo uses the configuration given in the file `phido.conf` in PhiDo's directory (in the same directory where PhiDo's `package.json` resides).

You may use `phido.conf-example` as an example. (Or even copy `phido.conf-example` to `phido.conf` and edit in your favourite text editor.)

The following configuration options are supported (in arbitrary order):

* `ConfigGoldED` — path to the configuration file of GoldED (or [GoldED+](http://golded-plus.sf.net), or GoldED-NSF). This setting is not necessary, but it allows to use PhiDo alongside that popular Fidonet mail editor (GoldED) when the former uses some settings of the latter. The following settings (also individually mentioned below) are used:
   * `UserName`
   * `ViewKludges`
   * `StyleCodes`
   * `AreaSep`

* `EncodingGoldED` — the encoding of non-ASCII characters in the GoldED config file. By default, `utf8` is used. You may use any encoding provided by the [`iconv-lite`](https://github.com/ashtuchkin/iconv-lite) module.

* `AreasHPT` — path to the area configuration file of HPT. This setting is necessary for PhiDo to know where the echomail resides.
   * The configuration lines for echomail are expected to start with `EchoArea` (literally; not case-sensitive), then a whitespace-separated echotag (such as `Ru.FTN.Develop` for example), then a whitespace-separated full path (without the extensions) to the echomail files of the area, in that order. (A sequence of several whitespaces is also a supported separator.) The rest of the configuration line is also whitespace-separated from the path.
   * If the `-d "some description"` is found on the same line, it is used as the echomail area's description.
   * Only JAM echomail areas are supported. Names of echo base files are generated by appending lowercase extensions (`.jhr`, `.jdt`, `.jdx`, `.jlr`) to the given path.

* `EncodingHPT` — the encoding of non-ASCII characters in the HPT areafile. By default, `utf8` is used. You may use any encoding provided by the [`iconv-lite`](https://github.com/ashtuchkin/iconv-lite) module.

* `UserName` — the user's name. May be borrowed from GoldED's configuration if omitted in PhiDo's.

* `ViewKludges` — if `Yes` (case-insensitive), Fidonet kludges (hidden lines) are displayed. This setting may be borrowed from GoldED's configuration if omitted in PhiDo's, but it affects unknown kludges as well (while in GoldED unknown kludges are controlled by a separate `ViewHidden` setting).

* ![(TODO: not ready)](https://img.shields.io/badge/TODO-%28not_ready%29-001f3f.svg?style=plastic) `StyleCodes` — may have one of the following values (not case-sensitive; borrowed from GoldED's configuration if omitted in PhiDo's) that control the processing of style codes:
   * `Yes` (default) — style codes affect the style of words surrounded by them. There are four types of style codes: `*asterisks*`, `_underscores_`, `#hashes#` or `/slashes/` around words.
   * `Hide` — same as above, but the style codes themselves are not displayed.
   * `No` — style codes are ignored (treated as any other characters).

* `AreaSep` — descriptions of separators between areas in the arealist. May be borrowed from GoldED's configuration if omitted in PhiDo's. Each separator consists of the following elements (separated with one or more spaces):
   * `AreaSep` (literally)
   * areatag (such as `Ru.FTN.Develop` for example)
   * `"separator text"` (in double quotes)
   * group ID (number, currently ignored)
   * group type (currently only `Echo` separators are displayed)

* `ZIPNodelist` — path to a ZIP-packed nodelist.

* `MaximizeWindow` — if `Yes` (case-insensitive), the PhiDo's window is maximized after PhiDo starts.

### Examples of external configuration files

Examples of the area configuration file of HPT are available in its own CVS repository on SourceForge [in English](http://husky.cvs.sf.net/viewvc/husky/hpt/config/areas) and [in Russian](http://husky.cvs.sf.net/viewvc/husky/hpt/config/areas.ru). Text lines of these examples are commented out (by `#` characters in the lines' beginnings) but your real configuration lines must be uncommented.

An example of GoldED configuration file is [available](http://golded-plus.cvs.sourceforge.net/viewvc/golded-plus/golded%2B/etc/golded.conf?revision=1.1&view=markup) in the CVS of GoldED+. It contains a lot of configuration directives; only the most basic of them are understood by PhiDo (and they already appear in `phido.conf-example` anyway).

### Launching PhiDo from GoldED

PhiDo can be configured and used as an advanced external viewer of echomail messages for any version of GoldED (for example, for GoldED+ or GoldED-NSF).

It is useful because PhiDo has the following features that are not present in GoldED:

* FGHI URLs become hyperlinks (GoldED-NSF also has this feature, but GoldED+ does not have it)

* Raster images (PNG, JPEG, GIF) and vector images (SVG) are automatically decoded from UUE and displayed instead of UUE

* Unicode support

* User's picture (avatar) in a message's header

* Fidonet Runes (Markdown-alike declarations of hyperlinks and images)

Two lines have to be added to configuration files of GoldED to enable launching of PhiDo.

The first additional line has to be added in the main GoldED's configuration file (usually called `golded.cfg` or `gedcyg.cfg`); this line defines a new external utility (15th in this example).

To launch a global installation of PhiDo, use the following line:

    ExternUtil 15 phido "--file=@file" "--area=@cecho"

To launch a local installation of PhiDo, use the following line:

    ExternUtil 15 node \path\to\PhiDo\phido "--file=@file" "--area=@cecho"

* Substitute `\path\to\PhiDo` with the real path that leads to PhiDo on your system.

* If not on Windows, `/` instead of `\` is likely to be used in your paths.

The second additional line has to be added in the GoldED's hotkey configuration file (usually `goldkeys.cfg`); this line defines a hotkey for the utility (`F12` in this example):

    F12 ExternUtil15

Afterwards press F12 to launch PhiDo from GoldED. If the message that you view in GoldED has a MSGID (it usually has; see [FTS-0009.001](http://ftsc.org/docs/fts-0009.001) for details), PhiDo shows the same message; otherwise PhiDo displays the list of available echomail areas.

## Testing PhiDo

[![(build testing status)](https://img.shields.io/travis/Mithgol/phido/master.svg?style=plastic)](https://travis-ci.org/Mithgol/phido)

It is necessary to install [JSHint](http://jshint.com/) for testing.

* You may install JSHint globally (`npm install jshint -g`) or locally (`npm install jshint` in the directory of PhiDo).

After that you may run `npm test` (in the directory of PhiDo). Only the JS code issues are caught; the code's behaviour is not tested.

## License

The source code is MIT-licensed (see `LICENSE`), with the following exceptions:

* The directory `bootstrap` contains [Bootstrap](http://getbootstrap.com/) v3.0.2 licensed under [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0). (It is planned to update it to a newer version, separately MIT-licensed.)

* This product uses the JAM(mbp) API — Copyright 1993 Joaquim Homrighausen, Andrew Milner, Mats Birch, Mats Wallin. ALL RIGHTS RESERVED. (JAM may be used by any developer as long as [its specifications](https://github.com/Mithgol/node-fidonet-jam/blob/master/JAM.txt) are followed exactly. JAM may be used free-of-charge by any developer for any purpose, commercially or otherwise.)

* Node.js modules (installed in the `node_modules` directory) belong to their respective owners.


text:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  externals: {
    'jquery': 'window.$'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}


text:
package com.amazonaws.services.lakeformation.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.lakeformation.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AuditContext JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AuditContextJsonUnmarshaller implements Unmarshaller<AuditContext, JsonUnmarshallerContext> {

    public AuditContext unmarshall(JsonUnmarshallerContext context) throws Exception {
        AuditContext auditContext = new AuditContext();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("AdditionalAuditContext", targetDepth)) {
                    context.nextToken();
                    auditContext.setAdditionalAuditContext(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return auditContext;
    }

    private static AuditContextJsonUnmarshaller instance;

    public static AuditContextJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AuditContextJsonUnmarshaller();
        return instance;
    }
}


text:
<!DOCTYPE html>

    <title>nirc</title>
    <meta name="viewport" content="width=device-width, user-scalable=no">

    <link href='//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet'>
    <link href='/stylesheets/style.css' media='screen' rel='stylesheet' type='text/css'/>
    <link ng-href='/stylesheets/themes/{{theme}}/theme.css' media='screen' rel='stylesheet' type='text/css'/>

            {{event.timestamp | date:'HH:mm:ss'}}

            {{event.from.nick}}:

          {{user.nick}}

    <input type="text" class="user-input" read-line="client.say(text)"
           complete-from="client.activeChannel.users">


text:
import unittest
import yaml
from ui.visualizations import VolumeVisualizationFactory
from ui.visualizations import VisualizationTypeCT
from ui.visualizations import VisualizationTypeSimple
from ui.visualizations import VolumeVisualizationWrapper
from core.vtkObjectWrapper import vtkVolumePropertyWrapper
from core.vtkObjectWrapper import vtkColorTransferFunctionWrapper
from core.vtkObjectWrapper import vtkPiecewiseFunctionWrapper

class VolumeVisualizationTest(unittest.TestCase):

	def setUp(self):
		self.visualizationCT = VolumeVisualizationFactory.CreateProperty(visualizationType=VisualizationTypeCT)
		self.visualizationSimple = VolumeVisualizationFactory.CreateProperty(visualizationType=VisualizationTypeSimple)

	def tearDown(self):
		del self.visualizationCT

	def testVolumeVisualization(self):
		self.assertTrue(self.visualizationCT is not None)

	def testvtkVolumePropertyWrapper(self):
		self.assertIsNotNone(self.visualizationCT.volProp)

		self.volumePropWrap = vtkVolumePropertyWrapper(self.visualizationCT.volProp)

		self.assertIsNotNone(self.volumePropWrap.independentComponents)
		self.assertIsNotNone(self.volumePropWrap.interpolationType)

	def testvtkVolumePropertyWrapperGetter(self):
		volPropWrapper = vtkVolumePropertyWrapper()
		volPropWrapper.setOriginalObject(self.visualizationCT.volProp)
		vtkVolProp = volPropWrapper.originalObject()
		# Check that it is a vtkVolumeProperty by checking specific vtkVolumeProperty attributes
		self.assertTrue(hasattr(vtkVolProp, "GetIndependentComponents"))
		self.assertEqual(self.visualizationCT.volProp.GetAmbient(), vtkVolProp.GetAmbient())

	def testvtkVolumePropertyWrapperYaml(self):
		volPropWrapper = vtkVolumePropertyWrapper()
		volPropWrapper.setOriginalObject(self.visualizationCT.volProp)

		dump = yaml.dump(volPropWrapper)
		VolumeVisualizationWrapper2 = yaml.load(dump)

		self.assertEqual(volPropWrapper.independentComponents, VolumeVisualizationWrapper2.independentComponents)
		self.assertEqual(volPropWrapper.interpolationType, VolumeVisualizationWrapper2.interpolationType)
		self.assertEqual(volPropWrapper.shade, VolumeVisualizationWrapper2.shade)

	def testvtkColorTransferFunctionWrapper(self):
		self.visualizationCT.updateTransferFunction()

		colorFunctionWrapper = vtkColorTransferFunctionWrapper()
		colorFunctionWrapper.setOriginalObject(self.visualizationCT.colorFunction)

		self.assertEqual(len(colorFunctionWrapper.nodes), self.visualizationCT.colorFunction.GetSize())

	def testColorTransferFunctionYaml(self):
		self.visualizationCT.updateTransferFunction()

		colorFunctionWrapper = vtkColorTransferFunctionWrapper()
		colorFunctionWrapper.setOriginalObject(self.visualizationCT.colorFunction)
		dump = yaml.dump(colorFunctionWrapper)
		colorFunctionWrapper2 = yaml.load(dump)

		self.assertEqual(len(colorFunctionWrapper.nodes), len(colorFunctionWrapper2.nodes))

	def testColorTransferFunctionWrapperGetter(self):
		self.visualizationCT.updateTransferFunction()

		colorFunctionWrapper = vtkColorTransferFunctionWrapper()
		colorFunctionWrapper.setOriginalObject(self.visualizationCT.colorFunction)
		colorFunction = colorFunctionWrapper.originalObject()

		self.assertEqual(len(colorFunctionWrapper.nodes), colorFunction.GetSize())

	def testPiecewiseFunctionWrapper(self):
		self.visualizationSimple.updateTransferFunction()

		piecewiseFunctionWrapper = vtkPiecewiseFunctionWrapper()
		piecewiseFunctionWrapper.setOriginalObject(self.visualizationSimple.opacityFunction)

		self.assertEqual(len(piecewiseFunctionWrapper.nodes), self.visualizationSimple.opacityFunction.GetSize())

	def testPiecewiseFunctionWrapperGetter(self):
		self.visualizationSimple.updateTransferFunction()

		piecewiseFunctionWrapper = vtkPiecewiseFunctionWrapper()
		piecewiseFunctionWrapper.setOriginalObject(self.visualizationSimple.opacityFunction)
		piecewiseFunction = piecewiseFunctionWrapper.originalObject()

		self.assertTrue(piecewiseFunction.GetSize(), self.visualizationSimple.opacityFunction.GetSize())

	def testPiecewiseFunctionWrapperYaml(self):
		self.visualizationSimple.updateTransferFunction()

		piecewiseFunctionWrapper = vtkPiecewiseFunctionWrapper(self.visualizationSimple.opacityFunction)
		dump = yaml.dump(piecewiseFunctionWrapper)
		piecewiseFunctionWrapper2 = yaml.load(dump)

		self.assertEqual(len(piecewiseFunctionWrapper.nodes), len(piecewiseFunctionWrapper2.nodes))

	def testVolumeVisualizationWrapper(self):
		self.visualizationSimple.updateTransferFunction()

		volPropWrapper = VolumeVisualizationWrapper(self.visualizationSimple)

		self.assertEqual(volPropWrapper.visualizationType, VisualizationTypeSimple)
		self.assertIsNotNone(volPropWrapper.volProp)
		self.assertIsNotNone(volPropWrapper.colorFunction)
		self.assertIsNotNone(volPropWrapper.opacityFunction)

		dump = yaml.dump(volPropWrapper)
		volPropWrapper2 = yaml.load(dump)

		self.assertEqual(volPropWrapper.visualizationType, volPropWrapper2.visualizationType)


text:
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;

namespace LinguagemCS6
{
    class ExpressionBodied
    {

        public static decimal CalculaPreco(decimal preco, int quantidade)
            => preco * quantidade;
        static void Main(string[] args)
        {
            WriteLine($"Valor do produto no estoque {CalculaPreco(10,2)}");

            var c = new carro
            {
                ID = 1,
                Modelo = "JEEP",
                AnoFabricacao = 2007,
                KmRodados = 800,
                Litros = 42
            };
            WriteLine($"O carro {c.Modelo}, fabricado em {c.AnoFabricacao} está com {c.Idade()} anos.");
            WriteLine($"Rodando {c.KmRodados} km com {c.Litros} litros, a média é de {c.Consumo():n2} km/litro.");
            WriteLine(c.ToString());

            var c2 = new carro
            {
                ID = 2,
                Modelo = "Landau",
                AnoFabricacao = 1980,
                KmRodados = 1200,
            };

        }
        class carro
        {
            public int ID { get; set; }
            public string Modelo { get; set; }
            public int Litros { get; set; }
            public double KmRodados { get; set; }
            public int AnoFabricacao { get; set; }
            public double Consumo()
                => KmRodados / Litros;
            public string Idade()
                => (DateTime.Now.Year - AnoFabricacao).ToString();
            public string ConsumoString()
                => Litros > 0? Consumo().ToString() : null;
            public override string ToString()
                => $"{ID} - {Modelo}";
        }
    }
}


text:
/*
 * PCB.h
 *
 * Author: Joshua Spence
 * SID:    308216350
 *
 * This file contains the functions relating to process control blocks (PCBs).
 */
#ifndef PCB_H_
#define PCB_H_

#define MAX_ARGS                        3 // maximum number of arguments to args array
#define LOWEST_PRIORITY                 3 // lowest priority (largest integer) that a process can be set to. priority will not be decremented below this value

#define REAL_TIME_PROCESS_PRIORITY      0 // priority of a real time process
#define REAL_TIME_PROCESS_MAX_MBYTES    64 // memory required for real time processes

#include <sys/types.h>
#include "MAB.h"

typedef struct PCB {
    unsigned int id; // unique identifier

    pid_t pid; // system process ID (0 when uninitialised)
    char * args[MAX_ARGS]; // program name and args - null terminated array

    unsigned int arrival_time; // time at which this process should begin execution
    unsigned int remaining_cpu_time; // remaining CPU time
    unsigned int priority; // priority of the process

    unsigned int num_printers; // number of printer resources required by the process
    unsigned int num_scanners; // number of scanner resources required by the process
    unsigned int num_modems; // number of modem resources required by the process
    unsigned int num_cds; // number of CD resources required by the process

    unsigned int mbytes; // size of memory required for this process
    MAB * memory; // the MAB assigned to this process

    struct PCB * prev; // prev PCB in the queue
    struct PCB * next; // next PCB in the queue
} PCB;

// Declaration to prevent compilation warnings
int kill(pid_t pid, int sig);

// Queue operations
PCB * create_null_PCB(void);
PCB * enqueue_PCB(PCB ** head, PCB ** pcb);
PCB * dequeue_PCB(PCB ** head);

// PCB operations
PCB * start_PCB(PCB **pcb);
PCB * decrement_remaining_cpu_time(PCB ** pcb);
PCB * lower_priority(PCB ** pcb);
PCB * suspend_PCB(PCB ** pcb);
PCB * restart_PCB(PCB ** pcb);
PCB * terminate_PCB(PCB ** pcb);
void free_PCB(PCB ** pcb);

#ifdef DEBUG
void print_PCB_queue(PCB * head);
void print_PCB(PCB * pcb);
#endif // #ifdef DEBUG
#endif // #ifndef PCB_H_


text:
package com.google.idea.blaze.base.sync;

import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.idea.blaze.base.model.primitives.WorkspacePath;
import com.google.idea.blaze.base.model.primitives.WorkspaceRoot;
import com.google.idea.blaze.base.scope.BlazeContext;
import com.google.idea.blaze.base.settings.BuildSystemName;
import com.google.idea.blaze.base.sync.workspace.WorkingSet;
import com.google.idea.blaze.base.vcs.BlazeVcsHandler;
import com.intellij.openapi.project.Project;
import javax.annotation.Nullable;

/** Provides a {@link BlazeVcsHandler} for integration tests. */
public class MockBlazeVcsHandler implements BlazeVcsHandler {

  @Override
  public String getVcsName() {
    return "Mock";
  }

  @Override
  public boolean handlesProject(BuildSystemName buildSystemName, WorkspaceRoot workspaceRoot) {
    return true;
  }

  @Override
  public ListenableFuture<WorkingSet> getWorkingSet(
      Project project,
      BlazeContext context,
      WorkspaceRoot workspaceRoot,
      ListeningExecutorService executor) {
    WorkingSet workingSet =
        new WorkingSet(ImmutableList.of(), ImmutableList.of(), ImmutableList.of());
    return Futures.immediateFuture(workingSet);
  }

  @Override
  public ListenableFuture<String> getUpstreamContent(
      Project project,
      BlazeContext context,
      WorkspaceRoot workspaceRoot,
      WorkspacePath path,
      ListeningExecutorService executor) {
    return Futures.immediateFuture("");
  }

  @Nullable
  @Override
  public BlazeVcsSyncHandler createSyncHandler(Project project, WorkspaceRoot workspaceRoot) {
    return null;
  }
}


text:
package org.pac4j.saml.metadata;

import org.opensaml.core.xml.XMLObject;
import org.opensaml.saml.metadata.resolver.MetadataResolver;

/**
 * Defines operations required to resolve metadata for idp and sp.
 * @author Misagh Moayyed
 * @since 1.7
 */
public interface SAML2MetadataResolver {
    MetadataResolver resolve();

    String getEntityId();

    String getMetadataPath();

    String getMetadata();

    XMLObject getEntityDescriptorElement();
}


text:
import os
import importlib
import sys
import dj_database_url

DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
SECRET_KEY = 'non-secret'
INSTALLED_APPS = ('opencivicdata.apps.BaseConfig', 'pupa',)

# scrape settings

SCRAPELIB_RPM = 60
SCRAPELIB_TIMEOUT = 60
SCRAPELIB_RETRY_ATTEMPTS = 3
SCRAPELIB_RETRY_WAIT_SECONDS = 20

CACHE_DIR = os.path.join(os.getcwd(), '_cache')
SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')

ENABLE_ELASTICSEARCH = False
ELASTICSEARCH_HOST = 'localhost'
ELASTICSEARCH_TIMEOUT = 2

# dump settings

API_KEY = os.environ.get('PUPA_API_KEY', None)
AWS_KEY = os.environ.get('AWS_KEY', None)
AWS_SECRET = os.environ.get('AWS_SECRET', None)

# Django settings
DEBUG = False
TEMPLATE_DEBUG = False

MIDDLEWARE_CLASSES = ()
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
            'datefmt': '%H:%M:%S'
        }
    },
    'handlers': {
        'default': {'level': 'DEBUG',
                    'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
                    'formatter': 'standard'},
    },
    'loggers': {
        '': {
            'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
        },
        'scrapelib': {
            'handlers': ['default'], 'level': 'INFO', 'propagate': False
        },
        'requests': {
            'handlers': ['default'], 'level': 'WARN', 'propagate': False
        },
        'boto': {
            'handlers': ['default'], 'level': 'WARN', 'propagate': False
        },
    },
}

sys.path.insert(1, os.getcwd())
loader = importlib.find_loader('pupa_settings')
if loader is None:
    print('no pupa_settings on path, using defaults')
else:
    from pupa_settings import *     # NOQA

DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}


text:
import numpy

class KalmanFilter(object):
    """
    Discretized continuous-time Kalman filter.
    """
    def __init__(self, F, B, H, x, P, Q, R):
        self.F = F  # state transition matrix
        self.B = B  # control model matrix
        self.H = H  # measurement model matrix
        self.x = x  # state vector
        self.P = P  # state covariance matrix
        self.Q = Q  # process error covariance matrix
        self.R = R  # measurement error covariance matrix
        self.I = numpy.eye(self.P.shape[0])

    def predict(self, u=0, dt=1):
        """
        Time update: predict future state with control u.
        """
        # Update model and error matrices for current dt
        F = result(self.F, dt)
        B = result(self.B, dt)
        Q = result(self.Q, dt)

        # Compute state prediction
        self.x = F * self.x + B * u

        # Incorporate process error
        self.P = (F * self.P) * F.T + Q

    def update(self, z):
        """
        Measurement update: incorporate measurement z.
        """
        # Compute estimate error (residual)
        y = z - self.H * self.x

        # Project into measurement space
        S = self.H * self.P * self.H.T + self.R

        # Compute Kalman gain
        K = self.P * self.H.T * S.I

        # Compute maximum likelihood state estimate
        self.x = self.x + K * y

        # Incorporate measurement error
        I_KH = self.I - K * self.H
        self.P = (I_KH * self.P) * I_KH.T + (K * self.R) * K.T

def result(f, *args, **kwargs):
    if callable(f):
        return f(*args, **kwargs)
    return f


text:
@implementation SPTopic

static  NSDateFormatter *dateFormatter;
static   NSCalendar *calendar;

#pragma 一次性初始化对象
+ (void)initialize{
    //1.设置时间格式
   dateFormatter = [[NSDateFormatter alloc] init];
    //2.创建日历
   calendar= [NSCalendar sp_Calendar];
}

#pragma 重写created_at方法,在里面改写时间的格式
- (NSString *)created_at{

    dateFormatter.dateFormat = @"yyyy-MM-dd HH-mm-ss";
    //获取发帖时间
    NSDate *createAtDate = [dateFormatter dateFromString:_created_at];

    if ([createAtDate isThisYear]) {//今年
        if ([createAtDate isToday]) {//今天

            //获取改时间和现在事件的components
            NSDateComponents *components = [createAtDate compareToNowDate];
            //间隔大于1小时
            if (components.hour < -1) {
                return [NSString stringWithFormat:@"%zd小时前", labs(components.hour)];
            }else if(components.minute < -1){  //间隔大于等于1分钟
                return [NSString stringWithFormat:@"%zd分钟前",labs(components.minute)];
            }else{ //间隔小雨1分钟
                return @"刚刚";
            }

        }else if ([createAtDate isYesterday]) {//昨天

            //设置时间格式、
            dateFormatter.dateFormat = @"昨天  HH:mm:ss";
            return [dateFormatter stringFromDate:createAtDate];

        } else {//其他天

            dateFormatter.dateFormat = @"MM-dd HH:mm:ss";
            return [dateFormatter stringFromDate:createAtDate];

        }

    }else {//非今年

        return _created_at;

    }

}

#pragma 重写cellHeight方法,获得当前cell的高度
- (CGFloat)cellHeight{

    //如果cellHeight不为0,不需要进行计算
    if (_cellHeight) return _cellHeight;
    //1.说说上端的高度
    _cellHeight += 55;

    //2.说说的高度
    CGSize textSize = [self.text boundingRectWithSize:CGSizeMake(SPScreenW - 2*SPCommonMargin, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size;
    _cellHeight += textSize.height + SPCommonMargin;

    //3.中间视图的高度
    if (self.type != SPTopicTypeJoke) {//视频,音频,图片 可以统一考虑图片设置问题imageW/imageH = uW/Wh
        CGFloat contentW = SPScreenW - 2*SPCommonMargin;
        CGFloat contentH = contentW * self.height/self.width;
        CGFloat contentX = SPCommonMargin;
        CGFloat contentY = _cellHeight;

        self.contentFrame = CGRectMake(contentX, contentY, contentW, contentH);

        _cellHeight += contentH + SPCommonMargin;
    }
    //4.最热评论的高度
    if (self.top_cmt.count) {//有最热评论
        _cellHeight += 25;
        //取出最热评论字典
        NSDictionary *cmtDic = self.top_cmt.firstObject;
        NSString *content = cmtDic[@"content"];
        if (content.length == 0) {
            content = @"语音评论";
        }
        //获取名称和内容
        NSString *username = cmtDic[@"user"][@"username"];
        NSString *mtText = [NSString stringWithFormat:@"%@ : %@",username,content];
        _cellHeight += [mtText boundingRectWithSize:CGSizeMake(SPScreenW - 2*SPCommonMargin, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.height +SPCommonMargin;
    }

    //5.工具条的高度
    _cellHeight += 35 + SPCommonMargin;

    return _cellHeight;
}
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.MapTour"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="5" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MapTourActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.xiledsystems.AlternateJavaBridgelib.ListPickerActivity2"></activity>

    </application>
</manifest>


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace CarrosAngulares.Carro
{
    public class CarroRepository : ICarroRepository
    {
        private int cont;
        private static String conexao = @"Data Source=(localdb)\Projects;Initial Catalog=carros;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";

        public CarroRepository()
        {
        }

        bool ICarroRepository.adicionarCarro(Carro car)
        {
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = conexao;
                conn.Open();
                String sql = "insert into dbo.carro (categoria, marca, tipo, modelo, ano, preco, proprietario, placa, cor, obs, data_aquisicao) values ("
                    + car.categoria + ","
                    + car.marca + ","
                    + car.tipo + ","
                    + "'" + car.modelo + "',"
                    + car.ano + ","
                    + car.preco.Replace(',', '.') + ","
                    + "'" + car.proprietario + "',"
                    +"'" + car.placa + "',"
                    +"'" + car.cor + "',"
                    +"'" + car.obs + "',"
                    +"'" + car.dataAquisicao + "'" +
                    ")";
                SqlCommand cmd = new SqlCommand(sql, conn);
                return cmd.ExecuteNonQuery() == 1;
            }
        }

        public List<Carro> listarDestaques()
        {
            var lista = new List<Carro>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = conexao;
                conn.Open();
                String sql = "Select top 5 * from dbo.carro order by preco desc";
                SqlCommand cmd = new SqlCommand(sql, conn);
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Carro c = new Carro();
                        c.codigo = (reader["id"]).ToString();
                        c.categoria = (reader["categoria"]).ToString();
                        c.marca = (reader["marca"]).ToString();
                        c.tipo = (reader["tipo"]).ToString();
                        c.modelo = (reader["modelo"]).ToString();
                        c.ano = (reader["ano"]).ToString();
                        c.preco = (reader["preco"]).ToString();
                        c.proprietario = (reader["proprietario"]).ToString();
                        c.placa = (reader["placa"]).ToString();
                        c.cor = (reader["cor"]).ToString();
                        c.obs = (reader["obs"]) != null ? (reader["obs"]).ToString() : "";
                        c.dataAquisicao = (reader["data_aquisicao"]).ToString();
                        lista.Add(c);
                    }
                }
            }
            return lista;
        }

        public List<Carro> listarFiltro(Filtro filtro)
        {
            var lista = new List<Carro>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = conexao;
                conn.Open();
                String sql = "Select * from dbo.carro where modelo like '%"+ filtro.palavraChave +"%' order by preco desc";
                SqlCommand cmd = new SqlCommand(sql, conn);
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Carro c = new Carro();
                        c.codigo = (reader["id"]).ToString();
                        c.categoria = (reader["categoria"]).ToString();
                        c.marca = (reader["marca"]).ToString();
                        c.tipo = (reader["tipo"]).ToString();
                        c.modelo = (reader["modelo"]).ToString();
                        c.ano = (reader["ano"]).ToString();
                        c.preco = (reader["preco"]).ToString();
                        c.proprietario = (reader["proprietario"]).ToString();
                        c.placa = (reader["placa"]).ToString();
                        c.cor = (reader["cor"]).ToString();
                        c.obs = (reader["obs"]) != null ? (reader["obs"]).ToString() : "";
                        c.dataAquisicao = (reader["data_aquisicao"]).ToString();
                        lista.Add(c);
                    }
                }
            }
            return lista;
        }

        public List<Marca> listarMarcas()
        {
            var lista = new List<Marca>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = conexao;
                conn.Open();
                String sql = "Select * from dbo.marca";
                SqlCommand cmd = new SqlCommand(sql, conn);
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        lista.Add(new Marca
                        {
                            id = Convert.ToInt16(reader["id"]),
                            descricao = reader["descricao"].ToString()
                        });
                    }
                }
            }
            return lista;
        }
    }
}


text:
* [Official site](https://www.unrealengine.com/zh-CN/what-is-unreal-engine-4)
* [Source code](https://www.unrealengine.com/zh-CN/ue4-on-github)
* [UnrealEngine on GitHub](https://github.com/EpicGames/UnrealEngine)
* [Source code on GitHub - old version](https://github.com/sinisterrook/unrealengine)
  Cloned: unreal-engine

* [Downloading Unreal Engine Source Code](https://docs.unrealengine.com/latest/INT/GettingStarted/DownloadingUnrealEngine/)
* [How can I access Epic's GitHub repository?](https://answers.unrealengine.com/questions/66686/when-i-go-on-githubepicgames-i-get-a-message-sayin.html)

* [Programming Guide](https://docs.unrealengine.com/latest/INT/Programming/index.html)
* [Document](http://api.unrealengine.com/INT/GettingStarted/DownloadingUnrealEngine/index.html)
* [Mobile Game Development](https://docs.unrealengine.com/en-us/Platforms/Mobile)

* [Unreal.js](https://github.com/ncsoft/Unreal.js)
  Unreal.js: Javascript runtime built for UnrealEngine 4

* [Mobile Game Development](https://docs.unrealengine.com/en-us/Platforms/Mobile)

## Document

* [Unreal Engine 4 vs. Unity: Which Game Engine Is Best for You?](https://www.pluralsight.com/blog/film-games/unreal-engine-4-vs-unity-game-engine-best)


text:
module Plugin::Ruby
  module Use include Plugin::Use
    def __use!(var)
      super
      __export("RUBYOPT", args[2])
      gem_path = raw("$HOME/.gem/$(basename #{var})")
      set_gem_paths!(gem_path)
      add_to_GEM_PATH(gem_path)
      add_to_PATH(raw("#{gem_path}/bin"))
    end
  end
end


text:
class Stock < ApplicationRecord
  has_many :user_stocks
  has_many :users, through: :user_stocks

  def self.find_by_ticker(ticker_symbol)
    where(ticker: ticker_symbol).first
  end

  def self.new_from_lookup(ticker_symbol)
    looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
    return nil unless looked_up_stock.name

    new_stock = new(ticker: looked_up_stock.symbol, name: looked_up_stock.name)
    new_stock.last_price = new_stock.price
    new_stock
  end

  def price
    closing_price = StockQuote::Stock.quote(ticker).close
    return "#{closing_price} (Closing)" if closing_price

    opening_price = StockQuote::Stock.quote(ticker).open
    return "#{opening_price} (Opening)" if opening_price
    "Unavailable"
  end
end


text:
using blink::WebServiceWorkerError;

namespace {

const char kDisabledErrorMessage[] =
    "ServiceWorker is disabled";
const char kDomainMismatchErrorMessage[] =
    "Scope and scripts do not have the same origin";

const uint32 kFilteredMessageClasses[] = {
  ServiceWorkerMsgStart,
  EmbeddedWorkerMsgStart,
};

}  // namespace

namespace content {

ServiceWorkerDispatcherHost::ServiceWorkerDispatcherHost(
    int render_process_id,
    MessagePortMessageFilter* message_port_message_filter)
    : BrowserMessageFilter(kFilteredMessageClasses,
                           arraysize(kFilteredMessageClasses)),
      render_process_id_(render_process_id),
      message_port_message_filter_(message_port_message_filter) {}

ServiceWorkerDispatcherHost::~ServiceWorkerDispatcherHost() {
  if (context_) {
    context_->RemoveAllProviderHostsForProcess(render_process_id_);
    context_->embedded_worker_registry()->RemoveChildProcessSender(
        render_process_id_);
  }
}

void ServiceWorkerDispatcherHost::Init(
    ServiceWorkerContextWrapper* context_wrapper) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ServiceWorkerDispatcherHost::Init,
                    this, make_scoped_refptr(context_wrapper)));
      return;
  }
  context_ = context_wrapper->context()->AsWeakPtr();
  context_->embedded_worker_registry()->AddChildProcessSender(
      render_process_id_, this);
}

void ServiceWorkerDispatcherHost::OnDestruct() const {
  BrowserThread::DeleteOnIOThread::Destruct(this);
}

bool ServiceWorkerDispatcherHost::OnMessageReceived(
    const IPC::Message& message,
    bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(
    ServiceWorkerDispatcherHost, message, *message_was_ok)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_RegisterServiceWorker,
                        OnRegisterServiceWorker)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_UnregisterServiceWorker,
                        OnUnregisterServiceWorker)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_ProviderCreated,
                        OnProviderCreated)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_ProviderDestroyed,
                        OnProviderDestroyed)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_AddScriptClient,
                        OnAddScriptClient)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_RemoveScriptClient,
                        OnRemoveScriptClient)
    IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_PostMessage, OnPostMessage)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerHostMsg_WorkerStarted,
                        OnWorkerStarted)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerHostMsg_WorkerStopped,
                        OnWorkerStopped)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerHostMsg_SendMessageToBrowser,
                        OnSendMessageToBrowser)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void ServiceWorkerDispatcherHost::OnRegisterServiceWorker(
    int32 thread_id,
    int32 request_id,
    const GURL& pattern,
    const GURL& script_url) {
  if (!context_ || !ServiceWorkerUtils::IsFeatureEnabled()) {
    Send(new ServiceWorkerMsg_ServiceWorkerRegistrationError(
        thread_id,
        request_id,
        WebServiceWorkerError::DisabledError,
        base::ASCIIToUTF16(kDisabledErrorMessage)));
    return;
  }

  // TODO(alecflett): This check is insufficient for release. Add a
  // ServiceWorker-specific policy query in
  // ChildProcessSecurityImpl. See http://crbug.com/311631.
  if (pattern.GetOrigin() != script_url.GetOrigin()) {
    Send(new ServiceWorkerMsg_ServiceWorkerRegistrationError(
        thread_id,
        request_id,
        WebServiceWorkerError::SecurityError,
        base::ASCIIToUTF16(kDomainMismatchErrorMessage)));
    return;
  }

  context_->RegisterServiceWorker(
      pattern,
      script_url,
      render_process_id_,
      base::Bind(&ServiceWorkerDispatcherHost::RegistrationComplete,
                 this,
                 thread_id,
                 request_id));
}

void ServiceWorkerDispatcherHost::OnUnregisterServiceWorker(
    int32 thread_id,
    int32 request_id,
    const GURL& pattern) {
  // TODO(alecflett): This check is insufficient for release. Add a
  // ServiceWorker-specific policy query in
  // ChildProcessSecurityImpl. See http://crbug.com/311631.
  if (!context_ || !ServiceWorkerUtils::IsFeatureEnabled()) {
    Send(new ServiceWorkerMsg_ServiceWorkerRegistrationError(
        thread_id,
        request_id,
        blink::WebServiceWorkerError::DisabledError,
        base::ASCIIToUTF16(kDisabledErrorMessage)));
    return;
  }

  context_->UnregisterServiceWorker(
      pattern,
      render_process_id_,
      base::Bind(&ServiceWorkerDispatcherHost::UnregistrationComplete,
                 this,
                 thread_id,
                 request_id));
}

void ServiceWorkerDispatcherHost::OnPostMessage(
    int64 registration_id,
    const base::string16& message,
    const std::vector<int>& sent_message_port_ids) {
  if (!context_ || !ServiceWorkerUtils::IsFeatureEnabled())
    return;

  std::vector<int> new_routing_ids(sent_message_port_ids.size());
  for (size_t i = 0; i < sent_message_port_ids.size(); ++i) {
    new_routing_ids[i] = message_port_message_filter_->GetNextRoutingID();
    MessagePortService::GetInstance()->UpdateMessagePort(
        sent_message_port_ids[i],
        message_port_message_filter_,
        new_routing_ids[i]);
  }

  context_->storage()->FindRegistrationForId(
      registration_id,
      base::Bind(&ServiceWorkerDispatcherHost::PostMessageFoundRegistration,
                 message,
                 sent_message_port_ids,
                 new_routing_ids));
}

namespace {
void NoOpStatusCallback(ServiceWorkerStatusCode status) {}
}  // namespace

// static
void ServiceWorkerDispatcherHost::PostMessageFoundRegistration(
    const base::string16& message,
    const std::vector<int>& sent_message_port_ids,
    const std::vector<int>& new_routing_ids,
    ServiceWorkerStatusCode status,
    const scoped_refptr<ServiceWorkerRegistration>& result) {
  if (status != SERVICE_WORKER_OK)
    return;
  DCHECK(result);

  // TODO(jsbell): Route message to appropriate version. crbug.com/351797
  ServiceWorkerVersion* version = result->active_version();
  if (!version)
    return;
  version->SendMessage(
      ServiceWorkerMsg_Message(message, sent_message_port_ids, new_routing_ids),
      base::Bind(&NoOpStatusCallback));
}

void ServiceWorkerDispatcherHost::OnProviderCreated(int provider_id) {
  if (!context_)
    return;
  if (context_->GetProviderHost(render_process_id_, provider_id)) {
    BadMessageReceived();
    return;
  }
  scoped_ptr<ServiceWorkerProviderHost> provider_host(
       new ServiceWorkerProviderHost(render_process_id_, provider_id));
  context_->AddProviderHost(provider_host.Pass());
}

void ServiceWorkerDispatcherHost::OnProviderDestroyed(int provider_id) {
  if (!context_)
    return;
  if (!context_->GetProviderHost(render_process_id_, provider_id)) {
    BadMessageReceived();
    return;
  }
  context_->RemoveProviderHost(render_process_id_, provider_id);
}

void ServiceWorkerDispatcherHost::OnAddScriptClient(
    int thread_id, int provider_id) {
  if (!context_)
    return;
  ServiceWorkerProviderHost* provider_host =
      context_->GetProviderHost(render_process_id_, provider_id);
  if (!provider_host)
    return;
  provider_host->AddScriptClient(thread_id);
}

void ServiceWorkerDispatcherHost::OnRemoveScriptClient(
    int thread_id, int provider_id) {
  if (!context_)
    return;
  ServiceWorkerProviderHost* provider_host =
      context_->GetProviderHost(render_process_id_, provider_id);
  if (!provider_host)
    return;
  provider_host->RemoveScriptClient(thread_id);
}

void ServiceWorkerDispatcherHost::RegistrationComplete(
    int32 thread_id,
    int32 request_id,
    ServiceWorkerStatusCode status,
    int64 registration_id) {
  if (status != SERVICE_WORKER_OK) {
    SendRegistrationError(thread_id, request_id, status);
    return;
  }

  Send(new ServiceWorkerMsg_ServiceWorkerRegistered(
      thread_id, request_id, registration_id));
}

void ServiceWorkerDispatcherHost::OnWorkerStarted(
    int thread_id, int embedded_worker_id) {
  if (!context_)
    return;
  context_->embedded_worker_registry()->OnWorkerStarted(
      render_process_id_, thread_id, embedded_worker_id);
}

void ServiceWorkerDispatcherHost::OnWorkerStopped(int embedded_worker_id) {
  if (!context_)
    return;
  context_->embedded_worker_registry()->OnWorkerStopped(
      render_process_id_, embedded_worker_id);
}

void ServiceWorkerDispatcherHost::OnSendMessageToBrowser(
    int embedded_worker_id,
    int request_id,
    const IPC::Message& message) {
  if (!context_)
    return;
  context_->embedded_worker_registry()->OnSendMessageToBrowser(
      embedded_worker_id, request_id, message);
}

void ServiceWorkerDispatcherHost::UnregistrationComplete(
    int32 thread_id,
    int32 request_id,
    ServiceWorkerStatusCode status) {
  if (status != SERVICE_WORKER_OK) {
    SendRegistrationError(thread_id, request_id, status);
    return;
  }

  Send(new ServiceWorkerMsg_ServiceWorkerUnregistered(thread_id, request_id));
}

void ServiceWorkerDispatcherHost::SendRegistrationError(
    int32 thread_id,
    int32 request_id,
    ServiceWorkerStatusCode status) {
  base::string16 error_message;
  blink::WebServiceWorkerError::ErrorType error_type;
  GetServiceWorkerRegistrationStatusResponse(
      status, &error_type, &error_message);
  Send(new ServiceWorkerMsg_ServiceWorkerRegistrationError(
      thread_id, request_id, error_type, error_message));
}

}  // namespace content


text:
'use strict';

var fs = require('fs');
var path = require('path');
var knox = require('knox');
var zlib = require('zlib');

var downloader;
function init (options) {
  downloader = knox.createClient(options);
}

function downloadFile (options, file, callback) {
  var remote = path.join(options.baseDir, file);
  var local = path.resolve(options.destDir, file);

  downloader.getFile(remote, function (err, response) {
    var isGzip = (response.headers['content-encoding'] === 'gzip');
    var stream = fs.createWriteStream(local);
    if (isGzip) {
      var gunzip = zlib.createGunzip();
      response.pipe(gunzip).pipe(stream);
    } else {
      response.pipe(stream);
    }

    stream.on('finish', function () {
      setImmediate(callback, null, local);
    });
  });
}

module.exports = downloadFile;
downloadFile.init = init;


text:
//
//  WallViewController.m
//  FlipView
//
//  Created by Reefaq Mohammed on 16/07/11.

//

#import "WallViewController.h"
#import "TitleAndTextView.h"
#import "Layout5.h"
#import "Layout6.h"
#import "Layout7.h"
#import "Layout8.h"

#import "Layout1.h"
#import "Layout2.h"
#import "Layout3.h"
#import "Layout4.h"

#import "UIViewExtention.h"
#import "AFKPageFlipper.h"
#import "FullScreenView.h"
#import "FooterView.h"
#import "HeaderView.h"

#import "MessageModel.h"

@implementation WallViewController

@synthesize viewControlerStack,gestureRecognizer,wallTitle;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if ( self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		[self.view setBackgroundColor:[UIColor whiteColor]];
		isInFullScreenMode = FALSE;

		NSMutableArray* messageArray = [[NSMutableArray alloc] init];

		for (int i = 1; i <= 18; i++) {

			MessageModel* messageModel1 = [[MessageModel alloc] init];
			messageModel1.messageID= i;
			messageModel1.userName = @"Harry Potter";
			messageModel1.userImage =  @"missing-people.png";
			messageModel1.createdAt = @"06/07/2011 at 01:00 AM";
			messageModel1.content = @"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

			[messageArray addObject:messageModel1];
			[messageModel1 release];
		}

		[self buildPages:messageArray];
		[messageArray release];
    }
    return self;
}

- (int)getRandomNumber:(int)from to:(int)to {
	return (int)from + random() % (to-from+1);
}

-(void)buildPages:(NSArray*)messageArrayCollection {

	self.view.autoresizesSubviews = YES;
	self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	viewControlerStack = [[NSMutableArray alloc] init];

	int remainingMessageCount = 0;
	int totalMessageCount = [messageArrayCollection count];
	int numOfGroup = totalMessageCount /5;

	remainingMessageCount = totalMessageCount;

	for (int i=1; i<=numOfGroup; i++) {

		remainingMessageCount = totalMessageCount - (i * 5);

		NSRange rangeForView = NSMakeRange( (i * 5) -5, 5);
		NSArray* messageArray= [messageArrayCollection subarrayWithRange:rangeForView];

		NSMutableDictionary* viewDictonary = [[[NSMutableDictionary alloc] init] autorelease];
		TitleAndTextView* view1forLayout;
		TitleAndTextView* view2forLayout;
		TitleAndTextView* view3forLayout;
		TitleAndTextView* view4forLayout;
		TitleAndTextView* view5forLayout;
		for (int i = 0; i < [messageArray count]; i++) {
			if (i == 0) {
				view1forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view1forLayout forKey:@"view1"];
			}
			if (i == 1) {
				view2forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view2forLayout forKey:@"view2"];
			}
			if (i == 2) {
				view3forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view3forLayout forKey:@"view3"];
			}
			if (i == 3) {
				view4forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view4forLayout forKey:@"view4"];
			}
			if (i == 4) {
				view5forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view5forLayout forKey:@"view5"];
			}
		}

		int randomNumber = [self getRandomNumber:5 to:8];

		Class class =  NSClassFromString([NSString stringWithFormat:@"Layout%d",randomNumber]);
		id layoutObject = [[[class alloc] init] autorelease];
		if ([layoutObject isKindOfClass:[LayoutViewExtention class]] ) {
			[(LayoutViewExtention*)layoutObject initalizeViews:viewDictonary];
			[(LayoutViewExtention*)layoutObject rotate:self.interfaceOrientation animation:NO];
			[(LayoutViewExtention*)layoutObject setFrame:self.view.bounds];
			((LayoutViewExtention*)layoutObject).autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
			[viewControlerStack addObject:layoutObject];
		}

	}

	if (remainingMessageCount > 0) {
			NSRange rangeForView = NSMakeRange( ([messageArrayCollection count]) - remainingMessageCount, remainingMessageCount);
			NSArray* messageArray= [messageArrayCollection subarrayWithRange:rangeForView];

			NSMutableDictionary* viewDictonary = [[[NSMutableDictionary alloc] init] autorelease];
			TitleAndTextView* view1forLayout;
			TitleAndTextView* view2forLayout;
			TitleAndTextView* view3forLayout;
			TitleAndTextView* view4forLayout;
			for (int i = 0; i < [messageArray count]; i++) {
				if (i == 0) {
					view1forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
					[viewDictonary setObject:view1forLayout forKey:@"view1"];
				}
				if (i == 1) {
					view2forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
					[viewDictonary setObject:view2forLayout forKey:@"view2"];
				}
				if (i == 2) {
					view3forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
					[viewDictonary setObject:view3forLayout forKey:@"view3"];
				}
				if (i == 3) {
					view4forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
					[viewDictonary setObject:view4forLayout forKey:@"view4"];
				}
			}

			Class class =  NSClassFromString([NSString stringWithFormat:@"Layout%d",remainingMessageCount]);
			id layoutObject = [[[class alloc] init] autorelease];
			if ([layoutObject isKindOfClass:[LayoutViewExtention class]] ) {
				[(LayoutViewExtention*)layoutObject initalizeViews:viewDictonary];
				[(LayoutViewExtention*)layoutObject rotate:self.interfaceOrientation animation:NO];
				[(LayoutViewExtention*)layoutObject setFrame:self.view.bounds];
				((LayoutViewExtention*)layoutObject).autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
				[viewControlerStack addObject:layoutObject];
			}

	}

	flipper = [[AFKPageFlipper alloc] initWithFrame:self.view.bounds];
	flipper.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	flipper.dataSource = self;

	[self.view addSubview:flipper];

}

#pragma mark -
#pragma mark Data source implementation

- (NSInteger) numberOfPagesForPageFlipper:(AFKPageFlipper *)pageFlipper {
	return [viewControlerStack count];
}

- (UIView *) viewForPage:(NSInteger) page inFlipper:(AFKPageFlipper *) pageFlipper {

	LayoutViewExtention* layoutView  = (LayoutViewExtention*)[viewControlerStack objectAtIndex:page-1];
	[layoutView setFrame:pageFlipper.bounds];
	[layoutView setHidden:FALSE];
	[layoutView setTag:page];
	[layoutView rotate:self.interfaceOrientation animation:NO];

	layoutView.alpha = 1;

	UIView* footerViewInLayout = (UIView*) [layoutView viewWithTag:200];
	[footerViewInLayout removeFromSuperview];

	UIView* headerViewInLayout = (UIView*) [layoutView viewWithTag:201];
	[(HeaderView*)headerViewInLayout rotate:self.interfaceOrientation animation:NO];

		FooterView* footerView = [[FooterView alloc] initWithFrame:CGRectMake(0, layoutView.frame.size.height - 20, layoutView.frame.size.width, 20)];
		[footerView setBackgroundColor:[UIColor whiteColor]];
		[footerView setTag:200];
		[footerView setFlipperView:flipper];
		[footerView setViewArray:viewControlerStack];
		[layoutView addSubview:footerView];
		[layoutView setBackgroundColor:[UIColor whiteColor]];
		[footerView release];

	if (headerViewInLayout == nil) {
		//self.wallTitle
		HeaderView* headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, layoutView.frame.size.width, 50)];
		headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		[headerView setWallTitleText:@"My Tweet"];
		[headerView setTag:201];
		[headerView setBackgroundColor:[UIColor whiteColor]];
		[layoutView addSubview:headerView];
		[headerView release];
	}

	return layoutView;
}

-(void)showViewInFullScreen:(UIViewExtention*)viewToShow withModel:(MessageModel*)model{
	if (!isInFullScreenMode) {
		isInFullScreenMode = TRUE;

		CGRect bounds = [UIScreen mainScreen].bounds;
		if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
			CGFloat width = bounds.size.width;
			bounds.size.width = bounds.size.height;
			bounds.size.height = width;
		}

		fullScreenBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, bounds.size.height)];
		fullScreenBGView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		[fullScreenBGView setBackgroundColor:RGBACOLOR(0,0,0,0.6)];
		fullScreenBGView.alpha = 0;
		[self.view addSubview:fullScreenBGView];

		viewToShowInFullScreen =  viewToShow;
		viewToShowInFullScreen.originalRect = viewToShowInFullScreen.frame;
		viewToShowInFullScreen.isFullScreen = TRUE;
		FullScreenView* fullView = [[FullScreenView alloc] initWithModel:model];
		fullView.frame = viewToShowInFullScreen.frame;
		fullView.viewToOverLap = viewToShowInFullScreen;
		fullView.fullScreenBG = fullScreenBGView;
		fullScreenView = fullView;
		[self.view addSubview:fullView];

		[self.view bringSubviewToFront:fullScreenBGView];
		[self.view bringSubviewToFront:fullView];

		[UIView beginAnimations:@"SHOWFULLSCREEN" context:NULL];
		[UIView setAnimationDuration:0.40];
		[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:nil cache:NO];
		fullScreenBGView.alpha = 1;
		if (self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
			[fullView setFrame:CGRectMake(10, 50, 768-20, 1004-60)];
		}else {
			[fullView setFrame:CGRectMake(10, 50, 1024-20, 746-60)];
		}
		[fullScreenView rotate:self.interfaceOrientation animation:YES];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(animationEnd:finished:context:)];
		[UIView commitAnimations];

	}

}

-(void)closeFullScreen {
	if (fullScreenView != nil) {
		fullScreenBGView.alpha=0;
		[fullScreenBGView removeFromSuperview];
		[fullScreenBGView release];

		fullScreenView.alpha = 0;
		[fullScreenView removeFromSuperview];
		[fullScreenView release];
		fullScreenView = nil;
		isInFullScreenMode = FALSE;
	}
}

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	if (fullScreenView != nil) {
		[UIView beginAnimations:@"WILLROTATE" context:NULL];
		[UIView setAnimationDuration:0.50];
		[UIView setAnimationCurve:UIViewAnimationOptionCurveEaseInOut];
		if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
			[fullScreenView setFrame:CGRectMake(10, 50, 768-20, 1004-60)];
		}else {
			[fullScreenView setFrame:CGRectMake(10, 50, 1024-20, 748-60)];
		}
		[fullScreenView rotate:toInterfaceOrientation animation:YES];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(animationEnd:finished:context:)];
		[UIView commitAnimations];
	}

	if ([viewControlerStack count] > 0) {
		LayoutViewExtention* layoutView = (LayoutViewExtention*)[viewControlerStack objectAtIndex:flipper.currentPage-1];
		[layoutView rotate:toInterfaceOrientation animation:YES];
		FooterView* footerView = (FooterView*)[layoutView viewWithTag:200];
		footerView.alpha = 0;
		HeaderView* headerView = (HeaderView*)[layoutView viewWithTag:201];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.10];
		if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
			[footerView setFrame:CGRectMake(0, 1004 - 20, 768, footerView.frame.size.height)];
		}else {
			[footerView setFrame:CGRectMake(0, 748 - 20, 1024, footerView.frame.size.height)];
		}
		[footerView rotate:toInterfaceOrientation animation:YES];
		[headerView rotate:toInterfaceOrientation animation:YES];
		[UIView commitAnimations];
	}

}

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
	if ([viewControlerStack count] > 0) {
		LayoutViewExtention* layoutView = (LayoutViewExtention*)[viewControlerStack objectAtIndex:flipper.currentPage-1];
		FooterView* footerView = (FooterView*)[layoutView viewWithTag:200];
		footerView.alpha = 1;
	}
}

- (void)animationEnd:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context {
	if ([animationID isEqualToString:@"WILLROTATE"]) {
		if (fullScreenView != nil) {
			[fullScreenView setBackgroundColor:RGBACOLOR(0,0,0,0.6)];
		}
	}else if ([animationID isEqualToString:@"FOOTER"]) {
		if (context) {
			((UIView*)context).alpha = 1;
		}
	}else if ([animationID isEqualToString:@"SHOWFULLSCREEN"]) {
		[fullScreenView showFields];
	}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

-(void) generateViews:(NSArray *)currentMesageArray {

	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	int remainingMessageCount = 0;
	int totalMessageCount = [currentMesageArray count];
	int numOfGroup = totalMessageCount /5;

	remainingMessageCount = totalMessageCount;

	for (int i=1; i<=numOfGroup; i++) {
		remainingMessageCount = totalMessageCount - (i * 5);

		NSRange rangeForView = NSMakeRange( (i * 5) -5, 5);
		NSArray* messageArray= [currentMesageArray subarrayWithRange:rangeForView];

		NSMutableDictionary* viewDictonary = [[NSMutableDictionary alloc] init];
		TitleAndTextView* view1forLayout;
		TitleAndTextView* view2forLayout;
		TitleAndTextView* view3forLayout;
		TitleAndTextView* view4forLayout;
		TitleAndTextView* view5forLayout;
		for (int i = 0; i < [messageArray count]; i++) {
			if (i == 0) {
				view1forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view1forLayout forKey:@"view1"];
			}
			if (i == 1) {
				view2forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view2forLayout forKey:@"view2"];
			}
			if (i == 2) {
				view3forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view3forLayout forKey:@"view3"];
			}
			if (i == 3) {
				view4forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view4forLayout forKey:@"view4"];
			}
			if (i == 4) {
				view5forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view5forLayout forKey:@"view5"];
			}
		}

		int randomNumber = [self getRandomNumber:5 to:8];

		Class class =  NSClassFromString([NSString stringWithFormat:@"Layout%d",randomNumber]);
		id layoutObject = [[[class alloc] init] autorelease];
		if ([layoutObject isKindOfClass:[LayoutViewExtention class]] ) {
			[(LayoutViewExtention*)layoutObject initalizeViews:viewDictonary];
			[(LayoutViewExtention*)layoutObject rotate:self.interfaceOrientation animation:NO];
			[(LayoutViewExtention*)layoutObject setFrame:self.view.bounds];
			((LayoutViewExtention*)layoutObject).autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
			[((LayoutViewExtention*)layoutObject) setHidden:TRUE];
			[viewControlerStack addObject:layoutObject];
		}
		[viewDictonary release];
	}

	flipper.numberOfPages = [viewControlerStack count];

	if (remainingMessageCount > 0) {
		NSRange rangeForView = NSMakeRange( [currentMesageArray count] - remainingMessageCount, remainingMessageCount);
		NSArray* messageArray= [currentMesageArray subarrayWithRange:rangeForView];

		NSMutableDictionary* viewDictonary = [[NSMutableDictionary alloc] init];
		TitleAndTextView* view1forLayout;
		TitleAndTextView* view2forLayout;
		TitleAndTextView* view3forLayout;
		TitleAndTextView* view4forLayout;
		for (int i = 0; i < [messageArray count]; i++) {
			if (i == 0) {
				view1forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view1forLayout forKey:@"view1"];
			}
			if (i == 1) {
				view2forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view2forLayout forKey:@"view2"];
			}
			if (i == 2) {
				view3forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view3forLayout forKey:@"view3"];
			}
			if (i == 3) {
				view4forLayout = [[[TitleAndTextView alloc] initWithMessageModel:(MessageModel*)[messageArray objectAtIndex:i]] autorelease];
				[viewDictonary setObject:view4forLayout forKey:@"view4"];
			}
		}

		Class class =  NSClassFromString([NSString stringWithFormat:@"Layout%d",remainingMessageCount]);
		id layoutObject = [[[class alloc] init] autorelease];
		if ([layoutObject isKindOfClass:[LayoutViewExtention class]] ) {
			[(LayoutViewExtention*)layoutObject initalizeViews:viewDictonary];
			[(LayoutViewExtention*)layoutObject rotate:self.interfaceOrientation animation:NO];
			[(LayoutViewExtention*)layoutObject setFrame:self.view.bounds];
			((LayoutViewExtention*)layoutObject).autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
			[((LayoutViewExtention*)layoutObject) setHidden:TRUE];
			[viewControlerStack addObject:layoutObject];
			numOfGroup += 1;
		}

		[viewDictonary release];
		flipper.numberOfPages = [viewControlerStack count];
	}

	LayoutViewExtention* layoutView = (LayoutViewExtention*)[viewControlerStack objectAtIndex:flipper.currentPage-1];
	FooterView* footerView = (FooterView*)[layoutView viewWithTag:200];
	[footerView performSelectorInBackground:@selector(updateBarButtons:) withObject:[NSString stringWithFormat:@"%d",numOfGroup]];

	[pool release];

}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	if (fullScreenBGView != nil) {
		[fullScreenBGView release];
	}
	[viewControlerStack release];
	[gestureRecognizer release];
	[flipper release];
	if (fullScreenView != nil) {
		[fullScreenView release];
	}
	[wallTitle release];
    [super dealloc];
}

@end


text:
package com.ccte.core;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**@类名 CCTEDocument
 * @说明	html文档类,用于解决html的include问题
 * @作者 Chenxj
 * @邮箱 chenios@foxmail.com
 * @日期 2017年4月7日-下午5:23:30
 */
public class CCTEDocument {
	private static final Pattern includePattern=Pattern.compile("<include src=.+?/>|<include src=.+?>[^<>]*?</include>");
	private static final Pattern srcPattern=Pattern.compile("(?<=src\\=\").*(?=\")");
	private List<CCTEElement>elements;
	private boolean hasRef=false;
	/**是否是代码片段,根据文件名是否包含snippet进行判断*/
	private boolean isSnippet=false;
	/**
	 * @param in
	 * @param charset
	 * @param filePath 文件路径用来判断是否包含snippet
	 */
	public CCTEDocument(InputStream in,Charset charset,String filePath){
		isSnippet=filePath.contains("snippet");
		int bufferSize=60000;
        byte[] buffer = new byte[bufferSize];
        ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
        int read;
        int remaining = bufferSize;
        try{
        	while (!Thread.interrupted()) {
                read = in.read(buffer);
                if (read == -1) break;
                if (read > remaining) {
                    outStream.write(buffer, 0, remaining);
                    break;
                }
                remaining -= read;
                outStream.write(buffer, 0, read);
            }
        }catch (Exception e) {
        	e.printStackTrace();
		}
        byte[]bytes=outStream.toByteArray();
        String html=new String(bytes,charset);

        Matcher matcher=includePattern.matcher(html);

        elements=new ArrayList<>();

		StringBuffer sb=new StringBuffer();
		while(matcher.find()){
			sb.delete(0, sb.length());
			matcher.appendReplacement(sb, "");
			elements.add(new CCTEElement(sb.toString(), null));
			elements.add(new CCTEElement(null, elementSrc(matcher.group())));
			if(!hasRef){
				hasRef=true;
			}
		}
		if(hasRef){
			sb.delete(0, sb.length());
			matcher.appendTail(sb);
			elements.add(new CCTEElement(sb.toString(), null));
		}else{
			sb=null;
			elements.add(new CCTEElement(html, null));
		}
	}
	public CCTEDocument repareRef(Map<String, CCTEDocument>cctedocMap){
		if(hasRef){
			int l=elements.size();
			for(int i=0;i<l;i++){
				if(elements.get(i).getRefName()!=null){
					elements.get(i).setRefDoc(cctedocMap.get(elements.get(i).getRefName()));
				}
			}
		}
		return this;
	}
	private String elementSrc(String s){
		Matcher matcher=srcPattern.matcher(s);
		if(matcher.find()){
			return matcher.group();
		}
		return null;
	}

	@Override
	public String toString() {
		if(elements==null){
			return "";
		}else{
			StringBuilder sb=new StringBuilder();
			int l=elements.size();
			for(int i=0;i<l;i++){
				sb.append(elements.get(i).toString());
			}
			return sb.toString();
		}
	}
	/**获取 isSnippet*/
	public boolean isSnippet() {
		return isSnippet;
	}
}


text:
struct PixRGBAF
{
	float Red;
	float Green;
	float Blue;
	float Alpha;
};

#define SPFLAGS_MAXGRADIENT 1

class FloatBitMap_t
{
public:
	int Width, Height;										// bitmap dimensions
	float *RGBAData;										// actual data

	FloatBitMap_t(void)										// empty one
	{
		Width=Height=0;
		RGBAData=0;
	}

	FloatBitMap_t(int width, int height);                  // make one and allocate space
	FloatBitMap_t(char const *filename);                   // read one from a file (tga or pfm)
	FloatBitMap_t(FloatBitMap_t const *orig);
	// quantize one to 8 bits
	void WriteTGAFile(char const *filename) const;

	bool LoadFromPFM(char const *filename);					// load from floating point pixmap (.pfm) file
	void WritePFM(char const *filename);					// save to floating point pixmap (.pfm) file

	void InitializeWithRandomPixelsFromAnotherFloatBM(FloatBitMap_t const &other);

	inline float & Pixel(int x, int y, int comp) const
	{
		Assert((x>=0) && (x<Width));
		Assert((y>=0) && (y<Height));
		return RGBAData[4*(x+Width*y)+comp];
	}

	inline float & PixelWrapped(int x, int y, int comp) const
	{
		// like Pixel except wraps around to other side
		if (x < 0)
			x+=Width;
		else
			if (x>= Width)
				x -= Width;

		if ( y < 0 )
			y+=Height;
		else
			if ( y >= Height )
				y -= Height;

		return RGBAData[4*(x+Width*y)+comp];
	}

	inline float & PixelClamped(int x, int y, int comp) const
	{
		// like Pixel except wraps around to other side
		x=clamp(x,0,Width-1);
		y=clamp(y,0,Height-1);
		return RGBAData[4*(x+Width*y)+comp];
	}

	inline float & Alpha(int x, int y) const
	{
		Assert((x>=0) && (x<Width));
		Assert((y>=0) && (y<Height));
		return RGBAData[3+4*(x+Width*y)];
	}

	// look up a pixel value with bilinear interpolation
	float InterpolatedPixel(float x, float y, int comp) const;

	inline PixRGBAF PixelRGBAF(int x, int y) const
	{
		Assert((x>=0) && (x<Width));
		Assert((y>=0) && (y<Height));

		PixRGBAF RetPix;
		int RGBoffset= 4*(x+Width*y);
		RetPix.Red= RGBAData[RGBoffset+0];
		RetPix.Green= RGBAData[RGBoffset+1];
		RetPix.Blue= RGBAData[RGBoffset+2];
		RetPix.Alpha= RGBAData[RGBoffset+3];

		return RetPix;
	}

	inline void WritePixelRGBAF(int x, int y, PixRGBAF value) const
	{
		Assert((x>=0) && (x<Width));
		Assert((y>=0) && (y<Height));

		int RGBoffset= 4*(x+Width*y);
		RGBAData[RGBoffset+0]= value.Red;
		RGBAData[RGBoffset+1]= value.Green;
		RGBAData[RGBoffset+2]= value.Blue;
		RGBAData[RGBoffset+3]= value.Alpha;

	}

	inline void WritePixel(int x, int y, int comp, float value)
	{
		Assert((x>=0) && (x<Width));
		Assert((y>=0) && (y<Height));
		RGBAData[4*(x+Width*y)+comp]= value;
	}

	// paste, performing boundary matching. Alpha channel can be used to make
	// brush shape irregular
	void SmartPaste(FloatBitMap_t const &brush, int xofs, int yofs, uint32 flags);

	// force to be tileable using poisson formula
	void MakeTileable(void);

	void ReSize(int NewXSize, int NewYSize);

	void LoadBRC(char const *filename);

	// find the bounds of the area that has non-zero alpha.
	void GetAlphaBounds(int &minx, int &miny, int &maxx,int &maxy);

	// Solve the poisson equation for an image. The alpha channel of the image controls which
	// pixels are "modifiable", and can be used to set boundary conditions. Alpha=0 means the pixel
	// is locked.  deltas are in the order [(x,y)-(x,y-1),(x,y)-(x-1,y),(x,y)-(x+1,y),(x,y)-(x,y+1)
	void Poisson(FloatBitMap_t *deltas[4],
		int n_iters,
		uint32 flags                                  // SPF_xxx
		);

	FloatBitMap_t *QuarterSize(void) const;					// get a new one downsampled
	FloatBitMap_t *QuarterSizeBlocky(void) const;          // get a new one downsampled

	FloatBitMap_t *QuarterSizeWithGaussian(void) const;		// downsample 2x using a gaussian

	void RaiseToPower(float pow);
	void ScaleGradients(void);
	void Logize(void);                                        // pix=log(1+pix)
	void UnLogize(void);                                      // pix=exp(pix)-1

	// compress to 8 bits converts the hdr texture to an 8 bit texture, encoding a scale factor
	// in the alpha channel. upon return, the original pixel can be (approximately) recovered
	// by the formula rgb*alpha*overbright.
	// this function performs special numerical optimization on the texture to minimize the error
	// when using bilinear filtering to read the texture.
	void CompressTo8Bits(float overbright);
	// decompress a bitmap converted by CompressTo8Bits
	void Uncompress(float overbright);

	Vector AverageColor(void);								// average rgb value of all pixels
	float BrightestColor(void);								// highest vector magnitude

	void Clear(float r, float g, float b, float alpha);		// set all pixels to speicifed values (0..1 nominal)

	void ScaleRGB(float scale_factor);						// for all pixels, r,g,b*=scale_factor

	~FloatBitMap_t();

	void AllocateRGB(int w, int h)
	{
		if (RGBAData) delete[] RGBAData;
		RGBAData=new float[w*h*4];
		Width=w;
		Height=h;
	}
};

// a FloatCubeMap_t holds the floating point bitmaps for 6 faces of a cube map
class FloatCubeMap_t
{
public:
	FloatBitMap_t face_maps[6];

	FloatCubeMap_t(int xfsize, int yfsize)
	{
		// make an empty one with face dimensions xfsize x yfsize
		for(int f=0;f<6;f++)
			face_maps[f].AllocateRGB(xfsize,yfsize);
	}

	// load basenamebk,pfm, basenamedn.pfm, basenameft.pfm, ...
	FloatCubeMap_t(char const *basename);

	// save basenamebk,pfm, basenamedn.pfm, basenameft.pfm, ...
	void WritePFMs(char const *basename);

	Vector AverageColor(void)
	{
		Vector ret(0,0,0);
		int nfaces=0;
		for(int f=0;f<6;f++)
			if (face_maps[f].RGBAData)
			{
				nfaces++;
				ret+=face_maps[f].AverageColor();
			}
			if (nfaces)
				ret*=(1.0/nfaces);
			return ret;
	}

	float BrightestColor(void)
	{
		float ret=0.0;
		int nfaces=0;
		for(int f=0;f<6;f++)
			if (face_maps[f].RGBAData)
			{
				nfaces++;
				ret=max(ret,face_maps[f].BrightestColor());
			}
			return ret;
	}

	Vector PixelDirection(int face, int x, int y);
};

static inline float FLerp(float f1, float f2, float t)
{
	return f1+(f2-f1)*t;
}

// Image Pyramid class.
#define MAX_IMAGE_PYRAMID_LEVELS 16							// up to 64kx64k

enum ImagePyramidMode_t
{
	PYRAMID_MODE_GAUSSIAN,
};

class FloatImagePyramid_t
{
public:
	int m_nLevels;
	FloatBitMap_t *m_pLevels[MAX_IMAGE_PYRAMID_LEVELS];		// level 0 is highest res

	FloatImagePyramid_t(void)
	{
		m_nLevels=0;
		memset(m_pLevels,0,sizeof(m_pLevels));
	}

	// build one. clones data from src for level 0.
	FloatImagePyramid_t(FloatBitMap_t const &src, ImagePyramidMode_t mode);

	// read or write a Pixel from a given level. All coordinates are specified in the same domain as the base level.
	float &Pixel(int x, int y, int component, int level) const;

	FloatBitMap_t *Level(int lvl) const
	{
		Assert(lvl<m_nLevels);
		return m_pLevels[lvl];
	}
	// rebuild all levels above the specified level
	void ReconstructLowerResolutionLevels(int starting_level);

	~FloatImagePyramid_t(void);

	void WriteTGAs(char const *basename) const;				// outputs name_00.tga, name_01.tga,...
};

#endif