text:
from data_collection import *
DATE_B = "20000101"
DATE_E = datetime.today().strftime("%Y%m%d")

def get_price(sec, date_b, date_e, filename=None):
    if filename is None:

        possible_filename = "/CSV_price_google/" + sec + ".csv"
        if os.path.isfile(possible_filename):
            return read_api_csv(possible_filename, sec).get_price(date_b, date_e)
        else:
            qt = GoogleQuote(sec, DATE_B, DATE_E)
            qt.write_csv(possible_filename)
            return read_api_csv(possible_filename, sec).get_price(date_b, date_e)
    else:
        try:
            return read_yahoo_csv(filename, sec).get_price(date_b, date_e)
        except:
            return read_sse_csv(filename, sec).get_price(date_b, date_e)

def get_low_price(sec, date_b, date_e, filename=None):
    if filename is None:
        possible_filename = "/CSV_price_google/" + sec + ".csv"
        if os.path.isfile(possible_filename):
            return read_api_csv(possible_filename, sec).get_low_price(date_b, date_e)
        else:
            qt = GoogleQuote(sec, DATE_B, DATE_E)
            qt.write_csv(possible_filename)
            return read_api_csv(possible_filename, sec).get_low_price(date_b, date_e)
    else:
        try:
            return read_yahoo_csv(filename, sec).get_low_price(date_b, date_e)
        except:
            return read_sse_csv(filename, sec).get_low_price(date_b, date_e)

def get_high_price(sec, date_b, date_e, filename=None):
    if filename is None:
        possible_filename = "/Users/apple/Desktop/TCH_api/Technical/CSV_price_google/" + sec + ".csv"
        if os.path.isfile(possible_filename):
            return read_api_csv(possible_filename, sec).get_high_price(date_b, date_e)
        else:
            qt = GoogleQuote(sec, DATE_B, DATE_E)
            qt.write_csv(possible_filename)
            return read_api_csv(possible_filename, sec).get_high_price(date_b, date_e)
    else:
        try:
            return read_yahoo_csv(filename, sec).get_high_price(date_b, date_e)
        except Exception:
            return read_sse_csv(filename, sec).get_high_price(date_b, date_e)

def get_price_sma(sec, date_b, date_e, day_num, filename=None):
    trading_day_num = len(get_price(sec, date_b, date_e, filename)[1])
    trading_days_needed = trading_day_num + day_num - 1

    date_b = (datetime.strptime(date_b, "%Y%m%d") - timedelta(days=2*day_num)).strftime("%Y%m%d")
    raw_prices = get_price(sec, date_b, date_e, filename)[1][-trading_days_needed:]

    prev = np.array(raw_prices[:day_num]).sum() / day_num
    result = [prev]

    for i in range(day_num, trading_days_needed):
        prev = (prev * day_num + raw_prices[i] - raw_prices[i-day_num]) / day_num
        result.append(prev)

    return result

def get_price_sma_crossover(sec, date_b, date_e, fast, slow, filename=None):
    sma_fast = get_price_sma(sec, date_b, date_e, fast, filename=filename)
    sma_slow = get_price_sma(sec, date_b, date_e, slow, filename=filename)
    fast_slow = np.array(sma_fast) - np.array(sma_slow)
    dates, prices = get_price(sec, date_b, date_e, filename)

    cross_overs_up = []
    cross_overs_down = []

    for i in range(1, len(dates)):
        if fast_slow[i] > 0 and fast_slow[i-1] <= 0:
            cross_overs_up.append([i, prices[i]])
        elif fast_slow[i] < 0 and fast_slow[i-1] >= 0:
            cross_overs_down.append([i, prices[i]])

    return cross_overs_up, cross_overs_down

def get_price_return(sec, date_b, date_e, filename=None):
    day_to_day_return = []

    num_returned = len(get_price(sec, date_b, date_e, filename)[1])
    num_needed = num_returned + 1

    temps = get_price(sec, (datetime.strptime(date_b, "%Y%m%d") - timedelta(days=10)).strftime("%Y%m%d"), date_e, filename)
    datas = temps[1][-num_needed:]
    dates = temps[0][-num_returned:]
    for i in range(1, len(datas)):
        day_to_day_return.append((datas[i] - datas[i - 1]) / datas[i - 1] if datas[i - 1] != 0 else 0)

    return dates, day_to_day_return

