text:
'use strict';

var Backbone = require('backbone'),
    debug    = require('debug')('app:init'),
    $        = require('jquery');

Backbone.$ = $;

var Marionette = require('backbone.marionette');

var App = new Marionette.Application();

var Layout = require('./components/Layout'),
    Router = require('./lib/Router'),
    MemberCollection = require('./collections/Members');

// TODO: temporary
// A temporary collection of 'members' with which to instantiate our app
var FIXTURES = [
  { name: 'Ray', age: 33 },
  { name: 'Sterling', age: 31 },
  { name: 'Lana', age: 34 }
];

App.addRegions({ body: 'body' });

App.navigate = function(pathname) {
  return Backbone.history.navigate(pathname);
};

App.on('start', function() {
  debug('App starting up. Initializing app layout');

  // Expose the app & jquery globally. There may be a better way to do this, but
  // since requiring BB or marionette requires more setup than a simple require
  // statement I prefer this solution.
  window.app = App;
  window.Backbone = Backbone;
  window.Marionette = Marionette;
  window.$ = $;

  app.members = new MemberCollection(FIXTURES);

  var appLayout = new Layout();

  // TODO: When should I render the layout to th page?
  app.body.show(appLayout);

  app.router = new Router({ controller: appLayout });

  Backbone.history.start({ pushState: true });
});

module.exports = App;


text:
drop if exists case_tbl;
CREATE TABLE case_tbl( a INT);
INSERT INTO case_tbl VALUES (1);
INSERT INTO case_tbl VALUES (2);
INSERT INTO case_tbl VALUES (3);
INSERT INTO case_tbl VALUES (NULL);

--case operation with a search when clause
SELECT a,
       CASE WHEN a in (with cte(a) as(select * from case_tbl where a=1) select * from cte) THEN 'one'
            WHEN a in (with cte(a) as(select * from case_tbl where a=2) select * from cte) THEN 'two'
            ELSE 'other'
       END
FROM case_tbl
order by 1,2;

--case operation with a simple when clause
SELECT a,
       CASE a WHEN (with cte(a) as(select * from case_tbl where a=1) select * from cte) THEN 'one'
              WHEN (with cte(a) as(select * from case_tbl where a=2) select * from cte) THEN 'two'
              ELSE 'other'
       END
FROM case_tbl
order by 1,2;

--an error occurs when result types are not convertible
SELECT a,
       CASE a WHEN (with cte(a) as(select * from case_tbl where a=1) select * from cte) THEN 'one'
              WHEN (with cte(a) as(select * from case_tbl where a=2) select * from cte) THEN 'two'
              ELSE 1.2345
       END
FROM case_tbl
order by 1,2;

--result types are converted to a single type containing all of significant figures
SELECT a,
       CASE a WHEN (with cte(a) as(select * from case_tbl where a=1) select * from cte) THEN 1
              WHEN (with cte(a) as(select * from case_tbl where a=2) select * from cte) THEN 1.2345
              ELSE 1.234567890
       END
FROM case_tbl
order by 1,2;
drop table case_tbl;

redpajama_set_name: RedPajamaGithub


text:
import pytest
import requests
import yaml
from settings import TEST_DATA
from suite.fixtures.custom_resource_fixtures import VirtualServerRoute
from suite.utils.resources_utils import (
    create_example_app,
    create_namespace_with_name_from_yaml,
    delete_namespace,
    ensure_response_from_backend,
    wait_until_all_pods_are_ready,
)
from suite.utils.vs_vsr_resources_utils import create_v_s_route_from_yaml, create_virtual_server_from_yaml
from suite.utils.yaml_utils import get_first_host_from_yaml, get_paths_from_vsr_yaml, get_route_namespace_from_vs_yaml
from yaml.loader import Loader

def get_weights_of_splitting(file) -> []:
    """
    Parse VSR yaml file into an array of weights.

    :param file: an absolute path to file
    :return: []
    """
    weights = []
    with open(file) as f:
        docs = yaml.load_all(f, Loader=Loader)
        for dep in docs:
            for item in dep["spec"]["subroutes"][0]["matches"][0]["splits"]:
                weights.append(item["weight"])
    return weights

def get_upstreams_of_splitting(file) -> []:
    """
    Parse VSR yaml file into an array of upstreams.

    :param file: an absolute path to file
    :return: []
    """
    upstreams = []
    with open(file) as f:
        docs = yaml.load_all(f, Loader=Loader)
        for dep in docs:
            for item in dep["spec"]["subroutes"][0]["matches"][0]["splits"]:
                upstreams.append(item["action"]["pass"])
    return upstreams

class VSRAdvancedRoutingSetup:
    """
    Encapsulate advanced routing VSR example details.

    Attributes:
        namespace (str):
        vs_host (str):
        vs_name (str):
        route (VirtualServerRoute):
        backends_url (str): backend url
    """

    def __init__(self, namespace, vs_host, vs_name, route: VirtualServerRoute, backends_url):
        self.namespace = namespace
        self.vs_host = vs_host
        self.vs_name = vs_name
        self.route = route
        self.backends_url = backends_url

@pytest.fixture(scope="class")
def vsr_canary_setup(
    request, kube_apis, ingress_controller_prerequisites, ingress_controller_endpoint
) -> VSRAdvancedRoutingSetup:
    """
    Prepare an example app for advanced routing VSR.

    Single namespace with VS+VSR and simple app.

    :param request: internal pytest fixture
    :param kube_apis: client apis
    :param ingress_controller_endpoint:
    :param ingress_controller_prerequisites:
    :return:
    """
    vs_routes_ns = get_route_namespace_from_vs_yaml(
        f"{TEST_DATA}/{request.param['example']}/standard/virtual-server.yaml"
    )
    ns_1 = create_namespace_with_name_from_yaml(kube_apis.v1, vs_routes_ns[0], f"{TEST_DATA}/common/ns.yaml")
    print("------------------------- Deploy Virtual Server -----------------------------------")
    vs_name = create_virtual_server_from_yaml(
        kube_apis.custom_objects, f"{TEST_DATA}/{request.param['example']}/standard/virtual-server.yaml", ns_1
    )
    vs_host = get_first_host_from_yaml(f"{TEST_DATA}/{request.param['example']}/standard/virtual-server.yaml")

    print("------------------------- Deploy Virtual Server Route -----------------------------------")
    vsr_name = create_v_s_route_from_yaml(
        kube_apis.custom_objects, f"{TEST_DATA}/{request.param['example']}/virtual-server-route.yaml", ns_1
    )
    vsr_paths = get_paths_from_vsr_yaml(f"{TEST_DATA}/{request.param['example']}/virtual-server-route.yaml")
    route = VirtualServerRoute(ns_1, vsr_name, vsr_paths)
    backends_url = f"http://{ingress_controller_endpoint.public_ip}:{ingress_controller_endpoint.port}{vsr_paths[0]}"

    print("---------------------- Deploy simple app ----------------------------")
    create_example_app(kube_apis, "simple", ns_1)
    wait_until_all_pods_are_ready(kube_apis.v1, ns_1)

    def fin():
        if request.config.getoption("--skip-fixture-teardown") == "no":
            print("Delete test namespace")
            delete_namespace(kube_apis.v1, ns_1)

    request.addfinalizer(fin)

    return VSRAdvancedRoutingSetup(ns_1, vs_host, vs_name, route, backends_url)

@pytest.mark.flaky(max_runs=3)
@pytest.mark.vsr
@pytest.mark.parametrize(
    "crd_ingress_controller, vsr_canary_setup",
    [
        (
            {"type": "complete", "extra_args": [f"-enable-custom-resources"]},
            {"example": "virtual-server-route-focused-canary"},
        )
    ],
    indirect=True,
)
class TestVSRFocusedCanaryRelease:
    def test_flow_with_header(self, kube_apis, crd_ingress_controller, vsr_canary_setup):
        ensure_response_from_backend(vsr_canary_setup.backends_url, vsr_canary_setup.vs_host)

        weights = get_weights_of_splitting(f"{TEST_DATA}/virtual-server-route-focused-canary/virtual-server-route.yaml")
        upstreams = get_upstreams_of_splitting(
            f"{TEST_DATA}/virtual-server-route-focused-canary/virtual-server-route.yaml"
        )
        sum_weights = sum(weights)
        ratios = [round(i / sum_weights, 1) for i in weights]

        counter_v1, counter_v2 = 0, 0
        for _ in range(100):
            ensure_response_from_backend(
                vsr_canary_setup.backends_url, vsr_canary_setup.vs_host, {"x-version": "canary"}, check404=True
            )
            status_code = 502
            while status_code == 502:
                resp = requests.get(
                    vsr_canary_setup.backends_url, headers={"host": vsr_canary_setup.vs_host, "x-version": "canary"}
                )
                status_code = resp.status_code

            if upstreams[0] in resp.text in resp.text:
                counter_v1 = counter_v1 + 1
            elif upstreams[1] in resp.text in resp.text:
                counter_v2 = counter_v2 + 1
            else:
                pytest.fail(f"An unexpected backend in response: {resp.text}")

        assert abs(round(counter_v1 / (counter_v1 + counter_v2), 1) - ratios[0]) <= 0.2
        assert abs(round(counter_v2 / (counter_v1 + counter_v2), 1) - ratios[1]) <= 0.2


text:
package org.usfirst.frc364;

import org.usfirst.frc364.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.buttons.*;

public class OI {

    public JoystickButton pullHooksUp;
    public JoystickButton dropHooksDown;
    public Joystick leftJoystick;
    public JoystickButton shiftLow;
    public JoystickButton shiftHigh;
    public Joystick rightJoystick;
    public JoystickButton closeArms;
    public JoystickButton openArms;
    public JoystickButton dropSetPoint;
    public JoystickButton liftSetPoint;
    public JoystickButton transportSetPoint;
    public JoystickButton pickupATote;
    public Joystick controller;

    public OI() {

    	//Init the commands on the controller
        controller = new Joystick(2);
        transportSetPoint = new JoystickButton(controller, 1);
        transportSetPoint.whenPressed(new setPointControl());
        liftSetPoint = new JoystickButton(controller, 6);
        liftSetPoint.whenPressed(new setPointControl());
        dropSetPoint = new JoystickButton(controller, 2);
        dropSetPoint.whenPressed(new setPointControl());
        pickupATote = new JoystickButton(controller, 3);
        pickupATote.whenPressed(new setPointControl());
        openArms = new JoystickButton(controller, 8);
        openArms.whenPressed(new armControl());
        closeArms = new JoystickButton(controller, 7);
        closeArms.whenPressed(new armControl());

        //Init commands on the right stick
        rightJoystick = new Joystick(1);
        shiftHigh = new JoystickButton(rightJoystick, 1);
        shiftHigh.whenPressed(new shiftControl());
        shiftLow = new JoystickButton(rightJoystick, 2);
        shiftLow.whenPressed(new shiftControl());
        leftJoystick = new Joystick(0);

        //Init the commands on the left stick
        dropHooksDown = new JoystickButton(leftJoystick, 4);
        dropHooksDown.whileHeld(new canControl());
        pullHooksUp = new JoystickButton(leftJoystick, 5);
        pullHooksUp.whileHeld(new canControl());

    }

    public Joystick getleftJoystick() {
        return leftJoystick;
    }

    public Joystick getrightJoystick() {
        return rightJoystick;
    }

    public Joystick getcontroller() {
        return controller;
    }

}


