text:
(function($) {
    TPL_TASK = ['
'];
    TPL_TASK.push('
');
    TPL_TASK.push('');
    TPL_TASK.push('<input type="checkbox" data-role="tasks-complete" data-tid="<%= task.get(\"task_id\") %>" />');
    TPL_TASK.push('');
    TPL_TASK.push('<% if(task.get("status") === 0) { %>');
    TPL_TASK.push('
<%= task.get(\"name\") %>
');
    TPL_TASK.push('<% } else { %>');
    TPL_TASK.push('
<%= task.get(\"name\") %>
');
    TPL_TASK.push('<% } %>');
    TPL_TASK.push("
");
    TPL_TASK.push("
");
    TPL_TASK.push("
");

    TPL_TASK = TPL_TASK.join("");

    function ListingController() {
        this._tasks = new Todo.Models.Tasks.TaskCollection();
        this._offset = 0;
        this._limit = 10;
        this._fetchMoreSize = 5;
    };

    ListingController.prototype.start = function() {
        this._tfNewTask = $("#txt-new-task");
        this._btnComplete = $("#btn-complete-task");
        this._btnRemove = $("#btn-remove-task");
        this._tasksArea = $(".tasks-area");
        this._pagerText = $(".tasks-pager").find("p");
        this._btnPagerFetch = $(".tasks-pager").find("button");

        this._initEvents();
    };

    ListingController.prototype._getSelectedTasks = function() {
        var ids = [],
            tasksChk = this._tasksArea.find("input[data-role='tasks-complete']");

        _.each(tasksChk, function(item) {
            item = $(item);

            if(!item.is(":checked")) {
                return;
            }

            ids.push(parseInt(item.attr("data-tid")));
        });

        return ids;
    };

    ListingController.prototype._initEvents = function() {
        var self = this;

        this._tfNewTask.keyup(function(evt) {
            if(evt.keyCode == 13) {
                self._createTask(self._tfNewTask.val());

                return false;
            }

            return true;
        });

        this._btnRemove.click(function() {
            var ids = self._getSelectedTasks();

            self._deleteTasks(ids);
        });

        this._btnComplete.click(function() {
            var ids = self._getSelectedTasks();

            self._completeTasks(ids);
        });

        this._btnPagerFetch.click(function() {
            self._fetchMoreTasks();
        });

        this._tasks.on("reset", function() {
            self._fetchTasks();
        });

        this._pagerText.html("");
        this._tasks.reset();
    };

    ListingController.prototype._fetchTasks = function() {
        var response = this._tasks.fetch({"offset": this._offset,
                                          "limit": this._limit}),
            self = this;

        response.done(function() {
            self._tasksArea.html("");
            self._tfNewTask.val("");

            self._tasks.each(function(task) {
                self._renderTask(task);
            });

            self._showPageText();
        });
    };

    ListingController.prototype._renderTask = function(task) {
        var taskUi = _.template(TPL_TASK),
            model = {"task": task},
            taskHtml = taskUi(model);

        this._tasksArea.append(taskHtml);
    };

    ListingController.prototype._createTask = function(taskName) {
        var task = new Todo.Models.Tasks.Task({"name": taskName, "status": 0}),
            self = this;

        task.save().always(function() {
            self._fetchTasks();
        });
    };

    ListingController.prototype._showPageText = function() {
        var totalItems = this._tasks.totalItems,
            displayedItems = Math.min(this._limit, totalItems),
            pagesText = displayedItems + " out of " + totalItems;

        this._pagerText.html(pagesText);
    };

    ListingController.prototype._deleteTasks = function(taskIds) {
        this._btnRemove.button("loading");

        taskIds = taskIds || [];

        var onGoing = 0,
            self = this;

        function deleteWhenAllDone() {
            onGoing--;

            if(onGoing > 0) {
                return;
            }

            self._btnRemove.button("reset");

            self._tasks.reset();
        }

        _.each(taskIds, function(taskId) {
            onGoing++;

            var response = new Todo.Models.Tasks.Task({"task_id": taskId}).destroy().always(deleteWhenAllDone);

            taskIds.push(response);
        });
    };

    ListingController.prototype._completeTasks = function(taskIds) {
        this._btnComplete.button("loading");

        taskIds = taskIds || [];

        var onGoing = 0,
            self = this;

        function completeWhenAllDone() {
            onGoing--;

            if(onGoing > 0) {
                return;
            }

            self._btnComplete.button("reset");

            self._tasks.reset();
        }

        _.each(taskIds, function(taskId) {
            var task = self._tasks.get(taskId);

            task.set({"status": 1});

            task.save().always(completeWhenAllDone);
        });
    };

    ListingController.prototype._fetchMoreTasks = function() {
        var newLimit = this._limit + this._fetchMoreSize;

        newLimit = Math.min(newLimit, this._tasks.totalItems);

        if(newLimit >= this._tasks.totalItems) {
            this._btnPagerFetch.hide();
        }

        this._limit = newLimit;

        this._tasks.reset();
    };

    Todo.Controllers.ListingController = ListingController;
})(jQuery);


text:
package org.seasar.doma.internal.apt.entity;

import org.seasar.doma.Entity;

/**
 * @author taedium
 *
 */
@Entity(listener = AbstractEntityListener.class)
public class AbstractEntityListenerEntity {

}

redpajama_set_name: RedPajamaGithub


text:
package com.flash3388.flashlib.scheduling;

import com.flash3388.flashlib.scheduling.actions.Action;
import com.flash3388.flashlib.scheduling.actions.ActionsMock;
import com.flash3388.flashlib.util.logging.Logging;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.collection.IsIterableContainingInAnyOrder;
import org.hamcrest.collection.IsIterableWithSize;
import org.hamcrest.collection.IsMapContaining;
import org.hamcrest.collection.IsMapWithSize;
import org.hamcrest.core.IsIterableContaining;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class RequirementsControlTest {

    private Map<Requirement, Action> mActionsOnSubsystems;
    private Map<Subsystem, Action> mDefaultActionsOnSubsystems;

    private RequirementsControl mRequirementsControl;

    @BeforeEach
    public void setup() throws Exception {
        mActionsOnSubsystems = new HashMap<>();
        mDefaultActionsOnSubsystems = new HashMap<>();
        mRequirementsControl = new RequirementsControl(Logging.stub(), mActionsOnSubsystems, mDefaultActionsOnSubsystems);
    }

    @Test
    public void updateRequirementsNoCurrentAction_actionUsesAllSubsystems_removesAllSubsystems() throws Exception {
        Collection<Subsystem> subsystems = Arrays.asList(
                mock(Subsystem.class),
                mock(Subsystem.class),
                mock(Subsystem.class));
        Action action = ActionsMock.actionMocker()
                .mockWithRequirements(subsystems)
                .build();

        subsystems.forEach((s) -> mActionsOnSubsystems.put(s, action));

        mRequirementsControl.updateRequirementsNoCurrentAction(action);

        MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.anEmptyMap());
    }

    @Test
    public void updateRequirementsNoCurrentAction_actionUsesSome_removesOnlyMatchingSubsystems() throws Exception {
        Collection<Subsystem> otherSubsystems = Arrays.asList(
                mock(Subsystem.class),
                mock(Subsystem.class),
                mock(Subsystem.class));
        Collection<Subsystem> usedSubsystems = Arrays.asList(
                mock(Subsystem.class),
                mock(Subsystem.class),
                mock(Subsystem.class));
        Action action = ActionsMock.actionMocker()
                .mockWithRequirements(usedSubsystems)
                .build();

        otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class)));
        usedSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, action));

        mRequirementsControl.updateRequirementsNoCurrentAction(action);

        MatcherAssert.assertThat(mActionsOnSubsystems.keySet(),
                IsIterableWithSize.iterableWithSize(otherSubsystems.size()));
        MatcherAssert.assertThat(mActionsOnSubsystems.keySet(),
                IsIterableContainingInAnyOrder.containsInAnyOrder(otherSubsystems.toArray()));
    }

    @Test
    public void updateRequirementsWithNewRunningAction_actionWithSomeRequirements_addsRequirementsToMap() throws Exception {
        Collection<Subsystem> otherSubsystems = Arrays.asList(
                mock(Subsystem.class),
                mock(Subsystem.class),
                mock(Subsystem.class));
        Collection<Subsystem> usedSubsystems = Arrays.asList(
                mock(Subsystem.class),
                mock(Subsystem.class),
                mock(Subsystem.class));
        Action action = ActionsMock.actionMocker()
                .mockWithRequirements(usedSubsystems)
                .build();

        otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class)));

        mRequirementsControl.updateRequirementsWithNewRunningAction(action);

        MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.aMapWithSize(usedSubsystems.size() + otherSubsystems.size()));
        otherSubsystems.forEach((s)-> MatcherAssert.assertThat(mActionsOnSubsystems,
                IsMapContaining.hasEntry(equalTo(s), any(Action.class))));

        usedSubsystems.forEach((s)->
                MatcherAssert.assertThat(mActionsOnSubsystems, IsMapContaining.hasEntry(s, action)));
    }

    @Test
    public void updateRequirementsWithNewRunningAction_requirementHasAction_returnsActionAsConflicting() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);
        Action action = ActionsMock.actionMocker().build();
        mActionsOnSubsystems.put(subsystem, action);

        Action newAction = ActionsMock.actionMocker()
                .mockWithRequirements(Collections.singleton(subsystem))
                .build();

        Set<Action> conflicting = mRequirementsControl.updateRequirementsWithNewRunningAction(newAction);

        assertThat(conflicting, contains(action));
    }

    @Test
    public void updateRequirementsWithNewRunningAction_requirementHasAction_replacesAction() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);
        Action action = ActionsMock.actionMocker().build();
        mActionsOnSubsystems.put(subsystem, action);

        Action newAction = ActionsMock.actionMocker()
                .mockWithRequirements(Collections.singleton(subsystem))
                .build();

        mRequirementsControl.updateRequirementsWithNewRunningAction(newAction);

        MatcherAssert.assertThat(mActionsOnSubsystems, Matchers.not(IsMapContaining.hasEntry(action, subsystem)));
    }

    @Test
    public void getActionOnSubsystem_forSubsystemWithAction_returnsAction() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);
        Action action = mock(Action.class);
        mActionsOnSubsystems.put(subsystem, action);

        Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem);
        assertThat(optionalAction.get(), equalTo(action));
    }

    @Test
    public void getActionOnSubsystem_subsystemHasNoAction_returnsEmpty() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);

        Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem);
        assertFalse(optionalAction.isPresent());
    }

    @Test
    public void setDefaultActionOnSubsystem_defaultAlreadyExists_replacesAction() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);
        Action action = mock(Action.class);
        mDefaultActionsOnSubsystems.put(subsystem, action);

        Action newAction = ActionsMock.actionMocker()
                .mockWithRequirements(Collections.singleton(subsystem))
                .build();

        mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction);

        MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction));
    }

    @Test
    public void setDefaultActionOnSubsystem_defaultNotExists_putAction() throws Exception {
        Subsystem subsystem = mock(Subsystem.class);

        Action newAction = ActionsMock.actionMocker()
                .mockWithRequirements(Collections.singleton(subsystem))
                .build();

        mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction);

        MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction));
    }

    @Test
    public void setDefaultActionOnSubsystem_subsystemNotInRequirements_throwsIllegalArguementException() throws Exception {
        assertThrows(IllegalArgumentException.class, ()-> {
            Subsystem subsystem = mock(Subsystem.class);
            Action newAction = ActionsMock.actionMocker().build();

            mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction);
        });
    }

    @Test
    public void getDefaultActionsToStart_noActionsAreRunning_returnsAll() throws Exception {
        Map<Subsystem, Action> defaultActions = new HashMap<>();
        defaultActions.put(mock(Subsystem.class), mock(Action.class));
        defaultActions.put(mock(Subsystem.class), mock(Action.class));

        mDefaultActionsOnSubsystems.putAll(defaultActions);

        Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart();

        MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(defaultActions.size()));
        defaultActions.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a)));
    }

    @Test
    public void getDefaultActionsToStart_someActionsRunning_returnsTheOnesNotRunning() throws Exception {
        Map<Subsystem, Action> notRunning = new HashMap<>();
        notRunning.put(mock(Subsystem.class), mock(Action.class));
        notRunning.put(mock(Subsystem.class), mock(Action.class));

        Map<Subsystem, Action> running = new HashMap<>();
        running.put(mock(Subsystem.class), mock(Action.class));
        running.put(mock(Subsystem.class), mock(Action.class));

        mDefaultActionsOnSubsystems.putAll(notRunning);
        mDefaultActionsOnSubsystems.putAll(running);

        mActionsOnSubsystems.putAll(running);

        Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart();

        MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(notRunning.size()));
        notRunning.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a)));
    }
}