def get_vol(sec, date_b, date_e, filename=None):
    if filename is None:
        possible_filename = "/Users/apple/Desktop/TCH_api/Technical/CSV_price_google/" + sec + ".csv"
        if os.path.isfile(possible_filename):
            return read_api_csv(possible_filename, sec).get_vol(date_b, date_e)
        else:
            qt = GoogleQuote(sec, DATE_B, DATE_E)
            qt.write_csv(possible_filename)
            return read_api_csv(possible_filename, sec).get_vol(date_b, date_e)
    else:
        try:
            return read_yahoo_csv(filename, sec).get_vol(date_b, date_e)
        except Exception:
            return read_sse_csv(filename, sec).get_vol(date_b, date_e)

def get_vol_change(sec, date_b, date_e, filename=None):
    day_to_day_change = []

    num_returned = len(get_vol(sec, date_b, date_e, filename)[1])
    num_needed = num_returned + 1

    temps = get_vol(sec, (datetime.strptime(date_b, "%Y%m%d") - timedelta(days=10)).strftime("%Y%m%d"), date_e, filename)
    datas = temps[1][-num_needed:]
    dates = temps[0][-num_returned:]
    for i in range(1, len(datas)):
        day_to_day_change.append((datas[i] - datas[i - 1]) / datas[i - 1] if datas[i - 1] != 0 else 0)

    return dates, day_to_day_change

def get_vol_sma(sec, date_b, date_e, day_num, filename=None):
    trading_day_num = len(get_vol(sec, date_b, date_e, filename)[1])
    trading_days_needed = trading_day_num + day_num - 1

    date_b = (datetime.strptime(date_b, "%Y%m%d") - timedelta(days=2*day_num)).strftime("%Y%m%d")
    raw_vols = get_vol(sec, date_b, date_e, filename)[1][-trading_days_needed:]

    prev = np.array(raw_vols[:day_num]).sum() / day_num
    result = [prev]

    for i in range(day_num, trading_days_needed):
        prev = (prev * day_num + raw_vols[i] - raw_vols[i-day_num]) / day_num
        result.append(prev)

    return result

def date_subtract_days(date_e, num_days):
    return (datetime.strptime(date_e, "%Y%m%d") - timedelta(days=num_days)).strftime("%Y%m%d")

def date_add_days(date_e, num_days):
    return (datetime.strptime(date_e, "%Y%m%d") + timedelta(days=num_days)).strftime("%Y%m%d")

def get_date_b(sec, date_e, num_periods, filename=None):
    dates = []
    datee = date_subtract_days(date_e, 2 * num_periods)
    while len(dates) < num_periods + 1:
        print(datee)
        dates = get_price(sec, datee, date_e, filename)[0]
        datee = date_subtract_days(datee, 2 * num_periods)

    return dates[-num_periods-1 if date_e in dates else -num_periods]

def get_date_e(sec, date_e, num_periods, filename=None):
    dates = []
    datee = date_add_days(date_e, 2 * num_periods)
    while len(dates) < num_periods + 1:
        print(datee)
        dates = get_price(sec, datee, date_e, filename)[0]
        datee = date_add_days(datee, 2 * num_periods)

    return dates[num_periods if date_e in dates else num_periods-1]


text:
bool MailWindow::init()
{
    if (!CCLayer::init()) {
        return false;
    }

    this->setTouchEnabled(true);

    size = CCDirector::sharedDirector()->getWinSize();

    arr= CCArray::create();
    arr->retain();
    CCSprite *mbkg=CCSprite::create("zjm_bkg.png");
    mbkg->setPosition(ccp(size.width/2, size.height/2));
    this->addChild(mbkg);

    CCSprite* bkg = CCSprite::create("mailwindow_bkg.png");
    bkg->setPosition(ccp(size.width/2, size.height/2-5));
    this->addChild(bkg);

    CCMenuItemImage* btn_write= CCMenuItemImage::create("mail_btn_write_1.png", "mail_btn_write_2.png", this, menu_selector(MailWindow::clk_btn_write));

    CCMenu* menu = CCMenu::create(btn_write,NULL);
    menu->setPosition(ccp(size.width/2, 180));//ccp(size.width-100, 155)
    this->addChild(menu);

    int w = 420;
    int h = 430;
    tableView = CCTableView::create(this,CCSizeMake(0, 0));

    tableView->setViewSize(CCSizeMake(420, 420));
    //    tableView->setContentSize(CCSizeMake(0, 0)) ;
    tableView->setContentOffset(ccp(0, 400-140));
    tableView->setVerticalFillOrder(kCCTableViewFillBottomUp);
    tableView->setAnchorPoint(ccp(0, 0));

    tableView->setPosition(ccp(30,210));
    tableView->setDelegate(this);
    this->addChild(tableView);

    Json::FastWriter writer;
    Json::Value root;

    root["characterId"]=CData::getCData()->getCharactorId();

    string json_file=writer.write(root);
    SocketManager::getInstance()->sendMessage(json_file.c_str(), 501);
    this->schedule(schedule_selector(MailWindow::rec_501));
    load = Loading::create();
    this->addChild(load, 9999);

    return true;
}