text:
See the
[official bootstrap documentation](http://v4-alpha.getbootstrap.com/components/card/)
 for further details.


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="@dimen/cardview_layout_width"
    android:layout_height="150dp"
    android:layout_marginBottom="16dp"
    android:padding="32dp"
    card_view:cardCornerRadius="3dp"
    card_view:cardUseCompatPadding="true"
    android:foreground="@drawable/item_background">
    <!--android:background="@drawable/item_doc_grid"-->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/generic_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:scaleType="centerCrop"
            android:src="@mipmap/ic_user" />

        <TextView
            android:id="@+id/text_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/generic_icon"
            android:gravity="center"
            android:paddingBottom="8dp"
            android:paddingTop="8dp"
            android:textColor="@color/colorAccent"
            android:textSize="13sp"/>

        <TextView
            android:id="@+id/text_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_name"
            android:gravity="center"
            android:paddingBottom="8dp"
            android:paddingTop="8dp"
            android:textColor="@color/colorAccent"
            android:textSize="13sp"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
import {StaticHtmlBrowser} from '../src/Browser'
import * as testServer from './server'
import {expect} from 'chai'
import * as fsExtra from 'fs-extra'
import { Store } from '../src/Store'
import { yamlLoader, fileExists } from '../src/utils'
import { tesMocks } from '../test-data'

describe("Offline TES test", function() {
  this.timeout(10000)
  let address: {port?: number}
  let localUrl = (path) => `http://localhost:${address.port}/${path}`

  let b: StaticHtmlBrowser
  let s: Store
  let resetStore = async() => {
    s = new Store()
    await s.setBaseUrl({
      "ref": "TES",
      "name": "TES Resources Marketplace",
      "secondary": null,
      "url": "https://www.tes.com/teaching-resources",
    })
    s.openBackupFolder = () => {}
    b = s.productStore.browser
    b.customUrlPrefix = localUrl('mock?for=')
  }

  before(async() => {
    address = await testServer.start()

  })

  after(async() => { await testServer.stop() })

  beforeEach(async() => {
    await resetStore()
  })

  it("browser is fixed to local server", async() => {
    const response = await b.get(`test`)
    expect(response).to.eql('OK')
  })

  it("tool creates download dir after setting baseUrl", async() => {
    let result = await fileExists('./test.temp')
    expect(result).to.eql(true)
    fsExtra.removeSync('./test.temp')
    result = await fileExists('./test.temp')
    expect(result).to.eql(false)
    await resetStore()
    result = await fileExists('./test.temp')
    expect(result).to.eql(true)
  })

  it("detects wrong login creditians", async() => {
    const loginResult = await s.login('badUser', 'badPwd')
    expect(loginResult).to.eql('Login error.')
    expect(s.productStore.loggedIn).to.eql(false)
    expect(b.getCookie('TESCookieUser')).not.to.eql('testUser')
  })

  it("can log in with valid creditians", async() => {
    const loginResult = await s.login('goodUser', 'goodPwd')
    expect(loginResult).to.eql('Logged in')
    expect(s.productStore.loggedIn).to.eql(true)
  })

  it("can get my userID from browser cookie after successful login", async() => {
    await s.login('goodUser', 'goodPwd')
    expect(b.getCookie('TESCookieUser')).to.eql('testUser')
  })

  it("can load all my products", async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    expect(s.products).to.eql(tesMocks.products)
  })

  it("can select and deselect all products", async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    s.toggleSelectAll()
    expect(s.selection.size).to.eql(3)
    s.toggleDeselectAll()
    expect(s.selection.size).to.eql(0)
  })

  it("can download selected products", async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    s.toggleSelectAll()
    s.suspendOnEach = false
    await s.backupSelection()
    expect(s.selection.size).to.eql(0)
  })

  it('downloaded yamls and binaries are as expected', async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    s.toggleSelectAll()
    s.suspendOnEach = false
    await s.backupSelection()

    const prod1Yaml = await yamlLoader('./test.temp/ResourceBackup/TES/resources/test_product_1/resource.info')
    const prod2Yaml = await yamlLoader('./test.temp/ResourceBackup/TES/resources/test_product_2/resource.info')
    const prod3Yaml = await yamlLoader('./test.temp/ResourceBackup/TES/resources/test_product_3/resource.info')

    expect(prod1Yaml).to.eql(tesMocks.prod1Yaml)
    expect(prod2Yaml).to.eql(tesMocks.prod2Yaml)
    expect(prod3Yaml).to.eql(tesMocks.prod3Yaml)

    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_1/kotcomes-(1).pdf').size).to.eql(319802)
    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_2/kotcomes-(1).pdf').size).to.eql(319802)
    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_3/20160605_194036-(1).jpg').size).to.eql(33451)

    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_1/coverImage').size).to.eql(33451)
    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_2/coverImage').size).to.eql(33451)
    expect(fsExtra.statSync('./test.temp/ResourceBackup/TES/resources/test_product_3/coverImage').size).to.eql(33451)
  })

  xit('pruduct download updates log', async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    s.toggleSelectAll()
    s.suspendOnEach = false
    await s.backupSelection()
    //logging has changed
    //const log = s.log.map((x) => x.props.children).join(' / ')
    //expect(log).to.eql('Getting authorId / Loading all products / Reading up to 50 products / ...read 3 items / Completed loading all products / start: ,hey kot / start: ,with some / start: ,kot comes / Backup job completed. Open folder. ')
  })

  it("finds backed up files when loading products next time", async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    s.toggleSelectAll()
    s.suspendOnEach = false
    await s.backupSelection()

    await resetStore()

    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()
    expect(s.products).not.to.eql(tesMocks.products)
    s.products.map(p => p.isBackedUp = false)
    expect(s.products).to.eql(tesMocks.products)
  })

  it("finds out of date backups when loading products next time", async() => {
    fsExtra.removeSync('./test.temp')
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()

    s.products.map(p => p.lastModified = new Date())

    s.toggleSelectAll()
    s.suspendOnEach = false
    await s.backupSelection()

    await resetStore()
    await s.login('goodUser', 'goodPwd')
    await s.loadProducts()

    expect(s.products).not.to.eql(tesMocks.products)
    s.products.map(p => {
      p.isOutOfDate = !p.isOutOfDate
      p.isBackedUp = !p.isBackedUp
    })
    expect(s.products).to.eql(tesMocks.products)
  })

})


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [("page", "0004_auto_20180803_0528")]

    operations = [
        migrations.RenameField(
            model_name="page", old_name="is_visible", new_name="is_published"
        ),
        migrations.RenameField(
            model_name="page", old_name="available_on", new_name="publication_date"
        ),
    ]