text:
require 'rails_helper'

describe AllocationCategory do
  before do
    @household = create(:household)
    ActsAsTenant.current_tenant = @household
  end
  it 'is valid with a name' do
    category = build(:allocation_category)
    expect(category.valid?).to eq(true)
  end

  it 'is invalid without a name' do
    category = build(:allocation_category, name: nil)
    expect(category.valid?).to eq(false)
  end

  it 'uppercases the first letter of its name' do
    pending "not yet implemented"
    category = create(:allocation_category, name: 'food')
    expect(category.name).to eq('Food')
  end

  it 'is unique per household' do
    food_for_first_household = create(:allocation_category, name: 'food')

    second_household = create(:household)
    ActsAsTenant.current_tenant = second_household

    food_for_second_household = create(:allocation_category, name: 'food')
    expect(food_for_second_household).to be_valid
  end
end


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import re

from pants_test.pants_run_integration_test import PantsRunIntegrationTest

class MissingDependencyFinderIntegrationTest(PantsRunIntegrationTest):

  def test_missing_deps_found(self):
    target = 'testprojects/src/java/org/pantsbuild/testproject/missingjardepswhitelist:missingjardepswhitelist'
    run = self.run_pants(['compile', target, '--compile-zinc-suggest-missing-deps'])
    self.assert_failure(run)
    self.assertTrue(re.search('Found the following deps from target\'s transitive dependencies '
                              'that provide the missing classes:.*'
                              'com.google.common.io.Closer: 3rdparty:guava', run.stdout_data,
                              re.DOTALL))
    self.assertTrue(re.search('please add the following to the dependencies of.*'
                              '\'3rdparty:guava\',', run.stdout_data,
                              re.DOTALL))
    self.assertFalse(re.search("buildozer", run.stdout_data, re.DOTALL))

  def test_missing_deps_found_buildozer(self):
    target = 'testprojects/src/java/org/pantsbuild/testproject/missingjardepswhitelist:missingjardepswhitelist'
    run = self.run_pants([
      'compile',
      target,
      '--compile-zinc-suggest-missing-deps',
      '--compile-zinc-buildozer=path/to/buildozer',
    ])
    self.assert_failure(run)
    self.assertTrue(re.search("path/to/buildozer 'add dependencies 3rdparty:guava' " + target,
                              run.stdout_data,
                              re.DOTALL))

  def test_missing_deps_not_found(self):
    target = 'testprojects/src/java/org/pantsbuild/testproject/dummies:compilation_failure_target'
    run = self.run_pants(['compile', target, '--compile-zinc-suggest-missing-deps', '-ldebug'])
    self.assert_failure(run)
    self.assertTrue(re.search('Unable to find any deps from target\'s transitive dependencies '
                              'that provide the following missing classes:.*'
                              'System2.out', run.stdout_data,
                              re.DOTALL))


text:
package com.google.enterprise.connector.notes;

public class TESTCONST {
  public enum NotesVersion {
    VERSION_8("Release 8.5.3FP6|November 22, 2013"),
    VERSION_9("Release 9.0|March 08, 2013");

    private final String versionString;

    private NotesVersion(String versionString) {
      this.versionString = versionString;
    }

    @Override
    public String toString() {
      return versionString;
    }
  }

  public static final String NOTES_VERSION = "javatest.notesversion";
  public static final String SERVER_DOMINO = "dominoserver1/ou=mtv/o=us";
  public static final String SERVER_DOMINO_WEB = "dominoserver1";
  public static final String DOMAIN = ".gsa-connectors.com";
  public static final String DBSRC_REPLICAID = "85257608004F5587";
  public static final String TEST_UNID1 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX0049";

  private TESTCONST() {
    // Not implemented
  }
}


text:
package randoop.contract;

import randoop.Globals;

/**
 * Checks that calling hashCode() on an object does not throw an exception.
 */
public final class HashCodeReturnsNormally implements ObjectContract {

  @Override
  public boolean equals(Object o) {
    if (o == null) return false;
    if (o == this) return true;
    if (!(o instanceof HashCodeReturnsNormally)) {
      return false;
    }
    return true; // no state to compare.
  }

  @Override
  public int hashCode() {
    int h = 29;
    return h; // no state to compare.
  }

  @Override
  public boolean evaluate(Object... objects) {
    assert objects != null && objects.length == 1;
    Object o = objects[0];
    assert o != null;
    o.hashCode();
    return true;
  }

  @Override
  public int getArity() {
    return 1;
  }

  @Override
  public String toCommentString() {
    return "x0.hashCode() throws no Exception.";
  }

  @Override
  public String get_observer_str() {
    return "hashCode() throws no Exception";
  }

  @Override
  public boolean evalExceptionMeansFailure() {
    return true;
  }

  @Override
  public String toCodeString() {
    StringBuilder b = new StringBuilder();
    b.append(Globals.lineSep);
    b.append("// Checks the contract: ");
    b.append(" " + toCommentString() + Globals.lineSep);
    b.append("org.junit.Assert.assertTrue(");
    b.append("\"Contract failed: " + toCommentString() + "\", ");
    b.append("x0.hashCode()");
    b.append(");");
    return b.toString();
  }
}


text:
import * as React from 'react';
import {Component} from 'react';
import {Card, CardHeader ,CardText} from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import NumberInput from 'material-ui-number-input';
import {Bound} from "../../utils/bound";
import TimePicker from 'material-ui/TimePicker';
import {System} from "../../system";
import RaisedButton from 'material-ui/RaisedButton';
import {Objects} from "../../utils/objects";
import Snackbar from 'material-ui/Snackbar';

export class Settings extends Component<any,any>{

    private data = Objects.merge({},System.app.settings.data);
    public state = {
        open: false,
    };

    @Bound
    private handleChangeOtherMinimum(e){
        this.data.other.minimum = this.formatNumber(e.target.value);
    }
    @Bound
    private handleChangeOtherOneHour(e){
        this.data.other.oneHour = this.formatNumber(e.target.value);
    }
    @Bound
    private handleChangeClubOneHour(e){
        this.data.club.oneHour = this.formatNumber(e.target.value);
    }
    @Bound
    private handleChangePackageTotalPrice(e){
        this.data.package.totalPrice = this.formatNumber(e.target.value);
    }
    @Bound
    private handleChangePackageFinishHour(e){
        this.data.package.finish_hour = this.formatNumber(e.target.value);
    }
    @Bound
    private handleMafiaThursdayStartTime(n,value:Date){
        this.data.mafia.THURSDAY.start_time = this.reformatTime(value);
    }
    @Bound
    private handleMafiaThursdayEndTime(n,value:Date){
        this.data.mafia.THURSDAY.end_time = this.reformatTime(value);
    }
    @Bound
    private handleMafiaSundayStartTime(n,value:Date){
        this.data.mafia.SUNDAY.start_time = this.reformatTime(value);
    }
    @Bound
    private handleMafiaSundayEndTime(n,value:Date){
        this.data.mafia.SUNDAY.end_time = this.reformatTime(value);
    }
    @Bound
    private handleMafiaThursdayTotalPrice(e){
        this.data.mafia.THURSDAY.totalPrice = this.formatNumber(e.target.value);
    }
    @Bound
    private handleMafiaSundayTotalPrice(e){
        this.data.mafia.SUNDAY.totalPrice = this.formatNumber(e.target.value);
    }
    @Bound
    private handleSaveSettings(e){
        System.app
            .settings
            .write(this.data)
            .then(r=>{
                this.setState({
                    open: true,
                });
            }).catch(System.app.log.error)
    }
    handleRequestClose = () => {
        this.setState({
            open: false,
        });
    };
    formatNumber = value =>{
        return Number(value) || 0;
    };
    reformatTime = d => {
        return {
            "hours"   : d.getHours(),
            "minutes" : d.getMinutes()
        }
    };
    formatTime = d =>{
        let date = new Date();
        date.setHours(d.hours);
        date.setMinutes(d.minutes);
        return date;
    };
    render(){
        let settings = System.app.settings.data;

        return (
            <Card style={{margin: 40}}>
                <CardHeader
                    title='Settings'
                    titleStyle={{fontSize: 20}}
                />
                <CardText>

                        <RaisedButton
                            label="Save Settings"
                            labelPosition="before"
                            primary={true}
                            onClick = {this.handleSaveSettings}
                            style={{marginLeft:'2%'}}
                        />

Other

                        <NumberInput
                            id = "minimum-text-field"
                            hintText="Minimum Price"
                            style = {{marginRight:10}}
                            strategy="ignore"
                            defaultValue = {settings.other.minimum}
                            floatingLabelText="Minimum Price"
                            onChange={this.handleChangeOtherMinimum}
                        />
                        <NumberInput
                            id = "oneHour-text-field"
                            style = {{marginRight:10}}
                            hintText="Price for an hour"
                            strategy="ignore"
                            defaultValue = {settings.other.oneHour}
                            floatingLabelText="Price for an hour"
                            onChange={this.handleChangeOtherOneHour}
                        />

Club

                        <NumberInput
                            id = "oneHour-club-text-field"
                            style = {{marginRight:10}}
                            hintText="Price for an hour"
                            strategy="ignore"
                            defaultValue = {settings.club.oneHour}
                            floatingLabelText="Price for an hour"
                            onChange={this.handleChangeClubOneHour}
                        />

Mafia

Thursday

                        <TimePicker
                            onChange ={this.handleMafiaThursdayStartTime}
                            value = {this.formatTime(settings.mafia.THURSDAY.start_time)}
                            id="Mafia-Thursday-start-time"
                            hintText="Start Time"
                        />
                        <TimePicker
                            onChange ={this.handleMafiaThursdayEndTime}
                            value = {this.formatTime(settings.mafia.THURSDAY.end_time)}
                            id="Mafia-Thursday-end-time"
                            hintText="End Time"
                        />
                        <NumberInput
                            id = "total---price-text-field"
                            style = {{marginRight:10}}
                            hintText="Price"
                            strategy="ignore"
                            defaultValue = {settings.mafia.THURSDAY.totalPrice}
                            floatingLabelText="Price"
                            onChange={this.handleMafiaThursdayTotalPrice}
                        />

Sunday

                        <TimePicker
                            onChange ={this.handleMafiaSundayStartTime}
                            value = {this.formatTime(settings.mafia.SUNDAY.start_time)}
                            id="Mafia-Sunday-start-time"
                            hintText="Start Time"
                        />
                        <TimePicker
                            onChange ={this.handleMafiaSundayEndTime}
                            value = {this.formatTime(settings.mafia.SUNDAY.end_time)}
                            id="Mafia-Sunday-end-time"
                            hintText="End Time"
                        />
                        <NumberInput
                            id = "total--Sunday-price-text-field"
                            style = {{marginRight:10}}
                            hintText="Price"
                            strategy="ignore"
                            defaultValue = {settings.mafia.THURSDAY.totalPrice}
                            floatingLabelText="Price"
                            onChange={this.handleMafiaSundayTotalPrice}
                        />

Package

                    <NumberInput
                        id = "minimum-p-text-field"
                        hintText="Total Price"
                        style = {{marginRight:10}}
                        strategy="ignore"
                        defaultValue = {settings.package.totalPrice}
                        floatingLabelText="Total Price"
                        onChange={this.handleChangePackageTotalPrice}
                    />
                    <NumberInput
                        id = "minimum-p-text-field"
                        hintText="Total Price"
                        style = {{marginRight:10}}
                        strategy="ignore"
                        defaultValue = {settings.package.finish_hour}
                        floatingLabelText="Duration (in hour)"
                        onChange={this.handleChangePackageFinishHour}
                    />

                        <RaisedButton
                            label="Save Settings"
                            labelPosition="before"
                            primary={true}
                            onClick = {this.handleSaveSettings}
                            style={{marginLeft:'2%'}}
                        />

                    <Snackbar
                        open={this.state.open}
                        message="Settings Successfully Saved."
                        autoHideDuration={4000}
                        onRequestClose={this.handleRequestClose}
                    />
                </CardText>
            </Card>
        )
    }
}