void MailWindow::clk_btn_write()
{
    MailWrite::show();
}

void MailWindow::registerWithTouchDispatcher()
{

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,(std::numeric_limits<int>::min()), true);
    CCLayer::registerWithTouchDispatcher();
}

bool MailWindow::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{

    istouch=tableView->ccTouchBegan(touch, event);

    if(istouch)
    {
        return true;
    }
    else
    {
        return false;
    }
    // 因为回调调不到了,所以resume写在了这里
    //   CCLog("loading layer");
    return true;
}

void MailWindow::ccTouchMoved(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{
    if(istouch){

        tableView->ccTouchMoved(touch, event);
    }
}
void MailWindow::ccTouchEnded(cocos2d::CCTouch *touch, cocos2d::CCEvent *event)
{

    if (istouch) {
        tableView->ccTouchEnded(touch, event);

        istouch=false;

    }
}

void MailWindow::scrollViewDidScroll(CCScrollView* view)
{

}
void MailWindow::scrollViewDidZoom(CCScrollView* view)
{

}

unsigned int MailWindow::numberOfCellsInTableView(CCTableView *table)
{
    return arr->count();
}

void MailWindow::send_505()
{

}

void MailWindow::rec_505()
{
    Message *revMsg=(Message *)CData::getCData()->m_dictionary->objectForKey(505);
    CData::getCData()->m_dictionary->removeObjectForKey(505);

    if(revMsg)
    {

        load->removeFromParent();

        this->unschedule(schedule_selector(MailWindow::rec_505));

        char* data=revMsg->data;
        CCLog("%s",data);
        Json::Reader read;
        Json::Value root;
        Json::Value jsonData;

        if(read.parse(data, root)){
            jsonData=root["data"];
            MailInfo* info = (MailInfo*)(arr->objectAtIndex(tmpid));
            info->isReaded = 1;
            info->content = jsonData["content"].asString();

            tableView->reloadData();

            MailRead::show(info);
        }

    }

}

//处理触摸事件,可以计算点击的是哪一个子项
void MailWindow::tableCellTouched(CCTableView* table, CCTableViewCell* cell)
{
    CCLog("点击了  %d",cell->getIdx());

    load = Loading::create();
    this->addChild(load, 9999);

    Json::FastWriter writer;
    Json::Value root;

    root["characterId"]=CData::getCData()->getCharactorId();
    root["mailID"] = ((MailInfo*)(arr->objectAtIndex(cell->getIdx())))->mailId;

    string json_file=writer.write(root);
    SocketManager::getInstance()->sendMessage(json_file.c_str(), 505);
    this->schedule(schedule_selector(MailWindow::rec_505));

            tmpCell = (MailRenderer*)cell;
            tmpid = cell->getIdx();
  }
//每一项的宽度和高度
CCSize MailWindow::cellSizeForTable(CCTableView *table)
{
    return CCSizeMake(420, 80);
}
//生成列表每一项的内容
CCTableViewCell* MailWindow::tableCellAtIndex(CCTableView *table, unsigned int idx)
{

    MailRenderer *cell = NULL;// table->dequeueCell();
    cell =new MailRenderer();
    cell->setInfo((MailInfo*)(arr->objectAtIndex(idx)));
    return cell;
}

void MailWindow::rec_501()
{
    Message *revMsg=(Message *)CData::getCData()->m_dictionary->objectForKey(501);
    CData::getCData()->m_dictionary->removeObjectForKey(501);

    if(revMsg)
    {
         load->removeFromParent();

        this->unschedule(schedule_selector(MailWindow::rec_501));
        char* data=revMsg->data;
        CCLog("%s",data);
        Json::Reader read;
        Json::Value root;
        Json::Value jsonData;
        Json::Value petlist;

        if(read.parse(data, root)){
            jsonData=root["data"];
            petlist=jsonData["maillist"];

            int len = petlist.size();

            for (int i=0; i<len; i++) {

                MailInfo* info = new MailInfo();
                info->autorelease();

                info->mailId = petlist[i]["id"].asInt();
                info->isReaded = petlist[i]["isReaded"].asInt();
                info->sender = petlist[i]["sender"].asString();
                info->title = petlist[i]["title"].asString();
                info->sendTime = petlist[i]["sendTime"].asString();

                arr->addObject(info);

            }

        }
         tableView->reloadData();
    }

}

redpajama_set_name: RedPajamaGithub


text:
**Contributors**
- Márk Kővári
- Roland Szőke
- Máté Szokolai

This repository contains our submission for the 'Project Tools' course.

Our goal was to make an application which would act as a workout planner and journal.

Features include:
- Choosing from premade *Worksheet*s, which describe a workout plan.
    - The plans vary in length, difficulty and complexity.
    - All of these attributes are displayed to the user when they choose a *Worksheet*
- Keeping a journal of the user's progress and completion of the chosen *Worksheet*
    - The user can complete a Workout, which consists of several predetermined exercises.
        - Notes can be assigned to each individual exercise.
        - Individual exercises can be marked skipped by not putting in it's parameters.
    - A Workout can be skipped, which will result in all of its exercises being skipped.

We have developed a solution which consists of the following layers:

- The **Front-end layer**, the layer the user will be interacting with. This layer will be ran in a web browser, written in JavaScript and consuming the REST API the server layer provides.
    - *responsible : Roland Szőke*
- The **Server layer**, which implements most of the business logic, provides the REST API and handles authentication. Written in C++ and using a HTTP framework, Pistache.
    - *responsible : Máté Szokolai*
- The **Database layer**, which ensures data persistance and implements the database interface for the Server layer. TODO: what it uses
    - *responsible : Márk Kővári*

**Note:** Do not use Chrome , POST requests are unreliable. Firefox works 100%.

Instructions for running the **Client** :

````
cd client
npm i
npm start
````
This will only launch a webpack server, which **does not provide the REST API**

 Instructions for running the **Server** :

 Install libraries : [libjwt](https://github.com/benmcollins/libjwt), [libnet from Pistache](https://github.com/oktal/pistache/) and [jansson](https://github.com/akheron/jansson) (usually available from default repositories)

 Install tools: `make, cmake, g++`

 If you wish to run the **test suite** install `gtest, gcov, lcov, genhtml`

 To generate the documentation, you will need `doxygen`

 If you are using Visual Code, just press `F5` to run the currently selected launcher or use the Launch and Task tools to select another.

 If not,
 ````
 mkdir build
 cd build
 cmake ..
 make $your_target
 ````
 The targets are:
    -Server
    -Test
    -coverage - to generate the test code coverage report (run the Test executable first)
    -doc - to generate the documentation
    -cleanup - to remove CMake's temporary files

 This will put the binary into `/build/bin` with the name `Server` or `Test`. Since Pistache only works on Linux, the server only works on Linux as well.

 You will also need to build the Client in order to serve it:

 ````
 cd client
 npm run build
 ````


text:
#ifndef LIB_JSONNET_H
#define LIB_JSONNET_H

/** \file This file is a library interface for evaluating Jsonnet.  It is written in C++ but exposes
 * a C interface for easier wrapping by other languages.  See \see jsonnet_lib_test.c for an example
 * of using the library.
 */

#define LIB_JSONNET_VERSION "v0.8.0"

/** Return the version string of the Jsonnet interpreter.  Conforms to semantic versioning
 * http://semver.org/ If this does not match LIB_JSONNET_VERSION then there is a mismatch between
 * header and compiled library.
 */
const char *jsonnet_version(void);

/** Jsonnet virtual machine context. */
struct JsonnetVm;

/** Create a new Jsonnet virtual machine. */
struct JsonnetVm *jsonnet_make(void);

/** Set the maximum stack depth. */
void jsonnet_max_stack(struct JsonnetVm *vm, unsigned v);

/** Set the number of objects required before a garbage collection cycle is allowed. */
void jsonnet_gc_min_objects(struct JsonnetVm *vm, unsigned v);

/** Run the garbage collector after this amount of growth in the number of objects. */
void jsonnet_gc_growth_trigger(struct JsonnetVm *vm, double v);

/** Expect a string as output and don't JSON encode it. */
void jsonnet_string_output(struct JsonnetVm *vm, int v);

/** Callback used to load imports.
 *
 * The returned char* should be allocated with jsonnet_realloc.  It will be cleaned up by
 * libjsonnet when no-longer needed.
 *
 * \param ctx User pointer, given in jsonnet_import_callback.
 * \param base The directory containing the code that did the import.
 * \param rel The path imported by the code.
 * \param found_here Set this byref param to path to the file, absolute or relative to the
 *     process's CWD.  This is necessary so that imports from the content of the imported file can
 *     be resolved correctly.  Allocate memory with jsonnet_realloc.  Only use when *success = 0.
 *\ param success Set this byref param to 1 to indicate success and 0 for failure.
 * \returns The content of the imported file, or an error message.
 */
typedef char *JsonnetImportCallback(void *ctx, const char *base, const char *rel, char **found_here, int *success);

/** Allocate, resize, or free a buffer.  This will abort if the memory cannot be allocated.  It will
 * only return NULL if sz was zero.
 *
 * \param buf If NULL, allocate a new buffer.  If an previously allocated buffer, resize it.
 * \param sz The size of the buffer to return.  If zero, frees the buffer.
 * \returns The new buffer.
 */
char *jsonnet_realloc(struct JsonnetVm *vm, char *buf, size_t sz);

/** Override the callback used to locate imports.
 */
void jsonnet_import_callback(struct JsonnetVm *vm, JsonnetImportCallback *cb, void *ctx);

/** Bind a Jsonnet external var to the given value.
 *
 * Argument values are copied so memory should be managed by caller.
 */
void jsonnet_ext_var(struct JsonnetVm *vm, const char *key, const char *val);

/** Bind a Jsonnet external code var to the given value.
 *
 * Argument values are copied so memory should be managed by caller.
 */
void jsonnet_ext_code(struct JsonnetVm *vm, const char *key, const char *val);

/** If set to 1, will emit the Jsonnet input after parsing / desugaring. */
void jsonnet_debug_ast(struct JsonnetVm *vm, int v);

/** Set the number of lines of stack trace to display (0 for all of them). */
void jsonnet_max_trace(struct JsonnetVm *vm, unsigned v);

/** Evaluate a file containing Jsonnet code, return a JSON string.
 *
 * The returned string should be cleaned up with jsonnet_realloc.
 *
 * \param filename Path to a file containing Jsonnet code.
 * \param error Return by reference whether or not there was an error.
 * \returns Either JSON or the error message.
 */
char *jsonnet_evaluate_file(struct JsonnetVm *vm,
                            const char *filename,
                            int *error);

/** Evaluate a string containing Jsonnet code, return a JSON string.
 *
 * The returned string should be cleaned up with jsonnet_realloc.
 *
 * \param filename Path to a file (used in error messages).
 * \param snippet Jsonnet code to execute.
 * \param error Return by reference whether or not there was an error.
 * \returns Either JSON or the error message.
 */
char *jsonnet_evaluate_snippet(struct JsonnetVm *vm,
                               const char *filename,
                               const char *snippet,
                               int *error);

/** Evaluate a file containing Jsonnet code, return a number of JSON files.
 *
 * The returned character buffer contains an even number of strings, the filename and JSON for each
 * JSON file interleaved.  It should be cleaned up with jsonnet_realloc.
 *
 * \param filename Path to a file containing Jsonnet code.
 * \param error Return by reference whether or not there was an error.
 * \returns Either the error, or a sequence of strings separated by \0, terminated with \0\0.
 */
char *jsonnet_evaluate_file_multi(struct JsonnetVm *vm,
                                  const char *filename,
                                  int *error);

/** Evaluate a string containing Jsonnet code, return a number of JSON files.
 *
 * The returned character buffer contains an even number of strings, the filename and JSON for each
 * JSON file interleaved.  It should be cleaned up with jsonnet_realloc.
 *
 * \param filename Path to a file containing Jsonnet code.
 * \param snippet Jsonnet code to execute.
 * \param error Return by reference whether or not there was an error.
 * \returns Either the error, or a sequence of strings separated by \0, terminated with \0\0.
 */
char *jsonnet_evaluate_snippet_multi(struct JsonnetVm *vm,
                                     const char *filename,
                                     const char *snippet,
                                     int *error);

/** Complement of \see jsonnet_vm_make. */
void jsonnet_destroy(struct JsonnetVm *vm);

#endif


text:
Copyright (c) 2014 Jon Maur

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]

local FontManager = {}

local fonts = {}

local charcodes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-"\'\\'

--- Get a font.
-- If the font is already loaded, no need to load it again.
-- @param _strFont string, the font filename without the directory or the extention
-- @param _size the size of the font
-- @return the font
function FontManager.getFont(_strFont, _size)

	_strFont = _strFont or "gridblock"
	_size = _size or 24

	local font = fonts[_strFont]

	if font == nil then
		-- load the font
		print("Creating new font:", _strFont, _size)

		font = MOAIFont.new()
		if MOAIFileSystem.checkFileExists('res/fonts/'.._strFont..'.ttf') then
			font:loadFromTTF('res/fonts/'.._strFont..'.ttf', charcodes, _size)
		elseif MOAIFileSystem.checkFileExists('res/fonts/'.._strFont..'.fnt') then
			font:loadFromBMFont('res/fonts/'.._strFont..'.fnt')
		end

		fonts[_strFont] = {}
		fonts[_strFont][_size] = font
	elseif font[_size] == nil then
		-- have the font but it's a new size
		-- load the font
		print("Creating new font:", _strFont, _size)

		font = MOAIFont.new()
		if MOAIFileSystem.checkFileExists('res/fonts/'.._strFont..'.ttf') then
			font:loadFromTTF('res/fonts/'.._strFont..'.ttf', charcodes, _size)
		elseif MOAIFileSystem.checkFileExists('res/fonts/'.._strFont..'.fnt') then
			font:loadFromBMFont('res/fonts/'.._strFont..'.fnt')
		end

		fonts[_strFont][_size] = font
	else
		-- found it
		font = font[_size]
	end

	return font
end

--- Clear the font and all sizes from the FontManager
-- it doesn't matter if there are things still using it, lua will gc it later
-- BUT this does mean the font will be re-loaded if asked for again, regardless of
-- whether or not some other thing is using the same font
-- @param _strFont the same font filename you used with getFont()
function FontManager.clearFont(_strFont)
	fonts[_strFont] = nil
end

return FontManager


text:
require File.expand_path("../../setup", __FILE__)
require "middleware"

describe Middleware::Builder do
  let(:data) { { :data => [] } }
  let(:instance) { described_class.new }

  # This returns a proc that can be used with the builder
  # that simply appends data to an array in the env.
  def appender_proc(data)
    Proc.new { |env| env[:data] << data }
  end

  context "basic `use`" do
    it "should add items to the stack and make them callable" do
      data = {}
      proc = Proc.new { |env| env[:data] = true }

      instance.use proc
      instance.call(data)

      data[:data].should == true
    end

    it "should be able to add multiple items" do
      data = {}
      proc1 = Proc.new { |env| env[:one] = true }
      proc2 = Proc.new { |env| env[:two] = true }

      instance.use proc1
      instance.use proc2
      instance.call(data)

      data[:one].should == true
      data[:two].should == true
    end

    it "should be able to add another builder" do
      data  = {}
      proc1 = Proc.new { |env| env[:one] = true }

      # Build the first builder
      one   = described_class.new
      one.use proc1

      # Add it to this builder
      two   = described_class.new
      two.use one

      # Call the 2nd and verify results
      two.call(data)
      data[:one].should == true
    end

    it "should default the env to `nil` if not given" do
      result = false
      proc = Proc.new { |env| result = env.nil? }

      instance.use proc
      instance.call

      result.should be
     end
  end

  context "inserting" do
    it "can insert at an index" do
      instance.use appender_proc(1)
      instance.insert(0, appender_proc(2))
      instance.call(data)

      data[:data].should == [2, 1]
    end

    it "can insert next to a previous object" do
      proc2 = appender_proc(2)
      instance.use appender_proc(1)
      instance.use proc2
      instance.insert(proc2, appender_proc(3))
      instance.call(data)

      data[:data].should == [1, 3, 2]
    end

    it "can insert before" do
      instance.use appender_proc(1)
      instance.insert_before 0, appender_proc(2)
      instance.call(data)

      data[:data].should == [2, 1]
    end

    it "raises an exception if attempting to insert before an invalid object" do
      expect { instance.insert "object", appender_proc(1) }.
        to raise_error(RuntimeError)
    end

    it "can insert after" do
      instance.use appender_proc(1)
      instance.use appender_proc(3)
      instance.insert_after 0, appender_proc(2)
      instance.call(data)

      data[:data].should == [1, 2, 3]
    end

    it "raises an exception if attempting to insert after an invalid object" do
      expect { instance.insert_after "object", appender_proc(1) }.
        to raise_error(RuntimeError)
    end
  end

  context "replace" do
    it "can replace an object" do
      proc1 = appender_proc(1)
      proc2 = appender_proc(2)

      instance.use proc1
      instance.replace proc1, proc2
      instance.call(data)

      data[:data].should == [2]
    end

    it "can replace by index" do
      proc1 = appender_proc(1)
      proc2 = appender_proc(2)

      instance.use proc1
      instance.replace 0, proc2
      instance.call(data)

      data[:data].should == [2]
    end
  end

  context "deleting" do
    it "can delete by object" do
      proc1 = appender_proc(1)

      instance.use proc1
      instance.use appender_proc(2)
      instance.delete proc1
      instance.call(data)

      data[:data].should == [2]
    end

    it "can delete by index" do
      proc1 = appender_proc(1)

      instance.use proc1
      instance.use appender_proc(2)
      instance.delete 0
      instance.call(data)

      data[:data].should == [2]
    end
  end
end


text:
'use strict';

const ACTIONS_PREFIX = 'TODO/';

export const ADD_TODO = ACTIONS_PREFIX + 'ADD_TODO';

export function addTodo(id, todo) {
    return {
        type: ADD_TODO,
        payload: {id, todo}
    };
}

export const REMOVE_TODO = ACTIONS_PREFIX + 'REMOVE_TODO';

export function removeTodo(id) {
    return {
        type: REMOVE_TODO,
        payload: {id}
    };
}


text:
package asciitosvg

import "fmt"

// A RenderHint suggests ways the SVG renderer may appropriately represent this point.
type RenderHint int

const (
	// None indicates no hints are provided for this point.
	None RenderHint = iota
	// RoundedCorner indicates the renderer should smooth corners on this path.
	RoundedCorner
	// StartMarker indicates this point should have an SVG marker-start attribute.
	StartMarker
	// EndMarker indicates this point should have an SVG marker-end attribute.
	EndMarker
	// Tick indicates the renderer should mark a tick in the path at this point.
	Tick
	// Dot indicates the renderer should insert a filled dot in the path at this point.
	Dot
)

// A Point is an X,Y coordinate in the diagram's grid. The grid represents (0, 0) as the top-left
// of the diagram. The Point also provides hints to the renderer as to how it should be interpreted.
type Point struct {
	// The X coordinate of this point.
	X int
	// The Y coordinate of this point.
	Y int
	// Hints for the renderer.
	Hint RenderHint
}

// String implements fmt.Stringer on Point.
func (p Point) String() string {
	return fmt.Sprintf("(%d,%d)", p.X, p.Y)
}

// isHorizontal returns true if p1 and p2 are horizontally aligned.
func isHorizontal(p1, p2 Point) bool {
	d := p1.X - p2.X
	return d <= 1 && d >= -1 && p1.Y == p2.Y
}

// isVertical returns true if p1 and p2 are vertically aligned.
func isVertical(p1, p2 Point) bool {
	d := p1.Y - p2.Y
	return d <= 1 && d >= -1 && p1.X == p2.X
}

// The following functions return true when the diagonals are connected in various compass directions.
func isDiagonalSE(p1, p2 Point) bool {
	return p1.X-p2.X == -1 && p1.Y-p2.Y == -1
}
func isDiagonalSW(p1, p2 Point) bool {
	return p1.X-p2.X == 1 && p1.Y-p2.Y == -1
}
func isDiagonalNW(p1, p2 Point) bool {
	return p1.X-p2.X == 1 && p1.Y-p2.Y == 1
}
func isDiagonalNE(p1, p2 Point) bool {
	return p1.X-p2.X == -1 && p1.Y-p2.Y == 1
}


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

using Foundation;
using UIKit;

namespace ImageProtocol
{
	public class Application
	{
		static void Main (string[] args)
		{
			UIApplication.Main (args, null, "AppDelegate");
		}
	}
}