text:
class Tag < ActiveRecord::Base
  has_and_belongs_to_many :articles, :order => 'created_at DESC'
  validates_uniqueness_of :name

  def self.get(name)
    tagname = name.tr(' ', '').downcase
    tag = find_by_name_or_display_name(tagname, name)
    if tag.nil?
      tag = Tag.create(:name => tagname, :display_name => name)
    end

    tag
  end

  def self.find_by_name_or_display_name(tagname, name)
    self.find(:first, :conditions => [%{name = ? OR display_name = ? OR display_name = ?}, tagname, tagname, name])
  end

  def self.find_by_name(name, *args)
    self.send(:method_missing, :find_by_name, name, *args) ||
      self.new(:name => name)
  end

  def ensure_naming_conventions
    if self.display_name.blank? or self.display_name != self.name
      self.display_name = self.name
    end
    self.name = self.name.tr('.', '-')
    self.name = self.name.tr(' ', '').downcase
  end

  before_save :ensure_naming_conventions

  def self.find_all_with_article_counters(limit=20, orderby='article_counter DESC', start=0)
    # Only count published articles
    self.find_by_sql([%{
      SELECT tags.id, tags.name, tags.display_name, COUNT(articles_tags.article_id) AS article_counter
      FROM #{Tag.table_name} tags LEFT OUTER JOIN #{Tag.table_name_prefix}articles_tags#{Tag.table_name_suffix} articles_tags
        ON articles_tags.tag_id = tags.id
      LEFT OUTER JOIN #{Tag.table_name_prefix + Article.table_name + Tag.table_name_prefix} articles
        ON articles_tags.article_id = articles.id
      WHERE articles.published = ?
      GROUP BY tags.id, tags.name, tags.display_name
      ORDER BY #{orderby}
      LIMIT ? OFFSET ?
      },true, limit, start]).each{|item| item.article_counter = item.article_counter.to_i }
  end

  def self.merge(from, to)
    self.update_by_sql([%{UPDATE article_tags SET tag_id = #{to} WHERE tag_id = #{from} }])
  end

  def self.find_by_permalink(*args)
    self.find_by_name(*args) || new(:name => args.first)
  end

  def self.to_prefix
    'tag'
  end

  # Return all tags with the char or string
  # send by parameter
  def self.find_with_char(char)
    find :all, :conditions => ['name LIKE ? ', "%#{char}%"], :order => 'name ASC'
  end

  def published_articles
    articles.find_already_published
  end

  def permalink
    self.name
  end

  def permalink_url(anchor=nil, only_path=true)
    blog = Blog.default # remove me...

    blog.url_for(
      :controller => 'tags',
      :action => 'show',
      :id => permalink
    )
  end

  def to_atom(xml)
    xml.category :term => display_name, :scheme => permalink_url
  end

  def to_rss(xml)
    xml.category display_name
  end

  def to_param
    permalink
  end

end


text:
package com.alibaba.jstorm.ui.model;

/**
 * componentpage:ComponentSummary
 *
 * @author xin.zhou
 *
 */
import java.io.Serializable;
import java.util.Map;

import com.alibaba.jstorm.common.stats.StaticsType;
import com.alibaba.jstorm.utils.JStormUtils;

public class ComponentStats implements Serializable {

	private static final long serialVersionUID = 2183846733736949858L;
	private String emitted;
	private String sendTps;
	private String recvTps;
	private String acked;
	private String failed;
	private String process;

	public String getEmitted() {
		return emitted;
	}

	public void setEmitted(String emitted) {
		this.emitted = emitted;
	}

	public String getSendTps() {
		return sendTps;
	}

	public void setSendTps(String sendTps) {
		this.sendTps = sendTps;
	}

	public String getRecvTps() {
		return recvTps;
	}

	public void setRecvTps(String recvTps) {
		this.recvTps = recvTps;
	}

	public String getAcked() {
		return acked;
	}

	public void setAcked(String acked) {
		this.acked = acked;
	}

	public String getFailed() {
		return failed;
	}

	public void setFailed(String failed) {
		this.failed = failed;
	}

	public String getProcess() {
		return process;
	}

	public void setProcess(String process) {
		this.process = process;
	}

	public void setValues(Map<StaticsType, Object> staticsType) {
		emitted = JStormUtils.formatValue(staticsType.get(StaticsType.emitted));
		sendTps = JStormUtils
				.formatValue(staticsType.get(StaticsType.send_tps));
		recvTps = JStormUtils
				.formatValue(staticsType.get(StaticsType.recv_tps));
		acked = JStormUtils.formatValue(staticsType.get(StaticsType.acked));
		failed = JStormUtils.formatValue(staticsType.get(StaticsType.failed));
		process = JStormUtils.formatValue(staticsType
				.get(StaticsType.process_latencies));
	}

}


text:
"""
Created on 17/02/17 at 11:28 AM

@author: neil

Program description here

Version 0.0.1
"""

import numpy as np
import matplotlib.pyplot as plt
import os
from tqdm import tqdm
from collections import OrderedDict
from astropy.table import Table
from matplotlib_select.Rectangle_Selector import Select_Rectange
try:
    import periodogram_functions2 as pf2
except ModuleNotFoundError:
    raise Exception("Program requires 'periodogram_functions.py'")

# =============================================================================
# Define variables
# =============================================================================
# set file paths
WORKSPACE = '/Astro/Projects/RayPaul_Work/SuperWASP/'
SPATH = WORKSPACE + '/Plots/fitted_lightcurves/'
DPATH = WORKSPACE + '/Data/selected_lightcurve_data_redo.fits'
# set database settings
HOSTNAME = 'localhost'
USERNAME = 'root'
PASSWORD = '1234'
DATABASE = 'swasp'
TABLE = 'swasp_sep16_tab'
# -----------------------------------------------------------------------------
# if plots exist assume that we don't need to reprocess
SKIPDONE = True
# write to database (else this is a test run)
WRITETODATABASE = True

# =============================================================================
# Define functions
# =============================================================================
def load_pre_existing_data(dpath):
    """
    Load pre-exisiting data

    :param dpath: string, filepath to the pre-existing data
    :return:
    """
    print("\n Loading pre existing files...")
    atable = Table.read(dpath)
    done_ids = list(atable['SID'])
    max_s = int(0.5*(len(atable.colnames)-1))
    sarr, earr = OrderedDict(), OrderedDict()
    for s, s_id in tqdm(enumerate(done_ids)):
        for r in range(max_s):
            start = list(atable['start{0}'.format(r+1)])[s]
            end = list(atable['end{0}'.format(r+1)])[s]
            sarr, earr = sort_data_in_dict(s_id, sarr, earr, start, end)
    del atable
    # ---------------------------------------------------------------------
    # skip sids if the are in table (assume this means they are done)
    do_ids, skips = [], 0
    for s_id in sids:
        if s_id in done_ids:
            skips += 1
        else:
            do_ids.append(s_id)
    # Print statement for how many files skipped due to pre existing data
    print('\n Skipping {0} sids'.format(skips))
    return sarr, earr, max_s, do_ids, done_ids

def sort_data_in_dict(s_id, sarr, earr, start, end):
    """
    Sort the data based on the id and the start and end points (into the sarr
    and earr dictionaries

    :param s_id: string, ID of this object (will be used as key)
    :param sarr: dict, start point list (list of time series data for each
                 segments i.e. if there are two segments list would be
                 [x pos start of segment 1, x pos start of segment 2]
    :param earr: dict, end point list (list of time series data for each
                 segments i.e. if there are two segments list would be
                 [x pos end of segment 1, x pos end of segment 2]
    :param start: float, the x starting position of this segment
    :param end: float, the x ending position of this segment
    :return:
    """
    if s_id not in sarr:
        sarr[s_id], earr[s_id] = [start], [end]
    else:
        sarr[s_id].append(start), earr[s_id].append(end)
    return sarr, earr

def write_to_table(done_ids, max_s, sarr, earr):
    """
    Writes the start and end dictionaries to the table (overwrites pre-existing
    data, which should be loaded into the memory at the start of this run)

    :param done_ids: list of strings, the ID of those objects already processed
                     either in this run or from pre-existing data
    :param max_s: int, the maximum number of segments for any object
    :param sarr: dict, start point list (list of time series data for each
                 segments i.e. if there are two segments list would be
                 [x pos start of segment 1, x pos start of segment 2]
    :param earr: dict, end point list (list of time series data for each
                 segments i.e. if there are two segments list would be
                 [x pos end of segment 1, x pos end of segment 2]
    :return:
    """
    arraystarts = np.zeros((len(done_ids), max_s))
    arrayends = np.zeros((len(done_ids), max_s))
    for s in tqdm(range(len(done_ids))):
        s_id = done_ids[s]
        for row1 in range(max_s):
            if s_id not in sarr:
                arraystarts[s][row1] = np.nan
                arrayends[s][row1] = np.nan
            elif len(sarr[s_id]) <= row1:
                arraystarts[s][row1] = np.nan
                arrayends[s][row1] = np.nan
            else:
                arraystarts[s][row1] = sarr[s_id][row1]
                arrayends[s][row1] = earr[s_id][row1]

    newtable = Table()
    newtable['SID'] = np.array(done_ids, dtype=str)
    for row1 in range(max_s):
        newtable['start{0}'.format(row1 + 1)] = arraystarts[:, row1]
        newtable['end{0}'.format(row1 + 1)] = arrayends[:, row1]
    newtable.write(DPATH, overwrite=True)

def plot_periodogram(s_id, x, y, ey=None):
    """
    Plots a periodogram with a rectangular selection interface, returns the
    object containing the chosen rectangular regions

    :param s_id: string, ID of this object
    :param x: numpy array, the time series data
    :param y: numpy array, the flux data
    :param ey: numpy array or None, the uncertainties on the flux data
    :return selection: instance of select_rectangle contains the data for the
                       selected rectangle regions in selection.data
                       in the form of a list of lists:

                       [[xA0, xA1, yA0, yA1], [xB0, xB1, yB0, yB1],  ...]

                        where A and B are two selected rectangles

                        and x0, y0 is the first selected corner of the rectangle
                            x1, y1 is the last selected corner of the rectangle
    """
    plt.close()
    # make days since first observation
    xarr = x - x.min()
    # Do plot
    fig, frame = plt.subplots(ncols=1, nrows=1)
    frame.errorbar(xarr, y, yerr=ey, ls='none', marker='o', markersize=2)
    frame.set_xlabel('Days from Start of observation')
    frame.set_ylabel('Flux')
    frame.set_title('Raw light curve of {0}'.format(s_id), fontsize=22)
    selection = Select_Rectange(frame)
    plt.show()
    plt.close()
    return selection

def print_to_screen(x, startx, endx):
    xarr = x - x.min()
    print('\n\tFull: {0} to {1}'.format(xarr.min(), xarr.max()))
    for it in range(len(startx)):
        args = it + 1, startx[it], endx[it]
        print('\n\tRegion {0}: {1} to {2}'.format(*args))

# =============================================================================
# Start of code
# =============================================================================
if __name__ == "__main__":
    # Main code here
    # -------------------------------------------------------------------------
    # get list of unique ids (for selecting each as a seperate curve)
    sql_kwargs = dict(host=HOSTNAME, db=DATABASE, table=TABLE,
                      user=USERNAME, passwd=PASSWORD, conn_timeout=100000)
    sids, conn = pf2.get_list_of_objects_from_db(conn=None, **sql_kwargs)
    # load file if it exists (to save on repeating on exit)
    if os.path.exists(DPATH) and SKIPDONE and WRITETODATABASE:
        ldata = load_pre_existing_data(DPATH)
        starts, ends, maxsegments, do_sids, done_sids = ldata
    else:
        do_sids, done_sids, maxsegments = list(sids), [], 0
        starts, ends = OrderedDict(), OrderedDict()
    # -------------------------------------------------------------------------
    # loop round the system ids and plot a graph of the lightcurve
    print("\nPlotting graphs of lightcurves...")
    for sid in tqdm(do_sids):
        print('\n\t Running for ID:\n\n\t{0}'.format(sid))
        # get data using SQL query on database
        pdata = pf2.get_lightcurve_data(conn=conn, sid=sid, sortcol='HJD',
                                        replace_infs=True, **sql_kwargs)
        time, flux = np.array(pdata['HJD']), np.array(pdata['FLUX2'])
        eflux = np.array(pdata['FLUX2_ERR'])
        # plot and show periodogram
        a = plot_periodogram(sid, time, flux, eflux)
        # Deal with data acquisition
        if maxsegments < len(a.data):
            maxsegments = len(a.data)
        for row in a.data:
            starts, ends = sort_data_in_dict(sid, starts, ends, row[0], row[1])
        done_sids.append(sid)
        # ----------------------------------------------------------------------
        # convert into fits table and save
        if WRITETODATABASE:
            print('\n Converting in to fits table...')
            write_to_table(done_sids, maxsegments, starts, ends)
        else:
            print('\n Selected region:')
            if sid in starts:
                print_to_screen(time, starts[sid], ends[sid])
            else:
                print("No peaks for {0}".format(sid))

# =============================================================================
# End of code
# =============================================================================


text:
$:.unshift File::dirname(__FILE__) + '/../../lib'

require 'test/unit'
require File::dirname(__FILE__) + '/../lib/clienttester'

require 'xmpp4r'
require 'xmpp4r/version/helper/responder'
require 'xmpp4r/version/helper/simpleresponder'
include Jabber

class Version::HelperTest < Test::Unit::TestCase
  include ClientTester

  def test_create
    h = Version::Responder::new(@client)
    assert_kind_of(Version::Responder, h)
    assert_respond_to(h, :add_version_callback)
  end

  def test_callback
    # Prepare helper
    h = Version::Responder::new(@client)

    calls = 0
    h.add_version_callback { |iq,responder|
      calls += 1
      assert('jabber:iq:version', iq.queryns)
      responder.call('Test program', '1.0', 'Ruby Test::Unit')
    }

    # Send stanzas which shouldn't match
    @server.send("<iq type='set'><query xmlns='jabber:iq:version'/></iq>")
    @server.send("<iq type='get'><query xmlns='jabber:iq:browse'/></iq>")
    assert_equal(0, calls)

    # Send a query
    @server.send("<iq type='get'><query xmlns='jabber:iq:version'/></iq>") { |reply|
      assert_equal('Test program', reply.query.iname)
      assert_equal('1.0', reply.query.version)
      assert_equal('Ruby Test::Unit', reply.query.os)
      true
    }
    assert_equal(1, calls)
  end

  def test_simple
    h = Version::SimpleResponder.new(@client, 'Test program', '1.0', 'Ruby Test::Unit')

    # Send a query
    @server.send("<iq type='get'><query xmlns='jabber:iq:version'/></iq>") { |reply|
      assert_equal('Test program', reply.query.iname)
      assert_equal('1.0', reply.query.version)
      assert_equal('Ruby Test::Unit', reply.query.os)
      true
    }

  end
end


text:
namespace bundle
{
    class runner_t
    {
    public:
        runner_t(const pal::string_t& bundle_path)
            : m_bundle_path(bundle_path)
            , m_bundle_map(nullptr)
            , m_bundle_length(0)
        {
        }

        StatusCode extract();

        pal::string_t extraction_dir()
        {
            return m_extraction_dir;
        }

    private:
        void map_host();
        void unmap_host();

        pal::string_t m_bundle_path;
        pal::string_t m_extraction_dir;
        int8_t* m_bundle_map;
        size_t m_bundle_length;
    };
}

#endif // __RUNNER_H__


text:
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM

#define EIGEN_USE_GPU

#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/cross_op.h"

namespace tensorflow {

typedef Eigen::GpuDevice GPUDevice;

#define INSTANTIATE_GPU_KERNEL(type) \
  template class functor::Cross<GPUDevice, type>;
TF_CALL_REAL_NUMBER_TYPES(INSTANTIATE_GPU_KERNEL);
#undef INSTANTIATE_GPU_KERNEL

}  // namespace tensorflow

#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM


text:
#include "config.h"
#include "SharedBuffer.h"

#include "PurgeableBuffer.h"
#include <algorithm>
#include <wtf/PassOwnPtr.h>
#include <wtf/unicode/UTF8.h>

#if ENABLE(DISK_IMAGE_CACHE)
#include "DiskImageCacheIOS.h"
#endif

namespace WebCore {

#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
static const unsigned segmentSize = 0x1000;
static const unsigned segmentPositionMask = 0x0FFF;

static inline unsigned segmentIndex(unsigned position)
{
    return position / segmentSize;
}

static inline unsigned offsetInSegment(unsigned position)
{
    return position & segmentPositionMask;
}

static inline char* allocateSegment() WARN_UNUSED_RETURN;
static inline char* allocateSegment()
{
    return static_cast<char*>(fastMalloc(segmentSize));
}

static inline void freeSegment(char* p)
{
    fastFree(p);
}
#endif

SharedBuffer::SharedBuffer()
    : m_size(0)
    , m_buffer(adoptRef(new DataBuffer))
    , m_shouldUsePurgeableMemory(false)
#if ENABLE(DISK_IMAGE_CACHE)
    , m_isMemoryMapped(false)
    , m_diskImageCacheId(DiskImageCache::invalidDiskCacheId)
    , m_notifyMemoryMappedCallback(nullptr)
    , m_notifyMemoryMappedCallbackData(nullptr)
#endif
{
}

SharedBuffer::SharedBuffer(unsigned size)
    : m_size(size)
    , m_buffer(adoptRef(new DataBuffer))
    , m_shouldUsePurgeableMemory(false)
#if ENABLE(DISK_IMAGE_CACHE)
    , m_isMemoryMapped(false)
    , m_diskImageCacheId(DiskImageCache::invalidDiskCacheId)
    , m_notifyMemoryMappedCallback(nullptr)
    , m_notifyMemoryMappedCallbackData(nullptr)
#endif
{
}

SharedBuffer::SharedBuffer(const char* data, unsigned size)
    : m_size(0)
    , m_buffer(adoptRef(new DataBuffer))
    , m_shouldUsePurgeableMemory(false)
#if ENABLE(DISK_IMAGE_CACHE)
    , m_isMemoryMapped(false)
    , m_diskImageCacheId(DiskImageCache::invalidDiskCacheId)
    , m_notifyMemoryMappedCallback(nullptr)
    , m_notifyMemoryMappedCallbackData(nullptr)
#endif
{
    append(data, size);
}

SharedBuffer::SharedBuffer(const unsigned char* data, unsigned size)
    : m_size(0)
    , m_buffer(adoptRef(new DataBuffer))
    , m_shouldUsePurgeableMemory(false)
#if ENABLE(DISK_IMAGE_CACHE)
    , m_isMemoryMapped(false)
    , m_diskImageCacheId(DiskImageCache::invalidDiskCacheId)
    , m_notifyMemoryMappedCallback(nullptr)
    , m_notifyMemoryMappedCallbackData(nullptr)
#endif
{
    append(reinterpret_cast<const char*>(data), size);
}

SharedBuffer::~SharedBuffer()
{
#if ENABLE(DISK_IMAGE_CACHE)
    if (m_diskImageCacheId) {
        diskImageCache().removeItem(m_diskImageCacheId);
        m_isMemoryMapped = false;
        m_diskImageCacheId = DiskImageCache::invalidDiskCacheId;
    }
#endif
    clear();
}

PassRefPtr<SharedBuffer> SharedBuffer::adoptVector(Vector<char>& vector)
{
    RefPtr<SharedBuffer> buffer = create();
    buffer->m_buffer->data.swap(vector);
    buffer->m_size = buffer->m_buffer->data.size();
    return buffer.release();
}

PassRefPtr<SharedBuffer> SharedBuffer::adoptPurgeableBuffer(PassOwnPtr<PurgeableBuffer> purgeableBuffer)
{
    ASSERT(!purgeableBuffer->isPurgeable());
    RefPtr<SharedBuffer> buffer = create();
    buffer->m_purgeableBuffer = purgeableBuffer;
    return buffer.release();
}

unsigned SharedBuffer::size() const
{
    if (hasPlatformData())
        return platformDataSize();

    if (m_purgeableBuffer)
        return m_purgeableBuffer->size();

    return m_size;
}

#if ENABLE(DISK_IMAGE_CACHE)
bool SharedBuffer::isAllowedToBeMemoryMapped() const
{
    return m_diskImageCacheId != DiskImageCache::invalidDiskCacheId;
}

SharedBuffer::MemoryMappingState SharedBuffer::allowToBeMemoryMapped()
{
    if (isMemoryMapped())
        return SharedBuffer::SuccessAlreadyMapped;

    if (isAllowedToBeMemoryMapped())
        return SharedBuffer::PreviouslyQueuedForMapping;

    m_diskImageCacheId = diskImageCache().writeItem(this);
    if (m_diskImageCacheId == DiskImageCache::invalidDiskCacheId)
        return SharedBuffer::FailureCacheFull;

    return SharedBuffer::QueuedForMapping;
}

void SharedBuffer::failedMemoryMap()
{
    if (m_notifyMemoryMappedCallback)
        m_notifyMemoryMappedCallback(this, SharedBuffer::Failed, m_notifyMemoryMappedCallbackData);
}

void SharedBuffer::markAsMemoryMapped()
{
    ASSERT(!isMemoryMapped());

    m_isMemoryMapped = true;
    unsigned savedSize = size();
    clear();
    m_size = savedSize;

    if (m_notifyMemoryMappedCallback)
        m_notifyMemoryMappedCallback(this, SharedBuffer::Succeeded, m_notifyMemoryMappedCallbackData);
}

SharedBuffer::MemoryMappedNotifyCallbackData SharedBuffer::memoryMappedNotificationCallbackData() const
{
    return m_notifyMemoryMappedCallbackData;
}

SharedBuffer::MemoryMappedNotifyCallback SharedBuffer::memoryMappedNotificationCallback() const
{
    return m_notifyMemoryMappedCallback;
}

void SharedBuffer::setMemoryMappedNotificationCallback(MemoryMappedNotifyCallback callback, MemoryMappedNotifyCallbackData data)
{
    ASSERT(!m_notifyMemoryMappedCallback || !callback);
    ASSERT(!m_notifyMemoryMappedCallbackData || !data);

    m_notifyMemoryMappedCallback = callback;
    m_notifyMemoryMappedCallbackData = data;
}
#endif

// Try to create a PurgeableBuffer. We can fail to create one for any of the
// following reasons:
//   - shouldUsePurgeableMemory is set to false.
//   - the size of the buffer is less than the minimum size required by
//     PurgeableBuffer (currently 16k).
//   - PurgeableBuffer::createUninitialized() call fails.
void SharedBuffer::createPurgeableBuffer() const
{
    if (m_purgeableBuffer)
        return;

    if (hasPlatformData())
        return;

#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    if (singleDataArrayBuffer())
        return;
#endif

    if (!m_buffer->hasOneRef())
        return;

    if (!m_shouldUsePurgeableMemory)
        return;

    char* destination = 0;
    m_purgeableBuffer = PurgeableBuffer::createUninitialized(m_size, destination);
    if (!m_purgeableBuffer)
        return;
    unsigned bufferSize = m_buffer->data.size();
    if (bufferSize) {
        memcpy(destination, m_buffer->data.data(), bufferSize);
        destination += bufferSize;
        (const_cast<SharedBuffer*>(this))->clearDataBuffer();
    }
    copyBufferAndClear(destination, m_size - bufferSize);
}

const char* SharedBuffer::data() const
{
#if ENABLE(DISK_IMAGE_CACHE)
    if (isMemoryMapped())
        return static_cast<const char*>(diskImageCache().dataForItem(m_diskImageCacheId));
#endif

    if (hasPlatformData())
        return platformData();

#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    if (const char* buffer = singleDataArrayBuffer())
        return buffer;
#endif

    createPurgeableBuffer();

    if (m_purgeableBuffer)
        return m_purgeableBuffer->data();

    return this->buffer().data();
}

PassRefPtr<ArrayBuffer> SharedBuffer::createArrayBuffer() const
{
    RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::createUninitialized(static_cast<unsigned>(size()), sizeof(char));

    const char* segment = 0;
    unsigned position = 0;
    while (unsigned segmentSize = getSomeData(segment, position)) {
        memcpy(static_cast<char*>(arrayBuffer->data()) + position, segment, segmentSize);
        position += segmentSize;
    }

    if (position != arrayBuffer->byteLength()) {
        ASSERT_NOT_REACHED();
        // Don't return the incomplete ArrayBuffer.
        return 0;
    }

    return arrayBuffer.release();
}

void SharedBuffer::append(SharedBuffer* data)
{
    if (maybeAppendPlatformData(data))
        return;
#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    if (maybeAppendDataArray(data))
        return;
#endif

    const char* segment;
    size_t position = 0;
    while (size_t length = data->getSomeData(segment, position)) {
        append(segment, length);
        position += length;
    }
}

void SharedBuffer::append(const char* data, unsigned length)
{
    ASSERT(!m_purgeableBuffer);
#if ENABLE(DISK_IMAGE_CACHE)
    ASSERT(!isMemoryMapped());
#endif
    if (!length)
        return;

    maybeTransferPlatformData();

#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    unsigned positionInSegment = offsetInSegment(m_size - m_buffer->data.size());
    m_size += length;

    if (m_size <= segmentSize) {
        // No need to use segments for small resource data
        if (m_buffer->data.isEmpty())
            m_buffer->data.reserveInitialCapacity(length);
        appendToDataBuffer(data, length);
        return;
    }

    char* segment;
    if (!positionInSegment) {
        segment = allocateSegment();
        m_segments.append(segment);
    } else
        segment = m_segments.last() + positionInSegment;

    unsigned segmentFreeSpace = segmentSize - positionInSegment;
    unsigned bytesToCopy = std::min(length, segmentFreeSpace);

    for (;;) {
        memcpy(segment, data, bytesToCopy);
        if (static_cast<unsigned>(length) == bytesToCopy)
            break;

        length -= bytesToCopy;
        data += bytesToCopy;
        segment = allocateSegment();
        m_segments.append(segment);
        bytesToCopy = std::min(length, segmentSize);
    }
#else
    m_size += length;
    if (m_buffer->data.isEmpty())
        m_buffer->data.reserveInitialCapacity(length);
    appendToDataBuffer(data, length);
#endif
}

void SharedBuffer::append(const Vector<char>& data)
{
    append(data.data(), data.size());
}

void SharedBuffer::clear()
{
    clearPlatformData();

#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    for (unsigned i = 0; i < m_segments.size(); ++i)
        freeSegment(m_segments[i]);

    m_segments.clear();
#else
    m_dataArray.clear();
#endif

    m_size = 0;
    clearDataBuffer();
    m_purgeableBuffer.clear();
}

PassRefPtr<SharedBuffer> SharedBuffer::copy() const
{
    RefPtr<SharedBuffer> clone(adoptRef(new SharedBuffer));
    if (m_purgeableBuffer || hasPlatformData()) {
        clone->append(data(), size());
        return clone;
    }

    clone->m_size = m_size;
    clone->m_buffer->data.reserveCapacity(m_size);
    clone->m_buffer->data.append(m_buffer->data.data(), m_buffer->data.size());
#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    for (unsigned i = 0; i < m_segments.size(); ++i)
        clone->m_buffer->data.append(m_segments[i], segmentSize);
#else
    for (unsigned i = 0; i < m_dataArray.size(); ++i)
        clone->append(m_dataArray[i].get());
#endif
    return clone;
}

PassOwnPtr<PurgeableBuffer> SharedBuffer::releasePurgeableBuffer()
{
    ASSERT(hasOneRef());
    return m_purgeableBuffer.release();
}

void SharedBuffer::duplicateDataBufferIfNecessary() const
{
    size_t currentCapacity = m_buffer->data.capacity();
    if (m_buffer->hasOneRef() || m_size <= currentCapacity)
        return;

    size_t newCapacity = std::max(static_cast<size_t>(m_size), currentCapacity * 2);
    RefPtr<DataBuffer> newBuffer = adoptRef(new DataBuffer);
    newBuffer->data.reserveInitialCapacity(newCapacity);
    newBuffer->data = m_buffer->data;
    m_buffer = newBuffer.release();
}

void SharedBuffer::appendToDataBuffer(const char *data, unsigned length) const
{
    duplicateDataBufferIfNecessary();
    m_buffer->data.append(data, length);
}

void SharedBuffer::clearDataBuffer()
{
    if (!m_buffer->hasOneRef())
        m_buffer = adoptRef(new DataBuffer);
    else
        m_buffer->data.clear();
}

#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
void SharedBuffer::copyBufferAndClear(char* destination, unsigned bytesToCopy) const
{
    for (unsigned i = 0; i < m_segments.size(); ++i) {
        unsigned effectiveBytesToCopy = std::min(bytesToCopy, segmentSize);
        memcpy(destination, m_segments[i], effectiveBytesToCopy);
        destination += effectiveBytesToCopy;
        bytesToCopy -= effectiveBytesToCopy;
        freeSegment(m_segments[i]);
    }
    m_segments.clear();
}
#endif

const Vector<char>& SharedBuffer::buffer() const
{
#if ENABLE(DISK_IMAGE_CACHE)
    ASSERT(!isMemoryMapped());
#endif
    unsigned bufferSize = m_buffer->data.size();
    if (m_size > bufferSize) {
        duplicateDataBufferIfNecessary();
        m_buffer->data.resize(m_size);
        copyBufferAndClear(m_buffer->data.data() + bufferSize, m_size - bufferSize);
    }
    return m_buffer->data;
}

unsigned SharedBuffer::getSomeData(const char*& someData, unsigned position) const
{
    unsigned totalSize = size();
    if (position >= totalSize) {
        someData = 0;
        return 0;
    }

#if ENABLE(DISK_IMAGE_CACHE)
    ASSERT(position < size());
    if (isMemoryMapped()) {
        const char* data = static_cast<const char*>(diskImageCache().dataForItem(m_diskImageCacheId));
        someData = data + position;
        return size() - position;
    }
#endif

    if (hasPlatformData() || m_purgeableBuffer) {
        ASSERT_WITH_SECURITY_IMPLICATION(position < size());
        someData = data() + position;
        return totalSize - position;
    }

    ASSERT_WITH_SECURITY_IMPLICATION(position < m_size);
    unsigned consecutiveSize = m_buffer->data.size();
    if (position < consecutiveSize) {
        someData = m_buffer->data.data() + position;
        return consecutiveSize - position;
    }

    position -= consecutiveSize;
#if !USE(NETWORK_CFDATA_ARRAY_CALLBACK)
    unsigned segments = m_segments.size();
    unsigned maxSegmentedSize = segments * segmentSize;
    unsigned segment = segmentIndex(position);
    if (segment < segments) {
        unsigned bytesLeft = totalSize - consecutiveSize;
        unsigned segmentedSize = std::min(maxSegmentedSize, bytesLeft);

        unsigned positionInSegment = offsetInSegment(position);
        someData = m_segments[segment] + positionInSegment;
        return segment == segments - 1 ? segmentedSize - position : segmentSize - positionInSegment;
    }
    ASSERT_NOT_REACHED();
    return 0;
#else
    return copySomeDataFromDataArray(someData, position);
#endif
}

#if !USE(CF) && !USE(SOUP)

inline void SharedBuffer::clearPlatformData()
{
}

inline void SharedBuffer::maybeTransferPlatformData()
{
}

inline bool SharedBuffer::hasPlatformData() const
{
    return false;
}

inline const char* SharedBuffer::platformData() const
{
    ASSERT_NOT_REACHED();

    return 0;
}

inline unsigned SharedBuffer::platformDataSize() const
{
    ASSERT_NOT_REACHED();

    return 0;
}

inline bool SharedBuffer::maybeAppendPlatformData(SharedBuffer*)
{
    return false;
}

#endif

PassRefPtr<SharedBuffer> utf8Buffer(const String& string)
{
    // Allocate a buffer big enough to hold all the characters.
    const int length = string.length();
    Vector<char> buffer(length * 3);

    // Convert to runs of 8-bit characters.
    char* p = buffer.data();
    WTF::Unicode::ConversionResult result;
    if (length) {
        if (string.is8Bit()) {
            const LChar* d = string.characters8();
            result = WTF::Unicode::convertLatin1ToUTF8(&d, d + length, &p, p + buffer.size());
        } else {
            const UChar* d = string.characters16();
            result = WTF::Unicode::convertUTF16ToUTF8(&d, d + length, &p, p + buffer.size(), true);
        }
        if (result != WTF::Unicode::conversionOK)
            return nullptr;
    }

    buffer.shrink(p - buffer.data());
    return SharedBuffer::adoptVector(buffer);
}

} // namespace WebCore


text:
namespace MyJiraWork.Common
{

    public enum UserStoryType
    {
        BUG,
        USERSTORY
    }
}


text:
using NUnit.Framework;
using Rhino.Mocks;
using StreamCompanion.Contract;
using StreamCompanion.Contract.StreamTemplate;
using StreamCompanion.StreamTemplate;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace StreamCompanion.Tests.StreamTemplate
{
    [TestFixture]
    public class ViewModelUnitTest
    {
        private IController controllerMock;
        private StreamCompanion.Contract.StreamTemplate.IViewModel viewModelSUT;
        [SetUp]
        public void SetUp()
        {
            controllerMock = MockRepository.GenerateMock<IController>();
            controllerMock.Stub(x => x.LoadStreamTemplates()).Return(new List<IStreamItem>());
            viewModelSUT = new ViewModel(controllerMock);
        }

        [Test]
        public void CanReturnTheCorrectStreams()
        {
            Assert.AreEqual(new ObservableCollection<IStreamItem>(), viewModelSUT.Streams);
        }

        [Test]
        public void CanReturnTheCorrectSelectedItem()
        {
            IStreamItem expectedStreamItem = new StreamItem("a", "b");
            viewModelSUT.SelectedItem = expectedStreamItem;

            Assert.AreEqual(expectedStreamItem, viewModelSUT.SelectedItem);
        }

        [Test]
        public void CanExecuteSaveAndExitCmd()
        {
            controllerMock.Expect(x => x.SaveStreamTemplates(null)).IgnoreArguments();
            viewModelSUT.SaveAndExitCmd.Execute(null);

            controllerMock.VerifyAllExpectations();
            Assert.AreEqual(true, viewModelSUT.IsDone);
        }

        [Test]
        public void CanExecuteAddStreamWebsiteCmd()
        {
            viewModelSUT.AddStreamWebsiteCmd.Execute(null);

            Assert.AreEqual(string.Empty, viewModelSUT.NewStreamingWebsite);
            Assert.AreEqual(string.Empty, viewModelSUT.GenericUrl);
            Assert.AreEqual(string.Empty, viewModelSUT.WhitespaceReplacement);
            Assert.AreEqual(false, viewModelSUT.IsGeneral);
            Assert.AreEqual(true, viewModelSUT.IsStreamingWebsiteVisible);
            Assert.AreEqual("English", viewModelSUT.SelectedStreamLanguage);
        }

        [TestCase("Mixed", true, true, true, true, true)]
        [TestCase("TV", false, true, false, false, false)]
        [TestCase("Anime", false, false, true, false, false)]
        [TestCase("Cartoon", false, false, false, true, false)]
        [TestCase("Movie", false, false, false, false, true)]
        public void CanExecuteEditStreamWebsiteCmd(string usedOnType, bool isGeneral, bool isTv, bool isAnime, bool isCartoon, bool isMovie)
        {
            viewModelSUT.SelectedItem = new StreamItem("website/123", "replacement", usedOnType, "English");
            viewModelSUT.EditStreamWebsiteCmd.Execute(null);

            Assert.AreEqual("website", viewModelSUT.NewStreamingWebsite);
            Assert.AreEqual("123", viewModelSUT.GenericUrl);
            Assert.AreEqual("replacement", viewModelSUT.WhitespaceReplacement);
            Assert.AreEqual("English", viewModelSUT.SelectedStreamLanguage);
            Assert.AreEqual(true, viewModelSUT.IsStreamingWebsiteVisible);

            Assert.AreEqual(isGeneral, viewModelSUT.IsGeneral);
            Assert.AreEqual(isTv, viewModelSUT.IsTv);
            Assert.AreEqual(isAnime, viewModelSUT.IsAnime);
            Assert.AreEqual(isCartoon, viewModelSUT.IsCartoon);
            Assert.AreEqual(isMovie, viewModelSUT.IsMovie);
        }

        [Test]
        public void CanExecuteMoveUpCmd()
        {
            IStreamItem expectedStreamItem = new StreamItem("c", "d");
            viewModelSUT.Streams.Add(new StreamItem("a", "b"));
            viewModelSUT.Streams.Add(expectedStreamItem);
            viewModelSUT.SelectedItem = viewModelSUT.Streams[1];

            viewModelSUT.MoveUpCmd.Execute(null);

            Assert.AreEqual(expectedStreamItem, viewModelSUT.Streams[0]);
        }

        [Test]
        public void CanExecuteMoveDownCmd()
        {
            IStreamItem expectedStreamItem = new StreamItem("a", "b");
            viewModelSUT.Streams.Add(expectedStreamItem);
            viewModelSUT.Streams.Add(new StreamItem("c", "d"));
            viewModelSUT.SelectedItem = viewModelSUT.Streams[0];

            viewModelSUT.MoveDownCmd.Execute(null);

            Assert.AreEqual(expectedStreamItem, viewModelSUT.Streams[1]);
        }

        [TestCase("http://kinox.to/Stream/", "Movie", true, 0)]
        [TestCase("http://kinox.to/Stream", "Movie,", false, 1)]
        public void CanExecuteDoneCmd(string newStreamingWebsite, string usedOnTypes, bool editMode, int expectedCount)
        {
            viewModelSUT.NewStreamingWebsite = newStreamingWebsite;
            viewModelSUT.WhitespaceReplacement = "_";
            viewModelSUT.GenericUrl = "{0}-1.html,s{1}e{2}";
            viewModelSUT.UsedOnTypes = usedOnTypes;
            if (editMode)
            {
                viewModelSUT.SelectedItem = new StreamItem("website/123", "replacement", "Movie", "English");
                viewModelSUT.EditStreamWebsiteCmd.Execute(null);
            }

            viewModelSUT.DoneCmd.Execute(null);

            Assert.AreEqual(expectedCount, viewModelSUT.Streams.Count);
        }

        [Test]
        public void CanExecuteCancelCmd()
        {
            viewModelSUT.IsStreamingWebsiteVisible = true;

            Assert.IsTrue(viewModelSUT.IsStreamingWebsiteVisible);

            viewModelSUT.CancelCmd.Execute(null);

            Assert.IsFalse(viewModelSUT.IsStreamingWebsiteVisible);
        }
    }
}


text:
	T.vs2010_vcxproj = { }
	local vs10_vcxproj = T.vs2010_vcxproj
	local include_directory = "bar/foo"
	local include_directory2 = "baz/foo"
	local debug_define = "I_AM_ALIVE_NUMBER_FIVE"
	local vs10_helpers = premake.vstudio.vs10_helpers

	local sln, prj
	function vs10_vcxproj.teardown()
		sln = nil
		prj = nil
	end
	function vs10_vcxproj.setup()
		_ACTION = "vs2010"

		sln = solution "MySolution"
		configurations { "Debug", "Release" }
		platforms {}

		prj = project "MyProject"
		language "C++"
		kind "ConsoleApp"
		uuid "AE61726D-187C-E440-BD07-2556188A6565"

		includedirs
		{
			include_directory,
			include_directory2
		}
		files
		{
			"foo/dummyHeader.h",
			"foo/dummySource.cpp",
			"../src/host/*h",
			"../src/host/*.c",
			"dummyResourceScript.rc"
		}

		configuration("Release")
			flags {"Optimize"}
			links{"foo","bar"}

		configuration("Debug")
			defines {debug_define}
			links{"foo_d"}

	end

	local function get_buffer()
		io.capture()
		premake.buildconfigs()
		sln.vstudio_configs = premake.vstudio_buildconfigs(sln)
		premake.vs2010_vcxproj(prj)
		local buffer = io.endcapture()
		return buffer
	end

	function vs10_vcxproj.xmlDeclarationPresent()
		local buffer = get_buffer()
		test.istrue(string.startswith(buffer, '<?xml version=\"1.0\" encoding=\"utf-8\"?>'))
	end

	function vs10_vcxproj.projectBlocksArePresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<Project.*</Project>')
	end

	function vs10_vcxproj.projectOpenTagIsCorrect()
		local buffer = get_buffer()
		test.string_contains(buffer,'<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">.*</Project>')
	end

	function vs10_vcxproj.configItemGroupPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ItemGroup Label="ProjectConfigurations">.*</ItemGroup>')
	end

	function vs10_vcxproj.configBlocksArePresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ProjectConfiguration.*</ProjectConfiguration>')
	end

	function vs10_vcxproj.configTypeBlockPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<PropertyGroup Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'.*\'" Label="Configuration">.*</PropertyGroup>')
	end

	function vs10_vcxproj.twoConfigTypeBlocksPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<PropertyGroup Condition.*</PropertyGroup>.*<PropertyGroup Condition=.*</PropertyGroup>')
	end

	function vs10_vcxproj.propsDefaultForCppProjArePresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<Import Project="$%(VCTargetsPath%)\\Microsoft.Cpp.Default.props" />')
	end

	function vs10_vcxproj.propsForCppProjArePresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<Import Project="%$%(VCTargetsPath%)\\Microsoft.Cpp.props" />')
	end

	function vs10_vcxproj.extensionSettingArePresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ImportGroup Label="ExtensionSettings">.*</ImportGroup>')
	end

	function vs10_vcxproj.userMacrosPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<PropertyGroup Label="UserMacros" />')
	end

	function vs10_vcxproj.intermediateAndOutDirsPropertyGroupWithMagicNumber()
		local buffer = get_buffer()
		test.string_contains(buffer,'<PropertyGroup>.*<_ProjectFileVersion>10%.0%.30319%.1</_ProjectFileVersion>')
	end

	function vs10_vcxproj.outDirPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<OutDir.*</OutDir>')
	end
	function vs10_vcxproj.initDirPresent()
		local buffer = get_buffer()
		test.string_contains(buffer,'<IntDir.*</IntDir>')
	end

	function vs10_vcxproj.projectWithDebugAndReleaseConfig_twoOutDirsAndTwoIntDirs()
		local buffer = get_buffer()
		test.string_contains(buffer,'<OutDir.*</OutDir>.*<IntDir.*</IntDir>.*<OutDir.*</OutDir>.*<IntDir.*</IntDir>')
	end

	function vs10_vcxproj.containsItemDefinition()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ItemDefinitionGroup Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'.*\'">.*</ItemDefinitionGroup>')
	end

	function vs10_vcxproj.containsClCompileBlock()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ClCompile>.*</ClCompile>')
	end

	function vs10_vcxproj.containsAdditionalOptions()
		buildoptions {"/Gm"}
		local buffer = get_buffer()
		test.string_contains(buffer,'<AdditionalOptions>/Gm %%%(AdditionalOptions%)</AdditionalOptions>')
	end

	local function cl_compile_string(version)
		return '<ItemDefinitionGroup Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\''..version..'|Win32\'">.*<ClCompile>'
	end

	function vs10_vcxproj.debugHasNoOptimisation()
		local buffer = get_buffer()
		test.string_contains(buffer, cl_compile_string('Debug').. '.*<Optimization>Disabled</Optimization>.*</ItemDefinitionGroup>')
	end

	function vs10_vcxproj.releaseHasFullOptimisation()
		local buffer = get_buffer()
		test.string_contains(buffer, cl_compile_string('Release').. '.*<Optimization>Full</Optimization>.*</ItemDefinitionGroup>')
	end

	function vs10_vcxproj.includeDirectories_debugEntryContains_include_directory()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Debug').. '.*<AdditionalIncludeDirectories>'.. path.translate(include_directory, '\\') ..'.*</AdditionalIncludeDirectories>')
	end

	function vs10_vcxproj.includeDirectories_debugEntryContains_include_directory2PrefixWithSemiColon()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Debug').. '.*<AdditionalIncludeDirectories>.*;'.. path.translate(include_directory2, '\\') ..'.*</AdditionalIncludeDirectories>')
	end

	function vs10_vcxproj.includeDirectories_debugEntryContains_include_directory2PostfixWithSemiColon()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Debug').. '.*<AdditionalIncludeDirectories>.*'.. path.translate(include_directory2, '\\') ..';.*</AdditionalIncludeDirectories>')
	end

	function vs10_vcxproj.debugContainsPreprossorBlock()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Debug').. '.*<PreprocessorDefinitions>.*</PreprocessorDefinitions>')
	end

	function vs10_vcxproj.debugHasDebugDefine()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Debug')..'.*<PreprocessorDefinitions>.*'..debug_define..'.*</PreprocessorDefinitions>')
	end

	function vs10_vcxproj.releaseHasStringPoolingOn()
		local buffer = get_buffer()
		test.string_contains(buffer,cl_compile_string('Release')..'.*<StringPooling>true</StringPooling>')
	end

	function vs10_vcxproj.hasItemGroupSection()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ItemGroup>.*</ItemGroup>')
	end

	function vs10_vcxproj.fileExtension_extEqualH()
		local ext = vs10_helpers.get_file_extension('foo.h')
		test.isequal('h', ext)
	end

	function vs10_vcxproj.fileExtension_containsTwoDots_extEqualH()
		local ext = vs10_helpers.get_file_extension('foo.bar.h')
		test.isequal('h', ext)
	end

	function vs10_vcxproj.fileExtension_alphaNumeric_extEqualOneH()
		local ext = vs10_helpers.get_file_extension('foo.1h')
		test.isequal('1h', ext)
	end

	function vs10_vcxproj.fileExtension_alphaNumericWithUnderscore_extEqualOne_H()
		local ext = vs10_helpers.get_file_extension('foo.1_h')
		test.isequal('1_h', ext)
	end

	function vs10_vcxproj.fileExtension_containsHyphen_extEqualHHyphenH()
		local ext = vs10_helpers.get_file_extension('foo.h-h')
		test.isequal('h-h', ext)
	end

	function vs10_vcxproj.fileExtension_containsMoreThanOneDot_extEqualOneH()
		local ext = vs10_helpers.get_file_extension('foo.bar.h')
		test.isequal('h', ext)
	end

	local function SortAndReturnSortedInputFiles(input)
		local sorted =
		{
			ClInclude	={},
			ClCompile	={},
			None		={},
			ResourceCompile ={}
		}
		vs10_helpers.sort_input_files(input,sorted)
		return sorted
	end
	function vs10_vcxproj.sortFile_headerFile_SortedClIncludeEqualToFile()
		local file = {"bar.h"}
		local sorted = SortAndReturnSortedInputFiles(file)
		test.isequal(file, sorted.ClInclude)
	end

	function vs10_vcxproj.sortFile_srcFile_SortedClCompileEqualToFile()
		local file = {"b.cxx"}
		local sorted = SortAndReturnSortedInputFiles(file)
		test.isequal(file, sorted.ClCompile)
	end

	function vs10_vcxproj.sortFile_notRegistered_SortedNoneEqualToFile()
		local file = {"foo.bar.00h"}
		local sorted = SortAndReturnSortedInputFiles(file)
		test.isequal(file, sorted.None)
	end

	function vs10_vcxproj.sortFile_resourceScript_resourceCompileEqualToFile()
		local file = {"foo.rc"}
		local sorted = SortAndReturnSortedInputFiles(file)
		test.isequal(file, sorted.ResourceCompile)
	end

	function vs10_vcxproj.itemGroupSection_hasResourceCompileSection()
		--for some reason this does not work here and it needs to be in
		--the project setting at the top ?
		--files{"dummyResourceScript.rc"}
		local buffer = get_buffer()
		test.string_contains(buffer,'<ItemGroup>.*<ResourceCompile.*</ItemGroup>')
	end

	function vs10_vcxproj.itemGroupSection_hasHeaderListed()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ItemGroup>.*<ClInclude Include="foo\\dummyHeader%.h" />.*</ItemGroup>')
	end

	function vs10_vcxproj.checkProjectConfigurationOpeningTag_hasACloseingAngleBracket()
		local buffer = get_buffer()
		test.string_contains(buffer,'<ProjectConfiguration Include="Debug|Win32">')
	end

	function vs10_vcxproj.postBuildEvent_isPresent()
		postbuildcommands { "doSomeThing" }
		local buffer = get_buffer()
		test.string_contains(buffer,'<PostBuildEvent>.*<Command>.*</Command>.*</PostBuildEvent>')
	end

	function vs10_vcxproj.postBuildEvent_containsCorrectInformationBetweenCommandTag()
		postbuildcommands { "doSomeThing" }
		local buffer = get_buffer()
		test.string_contains(buffer,'<PostBuildEvent>.*<Command>doSomeThing</Command>.*</PostBuildEvent>')
	end

	function vs10_vcxproj.postBuildEvent_eventEncloseByQuotes_containsCorrectInformationBetweenCommandTag()
		postbuildcommands { "\"doSomeThing\"" }
		local buffer = get_buffer()
		test.string_contains(buffer,'<PostBuildEvent>.*<Command>"doSomeThing"</Command>.*</PostBuildEvent>')
	end

	function vs10_vcxproj.outDir_directorySuppliedIsNotSlashPostFixed_bufferContainsOutDirSlashPostFixed()
		targetdir("dir")
		local buffer = get_buffer()
		test.string_contains(buffer,'<OutDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\.*\'">dir\\</OutDir>')
	end
	--postfixed directory slashes are removed by default
	--yet these following two tests are to ensure if this behaviour is changed they will fail
	function vs10_vcxproj.outDir_directorySuppliedWhichIsForwardSlashPostFixed_bufferContainsOutDirSlashPostFixed()
		targetdir("dir/")
		local buffer = get_buffer()
		test.string_contains(buffer,'<OutDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\.*\'">dir\\</OutDir>')
	end

	function vs10_vcxproj.outDir_directorySuppliedWhichIsWindowsSlashPostFixed_bufferContainsOutDirSlashPostFixed()
		targetdir("dir\\")
		local buffer = get_buffer()
		test.string_contains(buffer,'<OutDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\.*\'">dir\\</OutDir>')
	end

	function vs10_vcxproj.objectDir_directorySuppliedIsNotSlashPostFixed_bufferContainsIntermediateDirSlashPostFixed()
		objdir ("dir")

		local buffer = get_buffer()
		test.string_contains(buffer,'<IntDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'.*\'">dir\\</IntDir>')
	end

	--postfixed directory slashes are removed by default
	--yet these following two tests are to ensure if this behaviour is changed they will fail
	function vs10_vcxproj.objectDir_directorySuppliedWhichIsSlashPostFixed_bufferContainsIntermediateDirSlashPostFixed()
		objdir ("dir/")
		local buffer = get_buffer()
		test.string_contains(buffer,'<IntDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'.*\'">dir\\</IntDir>')
	end

	function vs10_vcxproj.objectDir_directorySuppliedWhichIsWindowsSlashPostFixed_bufferContainsIntermediateDirSlashPostFixed()
		objdir ("dir\\")
		local buffer = get_buffer()
		test.string_contains(buffer,'<IntDir Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'.*\'">dir\\</IntDir>')
	end
	function vs10_vcxproj.targetName()
		configuration("Debug")
		targetname ("foo_d")
		local buffer = get_buffer()
		test.string_contains(buffer,'<TargetName Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'Debug|Win32\'">foo_d</TargetName>')
	end

	function vs10_vcxproj.noExtraWarnings_bufferDoesNotContainSmallerTypeCheck()
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,'<SmallerTypeCheck>')
	end

	function vs10_vcxproj.debugAndExtraWarnings_bufferContainsSmallerTypeCheck()
		configuration("Debug")
		flags {"ExtraWarnings"}
		local buffer = get_buffer()
		test.string_contains(buffer,'<SmallerTypeCheck>true</SmallerTypeCheck>')
	end

	function vs10_vcxproj.releaseAndExtraWarnings_bufferDoesNotContainSmallerTypeCheck()
		configuration("Release")
		flags {"ExtraWarnings"}
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,'<SmallerTypeCheck>')
	end

	function vs10_vcxproj.onlyOneProjectConfigurationBlockWhenMultipleConfigs()
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,'<ItemGroup Label="ProjectConfigurations">.*<ItemGroup Label="ProjectConfigurations">')
	end

	function vs10_vcxproj.languageC_bufferContainsCompileAsC()
		language "C"
		local buffer = get_buffer()
		test.string_contains(buffer,'<CompileAs>CompileAsC</CompileAs>')
	end

	local debug_config_pch_string = '<PrecompiledHeader Condition="\'%$%(Configuration%)|%$%(Platform%)\'==\'Debug|Win32\'">Create</PrecompiledHeader>'

	function vs10_vcxproj.noPchFlagSet_bufferDoesNotContainPchCreate()
		configuration("Debug")
		flags{"NoPCH"}
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,debug_config_pch_string)
	end

	function vs10_vcxproj.pchHeaderSetYetPchSourceIsNot_bufferDoesNotContainPchCreate()
		configuration("Debug")
		pchheader "foo/dummyHeader.h"
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,debug_config_pch_string)
	end

	function vs10_vcxproj.pchHeaderAndPchSourceSet_bufferContainPchCreate()
		configuration("Debug")
			pchheader "foo/dummyHeader.h"
			pchsource "foo/dummySource.cpp"
		local buffer = get_buffer()
		test.string_contains(buffer,debug_config_pch_string)
	end

	function vs10_vcxproj.pchHeaderAndSourceSet_yetAlsoNoPch_bufferDoesNotContainpchCreate()
		configuration('Debug')
			pchheader "foo/dummyHeader.h"
			pchsource "foo/dummySource.cpp"
			flags{"NoPCH"}
		local buffer = get_buffer()
		test.string_does_not_contain(buffer,debug_config_pch_string)
	end