text:
/*eslint-env node*/

/** This module contains functions to interact with the database
 * (MongoDB for now).
 * @module
 */

var MongoClient = require("mongodb").MongoClient;
var util = require("./util");

// Inner db connection
var _db = null;

/**
 * Figures out the URL of the database: if we're on Amazon EBS,
 * we're connecting to the linked mongo, otherwise we're running
 * on localhost. And if we have the EXPERIGEN_MONGODB_ADDR environment
 * vairable set, use that; with EXPERIGEN_MONGODB_PORT or 27017
 * by default
 * @returns String
 */
var getURL = function(){
    var addr = process.env.EXPERIGEN_MONGODB_ADDR || process.env.MONGODB_PORT_27017_TCP_ADDR || "localhost",
        port = process.env.EXPERIGEN_MONGODB_PORT || process.env.MONGODB_PORT_27017_TCP_PORT || 27017,
        dbname = "experigen";
    return "mongodb://" + addr + ":" + port + "/" + dbname;
};

// memoize this
var url = getURL();
console.log("MongoDB database at " + url);

/**
 * Returns the database object to play with if necessary.
 * @returns {Promise<database>}
 */
module.exports.getDB = function(){
    if(!_db){
        return MongoClient.connect(url).then(function(db){
            console.log("Connected to MongoDB database");
            db.on("close", function(){
                _db = null;
            });
            _db = db;
            return db;
        }).catch(function(err){
            console.error("Cannot connect to " + url + "!");
            _db = null;
            return Promise.reject("Cannot connect to database");
        });
    }
    else{
        return Promise.resolve(_db);
    }
};

/** Closes the database.it really just closes the DB at the next available moment.
 * Since promisification, it does return the Promise.
 * @retruns {Promise}
 */
module.exports.closeDB = function(){
    if(_db){
        var rv = _db.close();
        _db = null;
        return rv;
    }
    else{
        return Promise.resolve(null);
    }
};


text:
package com.atlassian.jira.plugins.dvcs.spi.bitbucket;

import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.BitbucketRemoteClient;

public interface BitbucketClientBuilder
{
    BitbucketClientBuilder cached();

    BitbucketClientBuilder closeIdleConnections();

    BitbucketClientBuilder apiVersion(int apiVersion);

    BitbucketRemoteClient build();
}


text:
layout: post
date: '2015-05-29'
title: "PROM DRESSES Sherri Hill 21275 Satin Mermaid Prom Dress"
category: PROM DRESSES
tags: [PROM DRESSES]
---
### PROM DRESSES Sherri Hill 21275 Satin Mermaid Prom Dress
Just **$390.99**
###

Sherri Hill 21275 Satin Mermaid Prom Dress

Available in sizes 0-18.

