text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.296
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Xceed.Wpf.AvalonDock.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Xceed.Wpf.AvalonDock.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Auto Hide.
        /// </summary>
        public static string Anchorable_AutoHide {
            get {
                return ResourceManager.GetString("Anchorable_AutoHide", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Auto Hide.
        /// </summary>
        public static string Anchorable_BtnAutoHide_Hint {
            get {
                return ResourceManager.GetString("Anchorable_BtnAutoHide_Hint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Hide.
        /// </summary>
        public static string Anchorable_BtnClose_Hint {
            get {
                return ResourceManager.GetString("Anchorable_BtnClose_Hint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Window Position.
        /// </summary>
        public static string Anchorable_CxMenu_Hint {
            get {
                return ResourceManager.GetString("Anchorable_CxMenu_Hint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Dock.
        /// </summary>
        public static string Anchorable_Dock {
            get {
                return ResourceManager.GetString("Anchorable_Dock", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Dock as Tabbed Document.
        /// </summary>
        public static string Anchorable_DockAsDocument {
            get {
                return ResourceManager.GetString("Anchorable_DockAsDocument", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Float.
        /// </summary>
        public static string Anchorable_Float {
            get {
                return ResourceManager.GetString("Anchorable_Float", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Hide.
        /// </summary>
        public static string Anchorable_Hide {
            get {
                return ResourceManager.GetString("Anchorable_Hide", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Close.
        /// </summary>
        public static string Document_Close {
            get {
                return ResourceManager.GetString("Document_Close", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Close All But This.
        /// </summary>
        public static string Document_CloseAllButThis {
            get {
                return ResourceManager.GetString("Document_CloseAllButThis", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Window Position.
        /// </summary>
        public static string Document_CxMenu_Hint {
            get {
                return ResourceManager.GetString("Document_CxMenu_Hint", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Dock as Tabbed Document.
        /// </summary>
        public static string Document_DockAsDocument {
            get {
                return ResourceManager.GetString("Document_DockAsDocument", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Float.
        /// </summary>
        public static string Document_Float {
            get {
                return ResourceManager.GetString("Document_Float", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Move To Next Tab Group.
        /// </summary>
        public static string Document_MoveToNextTabGroup {
            get {
                return ResourceManager.GetString("Document_MoveToNextTabGroup", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Move To Previous Tab Group.
        /// </summary>
        public static string Document_MoveToPreviousTabGroup {
            get {
                return ResourceManager.GetString("Document_MoveToPreviousTabGroup", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to New Horizontal Tab Group.
        /// </summary>
        public static string Document_NewHorizontalTabGroup {
            get {
                return ResourceManager.GetString("Document_NewHorizontalTabGroup", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to New Vertical Tab Group.
        /// </summary>
        public static string Document_NewVerticalTabGroup {
            get {
                return ResourceManager.GetString("Document_NewVerticalTabGroup", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Maximize.
        /// </summary>
        public static string Window_Maximize {
            get {
                return ResourceManager.GetString("Window_Maximize", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Restore.
        /// </summary>
        public static string Window_Restore {
            get {
                return ResourceManager.GetString("Window_Restore", resourceCulture);
            }
        }
    }
}


text:
clean:
	rm *.png
	rm -rf __pycache__

test:
	nosetests tests/tests.py

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const DigsPrevalidator = require(`../../lib/definitions/prevalidator`);
const define = require(`../../lib/define`);

describe(`definitions/DigsPrevalidator`, () => {
  let sandbox;

  beforeEach(() => {
    sandbox = sinon.sandbox.create('DigsPrevalidator');
  });

  afterEach(() => {
    sandbox.restore();
  });

  it(`should be a function`, () => {
    expect(DigsPrevalidator).to.be.a('function');
  });

  describe(`static`, () => {
    describe(`method`, () => {
      describe(`prevalidate()`, () => {
        it(`should be a function`, () => {
          expect(DigsPrevalidator.prevalidate).to.be.a('function');
        });

        it(`should create a definition which creates an object with a ` +
          `"prevalidations" property`,
          () => {
            expect(DigsPrevalidator.prevalidate()()).to.have
              .property('prevalidations');
          });
      });
    });
  });

  describe(`init()`, () => {
    it(`should validate the object when a function is called`, () => {
      const validator = DigsPrevalidator.validator;
      const MyDef = define({
        methods: {
          foo() {
          }
        }
      }).compose(DigsPrevalidator)
        .prevalidate('foo',
          validator.object({
            bar: validator.string().required()
          }));

      const myDef = MyDef();
      expect(() => myDef.foo()).to.throw(Error);
      myDef.bar = 'baz';
      expect(() => myDef.foo()).not.to.throw();
    });
  });
});


text:
package org.apache.camel.attachment;

import java.io.File;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 */
public class MessageWithAttachmentRedeliveryIssueTest extends CamelTestSupport {

    @Test
    public void testMessageWithAttachmentRedeliveryIssue() throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(1);

        template.send("direct:start", new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody("Hello World");
                exchange.getIn(AttachmentMessage.class).addAttachment("message1.xml", new DataHandler(new FileDataSource(new File("src/test/data/message1.xml"))));
                exchange.getIn(AttachmentMessage.class).addAttachmentObject("message2.xml", new DefaultAttachment(new FileDataSource(new File("src/test/data/message2.xml"))));
            }
        });

        assertMockEndpointsSatisfied();

        AttachmentMessage msg = getMockEndpoint("mock:result").getReceivedExchanges().get(0).getIn(AttachmentMessage.class);
        Assert.assertNotNull(msg);

        assertEquals("Hello World", msg.getBody());
        Assert.assertTrue(msg.hasAttachments());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                onException(Exception.class).maximumRedeliveries(3).redeliveryDelay(0);

                from("direct:start")
                    .process(new Processor() {
                        private int counter;
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            if (counter++ < 2) {
                                throw new IllegalArgumentException("Forced");
                            }
                        }
                    }).to("mock:result");

            }
        };
    }
}


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Offlineimap Checker and notification in your macOS menu bar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content='Alert new emails and displays inbox count - install xbar for free to get started.'>
	<meta name='author' content='Andros Fenollosa'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<meta itemprop='name' content='Offlineimap Checker and notification in your macOS menu bar'>
	<meta itemprop='description' content='Alert new emails and displays inbox count - install xbar for free to get started.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Offlineimap Checker and notification in your macOS menu bar'>
	<meta name='twitter:description' content='Alert new emails and displays inbox count - install xbar for free to get started.'>
	<meta name='twitter:image' content='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Offlineimap Checker and notification in your macOS menu bar'>
	<meta property='og:description' content='Alert new emails and displays inbox count - install xbar for free to get started.'>
	<meta property='og:url' content='https://xbarapp.com/plugins/Email/offlineimap-notification.1s.py.html'>
	<meta property='og:site_name' content='xbar lets you put anything into your macOS menu bar'>
	<meta property='og:type' content='article'>
	<meta property='og:image' content='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<link rel='apple-touch-icon' sizes='180x180' href='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<link rel='icon' type='image/png' sizes='32x32' href='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<link rel='shortcut icon' href='https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

Offlineimap Checker and notification

										Andros Fenollosa (@tanrax on GitHub)

						Alert new emails and displays inbox count

						🖥 Open in xbar app

Requires xbar app

							offlineimap-notification.1s.py

						Edit

						Open on GitHub

#!/usr/bin/env python
# - * -coding: utf - 8 - * -
#
# <bitbar.title>Offlineimap Checker and notification</bitbar.title>
# <bitbar.version>v1.1</bitbar.version>
# <bitbar.author>Andros Fenollosa</bitbar.author>
# <bitbar.author.github>tanrax</bitbar.author.github>
# <bitbar.desc>Alert new emails and displays inbox count</bitbar.desc>
# <bitbar.image>https://programadorwebvalencia.com/wp-content/uploads/2016/07/Screen-Shot-2016-07-06-at-18.42.35.jpg</bitbar.image>
import os
import pickle
import tempfile
import re
from os.path import expanduser

# Location
PATH_MAIL = os.path.join(expanduser("~"), 'Mail')
DIR_NEW = 'INBOX/new'
ICON_EMPTY = '📪'
ICON_NEWS = '📬'

# Variables
SAVE_LOCATION = os.path.join(tempfile.gettempdir(),
                             'offlineimap-notification.pkl')
data_save = False
num_news = 0
data_temp = {}

try:
    dateFile = open(SAVE_LOCATION)
    data_temp = pickle.load(dateFile)
except:
    pass

def send_alert_osx(mail_from, mail_subject):
    os.system('osascript -e \'display notification \
    "{mail_subject}" with title "{mail_from}" sound name "Blow"\''
              .format(mail_from=mail_from, mail_subject=mail_subject))

def get_fields(path_mail):
    '''
    Function get elements: email from, email to and Subject

    return list(mail_from, mail_to, mail_subject)
    '''
    mail_from = False
    mail_from_temp = False
    mail_to = False
    mail_to_temp = False
    mail_subject = False
    mail_subject_temp = False
    f = open(path_mail, 'r')
    for line in f:
        mail_from_temp = re.search('(?<=[Ff]rom\: )(.*)(?=)', line)
        mail_to_temp = re.search('(?<=[Tt]o\: )(.*)(?=)', line)
        mail_subject_temp = re.search('(?<=[Ss]ubject\: )(.*)(?=)', line)
        if mail_from_temp:
            mail_from = mail_from_temp.group(1)
        if mail_to_temp:
            mail_to = mail_to_temp.group(1)
        if mail_subject_temp:
            mail_subject = mail_subject_temp.group(1)

    return {'mail_from': mail_from,
            'mail_to': mail_to,
            'mail_subject': mail_subject}

# Get info INGOX news
# Loop folders INBOX
list_dirs = os.listdir(os.path.join(PATH_MAIL))
data_news_emails = []
for name in list_dirs:
    path_news_INBOX = os.path.join(PATH_MAIL, name, DIR_NEW)
    if os.path.isdir(path_news_INBOX):
        # Loop mails news
        for name in os.listdir(path_news_INBOX):
            mail = os.path.join(path_news_INBOX, name)
            if os.path.isfile(mail):
                num_news += 1
                data_news_emails.append(get_fields(mail))

# Send notifications
# Check changes
if data_news_emails != data_temp:
    # Send native alert
    for item in data_news_emails:
        if item not in data_temp:
            print(item)
            send_alert_osx(item['mail_from'], item['mail_subject'])

# Save
data_save = open(SAVE_LOCATION, 'w+')
pickle.dump(data_news_emails, data_save)

# Print
icon = ICON_EMPTY
if num_news > 0:
    icon = ICON_NEWS
print('{icon}{num_news}'.format(icon=icon, num_news=num_news))

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
using UnityEngine;
using System;
using System.Collections.Generic;
using SinglePlayer.UI;
using Common;

namespace SinglePlayer {
	[Serializable]
	public struct TierUpgrade {
		public int level;
		public float health;
		public float attack;
		public float attackCooldown;
		public float speed;
		public float split;
		public float merge;
	}

	public class AIAttributeManager : MonoBehaviour {
		public List<TierUpgrade> tiers;
		public int maxTiersLimit;
		public AttributePanelUI attributePanelUI;
		public LevelRateHandler aiLevelRateHandler;

		public void Awake() {
			Debug.Log("Initializing AI attribute manager.");
			this.maxTiersLimit = Attributes.MAX_NUM_OF_LEVELS;
			this.tiers = new List<TierUpgrade>();
			for (int i = 0; i < this.maxTiersLimit; i++) {
				TierUpgrade tier = new TierUpgrade();
				if (i == 0) {
					tier.level = i + 1;
					tier.health = 3f;
					tier.attack = 1f;
					tier.speed = 1.2f;
					tier.split = 2f;
					tier.merge = 2f;
					tier.attackCooldown = 3f;
				}
				else {
					TierUpgrade previous = this.tiers[i - 1];
					tier.level = i + 1;
					tier.health = previous.health * 2f;
					tier.attack = previous.attack * 1.2f;
					tier.speed = previous.speed * 1.2f;
					tier.split = previous.split * 2f;
					tier.merge = previous.merge * 2f;
					tier.attackCooldown = previous.attackCooldown;
				}
				this.tiers.Add(tier);
			}
			GameObject tempAttribute = GameObject.FindGameObjectWithTag("AIAttributePanel");
			if (tempAttribute != null) {
				this.attributePanelUI = tempAttribute.GetComponent<AttributePanelUI>();
				if (this.attributePanelUI == null) {
					Debug.LogError("Something is not right.");
				}
			}
			//If tempAttribute is null, then it means the game does not allow the player to do customizations.
			//This means, the only scenario that doesn't allow the player to make customizations would be in
			//the menu screen, where the AI players are duking out without player's interventions.
		}

		public void Start() {
			if (this.attributePanelUI != null) {
				//This is only set if the game allows the player to do customizations to the AI players.
				//Else, the game is in the menu, with the AI players duking out in the background.
				this.aiLevelRateHandler = this.attributePanelUI.aiLevelingRatesObject;
				if (this.aiLevelRateHandler != null && this.aiLevelRateHandler.allAttributes != null) {
					List<LevelRate> healthList = this.aiLevelRateHandler.allAttributes[Category.Health.value];
					List<LevelRate> attackList = this.aiLevelRateHandler.allAttributes[Category.Attack.value];
					List<LevelRate> attackCooldownList = this.aiLevelRateHandler.allAttributes[Category.AttackCooldown.value];
					List<LevelRate> speedList = this.aiLevelRateHandler.allAttributes[Category.Speed.value];
					List<LevelRate> splitList = this.aiLevelRateHandler.allAttributes[Category.Split.value];
					List<LevelRate> mergeList = this.aiLevelRateHandler.allAttributes[Category.Merge.value];
					for (int i = 0; i < this.maxTiersLimit; i++) {
						TierUpgrade tierUpgrade = this.tiers[i];
						tierUpgrade.health = healthList[i].rate;
						tierUpgrade.attack = attackList[i].rate;
						tierUpgrade.attackCooldown = attackCooldownList[i].rate;
						tierUpgrade.speed = speedList[i].rate;
						tierUpgrade.split = splitList[i].rate;
						tierUpgrade.merge = mergeList[i].rate;
						this.tiers[i] = tierUpgrade;
					}
				}
				else {
					Debug.LogError("Something is wrong. Please check.");
				}
			}
		}

		public void SetHealthAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> healthList = this.aiLevelRateHandler.allAttributes[Category.Health.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < healthList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Health, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = healthList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - healthList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					healthList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.health = healthList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetAttackAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> attackList = this.aiLevelRateHandler.allAttributes[Category.Attack.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < attackList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Attack, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = attackList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - attackList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					attackList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.attack = attackList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetAttackCooldownAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> attackCooldownList = this.aiLevelRateHandler.allAttributes[Category.AttackCooldown.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < attackCooldownList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.AttackCooldown, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = attackCooldownList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - attackCooldownList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					attackCooldownList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.attackCooldown = attackCooldownList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetSpeedAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> speedList = this.aiLevelRateHandler.allAttributes[Category.Speed.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < speedList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Speed, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = speedList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - speedList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					speedList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.speed = speedList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetSplitAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> splitList = this.aiLevelRateHandler.allAttributes[Category.Split.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < splitList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Split, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = splitList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - splitList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					splitList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.split = splitList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetMergeAttribute(string mathExpression) {
			if (mathExpression.Equals("") || mathExpression.Length <= 0) {
				return;
			}
			List<LevelRate> mergeList = this.aiLevelRateHandler.allAttributes[Category.Merge.value];
			float previousAnswer = 0f;
			for (int i = 0; i < Attributes.MAX_NUM_OF_LEVELS; i++) {
				if (i < mergeList.Count) {
					float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Merge, i, i - 1, previousAnswer);
					previousAnswer = answer;
					LevelRate rate = mergeList[i];
					rate.rate = answer;
					rate.level = i + 1;
					if (i > 0) {
						float rateDiff = rate.rate - mergeList[i - 1].rate;
						if (rateDiff < 0) {
							rate.isIncreasing = -1;
						}
						else if (rateDiff > 0) {
							rate.isIncreasing = 1;
						}
						else {
							rate.isIncreasing = 0;
						}
					}
					mergeList[i] = rate;
				}
				if (i < this.tiers.Count) {
					TierUpgrade tier = this.tiers[i];
					tier.merge = mergeList[i].rate;
					this.tiers[i] = tier;
				}
			}
		}

		public void SetDirectHealthAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Health, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.health = answer;
				this.tiers[i] = tier;
			}
		}

		public void SetDirectAttackAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Attack, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.attack = answer;
				this.tiers[i] = tier;
			}
		}

		public void SetDirectSpeedAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Speed, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.speed = answer;
				this.tiers[i] = tier;
			}
		}

		public void SetDirectSplitAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Split, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.split = answer;
				this.tiers[i] = tier;
			}
		}

		public void SetDirectMergeAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.Merge, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.merge = answer;
				this.tiers[i] = tier;
			}
		}

		public void SetDirectAttackCooldownAttribute(string mathExpression) {
			float previousAnswer = 0f;
			for (int i = 0; i < this.tiers.Count; i++) {
				float answer = (float)MathParser.ProcessEquation(mathExpression, AttributeProperty.AttackCooldown, i, i - 1, previousAnswer);
				previousAnswer = answer;
				TierUpgrade tier = this.tiers[i];
				tier.attackCooldown = answer;
				this.tiers[i] = tier;
			}
		}
	}
}


text:
(function () {
    var TunnelPhantom = angular.module('TunnelPhantom')
    TunnelPhantom.provider('TunnelFieldsService', TunnelFieldsService);

    function TunnelFieldsService() {
        var _templateUrl,
            _fieldsUrl,
            _fields,
            _objectFields = {};

        function _loadFields() {
            var initInjector = angular.injector(['ng']);
            var $http = initInjector.get('$http');
            return $http.get(_fieldsUrl).then(function (request) {
                _fields = request.data;
                return _fields;
            });
        }

        this.setfieldsUrl = function (url) {
            _fieldsUrl = url;
        }
        this.setTemplateUrl = function (url) {
            _templateUrl = url;
        }
        this.$get = ['ProtoFieldFactory', '$q', '$log', '$cacheFactory', function (ProtoFieldFactory, $q, $log, $cacheFactory) {

            function _buildObjects(fields) {
                var templateBuffer = [], prev, name,fieldString;
                for (var i = 0, field; field = fields[i]; i++) {

                    name = field.name;
                    fieldString = 'tunnel.fields[\'' + name + '\']';

                    templateBuffer.push(['<div control-type-', field.type, ' parent-key="',fieldString,'.name" parent-tunnel="tunnel" field="',fieldString,'"></div>'].join(''));
                    _objectFields[name] = ProtoFieldFactory(field, field.type);
                    if (prev) {
                        _objectFields[name]['prev'] = prev;
                        prev['next'] = _objectFields[name];
                    }
                    prev = _objectFields[name];
                }
                return templateBuffer.join('');
            }

            function getFields() {
                if (!_fields) {
                    $log.error('The Fields are missing');
                }
                return _fields;
            }

            function getObjectFields(){
                if (Object.getOwnPropertyNames(_objectFields).length === 0) {
                    $log.error('The Fields are missing');
                }
                return _objectFields;
            }

            function getFirstObject() {
                if (!_fields || !_objectFields) {
                    $log.error('The Fields are missing');
                }
                return _objectFields[_fields[0].name];
            }

            function responseInterceptor(response) {
                var deferred = $q.defer();
                if (response.config.url == _templateUrl) {
                    _loadFields().then(function (fields) {
                        var data = response.data
                        response.data = data.replace('<!--replace-->', _buildObjects(fields))
                        deferred.resolve(response);
                    });
                } else {
                    deferred.resolve(response);
                }
                return deferred.promise;
            }

            function requestInterceptor(config) {
                var deferred = $q.defer();
                deferred.resolve(config);
                return deferred.promise;
            }

            var interceptor = {
                'response': responseInterceptor,
                'request': requestInterceptor,
                'getFields': getFields,
                'getObjectFields': getObjectFields,
                'getFirstObject': getFirstObject
            };
            return interceptor;
        }];
    }
})();


text:
var gulp = require('gulp');
var express = require('express');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var merge = require('merge-stream');
var del = require('del');

var port = 4000;

gulp.task('express', function(){

  var app = express();
  app.use(require('connect-livereload')({port: 4002}));
  app.use(express.static(__dirname));
  app.listen(port);

});

gulp.task('style', function(){

  return gulp.src('src/style/*.scss')
         .pipe(sass({style: 'expanded'}))
         .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
         }))
         .pipe(gulp.dest('src/style'))
         .pipe(minifycss())
         .pipe(rename(function(path){
            path.extname = ".min.css";
         }))
         .pipe(gulp.dest('src/style'));

});

gulp.task('clean:dest', function(cb){

  del('./dest', cb);

});

gulp.task('build', ['style', 'clean:dest'], function(){

  var js = gulp.src('src/js/pg-ng-range.js')
           .pipe(gulp.dest('dest/js'))
           .pipe(uglify({mangle: false}))
           .pipe(rename(function(path){
             path.extname = ".min.js";
           }))
           .pipe(gulp.dest('dest/js'));

  var css = gulp.src('src/style/*.css')
            .pipe(gulp.dest('dest/css'));

  return merge(js, css);

});

gulp.task('watch', function() {

  gulp.watch('src/style/*.scss', ['style']);
  gulp.watch('src/style/*.css', notifyLiveReload, ['style']);
  gulp.watch('index.html', notifyLiveReload);
  gulp.watch('src/js/*.js', notifyLiveReload);

});

var tinylr;
gulp.task('livereload', function() {
  tinylr = require('tiny-lr')();
  tinylr.listen(4002);
});

function notifyLiveReload(event) {
  var fileName = require('path').relative(__dirname, event.path);

  tinylr.changed({
    body: {
      files: [fileName]
    }
  });
}

gulp.task('server', ['style', 'express', 'livereload', 'watch'], function(){
  console.log('Awesomeness happens at local port: ' + port);
});


text:
<Type Name="ShaderParameterGroup" FullName="Urho.ShaderParameterGroup">
  <TypeSignature Language="C#" Value="public enum ShaderParameterGroup" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi sealed ShaderParameterGroup extends System.Enum" />
  <AssemblyInfo>
    <AssemblyName>Urho</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Enum</BaseTypeName>
  </Base>
  <Docs>

            Shader parameter groups for determining need to update. On APIs that support constant buffers, these correspond to different constant buffers.

    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="Camera">
      <MemberSignature Language="C#" Value="Camera" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Camera = int32(1)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Custom">
      <MemberSignature Language="C#" Value="Custom" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Custom = int32(6)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Frame">
      <MemberSignature Language="C#" Value="Frame" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Frame = int32(0)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Light">
      <MemberSignature Language="C#" Value="Light" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Light = int32(3)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Material">
      <MemberSignature Language="C#" Value="Material" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Material = int32(4)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="MaxShaderParameterGroups">
      <MemberSignature Language="C#" Value="MaxShaderParameterGroups" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup MaxShaderParameterGroups = int32(7)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Object">
      <MemberSignature Language="C#" Value="Object" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Object = int32(5)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Zone">
      <MemberSignature Language="C#" Value="Zone" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype Urho.ShaderParameterGroup Zone = int32(2)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.ShaderParameterGroup</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
  </Members>
</Type>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="index.css">


text:
//this has been modified to only read files.

/* ----------------------------------------------------------------------
 * RPly library, read PLY files
 * Diego Nehab, Princeton University
 * http://www.cs.princeton.edu/~diego/professional/rply
 *
 * This library is distributed under the MIT License. See notice
 * at the end of this file.
 * ---------------------------------------------------------------------- */
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <float.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stddef.h>

#include "rply.h"

/* ----------------------------------------------------------------------
 * Constants
 * ---------------------------------------------------------------------- */
#define WORDSIZE 256
#define LINESIZE 1024
#define BUFFERSIZE (8*1024)

static const char *const ply_storage_mode_list[] = {
    "binary_big_endian", "binary_little_endian", "ascii", NULL
};     /* order matches e_ply_storage_mode enum */

static const char *const ply_type_list[] = {
    "int8", "uint8", "int16", "uint16",
    "int32", "uint32", "float32", "float64",
    "char", "uchar", "short", "ushort",
    "int", "uint", "float", "double",
    "list", NULL
};     /* order matches e_ply_type enum */

/* ----------------------------------------------------------------------
 * Property reading callback argument
 *
 * element: name of element being processed
 * property: name of property being processed
 * nelements: number of elements of this kind in file
 * instance_index: index current element of this kind being processed
 * length: number of values in current list (or 1 for scalars)
 * value_index: index of current value int this list (or 0 for scalars)
 * value: value of property
 * pdata/idata: user data defined with ply_set_cb
 *
 * Returns handle to ply file if succesful, NULL otherwise.
 * ---------------------------------------------------------------------- */
typedef struct t_ply_argument_ {
    p_ply_element element;
    long instance_index;
    p_ply_property property;
    long length, value_index;
    double value;
    void *pdata;
    long idata;
} t_ply_argument;

/* ----------------------------------------------------------------------
 * Property information
 *
 * name: name of this property
 * type: type of this property (list or type of scalar value)
 * length_type, value_type: type of list property count and values
 * read_cb: function to be called when this property is called
 *
 * Returns 1 if should continue processing file, 0 if should abort.
 * ---------------------------------------------------------------------- */
typedef struct t_ply_property_ {
    char name[WORDSIZE];
    e_ply_type type, value_type, length_type;
    p_ply_read_cb read_cb;
    void *pdata;
    long idata;
} t_ply_property;

/* ----------------------------------------------------------------------
 * Element information
 *
 * name: name of this property
 * ninstances: number of elements of this type in file
 * property: property descriptions for this element
 * nproperty: number of properties in this element
 *
 * Returns 1 if should continue processing file, 0 if should abort.
 * ---------------------------------------------------------------------- */
typedef struct t_ply_element_ {
    char name[WORDSIZE];
    long ninstances;
    p_ply_property property;
    long nproperties;
} t_ply_element;

long get_nproperties(p_ply_element e) {
     return e->nproperties;
}

/* ----------------------------------------------------------------------
 * Input
 *
 * Depending on file mode, different functions are used to read
 * property fields. The drivers make it transparent to read in ascii,
 * big endian or little endian cases.
 * ---------------------------------------------------------------------- */
typedef int (*p_ply_ihandler)(p_ply ply, double *value);
typedef int (*p_ply_ichunk)(p_ply ply, void *anydata, size_t size);
typedef struct t_ply_idriver_ {
    p_ply_ihandler ihandler[16];
    p_ply_ichunk ichunk;
    const char *name;
} t_ply_idriver;
typedef t_ply_idriver *p_ply_idriver;

/* ----------------------------------------------------------------------
 * Ply file handle.
 *
 * storage_mode: mode of file associated with handle (from e_ply_storage_mode)
 * element: elements description for this file
 * nelement: number of different elements in file
 * comment: comments for this file
 * ncomments: number of comments in file
 * obj_info: obj_info items for this file
 * nobj_infos: number of obj_info items in file
 * fp: file pointer associated with ply file
 * c: last character read from ply file
 * buffer: last word/chunck of data read from ply file
 * buffer_first, buffer_last: interval of untouched good data in buffer
 * buffer_token: start of parsed token (line or word) in buffer
 * idriver: input driver used to get property fields from file
 * argument: storage space for callback arguments
 * error_cb: callback for error messages
 * ---------------------------------------------------------------------- */
typedef struct t_ply_ {
    e_ply_storage_mode storage_mode;
    p_ply_element element;
    long nelements;
    char *comment;
    long ncomments;
    char *obj_info;
    long nobj_infos;
    FILE *fp;
    int c;
    char buffer[BUFFERSIZE];
    size_t buffer_first, buffer_token, buffer_last;
    p_ply_idriver idriver;
    t_ply_argument argument;
    p_ply_error_cb error_cb;
} t_ply;

/* ----------------------------------------------------------------------
 * I/O functions and drivers
 * ---------------------------------------------------------------------- */
static t_ply_idriver ply_idriver_ascii;
static t_ply_idriver ply_idriver_binary;
static t_ply_idriver ply_idriver_binary_reverse;

static int ply_read_word(p_ply ply);
static int ply_check_word(p_ply ply);
static int ply_read_line(p_ply ply);
static int ply_check_line(p_ply ply);
static int ply_read_chunk(p_ply ply, void *anybuffer, size_t size);
static int ply_read_chunk_reverse(p_ply ply, void *anybuffer, size_t size);
static void ply_reverse(void *anydata, size_t size);

/* ----------------------------------------------------------------------
 * String functions
 * ---------------------------------------------------------------------- */
static int ply_find_string(const char *item, const char* const list[]);
 p_ply_element ply_find_element(p_ply ply, const char *name);
 p_ply_property ply_find_property(p_ply_element element,
        const char *name);

/* ----------------------------------------------------------------------
 * Header parsing
 * ---------------------------------------------------------------------- */
static int ply_read_header_format(p_ply ply);
static int ply_read_header_comment(p_ply ply);
static int ply_read_header_obj_info(p_ply ply);
static int ply_read_header_property(p_ply ply);
static int ply_read_header_element(p_ply ply);

/* ----------------------------------------------------------------------
 * Error handling
 * ---------------------------------------------------------------------- */
static void ply_error_cb(const char *message);
static void ply_error(p_ply ply, const char *fmt, ...);

/* ----------------------------------------------------------------------
 * Memory allocation and initialization
 * ---------------------------------------------------------------------- */
static void ply_init(p_ply ply);
static void ply_element_init(p_ply_element element);
static void ply_property_init(p_ply_property property);
static p_ply ply_alloc(void);
static p_ply_element ply_grow_element(p_ply ply);
static p_ply_property ply_grow_property(p_ply ply, p_ply_element element);
static void *ply_grow_array(p_ply ply, void **pointer, long *nmemb, long size);

/* ----------------------------------------------------------------------
 * Special functions
 * ---------------------------------------------------------------------- */
static e_ply_storage_mode ply_arch_endian(void);
static int ply_type_check(void);

/* ----------------------------------------------------------------------
 * Auxiliary read functions
 * ---------------------------------------------------------------------- */
static int ply_read_element(p_ply ply, p_ply_element element,
        p_ply_argument argument);
static int ply_read_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument);
static int ply_read_list_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument);
static int ply_read_scalar_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument);

/* ----------------------------------------------------------------------
 * Buffer support functions
 * ---------------------------------------------------------------------- */
/* pointers to tokenized word and line in buffer */
#define BWORD(p) (p->buffer + p->buffer_token)
#define BLINE(p) (p->buffer + p->buffer_token)

/* pointer to start of untouched bytes in buffer */
#define BFIRST(p) (p->buffer + p->buffer_first)

/* number of bytes untouched in buffer */
#define BSIZE(p) (p->buffer_last - p->buffer_first)

/* consumes data from buffer */
#define BSKIP(p, s) (p->buffer_first += s)

/* refills the buffer */
static int BREFILL(p_ply ply) {
    /* move untouched data to beginning of buffer */
    size_t size = BSIZE(ply);
    memmove(ply->buffer, BFIRST(ply), size);
    ply->buffer_last = size;
    ply->buffer_first = ply->buffer_token = 0;
    /* fill remaining with new data */
    size = fread(ply->buffer+size, 1, BUFFERSIZE-size-1, ply->fp);
    /* place sentinel so we can use str* functions with buffer */
    ply->buffer[BUFFERSIZE-1] = '\0';
    /* check if read failed */
    if (size <= 0) return 0;
    /* increase size to account for new data */
    ply->buffer_last += size;
    return 1;
}

/* ----------------------------------------------------------------------
 * Exported functions
 * ---------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
 * Read support functions
 * ---------------------------------------------------------------------- */
p_ply ply_open(const char *name, p_ply_error_cb error_cb) {
    char magic[5] = "    ";
    FILE *fp = NULL;
    p_ply ply = NULL;
    if (error_cb == NULL) error_cb = ply_error_cb;
    if (!ply_type_check()) {
        error_cb("Incompatible type system");
        return NULL;
    }
    assert(name);
    fp = fopen(name, "rb");
    if (!fp) {
        error_cb("Unable to open file");
        return NULL;
    }
    if (fread(magic, 1, 4, fp) < 4) {
        error_cb("Error reading from file");
        fclose(fp);
        return NULL;
    }
    if (strcmp(magic, "ply\n")) {
        fclose(fp);
        error_cb("Not a PLY file. Expected magic number 'ply\\n'");
        return NULL;
    }
    ply = ply_alloc();
    if (!ply) {
        error_cb("Out of memory");
        fclose(fp);
        return NULL;
    }
    ply->fp = fp;
    ply->error_cb = error_cb;
    return ply;
}

int ply_read_header(p_ply ply) {
    assert(ply && ply->fp);
    if (!ply_read_word(ply)) return 0;
    /* parse file format */
    if (!ply_read_header_format(ply)) {
        ply_error(ply, "Invalid file format");
        return 0;
    }
    /* parse elements, comments or obj_infos until the end of header */
    while (strcmp(BWORD(ply), "end_header")) {
        if (!ply_read_header_comment(ply) &&
                !ply_read_header_element(ply) &&
                !ply_read_header_obj_info(ply)) {
            ply_error(ply, "Unexpected token '%s'", BWORD(ply));
            return 0;
        }
    }
    return 1;
}

long ply_set_read_cb(p_ply ply, const char *element_name,
        const char* property_name, p_ply_read_cb read_cb,
        void *pdata, long idata) {
    p_ply_element element = NULL;
    p_ply_property property = NULL;
    assert(ply && element_name && property_name);
    element = ply_find_element(ply, element_name);
    if (!element) return 0;
    property = ply_find_property(element, property_name);
    if (!property) return 0;
    property->read_cb = read_cb;
    property->pdata = pdata;
    property->idata = idata;
    return (int) element->ninstances;
}

int ply_read(p_ply ply) {
    long i;
    p_ply_argument argument;
    assert(ply && ply->fp);
    argument = &ply->argument;
    /* for each element type */
    for (i = 0; i < ply->nelements; i++) {
        p_ply_element element = &ply->element[i];
        argument->element = element;
        if (!ply_read_element(ply, element, argument))
            return 0;
    }
    return 1;
}

int ply_add_comment(p_ply ply, const char *comment) {
    char *new_comment = NULL;
    assert(ply && comment && strlen(comment) < LINESIZE);
    if (!comment || strlen(comment) >= LINESIZE) {
        ply_error(ply, "Invalid arguments");
        return 0;
    }
    new_comment = (char *) ply_grow_array(ply, (void **) &ply->comment,
            &ply->ncomments, LINESIZE);
    if (!new_comment) return 0;
    strcpy(new_comment, comment);
    return 1;
}

int ply_add_obj_info(p_ply ply, const char *obj_info) {
    char *new_obj_info = NULL;
    assert(ply && obj_info && strlen(obj_info) < LINESIZE);
    if (!obj_info || strlen(obj_info) >= LINESIZE) {
        ply_error(ply, "Invalid arguments");
        return 0;
    }
    new_obj_info = (char *) ply_grow_array(ply, (void **) &ply->obj_info,
            &ply->nobj_infos, LINESIZE);
    if (!new_obj_info) return 0;
    strcpy(new_obj_info, obj_info);
    return 1;
}

int ply_close(p_ply ply) {
    long i;
    assert(ply && ply->fp);
    assert(ply->element || ply->nelements == 0);
    assert(!ply->element || ply->nelements > 0);
    fclose(ply->fp);
    /* free all memory used by handle */
    if (ply->element) {
        for (i = 0; i < ply->nelements; i++) {
            p_ply_element element = &ply->element[i];
            if (element->property) free(element->property);
        }
        free(ply->element);
    }
    if (ply->obj_info) free(ply->obj_info);
    if (ply->comment) free(ply->comment);
    free(ply);
    return 1;
}

/* ----------------------------------------------------------------------
 * Query support functions
 * ---------------------------------------------------------------------- */
p_ply_element ply_get_next_element(p_ply ply,
        p_ply_element last) {
    assert(ply);
    if (!last) return ply->element;
    last++;
    if (last < ply->element + ply->nelements) return last;
    else return NULL;
}

int ply_get_element_info(p_ply_element element, const char** name,
        long *ninstances) {
    assert(element);
    if (name) *name = element->name;
    if (ninstances) *ninstances = (long) element->ninstances;
    return 1;
}

p_ply_property ply_get_next_property(p_ply_element element,
        p_ply_property last) {
    assert(element);
    if (!last) return element->property;
    last++;
    if (last < element->property + element->nproperties) return last;
    else return NULL;
}

int ply_get_property_info(p_ply_property property, const char** name,
        e_ply_type *type, e_ply_type *length_type, e_ply_type *value_type) {
    assert(property);
    if (name) *name = property->name;
    if (type) *type = property->type;
    if (length_type) *length_type = property->length_type;
    if (value_type) *value_type = property->value_type;
    return 1;

}

const char *ply_get_next_comment(p_ply ply, const char *last) {
    assert(ply);
    if (!last) return ply->comment;
    last += LINESIZE;
    if (last < ply->comment + LINESIZE*ply->ncomments) return last;
    else return NULL;
}

const char *ply_get_next_obj_info(p_ply ply, const char *last) {
    assert(ply);
    if (!last) return ply->obj_info;
    last += LINESIZE;
    if (last < ply->obj_info + LINESIZE*ply->nobj_infos) return last;
    else return NULL;
}

/* ----------------------------------------------------------------------
 * Callback argument support functions
 * ---------------------------------------------------------------------- */
int ply_get_argument_element(p_ply_argument argument,
        p_ply_element *element, long *instance_index) {
    assert(argument);
    if (!argument) return 0;
    if (element) *element = argument->element;
    if (instance_index) *instance_index = argument->instance_index;
    return 1;
}

int ply_get_argument_property(p_ply_argument argument,
        p_ply_property *property, long *length, long *value_index) {
    assert(argument);
    if (!argument) return 0;
    if (property) *property = argument->property;
    if (length) *length = argument->length;
    if (value_index) *value_index = argument->value_index;
    return 1;
}

int ply_get_argument_user_data(p_ply_argument argument, void **pdata,
        long *idata) {
    assert(argument);
    if (!argument) return 0;
    if (pdata) *pdata = argument->pdata;
    if (idata) *idata = argument->idata;
    return 1;
}

double ply_get_argument_value(p_ply_argument argument) {
    assert(argument);
    if (!argument) return 0.0;
    return argument->value;
}

/* ----------------------------------------------------------------------
 * Internal functions
 * ---------------------------------------------------------------------- */
static int ply_read_list_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument) {
    int l;
    p_ply_read_cb read_cb = property->read_cb;
    p_ply_ihandler *driver = ply->idriver->ihandler;
    /* get list length */
    p_ply_ihandler handler = driver[property->length_type];
    double length;
    if (!handler(ply, &length)) {
        ply_error(ply, "Error reading '%s' of '%s' number %d",
                property->name, element->name, argument->instance_index);
        return 0;
    }
    /* invoke callback to pass length in value field */
    argument->length = (long) length;
    argument->value_index = -1;
    argument->value = length;
    if (read_cb && !read_cb(argument)) {
        ply_error(ply, "Aborted by user");
        return 0;
    }
    /* read list values */
    handler = driver[property->value_type];
    /* for each value in list */
    for (l = 0; l < (long) length; l++) {
        /* read value from file */
        argument->value_index = l;
        if (!handler(ply, &argument->value)) {
            ply_error(ply, "Error reading value number %d of '%s' of "
                    "'%s' number %d", l+1, property->name,
                    element->name, argument->instance_index);
            return 0;
        }
        /* invoke callback to pass value */
        if (read_cb && !read_cb(argument)) {
            ply_error(ply, "Aborted by user");
            return 0;
        }
    }
    return 1;
}

static int ply_read_scalar_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument) {
    p_ply_read_cb read_cb = property->read_cb;
    p_ply_ihandler *driver = ply->idriver->ihandler;
    p_ply_ihandler handler = driver[property->type];
    argument->length = 1;
    argument->value_index = 0;
    if (!handler(ply, &argument->value)) {
        ply_error(ply, "Error reading '%s' of '%s' number %d",
                property->name, element->name, argument->instance_index);
        return 0;
    }
    if (read_cb && !read_cb(argument)) {
        ply_error(ply, "Aborted by user");
        return 0;
    }
    return 1;
}

static int ply_read_property(p_ply ply, p_ply_element element,
        p_ply_property property, p_ply_argument argument) {
    if (property->type == PLY_LIST)
        return ply_read_list_property(ply, element, property, argument);
    else
        return ply_read_scalar_property(ply, element, property, argument);
}

static int ply_read_element(p_ply ply, p_ply_element element,
        p_ply_argument argument) {
    long j, k;
    /* for each element of this type */
    for (j = 0; j < element->ninstances; j++) {
        argument->instance_index = j;
        /* for each property */
        for (k = 0; k < element->nproperties; k++) {
            p_ply_property property = &element->property[k];
            argument->property = property;
            argument->pdata = property->pdata;
            argument->idata = property->idata;
            if (!ply_read_property(ply, element, property, argument))
                return 0;
        }
    }
    return 1;
}

static int ply_find_string(const char *item, const char* const list[]) {
    int i;
    assert(item && list);
    for (i = 0; list[i]; i++)
        if (!strcmp(list[i], item)) return i;
    return -1;
}

p_ply_element ply_find_element(p_ply ply, const char *name) {
    p_ply_element element;
    int i, nelements;
    assert(ply && name);
    element = ply->element;
    nelements = ply->nelements;
    assert(element || nelements == 0);
    assert(!element || nelements > 0);
    for (i = 0; i < nelements; i++)
        if (!strcmp(element[i].name, name)) return &element[i];
    return NULL;
}

p_ply_property ply_find_property(p_ply_element element,
        const char *name) {
    p_ply_property property;
    int i, nproperties;
    assert(element && name);
    property = element->property;
    nproperties = element->nproperties;
    assert(property || nproperties == 0);
    assert(!property || nproperties > 0);
    for (i = 0; i < nproperties; i++)
        if (!strcmp(property[i].name, name)) return &property[i];
    return NULL;
}

static int ply_check_word(p_ply ply) {
    if (strlen(BLINE(ply)) >= WORDSIZE) {
        ply_error(ply, "Word too long");
        return 0;
    }
    return 1;
}

static int ply_read_word(p_ply ply) {
    size_t t = 0;
    assert(ply && ply->fp);
    /* skip leading blanks */
    while (1) {
        t = strspn(BFIRST(ply), " \n\r\t");
        /* check if all buffer was made of blanks */
        if (t >= BSIZE(ply)) {
            if (!BREFILL(ply)) {
                ply_error(ply, "Unexpected end of file");
                return 0;
            }
        } else break;
    }
    BSKIP(ply, t);
    /* look for a space after the current word */
    t = strcspn(BFIRST(ply), " \n\r\t");
    /* if we didn't reach the end of the buffer, we are done */
    if (t < BSIZE(ply)) {
        ply->buffer_token = ply->buffer_first;
        BSKIP(ply, t);
        *BFIRST(ply) = '\0';
        BSKIP(ply, 1);
        return ply_check_word(ply);
    }
    /* otherwise, try to refill buffer */
    if (!BREFILL(ply)) {
        ply_error(ply, "Unexpected end of file");
        return 0;
    }
    /* keep looking from where we left */
    t += strcspn(BFIRST(ply) + t, " \n\r\t");
    /* check if the token is too large for our buffer */
    if (t >= BSIZE(ply)) {
        ply_error(ply, "Token too large");
        return 0;
    }
    /* we are done */
    ply->buffer_token = ply->buffer_first;
    BSKIP(ply, t);
    *BFIRST(ply) = '\0';
    BSKIP(ply, 1);
    return ply_check_word(ply);
}

static int ply_check_line(p_ply ply) {
    if (strlen(BLINE(ply)) >= LINESIZE) {
        ply_error(ply, "Line too long");
        return 0;
    }
    return 1;
}

static int ply_read_line(p_ply ply) {
    const char *end = NULL;
    assert(ply && ply->fp);
    /* look for a end of line */
    end = strchr(BFIRST(ply), '\n');
    /* if we didn't reach the end of the buffer, we are done */
    if (end) {
        ply->buffer_token = ply->buffer_first;
        BSKIP(ply, end - BFIRST(ply));
        *BFIRST(ply) = '\0';
        BSKIP(ply, 1);
        return ply_check_line(ply);
    } else {
        end = ply->buffer + BSIZE(ply);
        /* otherwise, try to refill buffer */
        if (!BREFILL(ply)) {
            ply_error(ply, "Unexpected end of file");
            return 0;
        }
    }
    /* keep looking from where we left */
    end = strchr(end, '\n');
    /* check if the token is too large for our buffer */
    if (!end) {
        ply_error(ply, "Token too large");
        return 0;
    }
    /* we are done */
    ply->buffer_token = ply->buffer_first;
    BSKIP(ply, end - BFIRST(ply));
    *BFIRST(ply) = '\0';
    BSKIP(ply, 1);
    return ply_check_line(ply);
}

static int ply_read_chunk(p_ply ply, void *anybuffer, size_t size) {
    char *buffer = (char *) anybuffer;
    size_t i = 0;
    assert(ply && ply->fp);
    assert(ply->buffer_first <= ply->buffer_last);
    while (i < size) {
        if (ply->buffer_first < ply->buffer_last) {
            buffer[i] = ply->buffer[ply->buffer_first];
            ply->buffer_first++;
            i++;
        } else {
            ply->buffer_first = 0;
            ply->buffer_last = fread(ply->buffer, 1, BUFFERSIZE, ply->fp);
            if (ply->buffer_last <= 0) return 0;
        }
    }
    return 1;
}

static int ply_read_chunk_reverse(p_ply ply, void *anybuffer, size_t size) {
    if (!ply_read_chunk(ply, anybuffer, size)) return 0;
    ply_reverse(anybuffer, size);
    return 1;
}

static void ply_reverse(void *anydata, size_t size) {
    char *data = (char *) anydata;
    char temp;
    size_t i;
    for (i = 0; i < size/2; i++) {
        temp = data[i];
        data[i] = data[size-i-1];
        data[size-i-1] = temp;
    }
}

static void ply_init(p_ply ply) {
    ply->c = ' ';
    ply->element = NULL;
    ply->nelements = 0;
    ply->comment = NULL;
    ply->ncomments = 0;
    ply->obj_info = NULL;
    ply->nobj_infos = 0;
    ply->idriver = NULL;
    ply->buffer[0] = '\0';
    ply->buffer_first = ply->buffer_last = ply->buffer_token = 0;
}

static void ply_element_init(p_ply_element element) {
    element->name[0] = '\0';
    element->ninstances = 0;
    element->property = NULL;
    element->nproperties = 0;
}

static void ply_property_init(p_ply_property property) {
    property->name[0] = '\0';
    property->type = (e_ply_type)-1;
    property->length_type = (e_ply_type)-1;
    property->value_type = (e_ply_type)-1;
    property->read_cb = (p_ply_read_cb) NULL;
    property->pdata = NULL;
    property->idata = 0;
}

static p_ply ply_alloc(void) {
    p_ply ply = (p_ply) malloc(sizeof(t_ply));
    if (!ply) return NULL;
    ply_init(ply);
    return ply;
}

static void *ply_grow_array(p_ply ply, void **pointer,
        long *nmemb, long size) {
    void *temp = *pointer;
    long count = *nmemb + 1;
    if (!temp) temp = malloc(count*size);
    else temp = realloc(temp, count*size);
    if (!temp) {
        ply_error(ply, "Out of memory");
        return NULL;
    }
    *pointer = temp;
    *nmemb = count;
    return (char *) temp + (count-1) * size;
}

static p_ply_element ply_grow_element(p_ply ply) {
    p_ply_element element = NULL;
    assert(ply);
    assert(ply->element || ply->nelements == 0);
    assert(!ply->element || ply->nelements > 0);
    element = (p_ply_element) ply_grow_array(ply, (void **) &ply->element,
            &ply->nelements, sizeof(t_ply_element));
    if (!element) return NULL;
    ply_element_init(element);
    return element;
}

static p_ply_property ply_grow_property(p_ply ply, p_ply_element element) {
    p_ply_property property = NULL;
    assert(ply);
    assert(element);
    assert(element->property || element->nproperties == 0);
    assert(!element->property || element->nproperties > 0);
    property = (p_ply_property) ply_grow_array(ply,
            (void **) &element->property,
            &element->nproperties, sizeof(t_ply_property));
    if (!property) return NULL;
    ply_property_init(property);
    return property;
}

static int ply_read_header_format(p_ply ply) {
    assert(ply && ply->fp);
    if (strcmp(BWORD(ply), "format")) return 0;
    if (!ply_read_word(ply)) return 0;
    ply->storage_mode = (e_ply_storage_mode)ply_find_string(BWORD(ply), ply_storage_mode_list);
    if (ply->storage_mode == (e_ply_storage_mode) (-1)) return 0;
    if (ply->storage_mode == PLY_ASCII) ply->idriver = &ply_idriver_ascii;
    else if (ply->storage_mode == ply_arch_endian())
        ply->idriver = &ply_idriver_binary;
    else ply->idriver = &ply_idriver_binary_reverse;
    if (!ply_read_word(ply)) return 0;
    if (strcmp(BWORD(ply), "1.0")) return 0;
    if (!ply_read_word(ply)) return 0;
    return 1;
}

static int ply_read_header_comment(p_ply ply) {
    assert(ply && ply->fp);
    if (strcmp(BWORD(ply), "comment")) return 0;
    if (!ply_read_line(ply)) return 0;
    if (!ply_add_comment(ply, BLINE(ply))) return 0;
    if (!ply_read_word(ply)) return 0;
    return 1;
}

static int ply_read_header_obj_info(p_ply ply) {
    assert(ply && ply->fp);
    if (strcmp(BWORD(ply), "obj_info")) return 0;
    if (!ply_read_line(ply)) return 0;
    if (!ply_add_obj_info(ply, BLINE(ply))) return 0;
    if (!ply_read_word(ply)) return 0;
    return 1;
}

static int ply_read_header_property(p_ply ply) {
    p_ply_element element = NULL;
    p_ply_property property = NULL;
    /* make sure it is a property */
    if (strcmp(BWORD(ply), "property")) return 0;
    element = &ply->element[ply->nelements-1];
    property = ply_grow_property(ply, element);
    if (!property) return 0;
    /* get property type */
    if (!ply_read_word(ply)) return 0;
    property->type = (e_ply_type)ply_find_string(BWORD(ply), ply_type_list);
    if (property->type == (e_ply_type) (-1)) return 0;
    if (property->type == PLY_LIST) {
        /* if it's a list, we need the base types */
        if (!ply_read_word(ply)) return 0;
        property->length_type = (e_ply_type)ply_find_string(BWORD(ply), ply_type_list);
        if (property->length_type == (e_ply_type) (-1)) return 0;
        if (!ply_read_word(ply)) return 0;
        property->value_type = (e_ply_type)ply_find_string(BWORD(ply), ply_type_list);
        if (property->value_type == (e_ply_type) (-1)) return 0;
    }
    /* get property name */
    if (!ply_read_word(ply)) return 0;
    strcpy(property->name, BWORD(ply));
    if (!ply_read_word(ply)) return 0;
    return 1;
}

static int ply_read_header_element(p_ply ply) {
    p_ply_element element = NULL;
    long dummy;
    assert(ply && ply->fp);
    if (strcmp(BWORD(ply), "element")) return 0;
    /* allocate room for new element */
    element = ply_grow_element(ply);
    if (!element) return 0;
    /* get element name */
    if (!ply_read_word(ply)) return 0;
    strcpy(element->name, BWORD(ply));
    /* get number of elements of this type */
    if (!ply_read_word(ply)) return 0;
    if (sscanf(BWORD(ply), "%ld", &dummy) != 1) {
        ply_error(ply, "Expected number got '%s'", BWORD(ply));
        return 0;
    }
    element->ninstances = dummy;
    /* get all properties for this element */
    if (!ply_read_word(ply)) return 0;
    while (ply_read_header_property(ply) ||
        ply_read_header_comment(ply) || ply_read_header_obj_info(ply))
        /* do nothing */;
    return 1;
}

static void ply_error_cb(const char *message) {
    fprintf(stderr, "RPly: %s\n", message);
}

static void ply_error(p_ply ply, const char *fmt, ...) {
    char buffer[1024];
    va_list ap;
    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    va_end(ap);
    ply->error_cb(buffer);
}

static e_ply_storage_mode ply_arch_endian(void) {
    unsigned long i = 1;
    unsigned char *s = (unsigned char *) &i;
    if (*s == 1) return PLY_LITTLE_ENDIAN;
    else return PLY_BIG_ENDIAN;
}

/* As far as I can tell, these checks aren't needed and they also
 * cause the program to fail on true 64 bit machines.
 */
static int ply_type_check(void) {
  /*    assert(sizeof(char) == 1);
    assert(sizeof(unsigned char) == 1);
    assert(sizeof(short) == 2);
    assert(sizeof(unsigned short) == 2);
    assert(sizeof(long) == 4);
    assert(sizeof(unsigned long) == 4);
    assert(sizeof(float) == 4);
    assert(sizeof(double) == 8);
    if (sizeof(char) != 1) return 0;
    if (sizeof(unsigned char) != 1) return 0;
    if (sizeof(short) != 2) return 0;
    if (sizeof(unsigned short) != 2) return 0;
    if (sizeof(long) != 4) return 0;
    if (sizeof(unsigned long) != 4) return 0;
    if (sizeof(float) != 4) return 0;
    if (sizeof(double) != 8) return 0;*/
    return 1;
}

/* ----------------------------------------------------------------------
 * Input  handlers
 * ---------------------------------------------------------------------- */
static int iascii_int8(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value > CHAR_MAX || *value < CHAR_MIN) return 0;
    return 1;
}

static int iascii_uint8(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value > UCHAR_MAX || *value < 0) return 0;
    return 1;
}

static int iascii_int16(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value > SHRT_MAX || *value < SHRT_MIN) return 0;
    return 1;
}

static int iascii_uint16(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value > USHRT_MAX || *value < 0) return 0;
    return 1;
}

static int iascii_int32(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value > LONG_MAX || *value < LONG_MIN) return 0;
    return 1;
}

static int iascii_uint32(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtol(BWORD(ply), &end, 10);
    if (*end || *value < 0) return 0;
    return 1;
}

static int iascii_float32(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtod(BWORD(ply), &end);
    if (*end || *value < -FLT_MAX || *value > FLT_MAX) return 0;
    return 1;
}

static int iascii_float64(p_ply ply, double *value) {
    char *end;
    if (!ply_read_word(ply)) return 0;
    *value = strtod(BWORD(ply), &end);
    if (*end || *value < -DBL_MAX || *value > DBL_MAX) return 0;
    return 1;
}

static int ibinary_int8(p_ply ply, double *value) {
    char int8;
    if (!ply->idriver->ichunk(ply, &int8, 1)) return 0;
    *value = int8;
    return 1;
}

static int ibinary_uint8(p_ply ply, double *value) {
    unsigned char uint8;
    if (!ply->idriver->ichunk(ply, &uint8, 1)) return 0;
    *value = uint8;
    return 1;
}

static int ibinary_int16(p_ply ply, double *value) {
    short int16;
    if (!ply->idriver->ichunk(ply, &int16, sizeof(int16))) return 0;
    *value = int16;
    return 1;
}

static int ibinary_uint16(p_ply ply, double *value) {
    unsigned short uint16;
    if (!ply->idriver->ichunk(ply, &uint16, sizeof(uint16))) return 0;
    *value = uint16;
    return 1;
}

static int ibinary_int32(p_ply ply, double *value) {
    int int32;
    if (!ply->idriver->ichunk(ply, &int32, sizeof(int32))) return 0;
    *value = int32;
    return 1;
}

static int ibinary_uint32(p_ply ply, double *value) {
    unsigned int uint32;
    if (!ply->idriver->ichunk(ply, &uint32, sizeof(uint32))) return 0;
    *value = uint32;
    return 1;
}

static int ibinary_float32(p_ply ply, double *value) {
    float float32;
    if (!ply->idriver->ichunk(ply, &float32, sizeof(float32))) return 0;
    *value = float32;
    ply_reverse(&float32, sizeof(float32));
    return 1;
}

static int ibinary_float64(p_ply ply, double *value) {
    return ply->idriver->ichunk(ply, value, sizeof(double));
}

/* ----------------------------------------------------------------------
 * Constants
 * ---------------------------------------------------------------------- */
static t_ply_idriver ply_idriver_ascii = {
    {   iascii_int8, iascii_uint8, iascii_int16, iascii_uint16,
        iascii_int32, iascii_uint32, iascii_float32, iascii_float64,
        iascii_int8, iascii_uint8, iascii_int16, iascii_uint16,
        iascii_int32, iascii_uint32, iascii_float32, iascii_float64
    }, /* order matches e_ply_type enum */
    NULL,
    "ascii input"
};

static t_ply_idriver ply_idriver_binary = {
    {   ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16,
        ibinary_int32, ibinary_uint32, ibinary_float32, ibinary_float64,
        ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16,
        ibinary_int32, ibinary_uint32, ibinary_float32, ibinary_float64
    }, /* order matches e_ply_type enum */
    ply_read_chunk,
    "binary input"
};

static t_ply_idriver ply_idriver_binary_reverse = {
    {   ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16,
        ibinary_int32, ibinary_uint32, ibinary_float32, ibinary_float64,
        ibinary_int8, ibinary_uint8, ibinary_int16, ibinary_uint16,
        ibinary_int32, ibinary_uint32, ibinary_float32, ibinary_float64
    }, /* order matches e_ply_type enum */
    ply_read_chunk_reverse,
    "reverse binary input"
};

/* ----------------------------------------------------------------------
 * Copyright (C) 2003 Diego Nehab.  All rights reserved.
 *
 * 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.
 * ---------------------------------------------------------------------- */


text:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:id="@+id/appBar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

  <androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:popupTheme="@style/Toolbar.Theme"
    />

</com.google.android.material.appbar.AppBarLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<centreProcedureSet xmlns="http://www.mousephenotype.org/dcc/exportlibrary/datastructure/core/procedure"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://www.mousephenotype.org/dcc/exportlibrary/datastructure/core/procedure http://www.mousephenotype.org/dcc/exportlibrary/datastructure/core/procedure/procedure_definition.xsd">
    <centre centreID="J" pipeline="IMPC_001" project="IMPC">
        <housing>
            <procedure procedureID="IMPC_HOU_001">
                <simpleParameter parameterID="IMPC_HOU_001_001">
                    <value>yes</value>
                </simpleParameter>
                <simpleParameter parameterID="IMPC_HOU_001_002">
                    <value>21</value>
                </simpleParameter>
                <simpleParameter parameterID="IMPC_HOU_001_003">
                    <value>23</value>
                </simpleParameter>
                <seriesParameter parameterID="ESLIM_HOU_001_004">
                    <value incrementValue="1">Wood chips</value>
                    <value incrementValue="2">Fun Tunnels</value>
                </seriesParameter>
                <seriesParameter parameterID="ESLIM_HOU_001_005">
                    <value incrementValue="1">Malburg</value>
                    <value incrementValue="2">Ebola</value>
                </seriesParameter>
            </procedure>
        </housing>
        <experiment experimentID="localExperimentID" dateOfExperiment="2012-06-30">
            <specimenID>specimenID_00_at_Jax</specimenID>
            <procedure procedureID="IMPC_002_001">
                <simpleParameter parameterID="IMPC_002_001_006_001">
                    <value>Straub tail</value>
                </simpleParameter>
                <procedureMetadata parameterID="IMPC_002_001_057_001">
                    <value>bench</value>
                </procedureMetadata>
                <procedureMetadata parameterID="IMPC_002_001_058_001">
                    <value>1</value>
                </procedureMetadata>
                <procedureMetadata parameterID="IMPC_002_001_059_001">
                    <value>3.2</value>
                </procedureMetadata>
                <procedureMetadata parameterID="IMPC_002_001_060_001">
                    <value>John Doe</value>
                </procedureMetadata>
            </procedure>
        </experiment>
    </centre>
</centreProcedureSet>


text:
@implementation ADALTelemetryAPIEvent

- (void)setResultStatus:(ADALAuthenticationResultStatus)status
{
    NSString* statusStr = nil;
    switch (status) {
        case AD_SUCCEEDED:
            statusStr = MSID_TELEMETRY_VALUE_SUCCEEDED;
            [self setProperty:MSID_TELEMETRY_KEY_IS_SUCCESSFUL value:MSID_TELEMETRY_VALUE_YES];
            break;
        case AD_FAILED:
            statusStr = MSID_TELEMETRY_VALUE_FAILED;
            [self setProperty:MSID_TELEMETRY_KEY_IS_SUCCESSFUL value:MSID_TELEMETRY_VALUE_NO];
            break;
        case AD_USER_CANCELLED:
            statusStr = MSID_TELEMETRY_VALUE_CANCELLED;
            [self setProperty:MSID_TELEMETRY_KEY_USER_CANCEL value:MSID_TELEMETRY_VALUE_YES];
            [self setProperty:MSID_TELEMETRY_KEY_IS_SUCCESSFUL value:MSID_TELEMETRY_VALUE_NO];
            break;
        default:
            statusStr = MSID_TELEMETRY_VALUE_UNKNOWN;
    }

    [self setProperty:MSID_TELEMETRY_KEY_RESULT_STATUS value:statusStr];
}

- (void)setUserInformation:(ADALUserInformation *)userInfo
{
    [self setProperty:MSID_TELEMETRY_KEY_USER_ID value:[userInfo userId]];
    [self setProperty:MSID_TELEMETRY_KEY_TENANT_ID value:[userInfo tenantId]];
    [self setProperty:MSID_TELEMETRY_KEY_IDP value:[userInfo identityProvider]];
}

- (void)setErrorCode:(NSUInteger)errorCode
{
    NSString *errorString = [ADALAuthenticationError stringForADALErrorCode:(ADALErrorCode)errorCode];
    [self setProperty:MSID_TELEMETRY_KEY_API_ERROR_CODE value:errorString];
}

- (void)setProtocolCode:(NSString *)protocolCode
{
    [self setProperty:MSID_TELEMETRY_KEY_PROTOCOL_CODE value:protocolCode];
}

- (void)setAuthority:(NSString *)authorityString
{
    [super setAuthority:authorityString];

    __auto_type factory = [MSIDAuthorityFactory new];
     __auto_type authority = [factory authorityFromUrl:[NSURL URLWithString:authorityString] context:nil error:nil];

    // set authority type
    NSString* authorityType = [authority telemetryAuthorityType];

    [self setAuthorityType:authorityType];
}

- (void)setPromptBehavior:(ADALPromptBehavior)promptBehavior
{
    NSString* promptBehaviorString = nil;
    switch (promptBehavior) {
        case AD_PROMPT_AUTO:
            promptBehaviorString = @"AD_PROMPT_AUTO";
            break;
        case AD_PROMPT_ALWAYS:
            promptBehaviorString = @"AD_PROMPT_ALWAYS";
            break;
        case AD_PROMPT_REFRESH_SESSION:
            promptBehaviorString = @"AD_PROMPT_REFRESH_SESSION";
            break;
        case AD_FORCE_PROMPT:
            promptBehaviorString = @"AD_FORCE_PROMPT";
            break;
        default:
            promptBehaviorString = MSID_TELEMETRY_VALUE_UNKNOWN;
    }

    [self setProperty:MSID_TELEMETRY_KEY_PROMPT_BEHAVIOR value:promptBehaviorString];
}

@end


text:
<?php
namespace Dandomain\Import;

class Category extends Import {
    protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><PRODUCT_CATEGORY_EXPORT type="PRODUCTCATEGORIES"><ELEMENTS>';
    protected $xmlEnd = '</ELEMENTS></PRODUCT_CATEGORY_EXPORT>';
}


text:
extends: ../../../../layouts/guide/index.jade
locals:
  title:
  description:
block: content
---

# Overview

[hyper+json](https://github.com/hypergroup/hyper-json) drives everything. It establishes the contract of how all pieces of the system communicate. This allows us to create generic clients that can be reused for any type of content and any type of client. hyper+json includes hypermedia controls, or [affordances](https://en.wikipedia.org/wiki/Affordance), to communicate the capibilities of the server at runtime. The clients then use this runtime information to make decisions for rendering and communicating back to the server.

hyper-json let's all components in the system evolve at a different pace. Features can be added to servers in a backwards-compatible way and clients don't break. Clients are written in a way that can adapt to different server implementations, where failures returned from servers isn't catastrophic.

Since hyper-json is at the heart of Poe, all of the decisions around technology are made with the idea that they will support hypermedia concepts. This makes choosing technologies relatively straightforward.

<hr/>

Dive into [Poe-UI](/guide/ui/introduction/overview) to start creating user interfaces in the browser.


text:
from requests.exceptions import ReadTimeout

class Posts:

    COUNT = 100
    fields_list = ['post_type', 'date', 'domain', 'id', 'from_id', 'text',
                   'attachments', 'likes', 'reposts']
    posts_transmitted = 0
    total_count = 0
    _current_offset = 0

    def __init__(self, owner_id, api=None, start_iteration=0):
        if not api:
            from vk import Session, API
            self.api = API(Session())
        else:
            self.api = api
        self.owner_id = owner_id
        self.iteration = start_iteration

    def __iter__(self):
        while True:
            posts = self.__get_posts(self.iteration)

            if not self.total_count:
                self.total_count = posts[0]

            if self.total_count < self.COUNT:
                self._current_offset -= self.COUNT
                posts = self.__get_posts(self.iteration, self.total_count)

            self.total_count -= len(posts) - 1
            self.iteration += 1

            for post in posts[1:]:
                yield post

            if self.total_count == 0:
                assert StopIteration
                break

    def __get_posts(self, iteration, count=COUNT):
        for _ in range(3):
            try:
                rv = self.api.wall.get(
                    owner_id=self.owner_id,
                    offset=self._current_offset,
                    count=count,
                    fields=','.join(self.fields_list)
                )
            except ReadTimeout:
                print('******************Timeout! Retying!******************')
            else:
                break
        else:
            raise ReadTimeout
        self._current_offset += self.COUNT

        return rv


text:
package com.jetbrains.python.debugger.attach;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.jetbrains.python.PythonHelper;
import com.jetbrains.python.debugger.PyRemoteDebugProcess;
import com.jetbrains.python.debugger.PyRemoteDebugProcessAware;
import com.jetbrains.python.run.PythonConfigurationType;
import com.jetbrains.python.run.PythonRunConfiguration;
import com.jetbrains.python.run.PythonScriptCommandLineState;
import org.jetbrains.annotations.NotNull;

import java.io.OutputStream;

public class PyAttachToProcessCommandLineState extends PythonScriptCommandLineState {

  private PyAttachToProcessCommandLineState(PythonRunConfiguration runConfiguration,
                                            ExecutionEnvironment env) {
    super(runConfiguration, env);
  }

  public static PyAttachToProcessCommandLineState create(@NotNull Project project, @NotNull String sdkPath, int port, int pid)
    throws ExecutionException {
    PythonRunConfiguration conf =
      (PythonRunConfiguration)PythonConfigurationType.getInstance().getFactory().createTemplateConfiguration(project);
    conf.setScriptName(PythonHelper.ATTACH_DEBUGGER.asParamString());
    conf.setSdkHome(sdkPath);
    conf.setScriptParameters("--port " + port + " --pid " + pid);

    ExecutionEnvironment env =
      ExecutionEnvironmentBuilder.create(project, DefaultDebugExecutor.getDebugExecutorInstance(), conf).build();

    return new PyAttachToProcessCommandLineState(conf, env);
  }

  @Override
  protected ProcessHandler doCreateProcess(GeneralCommandLine commandLine) throws ExecutionException {
    ProcessHandler handler = super.doCreateProcess(commandLine);

    return new PyRemoteDebugProcessHandler(handler);
  }

  public static class PyRemoteDebugProcessHandler extends ProcessHandler implements PyRemoteDebugProcessAware {
    private final ProcessHandler myHandler;
    private PyRemoteDebugProcess myProcess = null;

    public PyRemoteDebugProcessHandler(ProcessHandler handler) {
      myHandler = handler;
      myHandler.addProcessListener(new ProcessAdapter() {
        @Override
        public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
          PyRemoteDebugProcessHandler.this.notifyTextAvailable(event.getText(), outputType);
        }
      });
    }

    @Override
    public void startNotify() {
      super.startNotify();
      myHandler.startNotify();
    }

    @Override
    protected void destroyProcessImpl() {
      if (myProcess != null) {
        myProcess.stop();
      }
      detachProcessImpl();
    }

    @Override
    protected void detachProcessImpl() {
      notifyProcessTerminated(0);
      notifyTextAvailable("Server stopped.\n", ProcessOutputTypes.SYSTEM);
    }

    @Override
    public boolean detachIsDefault() {
      return false;
    }

    @Override
    public OutputStream getProcessInput() {
      return null;
    }

    @Override
    public void setRemoteDebugProcess(PyRemoteDebugProcess process) {
      myProcess = process;
    }
  }
}


text:
| ver   | Stable                                                                                | Develop                                                                                |
|-------|--------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
| 3.3.x | [![Build Status - 3.3/master](https://travis-ci.org/kohana/unittest.svg?branch=3.3%2Fmaster)](https://travis-ci.org/kohana/unittest) | [![Build Status - 3.3/develop](https://travis-ci.org/kohana/unittest.svg?branch=3.3%2Fdevelop)](https://travis-ci.org/kohana/unittest) |
| 3.4.x | [![Build Status - 3.4/master](https://travis-ci.org/kohana/unittest.svg?branch=3.4%2Fmaster)](https://travis-ci.org/kohana/unittest) | [![Build Status - 3.4/develop](https://travis-ci.org/kohana/unittest.svg?branch=3.4%2Fdevelop)](https://travis-ci.org/kohana/unittest) |

This module integrates PHPUnit with Kohana and is used to run all the core Kohana tests. In most cases you will not
need to use this module for testing your own projects. If there are particular helpers provided here that you rely on,
that may be a sign that your own code is too closely coupled to the behaviour of the Kohana core classes.

If you look through any of the tests provided in this module you'll probably notice all theHorribleCamelCase.
I've chosen to do this because it's part of the PHPUnit coding conventions and is required for certain features such as auto documentation.

## Requirements and installation

Dependencies are listed in the composer.json - run `composer install` to install the module and all external requirements.
Note that more usually you will add this module to your own module's composer.json:

```json
{
  "require-dev": {
    "kohana/unittest": "3.3.*@dev"
  }
}
```

## Usage

	$ phpunit --bootstrap=modules/unittest/bootstrap.php modules/unittest/tests.php

Alternatively you can use a `phpunit.xml` to have a more fine grained control
over which tests are included and which files are whitelisted.

Make sure you only whitelist the highest files in the cascading filesystem, else
you could end up with a lot of "class cannot be redefined" errors.

If you use the `tests.php` testsuite loader then it will only whitelist the
highest files. see `config/unittest.php` for details on configuring the
`tests.php` whitelist.


text:
{% extends "site_base.html" %}

{% load sitetree %}
{% load markdownify %}

{% block head_title %}Charla/Taller: {{ presentation.title }}{% endblock %}

{% block body_class %}presentation{% endblock %}

{% block breadcrumbs %}{% sitetree_breadcrumbs from "main" %}{% endblock %}

{% block body %}
{% if presentation.slot %}

        {{ presentation.slot.day.date|date:"l" }}
        {{ presentation.slot.start}}–{{ presentation.slot.end }}

{% endif %}

{{ presentation.title }}

    {% for speaker in presentation.speakers %}
        {{ speaker }}{% if not forloop.last %}, {% endif %}{% endfor %}

Audience level:

{{ presentation.proposal.get_audience_level_display }}

Descripción

{{ presentation.description|markdownify|safe }}

Resumen

{{ presentation.abstract|markdownify|safe }}

Slides

{% if presentation.proposal_base.supporting_documents.exists %}

    {% for document in presentation.proposal_base.supporting_documents.all %}

{{ document.description }}

    {% endfor %}

{% endif %}

Video

{% ifnotequal presentation.proposal.youtube_url '' %}

{% endifnotequal %}

{% endblock %}


text:
name: cljs.pprint/code-dispatch
see also:
---

## Summary

## Details

## Examples