text:
use std::ptr::Shared;
use std::iter::FromIterator;
use std::marker::PhantomData;

type Link = Option<Shared<Node>>;

struct Node {
    item: i32,
    next: Link,
    prev: Link
}

impl Node {
    pub fn new(item: i32) -> Box<Self> {
        Box::new(Node {
            item: item,
            next: None,
            prev: None
        })
    }
}

pub struct UnsafeDeque {
    head: Link,
    tail: Link
}

impl UnsafeDeque {
    pub fn new() -> Self {
        UnsafeDeque { head: None, tail: None }
    }

    pub fn pop_front(&mut self) -> Option<i32> {
        self.head.take().map(|old_head| unsafe {
            let mut old_head = Box::from_raw(*old_head);
            self.head = (*old_head).next.take();
            match self.head {
                Some(new_head) => { (**new_head).prev.take(); }
                None => { self.tail.take(); }
            }
            (*old_head).item
        })
    }

    pub fn push_front(&mut self, item: i32) {
        unsafe {
            let new_head = Shared::new(Box::into_raw(Node::new(item)));
            match self.head {
                Some(old_head) => {
                    (**old_head).prev = Some(new_head);
                    (**new_head).next = Some(old_head);
                }
                None => { self.tail = Some(new_head); }
            }
            self.head = Some(new_head);
        }
    }