Buy it: [https://www.eudances.com/en/prom-dresses/1107-sherri-hill-21275-satin-mermaid-prom-dress.html](https://www.eudances.com/en/prom-dresses/1107-sherri-hill-21275-satin-mermaid-prom-dress.html)


text:
Scripts to help build an Allo Sparky image

#### Prerequisites

```
git squashfs-tools kpartx multistrap qemu-user-static samba debootstrap parted dosfstools qemu binfmt-support qemu-utils
```

It is recommended, not a necessity, to use Debian Jessie 8 (as that's what we are building for).
If on Ubuntu, you may need to remove `$forceyes` from line 989 of /usr/sbin/multistrap

### How to
#### Prepare
- clone the help scripts repo to $HOME  :
git clone http://github.com/gkkpch/sparky-build  $HOME/sparky-build
- go to $HOME/sparky-build, type
```
./infrainit.sh
```
This will
- clone the sparky kernel repo to $HOME/sparky-linux
- clone the official Volumio 2 build repo to $HOME/volumio-build
- place the default platform-sparky files into the volumio-build folder

#### Build the platform files
- go to $HOME/sparky-build to start the kernel build, type:

```
./build-kernel.sh
```
In case you don't need kernel config changes, just exit menuconfig.
Otherwise do not forget to save the config (via menu or when prompted).

#### Build Sparky Image
- goto $HOME/volumio-build and type:

```
sudo ./build.sh -b arm -d sparky -v -<anything to identify>
```

You can do it separate, rootfs first and then the image:

```
sudo ./build.sh -b arm
sudo ./build.sh -d sparky -v -<anything to identify>
```

Once you built the arm rootfs, there is no need to repeat this (unless volumio has changed).
For subsequent image builds, just do:

```
sudo ./build.sh -d sparky -v -<anything to identify>


text:
using System;

namespace U2F.Server.Impl
{
	public class SessionIdGenerator : ISessionIdGenerator
	{
		public string GenerateSessionId(string accountName)
		{
			var generateSessionId = accountName + Guid.NewGuid();
			return generateSessionId.GetBytes().Base64Urlencode();
		}
	}
}


text:
package com.fannie.annotations;

import javax.persistence.Embeddable;

@Embeddable
public class CollegeDetails {
	private int collegeStrength;
	private String collegeLocation;
	private String collegeContact;
	public int getCollegeStrength() {
		return collegeStrength;
	}
	public void setCollegeStrength(int collegeStrength) {
		this.collegeStrength = collegeStrength;
	}
	public String getCollegeLocation() {
		return collegeLocation;
	}
	public void setCollegeLocation(String collegeLocation) {
		this.collegeLocation = collegeLocation;
	}
	public String getCollegeContact() {
		return collegeContact;
	}
	public void setCollegeContact(String collegeContact) {
		this.collegeContact = collegeContact;
	}

}


text:
namespace FastFood.Web.ViewModels.Items
{
    public class CreateItemViewModel
    {
        public int CategoryId { get; set; }
    }
}


text:
module Fog
  module DNS
    class DNSMadeEasy
      class Real
        # Delete the given domain from your account.
        #
        # ==== Parameters
        # * domain<~String> - domain name
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #   * status<~Integer> 200 - OK, 404 - specified domain name is not found
        def delete_domain(domain)
          request(
            :expects  => 200,
            :method   => 'DELETE',
            :path     => "/V1.2/domains/#{domain}"
          )
        end
      end
    end
  end
end


text:
@REM
@REM Copyright (C) 2011
@REM   Michael Mosmann <michael@mosmann.de>
@REM   Martin Jöhren <m.joehren@googlemail.com>
@REM
@REM with contributions from
@REM 	konstantin-ba@github,
	Archimedes Trajano (trajano@github),
	Kevin D. Keck (kdkeck@github),
	Ben McCann (benmccann@github)
@REM
@REM Licensed under the Apache License, Version 2.0 (the "License");
@REM you may not use this file except in compliance with the License.
@REM You may obtain a copy of the License at
@REM
@REM         http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing, software
@REM distributed under the License is distributed on an "AS IS" BASIS,
@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@REM See the License for the specific language governing permissions and
@REM limitations under the License.
@REM

Dummy Exe


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

namespace InstaAPI.Entities
{
    [Serializable]
    public class MetaData
    {
        /// <summary>
        ///     <para>gets or sets the api response code</para>
        ///     <para>set to default value 10 if meta data not exclusively set</para>
        /// </summary>
        public int Code = 10;
        /// <summary>
        ///     <para>gets or sets the error type if web exception is thrown</para>
        /// </summary>
        public String ErrorType = "No Error";
        /// <summary>
        ///     <para>gets or set the error message if web exception is thrown</para>
        /// </summary>
        public String ErrorMessage = "No Error Message";
    }
}


text:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

from bootcamp.decorators import ajax_required
from .models import Notification

@login_required
def notifications(request):
    user = request.user
    all_notifications = Notification.objects.filter(to_user=user)
    all_notifications.update(is_read=True)

    context = {'notifications': all_notifications}
    return render(request, 'activities/notifications.html', context)

@login_required
@ajax_required
def last_notifications(request):
    user = request.user
    last_unread_notifications = Notification.objects.filter(
        to_user=user, is_read=False)[:5]

    for unread_notification in last_unread_notifications:
        unread_notification.is_read = True
        unread_notification.save()

    context = {'notifications': last_unread_notifications}
    return render(request, 'activities/last_notifications.html', context)

@login_required
@ajax_required
def check_notifications(request):
    user = request.user
    notifications_count = Notification.objects.filter(
        to_user=user, is_read=False).count()
    return HttpResponse(notifications_count)


text:
from django.contrib import admin
from dynamicsettings import models

admin.site.register(models.Settings)


text:
.grayBorder {
	border: solid 0.2em gray;
	margin: 0.5em;
}

/* styles for totals of steps completed */
.blueBorder {
	border: solid 0.2em blue;
	margin: 0.5em;
}

.Green {
	background-color: lightgreen;
}
.Orange {
	background-color: lightsalmon;
}

.Italic {
	font-style: italic;
}
.Regular {
	font-style: normal;
}


text:
package com.sun.source.doctree;

import java.util.List;

/**
 * A tree node for an @param block tag.
 *
 * <p>
 * @param parameter-name description
 *
 * @since 1.8
 */
@jdk.Exported
public interface ParamTree extends BlockTagTree {
    boolean isTypeParameter();
    IdentifierTree getName();
    List<? extends DocTree> getDescription();
}


text:
Returns an integer identifying the hash slot the specified key hashes to.
This command is mainly useful for debugging and testing, since it exposes
via an API the underlying Redis implementation of the hashing algorithm.
Example use cases for this command:

1. Client libraries may use Redis in order to test their own hashing algorithm, generating random keys and hashing them with both their local implementation and using Redis `CLUSTER KEYSLOT` command, then checking if the result is the same.
2. Humans may use this command in order to check what is the hash slot, and then the associated Redis Cluster node, responsible for a given key.

## Example

```
> CLUSTER KEYSLOT somekey
11058
> CLUSTER KEYSLOT foo{hash_tag}
(integer) 2515
> CLUSTER KEYSLOT bar{hash_tag}
(integer) 2515
```

Note that the command implements the full hashing algorithm, including support for **hash tags**, that is the special property of Redis Cluster key hashing algorithm, of hashing just what is between `{` and `}` if such a pattern is found inside the key name, in order to force multiple keys to be handled by the same node.

@return

@integer-reply: The hash slot number.


text:
module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: 'standard',
  // required to lint *.vue files
  env: {
    browser: true,
    jest: true,
  },
  // add your custom rules here
  'rules': {
    // allow paren-less arrow functions
    'arrow-parens': 0,
    // allow async-await
    'generator-star-spacing': 0,
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
    // trailing comma
    'comma-dangle': ['error', 'always-multiline'],
    // beware of returning assignement
    'no-return-assign': 'off',
    'no-extend-native': 'warn',
  }
}


text:
/*
 * ClassesPage Messages
 *
 * This contains all the text for the ClassesPage component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.containers.ClassesPage.header',
    defaultMessage: 'Classes',
  },
});


text:
#ifndef __DEBUGGER_CPU_ARM7_FUNCTIONAL_H__
#define __DEBUGGER_CPU_ARM7_FUNCTIONAL_H__

#include "arm-isa.h"
#include "instructions.h"
#include "generic/cpu_generic.h"
#include "coreservices/icpuarm.h"
#include "cmds/cmd_br_arm7.h"
#include "cmds/cmd_reg_arm7.h"
#include "cmds/cmd_regs_arm7.h"

namespace debugger {

class CpuCortex_Functional : public CpuGeneric,
                             public ICpuArm {
 public:
     explicit CpuCortex_Functional(const char *name);
     virtual ~CpuCortex_Functional();

    /** IService interface */
    virtual void postinitService();
    virtual void predeleteService();

    /** IHap */
    virtual void hapTriggered(EHapType type, uint64_t param,
                              const char *descr);

    /** IResetListener interface */
    virtual void reset(IFace *isource);

    /** ICpuGeneric interface */
    virtual void raiseSignal(int idx);
    virtual void lowerSignal(int idx);
    virtual void raiseSoftwareIrq();
    virtual uint64_t getIrqAddress(int idx) { return 0; }

    /** ICpuArm */
    virtual void setInstrMode(EInstructionModes mode) {
        const uint32_t MODE[InstrModes_Total] = {0u, 1u};
        p_psr_->u.T = MODE[mode];
    }
    virtual EInstructionModes getInstrMode() {
        const EInstructionModes MODE[2] = {ARM_mode, THUMB_mode};
        return MODE[p_psr_->u.T];
    }
    virtual uint32_t getZ() { return p_psr_->u.Z; }
    virtual void setZ(uint32_t z) { p_psr_->u.Z = z; }
    virtual uint32_t getC() { return p_psr_->u.C; }
    virtual void setC(uint32_t c) { p_psr_->u.C = c; }
    virtual uint32_t getN() { return p_psr_->u.N; }
    virtual void setN(uint32_t n) { p_psr_->u.N = n; }
    virtual uint32_t getV() { return p_psr_->u.V; }
    virtual void setV(uint32_t v) { p_psr_->u.V = v; }
    virtual uint32_t getA() { return p_psr_->u.A; }
    virtual void setA(uint32_t v) { p_psr_->u.A = v; }
    virtual uint32_t getI() { return p_psr_->u.I; }
    virtual void setI(uint32_t v) { p_psr_->u.I = v; }
    virtual uint32_t getF() { return p_psr_->u.F; }
    virtual void setF(uint32_t v) { p_psr_->u.F = v; }

    // DZ = CP15[19] Divide-by-zero (generate fault exception)
    virtual uint32_t getDZ() { return 0; }

    virtual void StartITBlock(uint32_t firstcond, uint32_t mask);
    virtual bool InITBlock() { return ITBlockMask_ != 0; }
    virtual bool LastInITBlock() { return (ITBlockMask_ & 0xF) == 0x8; }
    virtual uint32_t ITBlockCondition() { return ITBlockCondition_; }

    virtual void enterException(int idx);
    virtual void exitException(uint32_t exc_return);

 protected:
    /** CpuGeneric common methods */
    virtual uint64_t getResetAddress();
    virtual EEndianessType endianess() { return LittleEndian; }
    virtual GenericInstruction *decodeInstruction(Reg64Type *cache);
    virtual void generateIllegalOpcode();
    virtual void handleException(int e) {}
    virtual void handleInterrupts() {}
    virtual void trackContextEnd() override;
    virtual void traceOutput() override;

    void addArm7tmdiIsa();
    void addThumb2Isa();
    unsigned addSupportedInstruction(ArmInstruction *instr);
    uint32_t hash32(uint32_t val) { return (val >> 24) & 0xf; }

 private:
    AttributeType defaultMode_;
    AttributeType vendorID_;
    AttributeType vectorTable_;

    static const int INSTR_HASH_TABLE_SIZE = 1 << 4;
    AttributeType listInstr_[INSTR_HASH_TABLE_SIZE];
    GenericInstruction *isaTableArmV7_[ARMV7_Total];

    ProgramStatusRegsiterType *p_psr_;

    char errmsg_[256];

    CmdBrArm *pcmd_br_;
    CmdRegArm *pcmd_reg_;
    CmdRegsArm *pcmd_regs_;

    // CPSR contains fields IT[7:0]
    //     IT[7:5] = cond_base, when IT Block enabled, 4'b0000 otherwise
    //     IT[4:0] = ITBlockMask_
    bool ITBlockEnabled;
    uint32_t ITBlockCondition_ : 4;
    uint32_t ITBlockBaseCond_ : 4;
    uint32_t ITBlockMask_ : 5;
};

DECLARE_CLASS(CpuCortex_Functional)

}  // namespace debugger

#endif  // __DEBUGGER_CPU_RISCV_FUNCTIONAL_H__


text:
/**
 *
 */
package eu.codesketch.adam.rest.infrastructure.docker.translator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import eu.codesketch.adam.rest.domain.model.container.Container;
import eu.codesketch.adam.rest.domain.model.container.ContainerId;
import eu.codesketch.adam.rest.domain.model.container.Container.Status;

/**
 * @author quirino
 *
 */
public class ContainerTranslator {

    public static List<Container> translate(List<com.github.dockerjava.api.model.Container> containers) {
        List<Container> answer = new ArrayList<Container>();
        for (com.github.dockerjava.api.model.Container container : containers) {
            ContainerId containerId = ContainerId.newInstance(container.getId());
            List<String> names = Arrays.asList(container.getNames());
            Status status = Container.Status.fromAlias(container.getStatus());
            answer.add(new Container(containerId, names, container.getImage(), container.getCreated(), status));
        }
        return answer;
    }

}


text:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}

module Text.Greek.IO.Process where

import Prelude hiding (words)
import Control.Monad.Except
import Data.Map (Map)
import Text.Greek.IO.Stage
import Text.Greek.Source.FileReference
import qualified Control.Lens as Lens
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Text as Text
import qualified Data.Tuple as Tuple
import qualified Text.Greek.IO.Json as Json
import qualified Text.Greek.IO.Morphgnt as Morphgnt
import qualified Text.Greek.IO.Type as Type
import qualified Text.Greek.IO.Utility as Utility
import qualified Text.Greek.Source.All as All
import qualified Text.Greek.Source.Work as Work
import qualified Text.Greek.Phonology.Consonant as Consonant
import qualified Text.Greek.Script.Abstract as Abstract
import qualified Text.Greek.Script.Concrete as Concrete
import qualified Text.Greek.Script.Elision as Elision
import qualified Text.Greek.Script.Mark as Mark
import qualified Text.Greek.Script.Marked as Marked
import qualified Text.Greek.Script.Place as Place
import qualified Text.Greek.Script.Punctuation as Punctuation
import qualified Text.Greek.Script.Syllable as Syllable
import qualified Text.Greek.Script.Word as Word
import qualified Text.Greek.Script.Unicode as Unicode
import qualified Text.Greek.Utility as Utility

processSblgnt :: ExceptT String IO ()
processSblgnt = do
  sourceWords <- All.loadSblgnt
  _ <- liftIO $ putStrLn "Processing"

  let (stage0, composedWords) = makeStage0 sourceWords
  let (stage1, decomposedWords) = makeStage1 composedWords
  (stage2, unicodeLetterMarks) <- Utility.handleError $ tryMakeStage2 decomposedWords
  (stage3, concreteLetterConcreteMarks) <- Utility.handleMaybe "stage3" $ tryMakeStage3 unicodeLetterMarks
  (stage4, abstractLetterConcreteMarks) <- Utility.handleMaybe "stage4" $ tryMakeStage4 concreteLetterConcreteMarks
  (stage5, abstractLetterMarkGroup) <- Utility.handleMaybe "stage5" $ tryMakeStage5 abstractLetterConcreteMarks
  let (stage6, vowelConsonantMarkGroup) = makeStage6 abstractLetterMarkGroup
  (stage7, vocalicSyllableABConsonantRh) <- Utility.handleMaybe "stage7" $ makeStage7 vowelConsonantMarkGroup
  (stage8, syllableRhAB) <- Utility.handleMaybe "stage8" $ makeStage8 vocalicSyllableABConsonantRh
  (stage9, syllableRBA) <- Utility.handleMaybe "stage9" $ makeStage9 syllableRhAB
  (stage10, syllableRBA') <- Utility.handleMaybe "stage10" $ makeStage10 syllableRBA
  let (stage11, _) = Morphgnt.makeStage syllableRBA'

  let
    stages =
      [ stage0
      , stage1
      , stage2
      , stage3
      , stage4
      , stage5
      , stage6
      , stage7
      , stage8
      , stage9
      , stage10
      , stage11
      ]
  let indexedStages = indexStages stages
  let indexedTypeDatas = getIndexedStageTypeDatas indexedStages
  let storedTypeDatas = fmap snd indexedTypeDatas

  let storedTypes = fmap typeDataJson storedTypeDatas
  liftIO $ putStrLn "Writing types"
  liftIO $ Json.writeTypes storedTypes

  let typeNameMap = Map.fromList . fmap (\(i,t) -> (typeDataName t, i)) $ indexedTypeDatas
  specialTypes <- Utility.handleMaybe "special types" $ Json.SpecialTypes
    <$> Map.lookup Type.SourceWord typeNameMap
    <*> Map.lookup Type.WordPrefix typeNameMap
    <*> Map.lookup Type.WordSuffix typeNameMap
  workInfoTypeIndexes <- Utility.handleMaybe "workInfoTypeIndexes" $
    lookupAll typeNameMap
      [ Type.SourceWord
      , Type.Verse
      , Type.WorkSource
      ]
  summaryTypeIndexes <- Utility.handleMaybe "summaryTypeIndexes" $
    lookupAll typeNameMap
      [ Type.MorphgntLemma
      , Type.MorphgntPartOfSpeech
      , Type.MorphgntParsingCode
      , Type.ListScriptSyllableConsonantRB
      , (Type.Count Type.Syllable)
      , Type.WordAccent
      , Type.InitialEnclitic
      , Type.Crasis
      , Type.Elision
      , Type.Verse
      , Type.ParagraphNumber
      ]

  let instanceMap = Json.makeInstanceMap storedTypes
  let ourWorks = getWorks summaryTypeIndexes instanceMap sourceWords
  liftIO $ putStrLn "Writing works"
  liftIO $ Json.writeWorks ourWorks

  let ourWorkInfos = fmap (Json.workToWorkInfo workInfoTypeIndexes) ourWorks
  let ourTypeInfos = fmap Json.makeTypeInfo storedTypes
  let ourStageInfos = fmap getStageInfo indexedStages
  let ourIndex = Json.Index ourWorkInfos ourTypeInfos specialTypes ourStageInfos
  liftIO $ putStrLn "Writing index"
  liftIO $ Json.writeIndex ourIndex

getStageInfo :: Stage (Json.TypeIndex, a) -> Json.StageInfo
getStageInfo (Stage p ps) = Json.StageInfo (fst p) (fmap fst ps)

makeStage0 :: [Work.Indexed [Word.Word Word.Basic Word.SourceInfo]]
  -> ( Stage TypeData
    , [Work.Indexed [Word.Word Word.Basic [Unicode.Composed]]]
    )
makeStage0 sourceWords = (stage, composedWords)
  where
    composedWords = toComposedWords sourceWords
    stage = Stage primaryType typeParts
    primaryType = makeSurfaceType Json.WordStageTypeKind Type.UnicodeComposed composedWords
    typeParts =
      [ makeWordPartType Json.WordPropertyTypeKind Type.SourceWord (pure . Word.getSourceInfoWord . Word.getSurface) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.SourceFile (pure . _fileReferencePath . Word.getSourceInfoFile . Word.getSurface) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.SourceFileLocation (pure . (\(FileReference _ l1 l2) -> (l1, l2)) . Word.getSourceInfoFile . Word.getSurface) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.ParagraphNumber (Lens.toListOf (Word.info . Word.paragraphIndexLens)) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.Verse (Lens.toListOf (Word.info . Word.verseLens)) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.WordPrefix (Lens.toListOf (Word.info . Word.prefixLens)) sourceWords
      , makeWordPartType Json.WordPropertyTypeKind Type.WordSuffix (Lens.toListOf (Word.info . Word.suffixLens)) sourceWords
      , makeWorkInfoType Json.WorkPropertyTypeKind Type.WorkSource (Lens.view Lens._2) sourceWords
      , makeWorkInfoType Json.WorkPropertyTypeKind Type.WorkTitle (Lens.view Lens._3) sourceWords
      ]

makeStage1 :: [Work.Indexed [Word.Word Word.Basic [Unicode.Composed]]]
  -> ( Stage TypeData
    , [Work.Indexed [Word.Word Word.Basic [Unicode.Decomposed]]]
    )
makeStage1 composedWords = (stage, decomposedWords)
  where
    decomposedWordPairs = toDecomposedWordPairs composedWords
    decomposedWords = toDecomposedWords decomposedWordPairs
    stage = Stage primaryType typeParts
    primaryType = makeSurfaceType Json.WordStageTypeKind Type.UnicodeDecomposed decomposedWords
    typeParts =
      [ makeSurfaceType Json.WordStageFunctionTypeKind (Type.Function Type.UnicodeComposed (Type.List Type.UnicodeDecomposed)) decomposedWordPairs
      ]

tryMakeStage2 :: WordSurface Word.Basic [Unicode.Decomposed]
  -> Either Unicode.Error (Stage TypeData, WordSurface Word.Elision [Marked.Unit Unicode.Letter [Unicode.Mark]])
tryMakeStage2 decomposedWords = (,) <$> mStage <*> mUnicodeLetterMarks
  where
    decomposedWordsE = splitDecomposedElision decomposedWords
    mUnicodeLetterMarksPairs = toUnicodeLetterMarksPairs decomposedWordsE
    mUnicodeLetterMarks = toUnicodeLetterMarks <$> mUnicodeLetterMarksPairs
    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.UnicodeLetterMarks <$> mUnicodeLetterMarks
    mTypeParts = sequence
      [ makeSurfaceType Json.WordStageFunctionTypeKind (Type.Function (Type.List Type.UnicodeDecomposed) Type.UnicodeLetterMarks) <$> mUnicodeLetterMarksPairs
      , makeSurfacePartType Json.WordStagePartTypeKind Type.UnicodeLetter (pure . Marked._item) <$> mUnicodeLetterMarks
      , makeSurfacePartType Json.WordStagePartTypeKind Type.UnicodeMark Marked._marks <$> mUnicodeLetterMarks
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.AbstractLetter) (pure . Word.LetterCount . length . Word.getSurface) <$> mUnicodeLetterMarks
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.ConcreteMark) (pure . Word.MarkCount . sum . fmap (length . Marked._marks) . Word.getSurface) <$> mUnicodeLetterMarks
      , pure $ makeWordPartType Json.WordPropertyTypeKind Type.Elision (pure . Lens.view (Word.info . Word.elisionLens . Lens._1)) decomposedWordsE
      , pure $ makeWordPartType Json.WordPropertyTypeKind Type.UnicodeElision (Lens.toListOf (Word.info . Word.elisionLens . Lens._2 . Lens._Just)) decomposedWordsE
      ]

tryMakeStage3 :: WordSurface (Word.IndexedP a) [Marked.Unit Unicode.Letter [Unicode.Mark]]
  -> Maybe (Stage TypeData, WordSurface (Word.IndexedP a) [Marked.Unit Concrete.Letter [Concrete.Mark]])
tryMakeStage3 unicodeLetterMarks = (,) <$> mStage <*> mConcreteLetterConcreteMarks
  where
    mMarkedUnicodeConcretePairsLM = toMarkedConcreteLetters unicodeLetterMarks >>= toMarkedConcreteMarks
    mMarkedUnicodeConcretePairsB = toMarkedUnicodeConcretePairs <$> mMarkedUnicodeConcretePairsLM
    mConcreteLetterConcreteMarks = Lens.over (Lens._Just . wordSurfaceLens . traverse) snd mMarkedUnicodeConcretePairsB

    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.ConcreteLetterMarks <$> mConcreteLetterConcreteMarks
    mTypeParts = sequence
      [ makeSurfaceType Json.WordStageFunctionTypeKind (Type.Function Type.UnicodeLetterMarks Type.ConcreteLetterMarks) <$> mMarkedUnicodeConcretePairsB
      , makeSurfacePartType Json.WordStagePartFunctionTypeKind (Type.Function Type.UnicodeLetter Type.ConcreteLetter) (pure . Marked._item) <$> mMarkedUnicodeConcretePairsLM
      , makeSurfacePartType Json.WordStagePartFunctionTypeKind (Type.Function Type.UnicodeMark Type.ConcreteMark) Marked._marks <$> mMarkedUnicodeConcretePairsLM
      , makeSurfacePartType Json.WordStagePartTypeKind Type.ConcreteLetter (pure . Marked._item) <$> mConcreteLetterConcreteMarks
      , makeSurfacePartType Json.WordStagePartTypeKind Type.ConcreteMark Marked._marks <$> mConcreteLetterConcreteMarks
      ]

tryMakeStage4 :: WordSurface Word.Elision [Marked.Unit Concrete.Letter [Concrete.Mark]]
  -> Maybe (Stage TypeData, WordSurface Word.Capital [Marked.Unit Abstract.Letter [Concrete.Mark]])
tryMakeStage4 concreteLetterConcreteMarks = (,) <$> mStage <*> mCapMarkedAbstractLetters
  where
    markedAbstractLetterPairs = Lens.over (wordSurfaceLens . traverse . Marked.item) (\x -> (x, Abstract.toLetterCaseFinal x)) concreteLetterConcreteMarks
    markedAbstractLettersCF = Lens.over (wordSurfaceLens . traverse . Marked.item) snd markedAbstractLetterPairs
    mCapMarkedAbstractLetters = toCapitalWord markedAbstractLettersCF >>= validateFinalForm
    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.AbstractLetterMarks <$> mCapMarkedAbstractLetters
    mTypeParts = sequence
      [ pure $ makeSurfacePartType Json.WordStagePartFunctionTypeKind (Type.Function Type.ConcreteLetter Type.AbstractLetterCaseFinal) (pure . Marked._item) markedAbstractLetterPairs
      , pure $ makeSurfaceType Json.WordStageTypeKind Type.AbstractLetterCaseFinalMarks markedAbstractLettersCF
      , pure $ makeSurfacePartType Json.WordStagePartTypeKind Type.AbstractLetter (pure . Lens.view (Marked.item . Lens._1)) markedAbstractLettersCF
      , pure $ makeSurfacePartType Json.WordStagePartTypeKind Type.LetterCase (pure . Lens.view (Marked.item . Lens._2)) markedAbstractLettersCF
      , pure $ makeSurfacePartType Json.WordStagePartTypeKind Type.LetterFinalForm (pure . Lens.view (Marked.item . Lens._3)) markedAbstractLettersCF
      , pure $ makeIndexedSurfacePartType Json.CompositePropertyTypeKind Type.LetterCase Abstract.CaseIndex (Lens.view (Marked.item . Lens._2)) markedAbstractLettersCF
      , pure $ makeReverseIndexedSurfacePartType Json.CompositePropertyTypeKind Type.LetterFinalForm Abstract.FinalReverseIndex (Lens.view (Marked.item . Lens._3)) markedAbstractLettersCF
      , pure $ makeIndexedSurfacePartType Json.CompositePropertyTypeKind Type.AbstractLetter Abstract.LetterIndex (Lens.view (Marked.item . Lens._1)) markedAbstractLettersCF
      , pure $ makeReverseIndexedSurfacePartType Json.CompositePropertyTypeKind Type.AbstractLetter Abstract.LetterReverseIndex (Lens.view (Marked.item . Lens._1)) markedAbstractLettersCF
      , makeWordPartType Json.WordPropertyTypeKind Type.WordCapitalization (pure . Lens.view (Word.info . Word.capitalLens)) <$> mCapMarkedAbstractLetters
      ]

tryMakeStage5 :: WordSurface (Word.IndexedP a) [Marked.Unit Abstract.Letter [Concrete.Mark]]
  -> Maybe (Stage TypeData, WordSurface (Word.IndexedP a) [Marked.Unit Abstract.Letter (Mark.Group Maybe)])
tryMakeStage5 capMarkedAbstractLetters = (,) <$> mStage <*> mMarkedAbstractLetterMarkGroups
  where
    markedAbstractLetterMarkKindPairs = toMarkedAbstractLetterMarkKindPairs capMarkedAbstractLetters
    markedAbstractLetterMarkKinds = Lens.over (wordSurfaceLens . traverse . Marked.marks . traverse) snd markedAbstractLetterMarkKindPairs

    mMarkedAbstractLetterMarkGroupPairs = dupApply (wordSurfaceLens . traverse . Marked.marks) Mark.toMarkGroup markedAbstractLetterMarkKinds
    mMarkedAbstractLetterMarkGroups = Lens.over (Lens._Just . wordSurfaceLens . traverse . Marked.marks) snd mMarkedAbstractLetterMarkGroupPairs

    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind (Type.AbstractLetterMarkGroup) <$> mMarkedAbstractLetterMarkGroups
    mTypeParts = sequence
      [ pure $ makeSurfacePartType Json.WordStageFunctionTypeKind (Type.Function Type.ConcreteMark Type.MarkKind) Marked._marks markedAbstractLetterMarkKindPairs
      , pure $ makeSurfaceType Json.WordStageTypeKind (Type.AbstractLetterMarkKinds) markedAbstractLetterMarkKinds
      , makeSurfacePartType Json.WordStageFunctionTypeKind (Type.Function (Type.List Type.MarkKind) (Type.MarkGroup)) (pure . Marked._marks) <$> mMarkedAbstractLetterMarkGroupPairs
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Accent) (pure . Mark.AccentCount . sum . fmap (maybeToOneOrZero . Lens.view (Marked.marks . Lens._1)) . Word.getSurface) <$> mMarkedAbstractLetterMarkGroups
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Breathing) (pure . Mark.BreathingCount . sum . fmap (maybeToOneOrZero . Lens.view (Marked.marks . Lens._2)) . Word.getSurface) <$> mMarkedAbstractLetterMarkGroups
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.SyllabicMark) (pure . Mark.SyllabicCount . sum . fmap (maybeToOneOrZero . Lens.view (Marked.marks . Lens._3)) . Word.getSurface) <$> mMarkedAbstractLetterMarkGroups
      ]

makeStage6 :: WordSurface (Word.IndexedP a) [Marked.Unit Abstract.Letter (Mark.Group Maybe)]
  -> (Stage TypeData, WordSurface (Word.IndexedP a) [Marked.Unit Abstract.VowelConsonant (Mark.Group Maybe)])
makeStage6 abstractLetterMarkGroup = (stage, vowelConsonantMarkGroup)
  where
    vowelConsonantMarkGroupPairs = dupApply' (wordSurfaceLens . traverse . Marked.item) Abstract.toVowelConsonant abstractLetterMarkGroup
    vowelConsonantMarkGroup = Lens.over (wordSurfaceLens . traverse . Marked.item) snd vowelConsonantMarkGroupPairs
    stage = Stage primaryType typeParts
    primaryType = makeSurfaceType Json.WordStageTypeKind Type.VowelConsonantMarkGroup vowelConsonantMarkGroup
    typeParts =
      [ makeSurfacePartType Json.WordStageFunctionTypeKind (Type.Function Type.AbstractLetter Type.VowelConsonant) (pure . Marked._item) vowelConsonantMarkGroupPairs
      , makeSurfacePartType Json.WordStagePartTypeKind Type.VowelConsonant (pure . Marked._item) vowelConsonantMarkGroup
      , makeSurfacePartType Json.WordStagePartTypeKind Type.Vowel (Lens.toListOf (Marked.item . Lens._Left)) vowelConsonantMarkGroup
      , makeSurfacePartType Json.WordStagePartTypeKind Type.Consonant (Lens.toListOf (Marked.item . Lens._Right)) vowelConsonantMarkGroup
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Vowel) (pure . Word.VowelCount . sum . fmap (length . (Lens.toListOf (Marked.item . Lens._Left))) . Word.getSurface) vowelConsonantMarkGroup
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Consonant) (pure . Word.ConsonantCount . sum . fmap (length . (Lens.toListOf (Marked.item . Lens._Right))) . Word.getSurface) vowelConsonantMarkGroup
      , makeSurfacePartType Json.CompositePropertyTypeKind  Type.SyllabicMarkVowelConsonant getSyllabicMarkVowelConsonant vowelConsonantMarkGroup
      ]

makeStage7 :: WordSurface (Word.IndexedP a) [Marked.Unit Abstract.VowelConsonant (Mark.Group Maybe)]
  -> Maybe (Stage TypeData, WordSurface (Word.IndexedP a) [Syllable.VocalicEither (Mark.AccentBreathing Maybe) Consonant.PlusRoughRho])
makeStage7 vowelConsonantMarkGroup = (,) <$> mStage <*> mVocalicSyllableABConsonantRh
  where
    startSyllable = Lens.over wordSurfaceLens (Syllable.makeStartVocalic . fmap (\(Marked.Unit a b) -> (a, b))) vowelConsonantMarkGroup
    mVocalicSyllableABConsonantBPair = dupApply (wordSurfaceLens . traverse) Syllable.validateVocalicConsonant startSyllable
    mVocalicSyllableABConsonantB = Lens.over (Lens._Just . wordSurfaceLens . traverse) snd mVocalicSyllableABConsonantBPair
    mVocalicSyllableABConsonantRhPair = mVocalicSyllableABConsonantB >>= dupApply (wordSurfaceLens . traverse . Lens._Right) Consonant.reifyBreathing
    mVocalicSyllableABConsonantRh = Lens.over (Lens._Just . wordSurfaceLens . traverse . Lens._Right) snd mVocalicSyllableABConsonantRhPair
    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.VocalicSyllableABConsonantRh <$> mVocalicSyllableABConsonantRh
    mTypeParts = sequence
      [ pure $ makeSurfaceType Json.WordStageTypeKind Type.StartSyllable startSyllable
      , makeSurfaceType Json.WordStageFunctionTypeKind (Type.Function Type.StartSyllable Type.VocalicSyllableABConsonantB) <$> mVocalicSyllableABConsonantBPair
      , makeSurfaceType Json.WordStageTypeKind Type.VocalicSyllableABConsonantB <$> mVocalicSyllableABConsonantB
      , makeSurfacePartType Json.WordStagePartTypeKind Type.VocalicSyllable (Lens.toListOf Lens._Left) <$> Lens.over (Lens._Just . wordSurfaceLens . traverse . Lens._Left) (fmap (const ())) mVocalicSyllableABConsonantB
      , makeSurfacePartType Json.WordStagePartTypeKind Type.VocalicSyllableSingle (concat . Lens.toListOf Lens._Left . Lens.over Lens._Left Syllable.vocalicToSingle) <$> mVocalicSyllableABConsonantB
      , makeSurfacePartType Json.WordStagePartTypeKind Type.ImproperDiphthong (concat . Lens.toListOf Lens._Left . Lens.over Lens._Left Syllable.vocalicToImproperDiphthong) <$> mVocalicSyllableABConsonantB
      , makeSurfacePartType Json.WordStagePartTypeKind Type.Diphthong (concat . Lens.toListOf Lens._Left . Lens.over Lens._Left Syllable.vocalicToDiphthong) <$> mVocalicSyllableABConsonantB
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Syllable) (pure . sum . fmap Syllable.getSyllableCount . Word.getSurface) <$> mVocalicSyllableABConsonantB
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.VocalicSyllableSingle) (pure . sum . fmap Syllable.getVocalicSingleCount . Word.getSurface) <$> mVocalicSyllableABConsonantB
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.ImproperDiphthong) (pure . sum . fmap Syllable.getImproperDiphthongCount . Word.getSurface) <$> mVocalicSyllableABConsonantB
      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.Diphthong) (pure . sum . fmap Syllable.getDiphthongCount . Word.getSurface) <$> mVocalicSyllableABConsonantB
      , makeSurfacePartType Json.WordStageFunctionTypeKind (Type.Function Type.ConsonantBreathing Type.ConsonantRh) (Lens.toListOf Lens._Right) <$> mVocalicSyllableABConsonantRhPair
      , makeSurfacePartType Json.WordStagePartTypeKind Type.ConsonantRh (Lens.toListOf Lens._Right) <$> mVocalicSyllableABConsonantRh
      ]

makeStage8 :: forall a. WordSurface (Word.IndexedP a) [Syllable.VocalicEither (Mark.AccentBreathing Maybe) Consonant.PlusRoughRho]
  -> Maybe (Stage TypeData, WordSurface (Word.IndexedP a)
    (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]))
makeStage8 vocalicSyllableABConsonantRh = (,) <$> mStage <*> mSyllableApproxAB
  where
    vocalicSyllableABConsonantCluster = Lens.over wordSurfaceLens Syllable.clusterConsonants vocalicSyllableABConsonantRh
    vocalicSyllableABConsonantClusterPlace3 = Lens.over wordSurfaceLens Syllable.tagConsonantPositions vocalicSyllableABConsonantCluster
    vocalicSyllableABConsonantClusterPlace3Swap = Lens.over (wordSurfaceLens . traverse . Lens._Right) Tuple.swap vocalicSyllableABConsonantClusterPlace3
    initialConsonantClusterSet = Place.getInitialSet . Lens.toListOf (wordSurfaceLens . traverse . Lens._Right) $ vocalicSyllableABConsonantClusterPlace3
    vocalicSyllableABConsonantClusterPlace4 = Lens.over (wordSurfaceLens . traverse . Lens._Right) (Place.applyAttestation initialConsonantClusterSet) vocalicSyllableABConsonantClusterPlace3
    vocalicSyllableABConsonantClusterMAI = Lens.over (wordSurfaceLens . traverse . Lens._Right . Lens._2) (\(_,b,_,d) -> (b,d)) vocalicSyllableABConsonantClusterPlace4

    mSyllableRightAB :: Maybe (WordSurface (Word.IndexedP a) (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]))
    mSyllableRightAB = wordSurfaceLens Syllable.makeSyllableMedialNext vocalicSyllableABConsonantCluster
    mSyllableRightABSurface :: Maybe (WordSurface (Word.IndexedP a) [Syllable.SyllableOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]])
    mSyllableRightABSurface = unifySurfaceSyllables mSyllableRightAB
    mSyllableRightSurface :: Maybe (WordSurface (Word.IndexedP a) [Syllable.SyllableOrConsonants () [Consonant.PlusRoughRho]])
    mSyllableRightSurface = dropMark mSyllableRightABSurface

    dropMark :: Maybe (WordSurface (Word.IndexedP a) [Syllable.SyllableOrConsonants b [Consonant.PlusRoughRho]])
       -> Maybe (WordSurface (Word.IndexedP a) [Syllable.SyllableOrConsonants () [Consonant.PlusRoughRho]])
    dropMark = Lens.over (Lens._Just . wordSurfaceLens . traverse . Lens._Left) (Syllable.mapSyllableMark (const ()))

    approxSplit = Consonant.splitScriptSyllable initialConsonantClusterSet
    mSyllableApproxAB :: Maybe (WordSurface (Word.IndexedP a) (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]))
    mSyllableApproxAB = mSyllableRightAB >>= (wordSurfaceLens . Lens._Left) (Syllable.splitMedial approxSplit)
    mSyllableApprox :: Maybe (WordSurface (Word.IndexedP a) (Syllable.SyllableListOrConsonants () [Consonant.PlusRoughRho]))
    mSyllableApprox = stripSyllableMark mSyllableApproxAB
    mSyllableApproxABSurface = unifySurfaceSyllables mSyllableRightAB
    mSyllableApproxSurface = dropMark mSyllableApproxABSurface

    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStagePartTypeKind Type.ScriptSyllableConsonantRhAB_Approx <$> mSyllableApproxABSurface
    mTypeParts = sequence
      [ makeWordPartType Json.WordPropertyTypeKind Type.ListScriptSyllableConsonantRh (pure . Lens.toListOf (Word.surface . Lens._Left . traverse)) <$> mSyllableApprox
      , makeSurfaceType Json.WordStagePartTypeKind Type.ScriptSyllableConsonantRh_Approx <$> mSyllableApproxSurface
      , makeSurfaceType Json.WordStageTypeKind Type.ScriptSyllableConsonantRhAB_Right <$> mSyllableRightABSurface
      , makeSurfaceType Json.WordStagePartTypeKind Type.ScriptSyllableConsonantRh_Right <$> mSyllableRightSurface
      , pure $ makeSurfaceType Json.WordStageTypeKind Type.VocalicSyllableABConsonantRhCluster vocalicSyllableABConsonantCluster
      , pure $ makeSurfacePartType Json.WordStagePartTypeKind Type.ConsonantRhCluster (Lens.toListOf Lens._Right) vocalicSyllableABConsonantCluster
      , pure $ makeSurfacePartType Json.CompositePropertyTypeKind Type.ConsonantRhClusterPlace3 (Lens.toListOf Lens._Right) vocalicSyllableABConsonantClusterPlace3
      , pure $ makeSurfacePartType Json.CompositePropertyTypeKind Type.ConsonantRhClusterPlace3Swap (Lens.toListOf Lens._Right) vocalicSyllableABConsonantClusterPlace3Swap
      , pure $ makeSurfacePartType Json.CompositePropertyTypeKind Type.ConsonantRhClusterPlaceInfo (fmap (\(a, (b, c)) -> (b, c, Consonant.splitScriptSyllableInfo a)) . Lens.toListOf Lens._Right) vocalicSyllableABConsonantClusterMAI
      ]

unifySurfaceSyllables :: Maybe (WordSurface c (Syllable.SyllableListOrConsonants m c1))
  -> Maybe (WordSurface c [Syllable.SyllableOrConsonants m c1])
unifySurfaceSyllables = Lens.over (Lens._Just . wordSurfaceLens) Syllable.unifySyllableConsonant

stripSyllableMark :: Traversable t0 => Maybe [Work.Indexed [Word.Word c (Either (t0 (Syllable.Syllable b c2)) c1)]]
  -> Maybe [Work.Indexed [Word.Word c (Either (t0 (Syllable.Syllable () c2)) c1)]]
stripSyllableMark = Lens.over (Lens._Just . wordSurfaceLens . Lens._Left . traverse) (Syllable.mapSyllableMark (const ()))

makeStage9 :: WordSurface Word.Capital (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho])
  -> Maybe (Stage TypeData, WordSurface Word.WithCrasis (Syllable.SyllableListOrConsonants (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing]))
makeStage9 syllableApproxAB = (,) <$> mStage <*> mProcessed
  where
    wordApplyCrasis :: Word.Word Word.Capital (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [c])
      -> Word.Word Word.WithCrasis (Syllable.SyllableListOrConsonants (Mark.AccentBreathing Maybe) [c])
    wordApplyCrasis w = Lens.over Word.info (Word.addCrasis (Syllable.getCrasis . Word.getSurface $ w)) w

    withCrasis = Lens.over (traverse . Work.content . traverse) wordApplyCrasis syllableApproxAB
    mProcessed = wordSurfaceLens Syllable.processBreathing withCrasis
    mProcessedSurfaceNoMarks = unifySurfaceSyllables . stripSyllableMark $ mProcessed

    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.ScriptSyllableConsonantRBA_Approx <$> unifySurfaceSyllables mProcessed
    mTypeParts = sequence
      [ makeWordPartType Json.WordPropertyTypeKind Type.ListScriptSyllableConsonantRB (pure . Lens.toListOf (Word.surface . traverse)) <$> mProcessedSurfaceNoMarks
      , makeSurfaceType Json.WordStagePartTypeKind Type.ScriptSyllableConsonantRB_Approx <$> mProcessedSurfaceNoMarks
      , makeWordPartType Json.WordPropertyTypeKind Type.Crasis (Lens.toListOf (Word.info . Word.crasisLens)) <$> mProcessed
      ]

makeStage10 :: WordSurface Word.WithCrasis (Syllable.SyllableListOrConsonants (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing])
  -> Maybe (Stage TypeData, WordSurface Word.WithAccent (Syllable.SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) [Consonant.PlusRoughRhoRoughBreathing]))
makeStage10 syllableRBA = (,) <$> mStage <*> mWithAccent
  where
    mWithSentence :: Maybe (WordSurface Word.Sentence (Syllable.SyllableListOrConsonants (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing]))
    mWithSentence = (traverse . Work.content . traverse) wordAddSentence syllableRBA
    wordAddSentence w = do
      pair <- Punctuation.tryGetSentencePair $ getSuffix w
      return $ Lens.over Word.info (Word.addSentencePair pair) w
    getSuffix w = concatMap Text.unpack . Lens.toListOf (Word.info . Word.suffixLens . Lens._Just . Word.suffix) $ w

    mGraveGonePairs :: Maybe (WordSurface Word.Sentence (Syllable.SyllableListOrConsonants (Maybe (Mark.Accent, Mark.AcuteCircumflex)) [Consonant.PlusRoughRhoRoughBreathing]))
    mGraveGonePairs = mWithSentence >>=
      ((traverse . Work.content . traverse)
      (\w -> dupApply
        (Word.surface . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just)
        (Syllable.processGrave (getEndOfSentence w))
        w))
    mGraveGone :: Maybe (WordSurface Word.Sentence (Syllable.SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) [Consonant.PlusRoughRhoRoughBreathing]))
    mGraveGone = Lens.over (Lens._Just . wordSurfaceLens . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just) snd mGraveGonePairs
    getEndOfSentence = Lens.view (Word.info . Word.sentenceLens . Lens._1)

    mWithEnclitic :: Maybe (WordSurface Word.WithEnclitic (Syllable.SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) [Consonant.PlusRoughRhoRoughBreathing]))
    mWithEnclitic = Lens.over (Lens._Just . traverse . Work.content) Syllable.markInitialEnclitic mGraveGone

    mWithAccent :: Maybe (WordSurface Word.WithAccent (Syllable.SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) [Consonant.PlusRoughRhoRoughBreathing]))
    mWithAccent = mWithEnclitic >>=
      ( (traverse . Work.content . traverse)
        (\w -> do
          a <- Syllable.getWordAccent (Word.getSurface w)
          return $ Lens.over Word.info (Word.addAccent a) w
        )
      )

    mStage = Stage <$> mPrimaryType <*> mTypeParts
    mPrimaryType = makeSurfaceType Json.WordStageTypeKind Type.ScriptSyllableConsonantRBAC_Approx <$> unifySurfaceSyllables mWithAccent
    mTypeParts = sequence
      [ makeWordPartType Json.WordPropertyTypeKind Type.WordAccent (Lens.toListOf (Word.info . Word.accentLens)) <$> mWithAccent

      , makeWordPartType Json.WordPropertyTypeKind Type.WordUltimaUnaccented
        (Lens.over traverse Word.getUltimaUnaccented . Lens.toListOf (Word.info . Word.accentLens)) <$> mWithAccent

      , makeWordPartType Json.WordPropertyTypeKind (Type.Count Type.AcuteCircumflex)
        (pure . Word.AcuteCircumflexCount . length . Lens.toListOf (Word.surface . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just))
        <$> mWithEnclitic

      , makeWordPartType Json.WordPropertyTypeKind Type.EndOfSentence (pure . getEndOfSentence) <$> mWithSentence

      , makeWordPartType Json.WordPropertyTypeKind Type.UnicodeEndOfSentence
        (Lens.toListOf (Word.info . Word.sentenceLens . Lens._2 . Lens._Just)) <$> mWithSentence

      , makeWordPartType Json.CompositePropertyTypeKind Type.EndOfSentenceAccent
        (\w -> fmap (\x -> (getEndOfSentence w, x)) . Lens.toListOf (Word.surface . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just) $ w)
        <$> mWithSentence

      , makeWordPartType Json.WordStagePartFunctionTypeKind (Type.Function Type.Accent Type.AcuteCircumflex)
        (Lens.toListOf (Word.surface . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just)) <$> mGraveGonePairs

      , makeWordPartType Json.WordStagePartTypeKind Type.AcuteCircumflex
        (Lens.toListOf (Word.surface . Lens._Left . traverse . Syllable.syllableMarkLens . Lens._Just)) <$> mGraveGone

      , makeReverseIndexedSurfacePartType2
        Json.CompositePropertyTypeKind
        Type.AcuteCircumflex
        Syllable.ReverseIndex
        (Lens.toListOf (Lens._Left . traverse . Syllable.syllableMarkLens))
        <$> mGraveGone

      , makeWordPartType Json.WordPropertyTypeKind Type.InitialEnclitic
        (Lens.toListOf (Word.info . Word.encliticLens)) <$> mWithEnclitic
      ]

getIndexedStageTypeDatas :: [Stage (Json.TypeIndex, TypeData)] -> [(Json.TypeIndex, TypeData)]
getIndexedStageTypeDatas = List.sortOn fst . concatMap getTypes
  where
    getTypes (Stage s ss) = s : ss

indexStage :: Json.TypeIndex -> Stage TypeData -> (Json.TypeIndex, Stage (Json.TypeIndex, TypeData))
indexStage i (Stage t parts) = (i', Stage (i, t) indexedParts)
  where
    (i', indexedParts) = Lens.over Lens._2 reverse . Foldable.foldl' go (i + 1, []) $ parts
    go (x, ps) p = (x + 1, (x, p) : ps)

indexStages :: [Stage TypeData] -> [Stage (Json.TypeIndex, TypeData)]
indexStages = reverse . snd . Foldable.foldl' go (0, [])
  where
    go (i, ss) s = (i', s' : ss)
      where
        (i', s') = indexStage i s

maybeToOneOrZero :: Maybe a -> Int
maybeToOneOrZero Nothing = 0
maybeToOneOrZero (Just _) = 1

lookupAll :: Ord a => Map a b -> [a] -> Maybe [b]
lookupAll m = traverse (flip Map.lookup m)

getWorks :: [Json.TypeIndex] -> Map WordLocation [(Json.TypeIndex, [Json.ValueIndex])] -> [Work.Indexed [Word.Word Word.Basic a]] -> [Json.Work]
getWorks summaryTypes m works = workInfos
  where
    workInfos = fmap getWorkInfo works
    getWorkInfo (Work.Work (workIndex, workSource, workTitle) workWords) =
      Json.Work workSource workTitle (getWords workIndex workWords) (getWordGroups workWords) summaryTypes
    getWords workIndex = fmap (getWord workIndex)
    getWord workIndex (Word.Word (i, _) _) = Json.Word . concat . Maybe.maybeToList . Map.lookup (workIndex, i) $ m

    getWordGroups ws = [Json.WordGroup "Paragraphs" (getParagraphs ws)]

    getParagraphs :: [Word.Word Word.Basic a] -> [[Word.Index]]
    getParagraphs
      = fmap snd
      . Map.toAscList
      . Lens.over (traverse . traverse) (Lens.view Word.indexLens)
      . Utility.mapGroupBy (Lens.view Word.paragraphIndexLens)
      . fmap Word.getInfo

toComposedWords
  :: WordSurfaceBasic Word.SourceInfo
  -> WordSurfaceBasic [Unicode.Composed]
toComposedWords = Lens.over wordSurfaceLens (Unicode.toComposed . Word.getSource . Word.getSourceInfoWord)

toDecomposedWordPairs
  :: WordSurfaceBasic [Unicode.Composed]
  -> WordSurfaceBasic [(Unicode.Composed, [Unicode.Decomposed])]
toDecomposedWordPairs = Lens.over (wordSurfaceLens . traverse) (\x -> (x, Unicode.decompose' x))

toDecomposedWords
  :: WordSurfaceBasic [(Unicode.Composed, [Unicode.Decomposed])]
  -> WordSurfaceBasic [Unicode.Decomposed]
toDecomposedWords = Lens.over wordSurfaceLens (concatMap snd)

splitDecomposedElision
  :: WordSurface Word.Basic [Unicode.Decomposed]
  -> WordSurface Word.Elision [Unicode.Decomposed]
splitDecomposedElision = Lens.over (traverse . Work.content . traverse) go
  where
    go :: Word.Word Word.Basic [Unicode.Decomposed] -> Word.Word Word.Elision [Unicode.Decomposed]
    go w = newInfo
      where
        newInfo = Lens.over Word.info (Word.addElisionPair e) newSurface
        newSurface = Lens.set Word.surface as w
        (e, as) = Elision.split Unicode.decomposed (Word.getSurface w)

toUnicodeLetterMarksPairs
  :: WordSurface b [Unicode.Decomposed]
  -> Either Unicode.Error (WordSurface b [([Unicode.Decomposed], Marked.Unit Unicode.Letter [Unicode.Mark])])
toUnicodeLetterMarksPairs = wordSurfaceLens Unicode.parseMarkedLetters

toUnicodeLetterMarks
  :: WordSurface b [([Unicode.Decomposed], Marked.Unit Unicode.Letter [Unicode.Mark])]
  -> WordSurface b [Marked.Unit Unicode.Letter [Unicode.Mark]]
toUnicodeLetterMarks = Lens.over (wordSurfaceLens . traverse) snd

toMarkedConcreteLetters
  :: WordSurface b [Marked.Unit Unicode.Letter a]
  -> Maybe (WordSurface b [Marked.Unit (Unicode.Letter, Concrete.Letter) a])
toMarkedConcreteLetters = dupApply (wordSurfaceLens . traverse . Marked.item) Concrete.toMaybeLetter

toMarkedConcreteMarks
  :: WordSurface b [Marked.Unit a [Unicode.Mark]]
  -> Maybe (WordSurface b [Marked.Unit a [(Unicode.Mark, Concrete.Mark)]])
toMarkedConcreteMarks = dupApply (wordSurfaceLens . traverse . Marked.marks . traverse) Concrete.toMaybeMark

toMarkedUnicodeConcretePairs
  :: WordSurface b [Marked.Unit (Unicode.Letter, Concrete.Letter) [(Unicode.Mark, Concrete.Mark)]]
  -> WordSurface b [(Marked.Unit Unicode.Letter [Unicode.Mark], Marked.Unit Concrete.Letter [Concrete.Mark])]
toMarkedUnicodeConcretePairs = Lens.over (wordSurfaceLens . traverse) go
  where
    overBoth f g = Lens.over (Marked.marks . traverse) g . Lens.over Marked.item f
    go x = (overBoth fst fst x, overBoth snd snd x)

toMarkedAbstractLetterMarkKindPairs
  :: WordSurface b [Marked.Unit a [Concrete.Mark]]
  -> WordSurface b [Marked.Unit a ([(Concrete.Mark, Mark.Kind)])]
toMarkedAbstractLetterMarkKindPairs = dupApply' (wordSurfaceLens . traverse . Marked.marks . traverse) Mark.toKind

toCapitalWord :: [Work.Indexed [Word.Word Word.Elision [Marked.Unit (t, Abstract.Case, t1) m0]]]
  -> Maybe [Work.Indexed [Word.Word Word.Capital [Marked.Unit (t, t1) m0]]]
toCapitalWord = fmap transferCapitalSurfaceToWord . toCapitalWordSurface

toCapitalWordSurface :: [Work.Indexed [Word.Word Word.Elision [Marked.Unit (t, Abstract.Case, t1) m0]]]
 -> Maybe [Work.Indexed [Word.Word Word.Elision (Word.IsCapitalized, [Marked.Unit (t, t1) m0])]]
toCapitalWordSurface = wordSurfaceLens (Abstract.validateIsCapitalized ((\(_,x,_) -> x) . Marked._item) (Lens.over Marked.item (\(x,_,y) -> (x,y))))

transferCapitalSurfaceToWord :: [Work.Indexed [Word.Word Word.Elision (Word.IsCapitalized, [Marked.Unit (t, t1) m0])]]
  -> [Work.Indexed [Word.Word Word.Capital [Marked.Unit (t, t1) m0]]]
transferCapitalSurfaceToWord = Lens.over (traverse . Work.content . traverse) setCapital
  where
    setCapital (Word.Word wi (c, m)) = Word.Word (Word.addCapital c wi) m

validateFinalForm :: [Work.Indexed [Word.Word a [Marked.Unit (t, Abstract.Final) m0]]]
  -> Maybe [Work.Indexed [Word.Word a [Marked.Unit t m0]]]
validateFinalForm = wordSurfaceLens $ Abstract.validateLetterFinal (Lens.view $ Marked.item . Lens._2) (Lens.over Marked.item fst)

getSyllabicMarkVowelConsonant :: Marked.Unit Abstract.VowelConsonant (Mark.Group Maybe) -> [(Mark.Syllabic, Abstract.VowelConsonant)]
getSyllabicMarkVowelConsonant (Marked.Unit vc (_, _, Just m)) = pure (m, vc)
getSyllabicMarkVowelConsonant _ = mempty


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
  ~ Copyright 2016 http://www.hswebframework.org
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~  See the License for the specific language governing permissions and
  ~  limitations under the License.
  ~
  -->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.hswebframework.web.dao.authorization.MenuGroupDao">
    <resultMap id="MenuGroupResultMap" type="org.hswebframework.web.entity.authorization.MenuGroupEntity">
        <id property="id" column="u_id" javaType="string" jdbcType="VARCHAR"/>
        <result property="name" column="name" javaType="String" jdbcType="VARCHAR"/>
        <result property="describe" column="describe" javaType="String" jdbcType="VARCHAR"/>
        <result property="defaultGroup" column="default_group" javaType="Boolean" jdbcType="DECIMAL"/>
        <result property="path" column="path" javaType="String" jdbcType="VARCHAR"/>
        <result property="parentId" column="parent_id" javaType="String" jdbcType="VARCHAR"/>
        <result property="level" column="level" javaType="Integer" jdbcType="DECIMAL"/>
        <result property="sortIndex" column="sort_index" javaType="Long" jdbcType="DECIMAL"/>
        <result property="status" column="status" javaType="Byte" jdbcType="DECIMAL"/>
        <collection property="bindInfo" column="u_id" select="org.hswebframework.web.dao.menu.MenuGroupBindDao.queryByGroupId"/>
    </resultMap>

    <!--用于动态生成sql所需的配置-->
    <sql id="config">
        <bind name="resultMapId" value="'MenuGroupResultMap'"/>
        <bind name="tableName" value="'s_menu_group'"/>
    </sql>

    <insert id="insert" parameterType="org.hswebframework.web.entity.authorization.MenuGroupEntity">
        <include refid="config"/>
        <include refid="BasicMapper.buildInsertSql"/>
    </insert>

    <delete id="deleteByPk" parameterType="String">
        delete from S_MENU_GROUP where u_id =#{id}
    </delete>

    <delete id="delete" parameterType="org.hswebframework.web.commons.entity.Entity">
        <include refid="config"/>
        <include refid="BasicMapper.buildDeleteSql"/>
    </delete>

    <update id="update" parameterType="org.hswebframework.web.commons.entity.Entity">
        <include refid="config"/>
        <include refid="BasicMapper.buildUpdateSql"/>
    </update>

    <select id="query" parameterType="org.hswebframework.web.commons.entity.Entity" resultMap="MenuGroupResultMap">
        <include refid="config"/>
        <include refid="BasicMapper.buildSelectSql"/>
    </select>

    <select id="count" parameterType="org.hswebframework.web.commons.entity.Entity" resultType="int">
        <include refid="config"/>
        <include refid="BasicMapper.buildTotalSql"/>
    </select>
</mapper>


text:
using SIL.Acknowledgements;

[assembly: Acknowledgement("Mono.Posix", Name = "Mono.Posix", Url = "https://www.nuget.org/packages/Mono.Posix/",
	LicenseUrl = "https://opensource.org/licenses/MIT")]


text:
CJRequireFunction::
CJRequireFunction(CJavaScript *js) :
 CJFunctionBase(js, "require")
{
}

CJRequireFunction::
CJRequireFunction(const CJRequireFunction &fn) :
 CJFunctionBase(fn)
{
}

CJValueP
CJRequireFunction::
exec(CJavaScript *js, const Values &values)
{
  if (values.size() <= 1)
    return CJValueP();

  std::string filename = values[1]->toString();

  bool rc = js->loadSubFile(filename);

  if (! rc) {
    js->errorMsg("Failed to load '" + filename + "'");
    return CJValueP();
  }

  return js->exec();
}


text: ALTER TABLE "OffersBackground" ALTER COLUMN "totalYoe" SET DEFAULT 0;


text:
package com.example.activitytaskdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
 * Created by Administrator on 2016/6/13.
 */
public class FirstActivity extends Activity implements View.OnClickListener {

    private Button button;

    private Button btnStartSelf;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(MainActivity.TAG, "FirstActivity onNewIntent ");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        Log.i(MainActivity.TAG, "FirstActivity taskId " + getTaskId());
        button = (Button) findViewById(R.id.button1);
        btnStartSelf = (Button) findViewById(R.id.btnStartSelf);
        button.setOnClickListener(this);
        btnStartSelf.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                Intent intent = new Intent(FirstActivity.this, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.btnStartSelf:
                Intent intent1 = new Intent(FirstActivity.this, FirstActivity.class);
                startActivity(intent1);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(MainActivity.TAG, "FirstActivity onDestroy");
    }

}


text:
class Address < ActiveRecord::Base
  belongs_to  :state
  belongs_to  :country
  belongs_to  :address_type
  belongs_to  :addressable, :polymorphic => true
  has_many     :phones, :as => :phoneable
  has_many     :shipments

  validates :first_name,  :presence => true,
                          :format   => { :with => CustomValidators::Names.name_validator },       :length => { :maximum => 25 }
  validates :last_name,   :presence => true,
                          :format   => { :with => CustomValidators::Names.name_validator },       :length => { :maximum => 25 }
  validates :address1,    :presence => true,       :length => { :maximum => 255 }
  validates :city,        :presence => true,
                          :format   => { :with => CustomValidators::Names.name_validator },       :length => { :maximum => 75 }
  validates :state_id,      :presence => true,  :if => Proc.new { |address| Settings.require_state_in_address}
  validates :country_id,    :presence => true,  :if => Proc.new { |address| !Settings.require_state_in_address}
  #validates :state_name,  :presence => true,  :if => Proc.new { |address| address.state_id.blank?   }
  validates :zip_code,    :presence => true,       :length => { :maximum => 12 }
  before_validation :sanitize_data

  attr_accessor :replace_address_id # if you are updating an address set this field.
  before_save :replace_address, if: :replace_address_id
  after_save  :invalidate_old_defaults

  #accepts_nested_attributes_for :phones

  # First and last name of the person on the address
  #
  # @example first_name == 'John', last_name == 'Doe'
  #    address.name  => 'John Doe'
  # @param none
  # @ return [String] first and last name on the address with a space between
  def name
    [first_name, last_name].compact.join(' ')
  end

  # Will inactivate and save the address
  #
  # @param none
  # @ return [Boolean] true or error(error will only happen if there is a bad record in the db)
  def inactive!
    self.active = false
    save!
  end

  # hash of all the address db attributes except created_at, updated_at, id
  #
  # @param none
  # @ return [Hash] address db attributes except created_at, updated_at, id
  def address_attributes
    attributes.delete_if {|key, value| ["id", 'updated_at', 'created_at'].any?{|k| k == key }}
  end

  # hash of all the address attributes to be passed to a creditcard processor
  #
  # @param none
  # @ return [Hash] address attributes for a creditcard processor
  def cc_params
    { :name     => name,
      :address1 => address1,
      :address2 => address2,
      :city     => city,
      :state    => state.abbreviation,
      :country  => state.country_id == Country::BRAZIL_ID ? 'BR' : 'US',
      :zip      => zip_code#,
      #:phone    => phone
    }
  end

  # Method used to determine the shipping methods ids available for this address
  def shipping_method_ids
    if state_id && state.shipping_zone
      state.shipping_zone.shipping_method_ids
    else
      country.shipping_zone_id ? country.shipping_zone.shipping_method_ids : []
    end
  end
  # Method used to determine the shipping_zone_id for this address
  #
  #  Specifically used to determine the order_item.shipping_rate_options
  def shipping_zone_id
    if state_id
      state.shipping_zone_id
    elsif country_id
      country.shipping_zone_id
    end
  end

  # Use this method to represent the full address as an array compacted
  #
  # @param [none]
  # @return [Array] Array has ("name", "address1", "address2"(unless nil), "city state zip")
  def full_address_array
    [name, address1, address2, city_state_zip].compact
  end

  # Use this method to represent the full address as an array compacted
  #
  # @param [Optional String] default is ', '
  # @return [String] address1 and address2 joined together with the string you pass in
  def address_lines(join_chars = ', ')
    [address1, address2].delete_if{|add| add.blank?}.join(join_chars)
  end

  # Use this method to represent the state abbreviation
  #  it is possible the state is nil. in that case the abbreviation will be stored in
  #  the state_name column in the DB
  #
  # @param [none]
  # @return [String] state abbreviation
  def state_abbr_name
    state ? state.abbreviation : state_name
  end

  # Use this method to represent the "city, state.abbreviation"
  #
  # @param [none]
  # @return [String] "city, state.abbreviation"
  def city_state_name
    [city, state_abbr_name].join(', ')
  end

  # Use this method to represent the "city, state.abbreviation"
  #
  # @param [none]
  # @return [String] "city, state.abbreviation"
  def state_country_name
    [state_abbr_name, country.try(:name)].compact.join(', ')
  end

  # Use this method to represent the "city, state.abbreviation zip_code"
  #
  # @param [none]
  # @return [String] "city, state.abbreviation zip_code"
  def city_state_zip
    [city_state_name, zip_code].join(' ')
  end

  private
    # This method is called to ensure data is formated without extra white space before_validation
    def sanitize_data
      sanitize_name
      sanitize_city
      sanitize_zip_code
      sanitize_address
    end

    def sanitize_zip_code
      self.zip_code    = self.zip_code.strip    unless self.zip_code.blank?
    end

    def sanitize_city
      self.city        = self.city.strip        unless self.city.blank?
    end

    def sanitize_name
      sanitize_first_name
      sanitize_last_name
    end

    def sanitize_first_name
      self.first_name  = self.first_name.strip  unless self.first_name.blank?
    end

    def sanitize_last_name
      self.last_name   = self.last_name.strip   unless self.last_name.blank?
    end

    def sanitize_address
      sanitize_address1
      sanitize_address2
    end

    def sanitize_address1
      self.address1    = self.address1.strip    unless self.address1.blank?
    end

    def sanitize_address2
      self.address2    = self.address2.strip    unless self.address2.blank?
    end

    def replace_address
      Address.where(id: replace_address_id).update_all(active: false)
    end

    def invalidate_old_defaults
      [:default, :billing_default].each do |attr|
        Address.where({
          addressable_type: addressable_type,
          addressable_id: addressable_id
        }).where("id <> ?", self.id).update_all(attr => false) if self[attr]
      end
    end
end


text:
============

Simple project to parse .pkpass files with boarding passes.

  - Extracts .pkpass file to temporary cache directory.
  - Checks contents against checksums in manifest file.
  - Generates barcode of specified type.
  - Parses color from pass.
  - Displays few sample lines among with barcode.

## Screenshots

![](https://raw.githubusercontent.com/shmoula/PkpassParser/master/Screenshots/2017-01-09-18-46-14.png)
![](https://raw.githubusercontent.com/shmoula/PkpassParser/master/Screenshots/2017-01-09-18-47-10.png)

## Contact

https://github.com/shmoula/PkpassParser
Email me at shmoula@gmail.com


text:
Contributors
============

Carl Meyer <carl@oddbird.net>
Mjumbe Poe <mjumbewu@gmail.com>
Eduard Iskandarov
Greg Hinch <ghinch@gmail.com>
Gehan Gonsalkorale
Paul Winkler <slinkp@gmail.com>


text:
Adds an AWS::IoTAnalytics::Datastore.DatastoreStorage resource property to the template.
Where data store data is stored.

## SYNTAX

```
Add-VSIoTAnalyticsDatastoreDatastoreStorage [[-CustomerManagedS3] <Object>] [[-ServiceManagedS3] <Object>]
 [<CommonParameters>]
```

## DESCRIPTION
Adds an AWS::IoTAnalytics::Datastore.DatastoreStorage resource property to the template.
Where data store data is stored.

## PARAMETERS

### -CustomerManagedS3
Use this to store data store data in an S3 bucket that you manage.
The choice of service-managed or customer-managed S3 storage cannot be changed after creation of the data store.

Type: CustomerManagedS3
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-datastorestorage.html#cfn-iotanalytics-datastore-datastorestorage-customermanageds3
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ServiceManagedS3
Use this to store data store data in an S3 bucket managed by the AWS IoT Analytics service.
The choice of service-managed or customer-managed S3 storage cannot be changed after creation of the data store.

Type: ServiceManagedS3
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-datastorestorage.html#cfn-iotanalytics-datastore-datastorestorage-servicemanageds3
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Vaporshell.Resource.IoTAnalytics.Datastore.DatastoreStorage
## NOTES

## RELATED LINKS

[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-datastorestorage.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-datastorestorage.html)