    pub fn pop_back(&mut self) -> Option<i32> {
        self.tail.take().map(|old_tail| unsafe {
            let mut old_tail = Box::from_raw(*old_tail);
            self.tail = (*old_tail).prev.take();
            match self.tail {
                Some(new_tail) => { (**new_tail).next.take(); }
                None => { self.head.take(); }
            }
            (*old_tail).item
        })
    }

    pub fn push_back(&mut self, item: i32) {
        unsafe {
            let new_tail = Shared::new(Box::into_raw(Node::new(item)));
            match self.tail {
                Some(old_tail) => {
                    (**old_tail).next = Some(new_tail);
                    (**new_tail).prev = Some(old_tail);
                }
                None => { self.head = Some(new_tail); }
            }
            self.tail = Some(new_tail);
        }
    }
}

impl AsMut<UnsafeDeque> for UnsafeDeque {
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}

impl<'mi> IntoIterator for &'mi mut UnsafeDeque {
    type Item = &'mi mut i32;
    type IntoIter = RefMutDequeIter<'mi>;

    fn into_iter(self) -> Self::IntoIter {
        RefMutDequeIter { head: self.head, tail: self.tail, empty: false, marker: PhantomData }
    }
}

pub struct RefMutDequeIter<'mi> {
    head: Link,
    tail: Link,
    empty: bool,
    marker: PhantomData<&'mi mut i32>
}

impl<'mi> Iterator for RefMutDequeIter<'mi> {
    type Item = &'mi mut i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.head.and_then(|head| unsafe {
            if self.empty {
                None
            } else {
                self.tail.map(|tail| {
                    self.empty = *head as *const i32 == *tail as *const i32;
                    self.head = (**head).next;
                    &mut (**head).item
                })
            }
        })
    }
}

impl<'mi> DoubleEndedIterator for RefMutDequeIter<'mi> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.tail.and_then(|tail| unsafe {
            if self.empty {
                None
            } else {
                self.head.map(|head| {
                    self.empty = *head as *const i32 == *tail as *const i32;
                    self.tail = (**tail).prev;
                    &mut (**tail).item
                })
            }
        })
    }
}

impl AsRef<UnsafeDeque> for UnsafeDeque {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<'i> IntoIterator for &'i UnsafeDeque {
    type Item = &'i i32;
    type IntoIter = RefDequeIter<'i>;

    fn into_iter(self) -> Self::IntoIter {
        RefDequeIter { head: self.head, tail: self.tail, empty: false, marker: PhantomData }
    }
}

pub struct RefDequeIter<'i> {
    head: Link,
    tail: Link,
    empty: bool,
    marker: PhantomData<&'i i32>
}

impl<'i> Iterator for RefDequeIter<'i> {
    type Item = &'i i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.head.and_then(|head| unsafe {
            if self.empty {
                None
            } else {
                self.tail.map(|tail| {
                    self.empty = *head as *const i32 == *tail as *const i32;
                    self.head = (**head).next;
                    &(**head).item
                })
            }
        })
    }
}

impl<'i> DoubleEndedIterator for RefDequeIter<'i> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.tail.and_then(|tail| unsafe {
            if self.empty {
                None
            } else {
                self.head.map(|head| {
                    self.empty = *head as *const i32 == *tail as *const i32;
                    self.tail = (**tail).prev;
                    &(**tail).item
                })
            }
        })
    }
}

impl IntoIterator for UnsafeDeque {
    type Item = i32;
    type IntoIter = DequeIter;

    fn into_iter(self) -> Self::IntoIter {
        DequeIter { deque: self }
    }
}

pub struct DequeIter {
    deque: UnsafeDeque
}

impl Iterator for DequeIter {
    type Item = i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.deque.pop_front()
    }
}

impl DoubleEndedIterator for DequeIter {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.deque.pop_back()
    }
}

impl FromIterator<i32> for UnsafeDeque {
    fn from_iter<I: IntoIterator<Item = i32>>(items: I) -> Self {
        let mut deque = UnsafeDeque::new();
        for item in items {
            deque.push_front(item);
        }
        deque
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn create_an_empty_deque() {
        let mut deque = UnsafeDeque::new();

        assert_eq!(deque.pop_front(), None);
    }

    #[test]
    fn pushes_one_element_in_front() {
        let mut deque = UnsafeDeque::new();

        deque.push_front(1);

        assert_eq!(deque.pop_front(), Some(1));
        assert_eq!(deque.pop_front(), None);
    }

    #[test]
    fn pushes_three_elements_in_front() {
        let mut deque = UnsafeDeque::new();

        deque.push_front(1);
        deque.push_front(2);
        deque.push_front(3);

        assert_eq!(deque.pop_front(), Some(3));
        assert_eq!(deque.pop_front(), Some(2));
        assert_eq!(deque.pop_front(), Some(1));
        assert_eq!(deque.pop_front(), None);
    }

    #[test]
    fn pops_from_back() {
        let mut deque = UnsafeDeque::from_iter(1..4);

        assert_eq!(deque.pop_back(), Some(1));
        assert_eq!(deque.pop_back(), Some(2));
        assert_eq!(deque.pop_back(), Some(3));
        assert_eq!(deque.pop_back(), None);
    }

    #[test]
    fn pushes_many_in_back() {
        let mut deque = UnsafeDeque::new();

        deque.push_back(1);
        deque.push_back(2);
        deque.push_back(3);

        assert_eq!(deque.pop_front(), Some(1));
        assert_eq!(deque.pop_front(), Some(2));
        assert_eq!(deque.pop_front(), Some(3));
        assert_eq!(deque.pop_front(), None);
    }

    #[test]
    fn iterator_over_deque() {
        let deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.into_iter();

        assert_eq!(iterator.next(), Some(3));
        assert_eq!(iterator.next(), Some(2));
        assert_eq!(iterator.next(), Some(1));
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn double_ended_iterator_over_deque() {
        let deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.into_iter();

        assert_eq!(iterator.next(), Some(3));
        assert_eq!(iterator.next_back(), Some(1));
        assert_eq!(iterator.next_back(), Some(2));
        assert_eq!(iterator.next_back(), None);
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn ref_iterator_over_deque() {
        let deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.as_ref().into_iter();

        assert_eq!(iterator.next(), Some(&3));
        assert_eq!(iterator.next(), Some(&2));
        assert_eq!(iterator.next(), Some(&1));
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn double_ended_ref_iterator_over_deque() {
        let deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.as_ref().into_iter();

        assert_eq!(iterator.next(), Some(&3));
        assert_eq!(iterator.next_back(), Some(&1));
        assert_eq!(iterator.next_back(), Some(&2));
        assert_eq!(iterator.next_back(), None);
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn mut_ref_iterator_over_deque() {
        let mut deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.as_mut().into_iter();

        assert_eq!(iterator.next(), Some(&mut 3));
        assert_eq!(iterator.next(), Some(&mut 2));
        assert_eq!(iterator.next(), Some(&mut 1));
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn double_ended_mut_ref_iterator_over_deque() {
        let mut deque = UnsafeDeque::from_iter(1..4);

        let mut iterator = deque.as_mut().into_iter();

        assert_eq!(iterator.next(), Some(&mut 3));
        assert_eq!(iterator.next_back(), Some(&mut 1));
        assert_eq!(iterator.next_back(), Some(&mut 2));
        assert_eq!(iterator.next_back(), None);
        assert_eq!(iterator.next(), None);
    }
}


text:
import ewebsockets
import logging, sys
from websocket import create_connection

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)

def handle_websocket_frame(client, frame):
    frame.mask = 0
    print(client.address, ': ', frame.payload, ' Opcode: ', ewebsockets.OpCode.opcodes[frame.opcode])
    frame.payload = b'SERVER: ' + frame.payload
    if frame.opcode == ewebsockets.OpCode.TEXT:
        for i in server.clients_list():
            i.send_frame(frame)
    return True

def handle_new_connection(client):
    print('Client connected')
    return True

def on_client_open(client):
    print('Client now in open state')

def on_client_close(client):
    print('Client now in closing state')

server = ewebsockets.Websocket(
    handle_new_connection=handle_new_connection,
    handle_websocket_frame=handle_websocket_frame,
    on_client_open=on_client_open,
    on_client_close=on_client_close
)

server.start()
print(server.server.host + ':' + str(server.server.port))
client = create_connection('ws://' + server.server.host + ':' + str(server.server.port))
client.send('hello\n', 1)


text:
package io.quarkus.hibernate.orm.runtime;

import java.util.Map;
import java.util.TreeMap;

import io.quarkus.runtime.annotations.ConfigDocMapKey;
import io.quarkus.runtime.annotations.ConfigDocSection;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class HibernateOrmRuntimeConfig {

    /**
     * Configuration for the default persistence unit.
     */
    @ConfigItem(name = ConfigItem.PARENT)
    public HibernateOrmRuntimeConfigPersistenceUnit defaultPersistenceUnit;

    /**
     * Additional named persistence units.
     */
    @ConfigDocSection
    @ConfigDocMapKey("persistence-unit-name")
    @ConfigItem(name = ConfigItem.PARENT)
    public Map<String, HibernateOrmRuntimeConfigPersistenceUnit> persistenceUnits;

    public Map<String, HibernateOrmRuntimeConfigPersistenceUnit> getAllPersistenceUnitConfigsAsMap() {
        Map<String, HibernateOrmRuntimeConfigPersistenceUnit> map = new TreeMap<>();
        if (defaultPersistenceUnit != null) {
            map.put(PersistenceUnitUtil.DEFAULT_PERSISTENCE_UNIT_NAME, defaultPersistenceUnit);
        }
        map.putAll(persistenceUnits);
        return map;
    }

    public static String extensionPropertyKey(String radical) {
        return "quarkus.hibernate-orm." + radical;
    }

    public static String puPropertyKey(String puName, String radical) {
        String prefix = PersistenceUnitUtil.isDefaultPersistenceUnit(puName)
                ? "quarkus.hibernate-orm."
                : "quarkus.hibernate-orm.\"" + puName + "\".";
        return prefix + radical;
    }

    public boolean isAnyPropertySet() {
        return defaultPersistenceUnit.isAnyPropertySet() ||
                !persistenceUnits.isEmpty();
    }
}


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.fail;

/**
 * No catch blocks but handle all should work
 */
public class ValidationFinallyBlockNoCatchTest extends ContextTestSupport {
    protected Processor validator = new MyValidator();
    protected MockEndpoint validEndpoint;
    protected MockEndpoint allEndpoint;
    protected MockEndpoint deadEndpoint;

    @Test
    public void testValidMessage() throws Exception {
        validEndpoint.expectedMessageCount(1);
        allEndpoint.expectedMessageCount(1);

        template.sendBodyAndHeader("direct:start", "<valid/>", "foo", "bar");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testInvalidMessage() throws Exception {
        validEndpoint.expectedMessageCount(0);

        // allEndpoint should only receive 1 when the message is being moved to
        // the dead letter queue
        allEndpoint.expectedMessageCount(1);

        // regular error handler is disbled for try .. catch .. finally
        deadEndpoint.expectedMessageCount(0);

        try {
            template.sendBodyAndHeader("direct:start", "<invalid/>", "foo", "notMatchedHeaderValue");
            fail("Should have thrown an exception");
        } catch (Exception e) {
            // expected
        }

        assertMockEndpointsSatisfied();
    }

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        super.setUp();

        validEndpoint = resolveMandatoryEndpoint("mock:valid", MockEndpoint.class);
        allEndpoint = resolveMandatoryEndpoint("mock:all", MockEndpoint.class);
        deadEndpoint = resolveMandatoryEndpoint("mock:dead", MockEndpoint.class);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                // use dead letter channel that supports redeliveries
                errorHandler(deadLetterChannel("mock:dead").redeliveryDelay(0).maximumRedeliveries(3).logStackTrace(false));

                from("direct:start").doTry().process(validator).to("mock:valid").doFinally().to("mock:all");
            }
        };
    }
}


text:
var hbs                  = require('express-hbs'),
    Promise              = require('bluebird'),
    Amperize             = require('amperize'),
    moment               = require('moment'),
    sanitizeHtml         = require('sanitize-html'),
    config               = require('../../../../config'),
    logging              = require('../../../../logging'),
    i18n                 = require('../../../../i18n'),
    errors               = require('../../../../errors'),
    makeAbsoluteUrl      = require('../../../../utils/make-absolute-urls'),
    cheerio              = require('cheerio'),
    amperize             = new Amperize(),
    amperizeCache        = {},
    allowedAMPTags       = [],
    allowedAMPAttributes = {},
    cleanHTML,
    ampHTML;

allowedAMPTags = ['html', 'body', 'article', 'section', 'nav', 'aside', 'h1', 'h2',
                'h3', 'h4', 'h5', 'h6', 'header', 'footer', 'address', 'p', 'hr',
                'pre', 'blockquote', 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'figure',
                'figcaption', 'div', 'main', 'a', 'em', 'strong', 'small', 's', 'cite',
                'q', 'dfn', 'abbr', 'data', 'time', 'code', 'var', 'samp', 'kbd', 'sub',
                'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'bdi',
                'bdo', 'span', 'br', 'wbr', 'ins', 'del', 'source', 'track', 'svg', 'g',
                'path', 'glyph', 'glyphref', 'marker', 'view', 'circle', 'line', 'polygon',
                'polyline', 'rect', 'text', 'textpath', 'tref', 'tspan', 'clippath',
                'filter', 'lineargradient', 'radialgradient', 'mask', 'pattern', 'vkern',
                'hkern', 'defs', 'stop', 'use', 'foreignobject', 'symbol', 'desc', 'title',
                'table', 'caption', 'colgroup', 'col', 'tbody', 'thead', 'tfoot', 'tr', 'td',
                'th', 'button', 'noscript', 'acronym', 'center', 'dir', 'hgroup', 'listing',
                'multicol', 'nextid', 'nobr', 'spacer', 'strike', 'tt', 'xmp', 'amp-img',
                'amp-video', 'amp-ad', 'amp-embed', 'amp-anim', 'amp-iframe', 'amp-pixel',
                'amp-audio', 'O:P'];

allowedAMPAttributes = {
    '*': ['itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype', 'accesskey', 'class', 'dir', 'draggable',
          'id', 'lang', 'tabindex', 'title', 'translate', 'aria-*', 'role', 'placeholder', 'fallback', 'lightbox',
          'overflow', 'amp-access', 'amp-access-*', 'i-amp-access-id'],
    h1: ['align'],
    h2: ['align'],
    h3: ['align'],
    h4: ['align'],
    h5: ['align'],
    h6: ['align'],
    p: ['align'],
    blockquote: ['align'],
    ol: ['reversed', 'start', 'type'],
    li: ['value'],
    div: ['align'],
    a: ['href', 'hreflang', 'rel', 'role', 'tabindex', 'target', 'download', 'media', 'type', 'border', 'name'],
    time: ['datetime'],
    bdo: ['dir'],
    ins: ['datetime'],
    del: ['datetime'],
    source: ['src', 'srcset', 'sizes', 'media', 'type', 'kind', 'label', 'srclang'],
    track: ['src', 'default', 'kind', 'label', 'srclang'],
    svg: ['*'],
    g: ['*'],
    glyph: ['*'],
    glyphref: ['*'],
    marker: ['*'],
    path: ['*'],
    view: ['*'],
    circle: ['*'],
    line: ['*'],
    polygon: ['*'],
    polyline: ['*'],
    rect: ['*'],
    text: ['*'],
    textpath: ['*'],
    tref: ['*'],
    tspan: ['*'],
    clippath: ['*'],
    filter: ['*'],
    hkern: ['*'],
    lineargradient: ['*'],
    mask: ['*'],
    pattern: ['*'],
    radialgradient: ['*'],
    stop: ['*'],
    vkern: ['*'],
    defs: ['*'],
    symbol: ['*'],
    use: ['*'],
    foreignobject: ['*'],
    desc: ['*'],
    title: ['*'],
    table: ['sortable', 'align', 'border', 'bgcolor', 'cellpadding', 'cellspacing', 'width'],
    colgroup: ['span'],
    col: ['span'],
    tr: ['align', 'bgcolor', 'height', 'valign'],
    td: ['align', 'bgcolor', 'height', 'valign', 'colspan', 'headers', 'rowspan'],
    th: ['align', 'bgcolor', 'height', 'valign', 'colspan', 'headers', 'rowspan', 'abbr', 'scope', 'sorted'],
    button: ['disabled', 'name', 'role', 'tabindex', 'type', 'value', 'formtarget'],
    // built ins
    'amp-img': ['media', 'noloading', 'alt', 'attribution', 'placeholder', 'src', 'srcset', 'width', 'height', 'layout'],
    'amp-pixel': ['src'],
    'amp-video': ['src', 'srcset', 'media', 'noloading', 'width', 'height', 'layout', 'alt', 'attribution',
                  'autoplay', 'controls', 'loop', 'muted', 'poster', 'preload'],
    'amp-embed': ['media', 'noloading', 'width', 'height', 'layout', 'type', 'data-*', 'json'],
    'amp-ad': ['media', 'noloading', 'width', 'height', 'layout', 'type', 'data-*', 'json'],
    // extended components we support
    'amp-anim': ['media', 'noloading', 'alt', 'attribution', 'placeholder', 'src', 'srcset', 'width', 'height', 'layout'],
    'amp-audio': ['src', 'width', 'height', 'autoplay', 'loop', 'muted', 'controls'],
    'amp-iframe': ['src', 'srcdoc', 'width', 'height', 'layout', 'frameborder', 'allowfullscreen', 'allowtransparency',
                   'sandbox', 'referrerpolicy']
};

function getAmperizeHTML(html, post) {
    if (!html) {
        return;
    }

    // make relative URLs abolute
    html = makeAbsoluteUrl(html, config.get('url'), post.url).html();

    if (!amperizeCache[post.id] || moment(new Date(amperizeCache[post.id].updated_at)).diff(new Date(post.updated_at)) < 0) {
        return new Promise(function (resolve) {
            amperize.parse(html, function (err, res) {
                if (err) {
                    if (err.src) {
                        logging.error(new errors.GhostError({
                            err: err,
                            context: 'AMP HTML couldn\'t get parsed: ' + err.src,
                            help: i18n.t('errors.apps.appWillNotBeLoaded.help')
                        }));
                    } else {
                        logging.error(new errors.GhostError({err: err}));
                    }

                    // save it in cache to prevent multiple calls to Amperize until
                    // content is updated.
                    amperizeCache[post.id] = {updated_at: post.updated_at, amp: html};
                    // return the original html on an error
                    return resolve(html);
                }

                amperizeCache[post.id] = {updated_at: post.updated_at, amp: res};
                return resolve(amperizeCache[post.id].amp);
            });
        });
    }

    return Promise.resolve(amperizeCache[post.id].amp);
}

function ampContent() {
    var amperizeHTML = {
            amperize: getAmperizeHTML(this.html, this)
        };

    return Promise.props(amperizeHTML).then(function (result) {
        var $;

        // our Amperized HTML
        ampHTML = result.amperize || '';

        // Use cheerio to traverse through HTML and make little clean-ups
        $ = cheerio.load(ampHTML);

        // We have to remove source children in video, as source
        // is whitelisted for audio, but causes validation
        // errors in video, because video will be stripped out.
        // @TODO: remove this, when Amperize support video transform
        $('video').children('source').remove();
        $('video').children('track').remove();

        // Case: AMP parsing failed and we returned the regular HTML,
        // then we have to remove remaining, invalid HTML tags.
        $('audio').children('source').remove();
        $('audio').children('track').remove();

        ampHTML = $.html();

        // @TODO: remove this, when Amperize supports HTML sanitizing
        cleanHTML = sanitizeHtml(ampHTML, {
            allowedTags: allowedAMPTags,
            allowedAttributes: allowedAMPAttributes,
            selfClosing: ['source', 'track']
        });

        return new hbs.handlebars.SafeString(cleanHTML);
    });
}

module.exports = ampContent;