text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="f53105d0-603e-4112-8844-ac62c38237cf" name="Default" comment="Update with some simple validations">
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/budgetn.iml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/deployment.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/encodings.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/misc.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/modules.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/scopes/scope_settings.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/vcs.xml" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.gitignore" afterPath="$PROJECT_DIR$/.gitignore" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/js/app.js" afterPath="$PROJECT_DIR$/js/app.js" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/bower.json" afterPath="$PROJECT_DIR$/bower.json" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/index.html" afterPath="$PROJECT_DIR$/index.html" />
    </list>
    <ignored path="budgetn.iws" />
    <ignored path=".idea/workspace.xml" />
    <ignored path=".idea/dataSources.local.xml" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="budgetn" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="index.html" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/index.html">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="-5.625" vertical-offset="0" max-vertical-offset="1530">
              <caret line="18" column="0" selection-start-line="18" selection-start-column="0" selection-end-line="18" selection-end-column="0" />
              <folding>
                <marker date="1427663942000" expanded="true" signature="3874:4108" placeholder="..." />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name=".gitignore" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/.gitignore">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.6362468" vertical-offset="0" max-vertical-offset="778">
              <caret line="33" column="7" selection-start-line="33" selection-start-column="7" selection-end-line="33" selection-end-column="7" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="LICENSE" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/LICENSE">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="420">
              <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
              <folding />
            </state>
          </provider>
          <provider editor-type-id="com.intellij.database.editor.CsvTableFileEditorProvider">
            <state />
          </provider>
        </entry>
      </file>
      <file leaf-file-name="styles.css" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/css/styles.css">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.0" vertical-offset="144" max-vertical-offset="1305">
              <caret line="30" column="21" selection-start-line="30" selection-start-column="21" selection-end-line="30" selection-end-column="21" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="app.js" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/js/app.js">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="-24.5" vertical-offset="2078" max-vertical-offset="3090">
              <caret line="181" column="33" selection-start-line="181" selection-start-column="33" selection-end-line="181" selection-end-column="33" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="FindManager">
    <FindUsagesManager>
      <setting name="OPEN_NEW_TAB" value="true" />
    </FindUsagesManager>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="changedFiles">
      <list>
        <option value="$PROJECT_DIR$/.bowerrc" />
        <option value="$PROJECT_DIR$/css/styles.css" />
        <option value="$PROJECT_DIR$/package.json" />
        <option value="$PROJECT_DIR$/js/app.js" />
        <option value="$PROJECT_DIR$/index.html" />
        <option value="$PROJECT_DIR$/.gitignore" />
      </list>
    </option>
  </component>
  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
  <component name="ProjectFrameBounds">
    <option name="y" value="23" />
    <option name="width" value="1920" />
    <option name="height" value="1141" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="true">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectReloadState">
    <option name="STATE" value="0" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
    </navigator>
    <panes>
      <pane id="Scope" />
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="js" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="budgetn" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="css" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="options.lastSelected" value="editor.preferences.appearance" />
    <property name="options.splitter.main.proportions" value="0.3" />
    <property name="options.splitter.details.proportions" value="0.2" />
    <property name="WebServerToolWindowFactoryState" value="true" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$/package.json" />
    <property name="WebServerToolWindowPanel.toolwindow.show.size" value="false" />
    <property name="WebServerToolWindowPanel.toolwindow.show.date" value="false" />
    <property name="WebServerToolWindowPanel.toolwindow.show.permissions" value="false" />
    <property name="WebServerToolWindowPanel.toolwindow.highlight.symlinks" value="true" />
    <property name="WebServerToolWindowPanel.toolwindow.highlight.mappings" value="true" />
  </component>
  <component name="RunManager">
    <configuration default="true" type="PHPUnitRunConfigurationType" factoryName="PHPUnit">
      <TestRunner />
      <method />
    </configuration>
    <configuration default="true" type="PhpLocalRunConfigurationType" factoryName="PHP Console">
      <method />
    </configuration>
    <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug">
      <method />
    </configuration>
    <configuration default="true" type="PhpBehatConfigurationType" factoryName="Behat">
      <BehatRunner />
      <method />
    </configuration>
    <configuration default="true" type="PhpUnitRemoteRunConfigurationType" factoryName="PHPUnit on Server" server_id="7db8ce0c-4dca-4e97-b1b3-0fba37c860c8" server_name="Budgetn">
      <method />
    </configuration>
    <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js">
      <node-options />
      <gulpfile />
      <tasks />
      <pass-parent-env-vars>false</pass-parent-env-vars>
      <envs />
      <method />
    </configuration>
    <list size="0" />
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="SvnConfiguration">
    <configuration />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="f53105d0-603e-4112-8844-ac62c38237cf" name="Default" comment="" />
      <created>1423191054445</created>
      <option name="number" value="Default" />
      <updated>1423191054445</updated>
    </task>
    <task id="LOCAL-00001" summary="Init">
      <created>1423876517812</created>
      <option name="number" value="00001" />
      <option name="project" value="LOCAL" />
      <updated>1423876517812</updated>
    </task>
    <task id="LOCAL-00002" summary="Merge branch 'master' of github.com:phpistasty/Budgetn
">
      <created>1423876812346</created>
      <option name="number" value="00002" />
      <option name="project" value="LOCAL" />
      <updated>1423876812346</updated>
    </task>
    <option name="localTasksCounter" value="3" />
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1920" height="1141" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info id="File Transfer" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.18553758" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.23311132" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Remote Host" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.21778488" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.15388711" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="Vcs.Log.UiProperties">
    <option name="RECENTLY_FILTERED_USER_GROUPS">
      <collection />
    </option>
    <option name="RECENTLY_FILTERED_BRANCH_GROUPS">
      <collection />
    </option>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="myTodoPanelSettings">
      <TodoPanelSettings />
    </option>
    <MESSAGE value="Init" />
    <MESSAGE value="Merge branch 'master' of github.com:phpistasty/Budgetn
" />
    <MESSAGE value="Update with some simple validations" />
    <option name="LAST_COMMIT_MESSAGE" value="Update with some simple validations" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1470">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding>
            <marker date="1427663942000" expanded="true" signature="3874:4108" placeholder="..." />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/LICENSE">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="420">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
      <provider editor-type-id="com.intellij.database.editor.CsvTableFileEditorProvider">
        <state />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/styles.css">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="144" max-vertical-offset="1305">
          <caret line="30" column="21" selection-start-line="30" selection-start-column="21" selection-end-line="30" selection-end-column="21" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/app.js">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="2925">
          <caret line="0" column="1" selection-start-line="0" selection-start-column="1" selection-end-line="0" selection-end-column="1" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1380">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding>
            <marker date="1427663942000" expanded="true" signature="3874:4108" placeholder="..." />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/styles.css">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="144" max-vertical-offset="1305">
          <caret line="30" column="21" selection-start-line="30" selection-start-column="21" selection-end-line="30" selection-end-column="21" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/app.js">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="123" max-vertical-offset="2925">
          <caret line="24" column="39" selection-start-line="24" selection-start-column="39" selection-end-line="24" selection-end-column="39" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1380">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding>
            <marker date="1427663942000" expanded="true" signature="3874:4108" placeholder="..." />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/styles.css">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="144" max-vertical-offset="1305">
          <caret line="30" column="21" selection-start-line="30" selection-start-column="21" selection-end-line="30" selection-end-column="21" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/app.js">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="123" max-vertical-offset="2925">
          <caret line="24" column="39" selection-start-line="24" selection-start-column="39" selection-end-line="24" selection-end-column="39" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/.bowerrc">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.021367522" vertical-offset="0" max-vertical-offset="702">
          <caret line="1" column="26" selection-start-line="1" selection-start-column="26" selection-end-line="1" selection-end-column="26" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/bower.json">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.2777778" vertical-offset="0" max-vertical-offset="702">
          <caret line="13" column="11" selection-start-line="13" selection-start-column="11" selection-end-line="13" selection-end-column="11" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/css/styles.css">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="144" max-vertical-offset="1305">
          <caret line="30" column="21" selection-start-line="30" selection-start-column="21" selection-end-line="30" selection-end-column="21" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/LICENSE">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="433">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
      <provider editor-type-id="com.intellij.database.editor.CsvTableFileEditorProvider">
        <state />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/vendor/angular-material/angular-material.min.js">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.15332198" vertical-offset="0" max-vertical-offset="4230">
          <caret line="6" column="417" selection-start-line="6" selection-start-column="407" selection-end-line="6" selection-end-column="417" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/js/app.js">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-24.5" vertical-offset="2078" max-vertical-offset="3090">
          <caret line="181" column="33" selection-start-line="181" selection-start-column="33" selection-end-line="181" selection-end-column="33" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-5.625" vertical-offset="0" max-vertical-offset="1530">
          <caret line="18" column="0" selection-start-line="18" selection-start-column="0" selection-end-line="18" selection-end-column="0" />
          <folding>
            <marker date="1427663942000" expanded="true" signature="3874:4108" placeholder="..." />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/.gitignore">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.6362468" vertical-offset="0" max-vertical-offset="778">
          <caret line="33" column="7" selection-start-line="33" selection-start-column="7" selection-end-line="33" selection-end-column="7" />
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using Utils.FileSystemUtil;
using static System.Environment.SpecialFolder;

namespace Constants
{
    public static class Global
    {
        public static string StartUpShortcutName => "uBox.lnk";
        public static string LocalHost => "127.0.0.1";
        public static int TcpPort => 8008;
        public static DateTime FilesTime => new DateTime(2016, 7, 21);
        public static DateTime FoldersTime => new DateTime(2016, 7, 20);
        public static TimeSpan AgentSleepTime => TimeSpan.FromMilliseconds(4.0);

        public static readonly object DokanRunningObject = new object();
        public static readonly string CifsDirectoryPath = MyDocuments.GetPath().CombinePathWith("uBox");
        public static readonly string CifsIconPath = CifsDirectoryPath.CombinePathWith("uBoxIcon.ico");
        public static readonly string CifsPreferencesDataPath = CifsDirectoryPath.CombinePathWith("Preferences.dat");
        public static readonly string CifsIndexDataPath = CifsDirectoryPath.CombinePathWith("Index.dat");

        public static char[] AvailableDriverChars()
        {
            const string chars = "BCDEFGHIJKLMNOPQRSTUVWXYZ"; /* 'A' is not allowed! */
            var driverChars = DriveInfo.GetDrives().Select(d => d.Name.First()).ToArray();
            return chars.Where(c => !driverChars.Contains(c)).ToArray();
        }
        public static char DefaultDriverChar => AvailableDriverChars().First();

        public static DirectoryInfo ReadOnlyDirectory(Action<string> log)
        {
            var path = CifsDirectoryPath.CombinePathWith("ReadOnlyDir");
            if (!path.DoesFolderExists(log))
                path.CreateDirectory(FileAttributes.ReadOnly, log);
            return path.GetDirectoryInfo();
        }
        public static FileInfo ReadOnlyFile(Action<string> log)
        {
            var path = CifsDirectoryPath.CombinePathWith("ReadOnlyFile.txt");
            if (!path.DoesFileExists(log))
                path.CreateFile(new byte[0], log);
            path.GetFileInfo().Attributes |= FileAttributes.ReadOnly;
            return path.GetFileInfo();
        }
        public static DirectoryInfo RegularDirectory(Action<string> log)
        {
            var path = CifsDirectoryPath.CombinePathWith("RegularDir");
            if (!path.DoesFolderExists(log))
                path.CreateDirectory(FileAttributes.Directory, log);
            return path.GetDirectoryInfo();
        }
        public static FileInfo RegularFile(Action<string> log)
        {
            var path = CifsDirectoryPath.CombinePathWith("RegularFile.txt");
            if (!path.DoesFileExists(log))
                path.CreateFile(new byte[0], log);
            path.GetFileInfo().Attributes |= FileAttributes.Normal;
            return path.GetFileInfo();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Generic;

namespace Microsoft.MixedReality.Toolkit.UI
{
    /// <summary>
    /// State data model, state management and comparison instructions
    /// </summary>

    /*
     * Have an enum with all the button states -
     * Create a list using the enums as the state type -
     * Setup the bit and index automatically -
     * Store the values for all the states -
     * Have a sub state with only the states we care about -
     * On update, set those states and update the current state
     * The other states can be checked anytime through the Interactive.
     *
     */

    [System.Serializable]
    public class State
    {
        public string Name;
        public int Index;
        public int Bit;
        public int Value;
        public int ActiveIndex;

        public override string ToString()
        {
            return Name;
        }

        public int ToInt()
        {
            return Index;
        }

        public int ToBit()
        {
            return Bit;
        }
    }

    public abstract class InteractableStateModel
    {
        protected State currentState;
        protected List<State> stateList;
        protected State[] allStates;

        public void ImportStates(List<State> states)
        {
            stateList = states;
            for (int i = 0; i < stateList.Count; i++)
            {
                State state = allStates[stateList[i].Index];
                state.ActiveIndex = i;
            }
        }

        public virtual void SetStateOn(int index)
        {
            if (allStates.Length > index && index > 0)
            {
                State state = allStates[index];
                state.Value = 1;
                SetStateListValue(state.ActiveIndex, 1);
            }
        }

        public virtual void SetStateOff(int index)
        {
            if (allStates.Length > index && index > 0)
            {
                State state = allStates[index];
                state.Value = 0;
                SetStateListValue(state.ActiveIndex, 0);
            }
        }

        public virtual void SetStateValue(int index, int value)
        {
            if (allStates.Length > index && index > 0)
            {
                State state = allStates[index];
                state.Value = value;
                SetStateListValue(state.ActiveIndex, value);
            }
        }

        protected virtual void SetStateListValue(int index, int value)
        {
            if (index < stateList.Count && index > -1)
            {
                State state = stateList[index];
                state.Value = value;
            }
        }

        public int GetStateValue(int index)
        {
            if (allStates.Length > index && index > 0)
            {
                State state = allStates[index];
                return state.Value;
            }
            return 0;
        }

        public State GetState(int index)
        {
            if (allStates.Length > index && index > 0)
            {
                State state = allStates[index];
                return state;
            }
            return new State();
        }

        public InteractableStateModel(State defaultState)
        {
            currentState = defaultState;
        }

        public virtual void SetSate(State state)
        {
            currentState = state;
        }

        public virtual State CurrentState()
        {
            return currentState;
        }

        public abstract State CompareStates();

        public abstract State[] GetStates();

        protected int GetBit()
        {
            int bit = 0;
            int bitCount = 0;
            for (int i = 0; i < stateList.Count; i++)
            {
                if (i == 0)
                {
                    bit += 1;
                }
                else
                {
                    bit += bit;
                }

                if (stateList[i].Value > 0)
                {
                    bitCount += bit;
                }
            }

            return bitCount;
        }
    }
}


text:
namespace Microsoft
{
    namespace glTF
    {
        constexpr const char SCHEMA_URI_GLTF[] = "glTF.schema.json";
        constexpr const char SCHEMA_URI_GLTFID[] = "glTFid.schema.json";
        constexpr const char SCHEMA_URI_GLTFCHILDOFROOTPROPERTY[] = "glTFChildOfRootProperty.schema.json";
        constexpr const char SCHEMA_URI_GLTFPROPERTY[] = "glTFProperty.schema.json";
        constexpr const char SCHEMA_URI_BUFFER[] = "buffer.schema.json";
        constexpr const char SCHEMA_URI_BUFFERVIEW[] = "bufferView.schema.json";
        constexpr const char SCHEMA_URI_ACCESSOR[] = "accessor.schema.json";
        constexpr const char SCHEMA_URI_ACCESSORSPARSE[] = "accessor.sparse.schema.json";
        constexpr const char SCHEMA_URI_ACCESSORSPARSEVALUES[] = "accessor.sparse.values.schema.json";
        constexpr const char SCHEMA_URI_ACCESSORSPARSEINDICES[] = "accessor.sparse.indices.schema.json";
        constexpr const char SCHEMA_URI_ASSET[] = "asset.schema.json";
        constexpr const char SCHEMA_URI_SCENE[] = "scene.schema.json";
        constexpr const char SCHEMA_URI_NODE[] = "node.schema.json";
        constexpr const char SCHEMA_URI_MESH[] = "mesh.schema.json";
        constexpr const char SCHEMA_URI_MESHPRIMITIVE[] = "mesh.primitive.schema.json";
        constexpr const char SCHEMA_URI_SKIN[] = "skin.schema.json";
        constexpr const char SCHEMA_URI_CAMERA[] = "camera.schema.json";
        constexpr const char SCHEMA_URI_CAMERAORTHOGRAPHIC[] = "camera.orthographic.schema.json";
        constexpr const char SCHEMA_URI_CAMERAPERSPECTIVE[] = "camera.perspective.schema.json";
        constexpr const char SCHEMA_URI_MATERIAL[] = "material.schema.json";
        constexpr const char SCHEMA_URI_MATERIALNORMALTEXTUREINFO[] = "material.normalTextureInfo.schema.json";
        constexpr const char SCHEMA_URI_MATERIALOCCLUSIONTEXTUREINFO[] = "material.occlusionTextureInfo.schema.json";
        constexpr const char SCHEMA_URI_MATERIALPBRMETALLICROUGHNESS[] = "material.pbrMetallicRoughness.schema.json";
        constexpr const char SCHEMA_URI_TEXTURE[] = "texture.schema.json";
        constexpr const char SCHEMA_URI_TEXTUREINFO[] = "textureInfo.schema.json";
        constexpr const char SCHEMA_URI_IMAGE[] = "image.schema.json";
        constexpr const char SCHEMA_URI_SAMPLER[] = "sampler.schema.json";
        constexpr const char SCHEMA_URI_ANIMATION[] = "animation.schema.json";
        constexpr const char SCHEMA_URI_ANIMATIONSAMPLER[] = "animation.sampler.schema.json";
        constexpr const char SCHEMA_URI_ANIMATIONCHANNEL[] = "animation.channel.schema.json";
        constexpr const char SCHEMA_URI_ANIMATIONCHANNELTARGET[] = "animation.channel.target.schema.json";
        constexpr const char SCHEMA_URI_EXTENSION[] = "extension.schema.json";
        constexpr const char SCHEMA_URI_EXTRAS[] = "extras.schema.json";

        const std::unordered_map<std::string, std::string>& GetDefaultSchemaUriMap();

        enum class SchemaFlags : uint64_t
        {
            None = 0x0,
            DisableSchemaRoot = 0x1, // Disables all schema validation
            DisableSchemaId = 0x2,
            DisableSchemaChildOfRoot = 0x4,
            DisableSchemaProperty = 0x8,
            DisableSchemaBuffer = 0x10,
            DisableSchemaBufferView = 0x20,
            DisableSchemaAccessor = 0x40,
            DisableSchemaAccessorSparse = 0x80,
            DisableSchemaAccessorSparseValues = 0x80,
            DisableSchemaAccessorSparseIndices = 0x100,
            DisableSchemaAsset = 0x200,
            DisableSchemaScene = 0x400,
            DisableSchemaNode = 0x800,
            DisableSchemaMesh = 0x1000,
            DisableSchemaMeshPrimitive = 0x2000,
            DisableSchemaSkin = 0x4000,
            DisableSchemaCamera = 0x8000,
            DisableSchemaCameraOrthographic = 0x10000,
            DisableSchemaCameraPerspective = 0x20000,
            DisableSchemaMaterial = 0x40000,
            DisableSchemaMaterialNormalTextureInfo = 0x80000,
            DisableSchemaMaterialOcclusionTextureInfo = 0x100000,
            DisableSchemaMaterialPBRMetallicRoughness = 0x200000,
            DisableSchemaTexture = 0x400000,
            DisableSchemaTextureInfo = 0x800000,
            DisableSchemaImage = 0x1000000,
            DisableSchemaSampler = 0x2000000,
            DisableSchemaAnimation = 0x4000000,
            DisableSchemaAnimationSampler = 0x8000000,
            DisableSchemaAnimationChannel = 0x10000000,
            DisableSchemaAnimationChannelTarget = 0x20000000,
            DisableSchemaExtension = 0x40000000,
            DisableSchemaExtras = 0x80000000
        };

        SchemaFlags  operator| (SchemaFlags lhs,  SchemaFlags rhs);
        SchemaFlags& operator|=(SchemaFlags& lhs, SchemaFlags rhs);
        SchemaFlags  operator& (SchemaFlags lhs,  SchemaFlags rhs);
        SchemaFlags& operator&=(SchemaFlags& lhs, SchemaFlags rhs);

        std::unique_ptr<const class ISchemaLocator> GetDefaultSchemaLocator(SchemaFlags schemaFlags);
    }
}


text:
require "spec_helper"

describe Mongoid::Relations::Synchronization do

  describe ".update_inverse_keys" do

    let(:agent) do
      Agent.create!
    end

    let(:user) do
      User.create!
    end

    let(:person) do
      Person.create!
    end

    context "when an unpersisted account is created" do

      let(:account) do
        Account.new do |a|
          a.name = "testing"
          a.creator = user
          a.person = person
        end
      end

      it "has persisted :agent" do
        agent.persisted?.should be_true
      end

      it "has persisted :user" do
        user.persisted?.should be_true
      end

      it "has persisted :person" do
        person.persisted?.should be_true
      end

      it "does not have persisted :account" do
        account.persisted?.should be_false
      end

      it "has instantiated a .valid? :account" do
        account.valid?
        account.valid?.should be_true
      end

      context "and is Persisted" do

        it "is able to :save" do
          account.save.should be_true
        end
      end

      context "check for existing Agent, then Persisted" do

        before do
          account.agents.where(:_id => agent.id).exists?
        end

        it "is able to :save" do
          account.save.should be_true
        end
      end
    end
  end

  context "when the inverse of is nil" do

    let(:preference) do
      Preference.new(:name => "test")
    end

    let(:article) do
      Article.new
    end

    before do
      article.preferences << preference
    end

    it "does not attempt synchronization" do
      expect { article.save }.to_not raise_error(TypeError)
    end

    it "sets the one side of the relation" do
      article.preferences.should eq([ preference ])
    end
  end

  context "when first setting by the relation itself" do

    let!(:person) do
      Person.create
    end

    let!(:one) do
      Preference.create(:name => "one")
    end

    before do
      person.preferences << one
    end

    it "sets the inverse foreign key" do
      one.person_ids.should eq([ person.id ])
    end

    it "resets the synced flag" do
      person.synced["preference_ids"].should be_false
    end

    context "when subsequently setting with keys" do

      let!(:two) do
        Preference.create(:name => "two")
      end

      before do
        person.preference_ids << two.id
        person.save
      end

      it "sets the inverse foreign key" do
        two.reload.person_ids.should eq([ person.id ])
      end
    end
  end

  context "when setting new ids" do

    let!(:person) do
      Person.create
    end

    let!(:one) do
      Preference.create(:name => "one")
    end

    let!(:two) do
      Preference.create(:name => "two")
    end

    before do
      person.preference_ids = [ one.id, two.id ]
    end

    it "sets the foreign_key" do
      person.preference_ids.should eq([ one.id, two.id ])
    end

    it "does not set the first inverse key" do
      one.reload.person_ids.should be_empty
    end

    it "does not set the second inverse key" do
      two.reload.person_ids.should be_empty
    end

    context "when saving the base" do

      context "when validation passes" do

        before do
          person.save
        end

        it "persists the foreign_key" do
          person.reload.preference_ids.should eq([ one.id, two.id ])
        end

        it "sets the first inverse key" do
          one.reload.person_ids.should eq([ person.id ])
        end

        it "sets the second inverse key" do
          two.reload.person_ids.should eq([ person.id ])
        end
      end
    end
  end

  context "when replacing ids" do

    let!(:one) do
      Preference.create(:name => "one")
    end

    let!(:two) do
      Preference.create(:name => "two")
    end

    let!(:person) do
      Person.create(:preference_ids => [ one.id, two.id ])
    end

    let!(:three) do
      Preference.create(:name => "three")
    end

    before do
      person.preference_ids = [ three.id ]
    end

    it "sets the foreign_key" do
      person.preference_ids.should eq([ three.id ])
    end

    it "does not remove the first inverse key" do
      one.reload.person_ids.should eq([ person.id ])
    end

    it "does not remove the second inverse key" do
      two.reload.person_ids.should eq([ person.id ])
    end

    it "does not set the third inverse key" do
      three.reload.person_ids.should be_empty
    end

    context "when saving the base" do

      context "when validation passes" do

        before do
          person.save
        end

        it "persists the foreign_key" do
          person.reload.preference_ids.should eq([ three.id ])
        end

        it "removes the first inverse key" do
          one.reload.person_ids.should be_empty
        end

        it "removes the second inverse key" do
          two.reload.person_ids.should be_empty
        end

        it "sets the third inverse key" do
          three.reload.person_ids.should eq([ person.id ])
        end
      end
    end
  end

  context "when setting ids to empty" do

    let!(:one) do
      Preference.create(:name => "one")
    end

    let!(:two) do
      Preference.create(:name => "two")
    end

    let!(:person) do
      Person.create(:preference_ids => [ one.id, two.id ])
    end

    before do
      person.preference_ids = []
    end

    it "sets the foreign_key" do
      person.preference_ids.should be_empty
    end

    it "does not remove the first inverse key" do
      one.reload.person_ids.should eq([ person.id ])
    end

    it "does not remove the second inverse key" do
      two.reload.person_ids.should eq([ person.id ])
    end

    context "when saving the base" do

      context "when validation passes" do

        before do
          person.save
        end

        it "persists the foreign_key" do
          person.reload.preference_ids.should be_empty
        end

        it "removes the first inverse key" do
          one.reload.person_ids.should be_empty
        end

        it "removes the second inverse key" do
          two.reload.person_ids.should be_empty
        end
      end
    end
  end

  context "when setting ids to nil" do

    let!(:one) do
      Preference.create(:name => "one")
    end

    let!(:two) do
      Preference.create(:name => "two")
    end

    let!(:person) do
      Person.create(:preference_ids => [ one.id, two.id ])
    end

    before do
      person.preference_ids = nil
    end

    it "sets the foreign_key" do
      person.preference_ids.should be_empty
    end

    it "does not remove the first inverse key" do
      one.reload.person_ids.should eq([ person.id ])
    end

    it "does not remove the second inverse key" do
      two.reload.person_ids.should eq([ person.id ])
    end

    context "when saving the base" do

      context "when validation passes" do

        before do
          person.save
        end

        it "persists the foreign_key" do
          person.reload.preference_ids.should be_empty
        end

        it "removes the first inverse key" do
          one.reload.person_ids.should be_empty
        end

        it "removes the second inverse key" do
          two.reload.person_ids.should be_empty
        end
      end
    end
  end

  context "when destroying" do

    let!(:one) do
      Preference.create(:name => "one")
    end

    let!(:two) do
      Preference.create(:name => "two")
    end

    let!(:person) do
      Person.create(:preferences => [ one, two ])
    end

    context "when destroying the parent" do

      before do
        person.destroy
      end

      it "removes the first inverse key" do
        one.reload.person_ids.should be_empty
      end

      it "removes the second inverse key" do
        two.reload.person_ids.should be_empty
      end
    end

    context "when destroying the child" do

      before do
        one.destroy
      end

      it "removes the inverse key" do
        person.reload.preference_ids.should eq([ two.id ])
      end
    end
  end

  context "when appending an existing document to a new one" do

    let!(:peristed) do
      Tag.create
    end

    let(:article) do
      Article.new
    end

    before do
      article.tags << Tag.first
      article.save
    end

    let(:tag) do
      Tag.first
    end

    it "persists the foreign key on the inverse" do
      tag.article_ids.should eq([ article.id ])
    end

    it "persists the inverse relation" do
      tag.articles.should eq([ article ])
    end
  end
end


text:
<?php

namespace React\Tests\Http\Message;

use React\Http\Io\HttpBodyStream;
use React\Http\Message\Response;
use React\Stream\ThroughStream;
use React\Tests\Http\TestCase;

class ResponseTest extends TestCase
{
    public function testConstructWithStringBodyWillReturnStreamInstance()
    {
        $response = new Response(200, array(), 'hello');
        $body = $response->getBody();

        /** @var \Psr\Http\Message\StreamInterface $body */
        $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body);
        $this->assertEquals('hello', (string) $body);
    }

    public function testConstructWithStreamingBodyWillReturnReadableBodyStream()
    {
        $response = new Response(200, array(), new ThroughStream());
        $body = $response->getBody();

        /** @var \Psr\Http\Message\StreamInterface $body */
        $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body);
        $this->assertInstanceof('React\Stream\ReadableStreamInterface', $body);
        $this->assertInstanceOf('React\Http\Io\HttpBodyStream', $body);
        $this->assertNull($body->getSize());
    }

    public function testConstructWithHttpBodyStreamReturnsBodyAsIs()
    {
        $response = new Response(
            200,
            array(),
            $body = new HttpBodyStream(new ThroughStream(), 100)
        );

        $this->assertSame($body, $response->getBody());
    }

    public function testFloatBodyWillThrow()
    {
        $this->setExpectedException('InvalidArgumentException');
        new Response(200, array(), 1.0);
    }

    public function testResourceBodyWillThrow()
    {
        $this->setExpectedException('InvalidArgumentException');
        new Response(200, array(), tmpfile());
    }

    public function testHtmlMethodReturnsHtmlResponse()
    {
        $response = Response::html('<!doctype html>Hello wörld!');

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('text/html; charset=utf-8', $response->getHeaderLine('Content-Type'));
        $this->assertEquals('<!doctype html>Hello wörld!', (string) $response->getBody());
    }

    /**
     * @requires PHP 5.4
     */
    public function testJsonMethodReturnsPrettyPrintedJsonResponse()
    {
        $response = Response::json(array('text' => 'Hello wörld!'));

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json', $response->getHeaderLine('Content-Type'));
        $this->assertEquals("{\n    \"text\": \"Hello wörld!\"\n}\n", (string) $response->getBody());
    }

    /**
     * @requires PHP 5.6.6
     */
    public function testJsonMethodReturnsZeroFractionsInJsonResponse()
    {
        $response = Response::json(1.0);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json', $response->getHeaderLine('Content-Type'));
        $this->assertEquals("1.0\n", (string) $response->getBody());
    }

    public function testJsonMethodReturnsJsonTextForSimpleString()
    {
        $response = Response::json('Hello world!');

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/json', $response->getHeaderLine('Content-Type'));
        $this->assertEquals("\"Hello world!\"\n", (string) $response->getBody());
    }

    public function testJsonMethodThrowsForInvalidString()
    {
        if (PHP_VERSION_ID < 50500) {
            $this->setExpectedException('InvalidArgumentException', 'Unable to encode given data as JSON');
        } else {
            $this->setExpectedException('InvalidArgumentException', 'Unable to encode given data as JSON: Malformed UTF-8 characters, possibly incorrectly encoded');
        }
        Response::json("Hello w\xF6rld!");
    }

    public function testPlaintextMethodReturnsPlaintextResponse()
    {
        $response = Response::plaintext("Hello wörld!\n");

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('text/plain; charset=utf-8', $response->getHeaderLine('Content-Type'));
        $this->assertEquals("Hello wörld!\n", (string) $response->getBody());
    }

    public function testXmlMethodReturnsXmlResponse()
    {
        $response = Response::xml('<?xml version="1.0" encoding="utf-8"?>Hello wörld!');

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/xml', $response->getHeaderLine('Content-Type'));
        $this->assertEquals('<?xml version="1.0" encoding="utf-8"?>Hello wörld!', (string) $response->getBody());
    }
}


text:
package de.taimos.dao.mongo;

public class TestDAO extends AbstractMongoDAO<TestObject> {

	@Override
	protected Class<TestObject> getEntityClass() {
		return TestObject.class;
	}

	public TestObject findByName(String name) {
		return this.findFirstByQuery("{name:#}", null, name);
	}
}


text:
Infrastructure for data distribution network

# Host setup using raspbian
* Image raspbian minimal image to SD card and boot
* Reserve an IP for the rpi MAC
* Set up port forwarding of 22, 8080, 60000-61000 in the router to the rpi
* Install applications:
'''sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common docker-ce vim git'''
* Add pi user to docker group:
'''sudo groupadd docker;sudo gpasswd -a $USER docker;newgrp docker'''
* Create a jenkins docker image:
'''docker run -p 8080:8080 -p 50000:50000 -v jenkins:/var/jenkins_home wouterds/rpi-jenkins'''
* TODO: clone this repo and start jenkins image as daemon (includes clone of jenkins settings)
* TODO: Test connectivity to kenkins

# Client Setup
* Image SD with arch Linux image
* Configure image to run ssh on boot and over USB (https://gist.github.com/gbaman/975e2db164b3ca2b51ae11e45e8fd40a)
* Configure DuckDNS to use our token and domain name & store logs in /var/log/duckdns dir
* Increase temporary disk size by adding "tmpfs   /tmp         tmpfs   nodev,nosuid,size=2G          0  0" to /etc/fstab (src: https://wiki.archlinux.org/index.php/Tmpfs)
* Create a swap file using the instructions in https://wiki.archlinux.org/index.php/swap
* Generate UTF-8 locales using the instructions from https://wiki.archlinux.org/index.php/locale
* Run the install script install.sh
* Follow arch linux set using https://github.com/phortx/Raspberry-Pi-Setup-Guide
* Install docker using Note: Use the architecture version specified in https://archlinuxarm.org/forum/viewtopic.php?f=31&t=4570
* Clone the this repo and build the JaaS image using docker build -t "jaas" .
* docker run -i -t jaas:latest /bin/bash


text:
namespace Neo4j.NDP.CSharpDriver.Logging
{
    /// <summary>
    /// Simple logging interface.
    /// </summary>
    /// <remarks>
    /// Marker interface. See <see cref="LogExtensions"/>
    /// </remarks>
    public interface ILogger
    {
    }

    /// <summary>
    /// Extensions methods for handling null
    /// </summary>
    /// <example>
    /// <code>
    /// ILog log = null;
    /// log.Info("This will NOT throw an NullReferenceException");
    /// </code>
    /// </example>
    public static class LoggerExtensions
    {
        // TODO: Write documentation

        public static void Debug(this ILogger logger, string format, params object[] arguments)
        {
            IInternalLogger internalLogger = logger as IInternalLogger;
            if (internalLogger == null) return;

            internalLogger.Write(LogSeverity.Debug, format, arguments);
        }

        public static void Info(this ILogger logger, string format, params object[] arguments)
        {
            IInternalLogger internalLogger = logger as IInternalLogger;
            if (internalLogger == null) return;

            internalLogger.Write(LogSeverity.Information, format, arguments);
        }

        public static void Warn(this ILogger logger, string format, params object[] arguments)
        {
            IInternalLogger internalLogger = logger as IInternalLogger;
            if (internalLogger == null) return;

            internalLogger.Write(LogSeverity.Warning, format, arguments);
        }

        public static void Error(this ILogger logger, string format, params object[] arguments)
        {
            IInternalLogger internalLogger = logger as IInternalLogger;
            if (internalLogger == null) return;

            internalLogger.Write(LogSeverity.Error, format, arguments);
        }

        public static void Fatal(this ILogger logger, string format, params object[] arguments)
        {
            IInternalLogger internalLogger = logger as IInternalLogger;
            if (internalLogger == null) return;

            internalLogger.Write(LogSeverity.Fatal, format, arguments);
        }
    }
}


text:
""" Misc utilities for accessing and manipulating tulip graphs """

import tulippaths as tp
import re

# Returns true if node can be reached from sourceTypes.
# sourceTypes is a list of node types (strings).
def canBeReachedFromTypes(node, sourceTypes, graph):
    paths = []
    for edge in graph.getInEdges(node):
        sourceNode = graph.source(edge)
        edgeSourceType = getNodeType(sourceNode, graph)
        edgeType = getEdgeType(edge, graph)
        if edgeSourceType in sourceTypes and edgeType not in ['Adherens', 'Touch']:
            path = tp.Path(graph)
            path.addNode(sourceNode)
            path.addEdge(edge)
            path.addNode(node)

            paths.append(path)

    return paths

# Returns true only if node can reach target types.
# targetTypes is a list of node types (strings).
def canReachTypes(node, targetTypes, graph):
    paths = []
    for edge in graph.getOutEdges(node):
        targetNode = graph.target(edge)
        edgeTargetType = getNodeType(targetNode, graph)
        edgeType = getEdgeType(edge, graph)
        if edgeTargetType in targetTypes and edgeType not in ['Adherens', 'Touch']:
            path = tp.Path(graph)
            path.addNode(node)
            path.addEdge(edge)
            path.addNode(targetNode)
            paths.append(path)
    return paths

def getAllEdgeTypes(graph):
    edgeTypes = []
    for edge in graph.getEdges():
        edgeType = getEdgeType(edge, graph)
        if edgeType not in edgeTypes:
            edgeTypes.append(edgeType)
    return edgeTypes

# Returns a dictionary of nodes: percent completeness
# Max completeness = max number of synapses going into and out of a node
def getApproximateAnnotationCompleteness(graph):
    completeness = {}
    touched = {}

    for node in graph.getNodes():
        touched[node] = 0

    # While there are nodes that we haven't computed completeness values for...
    while 0 in list(touched.values()):

        # Find first available node that we haven't touched.
        for node in graph.getNodes():
            if not touched[node] == 1:
                # Get all nodes of the same type.
                label = getNodeType(node, graph)
                nodes = getNodesByType(label, graph)

                # Count num annotations for all nodes of same type
                numAnnotations = {}
                for localNode in nodes:
                    numAnnotations[localNode] = getApproximateNumAnnotations(localNode, graph)
                    touched[localNode] = 1

                # Find max num of annotations for this type
                maxNumAnnotations = max(numAnnotations.values())

                # Compute completeness as a percent of annotations relative to the most annotated node
                for localNode in nodes:
                    completeness[localNode] = float(numAnnotations[localNode]) / float(maxNumAnnotations)
                    assert completeness[localNode] <= 1.0, 'Error - node has more than 100% completeness'

    return completeness

# Returns an approximate number of annotations for a given cell
def getApproximateNumAnnotations(node, graph):
    approximateNumAnnotations = 0

    for edge in graph.getInOutEdges(node):
        approximateNumAnnotations += getEdgeWeight(edge, graph)

    return approximateNumAnnotations

def getDictionaryOfEdgeTypes(graph):

    dictionary = {}

    for edge in graph.getEdges():

        edgeType = getEdgeType(edge, graph)

        if edgeType in dictionary:
            dictionary[edgeType].append(edge)
        else:
            dictionary[edgeType] = [edge]

    return dictionary

def getDictionaryOfNodeTypes(graph):

    dictionary = {}

    for node in graph.getNodes():
        nodeType = getNodeType(node, graph)
        if nodeType in dictionary:
            dictionary[nodeType].append(node)
        else:
            dictionary[nodeType] = [node]

    return dictionary

def getEdgesByType(type, graph):
    edges = []
    for edge in graph.getEdges():
        if getEdgeType(edge, graph) == type:
            edges.append(edge)
    return edges

def getEdgesByTypes(types, graph):
    edges = []
    for edgeType in types:
        edges += getEdgesByType(edgeType, graph)
    return edges

# Returns a list of edges whose type labels contain a sequence matching
# the specified regular expression. (Corresponds to getEdgesByType() but
# with a regex search)
def getEdgesByTypeRegex(typeRegex, graph):
    edges = []
    for edge in graph.getEdges():
        edgeType = getEdgeType(edge, graph)
        if isRegexExactMatch(typeRegex, edgeType):
            edges.append(edge)
    return edges

def getEdgeType(edge, graph):
    edgeTypes = graph.getProperty("edgeType")
    return edgeTypes[edge]

# Returns number of linked children structures that an edge represents.
# AkA number of synapses between 2 nodes
def getEdgeWeight(edge, graph):
    linkedStructures = graph.getProperty("LinkedStructures")
    structures = linkedStructures[edge].strip()
    return len(structures.split('    '))

def getEdgeLinkedStructures(edge, graph):
    linkedStructures = graph.getProperty("LinkedStructures")
    structures = linkedStructures[edge].strip()
    return structures.lstrip(' ')

def getNodeById(id, graph):
    nodeIds = graph.getProperty("ID")
    for node in graph.getNodes():
        if int(nodeIds[node]) == id:
            return node
    assert False, "Failed to find node by id " + id

def getNodesByType(type, graph):
    nodes = []
    for node in graph.getNodes():
        if getNodeType(node, graph) == type:
            nodes.append(node)
    return nodes

def getNodesByTypes(types, graph):
    nodes = []
    for nodeType in types:
        nodes += getNodesByType(nodeType, graph)
    return nodes

# Returns a list of nodes whose type labels contain a sequence matching
# the specified regular expression. (Corresponds to getNodesByType() but
# with a regex search)
def getNodesByTypeRegex(typeRegex, graph):
    nodes = []
    for node in graph.getNodes():
        nodeType = getNodeType(node, graph)
        if isRegexExactMatch(typeRegex, nodeType):
            nodes.append(node)
    return nodes

def getNodesByTypeRegexes(typeRegexes, graph):
    nodes = []
    for nodeTypeRegex in typeRegexes:
        nodes += getNodesByTypeRegex(nodeTypeRegex, graph)
    return nodes

def getNodeId(node, graph):
    nodeIds = graph.getProperty("ID")
    return nodeIds[node]

def getNodeType(node, graph):
    viewLabels = graph.getProperty("viewLabel")
    viewLabel = viewLabels[node].split('\n')
    if len(viewLabel) == 2:
        return viewLabel[0].strip()
    else:
        return 'null'

def getNodesTypes(nodes, graph):
    types = []
    for node in nodes:
        nodeType = getNodeType(node, graph)
        if nodeType not in types:
            types.append(nodeType)
    return types

def isEdgeTypeInGraph(edgeType, graph):
    for edge in graph.getEdges():
        otherType = getEdgeType(edge, graph)
        if otherType == edgeType:
            return True

    return False

def isRegexExactMatch(regex, target):
    match = re.search(re.compile(regex), target)
    return match and match.group(0) == target

def setNodeColor(color, graph):
    viewColor = graph.getColorProperty("viewColor")
    for node in graph.getNodes():
        viewColor[node] = color

def setEdgeColor(color, graph):
    viewColor = graph.getColorProperty("viewColor")
    for edge in graph.getEdges():
        viewColor[edge] = color

def setColor(item, color, graph):
    viewColor = graph.getColorProperty("viewColor")
    viewColor[item] = color

def setPathColor(path, color, graph):
    for node in path.nodes:
        setColor(node, color, graph)
    for edge in path.edges:
        setColor(edge, color, graph)


text:
#include "modules/audio_device/android/audio_record_jni.h"

#include <string>
#include <utility>

#include "modules/audio_device/android/audio_common.h"
#include BOSS_WEBRTC_U_rtc_base__arraysize_h //original-code:"rtc_base/arraysize.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__format_macros_h //original-code:"rtc_base/format_macros.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
#include BOSS_WEBRTC_U_rtc_base__platform_thread_h //original-code:"rtc_base/platform_thread.h"
#include BOSS_WEBRTC_U_rtc_base__timeutils_h //original-code:"rtc_base/timeutils.h"
#include BOSS_WEBRTC_U_system_wrappers__include__metrics_h //original-code:"system_wrappers/include/metrics.h"

namespace webrtc {

namespace {
// Scoped class which logs its time of life as a UMA statistic. It generates
// a histogram which measures the time it takes for a method/scope to execute.
class ScopedHistogramTimer {
 public:
  explicit ScopedHistogramTimer(const std::string& name)
      : histogram_name_(name), start_time_ms_(rtc::TimeMillis()) {}
  ~ScopedHistogramTimer() {
    const int64_t life_time_ms = rtc::TimeSince(start_time_ms_);
    RTC_HISTOGRAM_COUNTS_1000(histogram_name_, life_time_ms);
    RTC_LOG(INFO) << histogram_name_ << ": " << life_time_ms;
  }

 private:
  const std::string histogram_name_;
  int64_t start_time_ms_;
};
}  // namespace

// AudioRecordJni::JavaAudioRecord implementation.
AudioRecordJni::JavaAudioRecord::JavaAudioRecord(
    NativeRegistration* native_reg,
    std::unique_ptr<GlobalRef> audio_record)
    : audio_record_(std::move(audio_record)),
      init_recording_(native_reg->GetMethodId("initRecording", "(II)I")),
      start_recording_(native_reg->GetMethodId("startRecording", "()Z")),
      stop_recording_(native_reg->GetMethodId("stopRecording", "()Z")),
      enable_built_in_aec_(native_reg->GetMethodId("enableBuiltInAEC", "(Z)Z")),
      enable_built_in_ns_(native_reg->GetMethodId("enableBuiltInNS", "(Z)Z")) {}

AudioRecordJni::JavaAudioRecord::~JavaAudioRecord() {}

int AudioRecordJni::JavaAudioRecord::InitRecording(int sample_rate,
                                                   size_t channels) {
  return audio_record_->CallIntMethod(init_recording_,
                                      static_cast<jint>(sample_rate),
                                      static_cast<jint>(channels));
}

bool AudioRecordJni::JavaAudioRecord::StartRecording() {
  return audio_record_->CallBooleanMethod(start_recording_);
}

bool AudioRecordJni::JavaAudioRecord::StopRecording() {
  return audio_record_->CallBooleanMethod(stop_recording_);
}

bool AudioRecordJni::JavaAudioRecord::EnableBuiltInAEC(bool enable) {
  return audio_record_->CallBooleanMethod(enable_built_in_aec_,
                                          static_cast<jboolean>(enable));
}

bool AudioRecordJni::JavaAudioRecord::EnableBuiltInNS(bool enable) {
  return audio_record_->CallBooleanMethod(enable_built_in_ns_,
                                          static_cast<jboolean>(enable));
}

// AudioRecordJni implementation.
AudioRecordJni::AudioRecordJni(AudioManager* audio_manager)
    : j_environment_(JVM::GetInstance()->environment()),
      audio_manager_(audio_manager),
      audio_parameters_(audio_manager->GetRecordAudioParameters()),
      total_delay_in_milliseconds_(0),
      direct_buffer_address_(nullptr),
      direct_buffer_capacity_in_bytes_(0),
      frames_per_buffer_(0),
      initialized_(false),
      recording_(false),
      audio_device_buffer_(nullptr) {
  RTC_LOG(INFO) << "ctor";
  RTC_DCHECK(audio_parameters_.is_valid());
  RTC_CHECK(j_environment_);
  JNINativeMethod native_methods[] = {
      {"nativeCacheDirectBufferAddress", "(Ljava/nio/ByteBuffer;J)V",
       reinterpret_cast<void*>(
           &webrtc::AudioRecordJni::CacheDirectBufferAddress)},
      {"nativeDataIsRecorded", "(IJ)V",
       reinterpret_cast<void*>(&webrtc::AudioRecordJni::DataIsRecorded)}};
  j_native_registration_ = j_environment_->RegisterNatives(
      "org/webrtc/voiceengine/WebRtcAudioRecord", native_methods,
      arraysize(native_methods));
  j_audio_record_.reset(
      new JavaAudioRecord(j_native_registration_.get(),
                          j_native_registration_->NewObject(
                              "<init>", "(J)V", PointerTojlong(this))));
  // Detach from this thread since we want to use the checker to verify calls
  // from the Java based audio thread.
  thread_checker_java_.DetachFromThread();
}

AudioRecordJni::~AudioRecordJni() {
  RTC_LOG(INFO) << "dtor";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  Terminate();
}

int32_t AudioRecordJni::Init() {
  RTC_LOG(INFO) << "Init";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return 0;
}

int32_t AudioRecordJni::Terminate() {
  RTC_LOG(INFO) << "Terminate";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  StopRecording();
  return 0;
}

int32_t AudioRecordJni::InitRecording() {
  RTC_LOG(INFO) << "InitRecording";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!initialized_);
  RTC_DCHECK(!recording_);
  ScopedHistogramTimer timer("WebRTC.Audio.InitRecordingDurationMs");
  int frames_per_buffer = j_audio_record_->InitRecording(
      audio_parameters_.sample_rate(), audio_parameters_.channels());
  if (frames_per_buffer < 0) {
    direct_buffer_address_ = nullptr;
    RTC_LOG(LS_ERROR) << "InitRecording failed";
    return -1;
  }
  frames_per_buffer_ = static_cast<size_t>(frames_per_buffer);
  RTC_LOG(INFO) << "frames_per_buffer: " << frames_per_buffer_;
  const size_t bytes_per_frame = audio_parameters_.channels() * sizeof(int16_t);
  RTC_CHECK_EQ(direct_buffer_capacity_in_bytes_,
               frames_per_buffer_ * bytes_per_frame);
  RTC_CHECK_EQ(frames_per_buffer_, audio_parameters_.frames_per_10ms_buffer());
  initialized_ = true;
  return 0;
}

int32_t AudioRecordJni::StartRecording() {
  RTC_LOG(INFO) << "StartRecording";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!recording_);
  if (!initialized_) {
    RTC_DLOG(LS_WARNING)
        << "Recording can not start since InitRecording must succeed first";
    return 0;
  }
  ScopedHistogramTimer timer("WebRTC.Audio.StartRecordingDurationMs");
  if (!j_audio_record_->StartRecording()) {
    RTC_LOG(LS_ERROR) << "StartRecording failed";
    return -1;
  }
  recording_ = true;
  return 0;
}

int32_t AudioRecordJni::StopRecording() {
  RTC_LOG(INFO) << "StopRecording";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  if (!initialized_ || !recording_) {
    return 0;
  }
  if (!j_audio_record_->StopRecording()) {
    RTC_LOG(LS_ERROR) << "StopRecording failed";
    return -1;
  }
  // If we don't detach here, we will hit a RTC_DCHECK in OnDataIsRecorded()
  // next time StartRecording() is called since it will create a new Java
  // thread.
  thread_checker_java_.DetachFromThread();
  initialized_ = false;
  recording_ = false;
  direct_buffer_address_ = nullptr;
  return 0;
}

void AudioRecordJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
  RTC_LOG(INFO) << "AttachAudioBuffer";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  audio_device_buffer_ = audioBuffer;
  const int sample_rate_hz = audio_parameters_.sample_rate();
  RTC_LOG(INFO) << "SetRecordingSampleRate(" << sample_rate_hz << ")";
  audio_device_buffer_->SetRecordingSampleRate(sample_rate_hz);
  const size_t channels = audio_parameters_.channels();
  RTC_LOG(INFO) << "SetRecordingChannels(" << channels << ")";
  audio_device_buffer_->SetRecordingChannels(channels);
  total_delay_in_milliseconds_ =
      audio_manager_->GetDelayEstimateInMilliseconds();
  RTC_DCHECK_GT(total_delay_in_milliseconds_, 0);
  RTC_LOG(INFO) << "total_delay_in_milliseconds: "
                << total_delay_in_milliseconds_;
}

int32_t AudioRecordJni::EnableBuiltInAEC(bool enable) {
  RTC_LOG(INFO) << "EnableBuiltInAEC(" << enable << ")";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return j_audio_record_->EnableBuiltInAEC(enable) ? 0 : -1;
}

int32_t AudioRecordJni::EnableBuiltInAGC(bool enable) {
  // TODO(henrika): possibly remove when no longer used by any client.
  FATAL() << "Should never be called";
  return -1;
}

int32_t AudioRecordJni::EnableBuiltInNS(bool enable) {
  RTC_LOG(INFO) << "EnableBuiltInNS(" << enable << ")";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  return j_audio_record_->EnableBuiltInNS(enable) ? 0 : -1;
}

JNI_FUNCTION_ALIGN
void JNICALL AudioRecordJni::CacheDirectBufferAddress(JNIEnv* env,
                                                      jobject obj,
                                                      jobject byte_buffer,
                                                      jlong nativeAudioRecord) {
  webrtc::AudioRecordJni* this_object =
      reinterpret_cast<webrtc::AudioRecordJni*>(nativeAudioRecord);
  this_object->OnCacheDirectBufferAddress(env, byte_buffer);
}

void AudioRecordJni::OnCacheDirectBufferAddress(JNIEnv* env,
                                                jobject byte_buffer) {
  RTC_LOG(INFO) << "OnCacheDirectBufferAddress";
  RTC_DCHECK(thread_checker_.CalledOnValidThread());
  RTC_DCHECK(!direct_buffer_address_);
  direct_buffer_address_ = env->GetDirectBufferAddress(byte_buffer);
  jlong capacity = env->GetDirectBufferCapacity(byte_buffer);
  RTC_LOG(INFO) << "direct buffer capacity: " << capacity;
  direct_buffer_capacity_in_bytes_ = static_cast<size_t>(capacity);
}

JNI_FUNCTION_ALIGN
void JNICALL AudioRecordJni::DataIsRecorded(JNIEnv* env,
                                            jobject obj,
                                            jint length,
                                            jlong nativeAudioRecord) {
  webrtc::AudioRecordJni* this_object =
      reinterpret_cast<webrtc::AudioRecordJni*>(nativeAudioRecord);
  this_object->OnDataIsRecorded(length);
}

// This method is called on a high-priority thread from Java. The name of
// the thread is 'AudioRecordThread'.
void AudioRecordJni::OnDataIsRecorded(int length) {
  RTC_DCHECK(thread_checker_java_.CalledOnValidThread());
  if (!audio_device_buffer_) {
    RTC_LOG(LS_ERROR) << "AttachAudioBuffer has not been called";
    return;
  }
  audio_device_buffer_->SetRecordedBuffer(direct_buffer_address_,
                                          frames_per_buffer_);
  // We provide one (combined) fixed delay estimate for the APM and use the
  // |playDelayMs| parameter only. Components like the AEC only sees the sum
  // of |playDelayMs| and |recDelayMs|, hence the distributions does not matter.
  audio_device_buffer_->SetVQEData(total_delay_in_milliseconds_, 0);
  if (audio_device_buffer_->DeliverRecordedData() == -1) {
    RTC_LOG(INFO) << "AudioDeviceBuffer::DeliverRecordedData failed";
  }
}

}  // namespace webrtc


text:
"""
Parser for HTML forms, that fills in defaults and errors.  See ``render``.
"""

import re

from formencode.rewritingparser import RewritingParser, html_quote

__all__ = ['render', 'htmlliteral', 'default_formatter',
           'none_formatter', 'escape_formatter',
           'FillingParser']

def render(form, defaults=None, errors=None, use_all_keys=False,
           error_formatters=None, add_attributes=None,
           auto_insert_errors=True, auto_error_formatter=None,
           text_as_default=False, listener=None, encoding=None,
           error_class='error', prefix_error=True,
           force_defaults=True):
    """
    Render the ``form`` (which should be a string) given the defaults
    and errors.  Defaults are the values that go in the input fields
    (overwriting any values that are there) and errors are displayed
    inline in the form (and also effect input classes).  Returns the
    rendered string.

    If ``auto_insert_errors`` is true (the default) then any errors
    for which ``<form:error>`` tags can't be found will be put just
    above the associated input field, or at the top of the form if no
    field can be found.

    If ``use_all_keys`` is true, if there are any extra fields from
    defaults or errors that couldn't be used in the form it will be an
    error.

    ``error_formatters`` is a dictionary of formatter names to
    one-argument functions that format an error into HTML.  Some
    default formatters are provided if you don't provide this.

    ``error_class`` is the class added to input fields when there is
    an error for that field.

    ``add_attributes`` is a dictionary of field names to a dictionary
    of attribute name/values.  If the name starts with ``+`` then the
    value will be appended to any existing attribute (e.g.,
    ``{'+class': ' important'}``).

    ``auto_error_formatter`` is used to create the HTML that goes
    above the fields.  By default it wraps the error message in a span
    and adds a ``
``.

    If ``text_as_default`` is true (default false) then ``<input
    type=unknown>`` will be treated as text inputs.

    ``listener`` can be an object that watches fields pass; the only
    one currently is in ``htmlfill_schemabuilder.SchemaBuilder``

    ``encoding`` specifies an encoding to assume when mixing str and
    unicode text in the template.

    ``prefix_error`` specifies if the HTML created by auto_error_formatter is
    put before the input control (default) or after the control.

    ``force_defaults`` specifies if a field default is not given in
    the ``defaults`` dictionary then the control associated with the
    field should be set as an unsuccessful control. So checkboxes will
    be cleared, radio and select controls will have no value selected,
    and textareas will be emptied. This defaults to ``True``, which is
    appropriate the defaults are the result of a form submission.
    """
    if defaults is None:
        defaults = {}
    if auto_insert_errors and auto_error_formatter is None:
        auto_error_formatter = default_formatter
    p = FillingParser(
        defaults=defaults, errors=errors,
        use_all_keys=use_all_keys,
        error_formatters=error_formatters,
        add_attributes=add_attributes,
        auto_error_formatter=auto_error_formatter,
        text_as_default=text_as_default,
        listener=listener, encoding=encoding,
        prefix_error=prefix_error,
        error_class=error_class,
        force_defaults=force_defaults,
        )
    p.feed(form)
    p.close()
    return p.text()

class htmlliteral(object):

    def __init__(self, html, text=None):
        if text is None:
            text = re.sub(r'<.*?>', '', html)
            text = html.replace('>', '>')
            text = html.replace('<', '<')
            text = html.replace('"', '"')
            # @@: Not very complete
        self.html = html
        self.text = text

    def __str__(self):
        return self.text

    def __repr__(self):
        return '<%s html=%r text=%r>' % (
            self.__class__.__name__, self.html, self.text)

    def __html__(self):
        return self.html

def default_formatter(error):
    """
    Formatter that escapes the error, wraps the error in a span with
    class ``error-message``, and adds a ``
``
    """
    return '%s
\n' % html_quote(error)

def none_formatter(error):
    """
    Formatter that does nothing, no escaping HTML, nothin'
    """
    return error

def escape_formatter(error):
    """
    Formatter that escapes HTML, no more.
    """
    return html_quote(error)

def escapenl_formatter(error):
    """
    Formatter that escapes HTML, and translates newlines to ``
``
    """
    error = html_quote(error)
    error = error.replace('\n', '
\n')
    return error

def ignore_formatter(error):
    """
    Formatter that emits nothing, regardless of the error.
    """
    return ''

class FillingParser(RewritingParser):
    r"""
    Fills HTML with default values, as in a form.

    Examples::

        >>> defaults = dict(name='Bob Jones',
        ...             occupation='Crazy Cultist',
        ...             address='14 W. Canal\nNew Guinea',
        ...             living='no',
        ...             nice_guy=0)
        >>> parser = FillingParser(defaults)
        >>> parser.feed('''<input type="text" name="name" value="fill">
        ... <select name="occupation"> <option value="">Default</option>
        ... <option value="Crazy Cultist">Crazy cultist</option> </select>
        ... <textarea cols="20" style="width: 100%" name="address">
        ... An address</textarea>
        ... <input type="radio" name="living" value="yes">
        ... <input type="radio" name="living" value="no">
        ... <input type="checkbox" name="nice_guy" checked="checked">''')
        >>> parser.close()
        >>> print parser.text() # doctest: +NORMALIZE_WHITESPACE
        <input type="text" name="name" value="Bob Jones">
        <select name="occupation">
        <option value="">Default</option>
        <option value="Crazy Cultist" selected="selected">Crazy cultist</option>
        </select>
        <textarea cols="20" style="width: 100%" name="address">14 W. Canal
        New Guinea</textarea>
        <input type="radio" name="living" value="yes">
        <input type="radio" name="living" value="no" checked="checked">
        <input type="checkbox" name="nice_guy">

    """

    default_encoding = 'utf8'

    def __init__(self, defaults, errors=None, use_all_keys=False,
                 error_formatters=None, error_class='error',
                 add_attributes=None, listener=None,
                 auto_error_formatter=None,
                 text_as_default=False, encoding=None, prefix_error=True,
                 force_defaults=True):
        RewritingParser.__init__(self)
        self.source = None
        self.lines = None
        self.source_pos = None
        self.defaults = defaults
        self.in_textarea = None
        self.skip_textarea = False
        self.last_textarea_name = None
        self.in_select = None
        self.skip_next = False
        self.errors = errors or {}
        if isinstance(self.errors, (str, unicode)):
            self.errors = {None: self.errors}
        self.in_error = None
        self.skip_error = False
        self.use_all_keys = use_all_keys
        self.used_keys = {}
        self.used_errors = {}
        if error_formatters is None:
            self.error_formatters = default_formatter_dict
        else:
            self.error_formatters = error_formatters
        self.error_class = error_class
        self.add_attributes = add_attributes or {}
        self.listener = listener
        self.auto_error_formatter = auto_error_formatter
        self.text_as_default = text_as_default
        self.encoding = encoding
        self.prefix_error = prefix_error
        self.force_defaults = force_defaults

    def str_compare(self, str1, str2):
        """
        Compare the two objects as strings (coercing to strings if necessary).
        Also uses encoding to compare the strings.
        """
        if not isinstance(str1, basestring):
            if hasattr(str1, '__unicode__'):
                str1 = unicode(str1)
            else:
                str1 = str(str1)
        if type(str1) == type(str2):
            return str1 == str2
        if isinstance(str1, unicode):
            str1 = str1.encode(self.encoding or self.default_encoding)
        else:
            str2 = str2.encode(self.encoding or self.default_encoding)
        return str1 == str2

    def close(self):
        self.handle_misc(None)
        RewritingParser.close(self)
        unused_errors = self.errors.copy()
        for key in self.used_errors.keys():
            if key in unused_errors:
                del unused_errors[key]
        if self.auto_error_formatter:
            for key, value in unused_errors.items():
                error_message = self.auto_error_formatter(value)
                error_message = '\n%s' % (key, error_message)
                self.insert_at_marker(
                    key, error_message)
            unused_errors = {}
        if self.use_all_keys:
            unused = self.defaults.copy()
            for key in self.used_keys.keys():
                if key in unused:
                    del unused[key]
            assert not unused, (
                "These keys from defaults were not used in the form: %s"
                % unused.keys())
            if unused_errors:
                error_text = []
                for key in unused_errors.keys():
                    error_text.append("%s: %s" % (key, self.errors[key]))
                assert False, (
                    "These errors were not used in the form: %s" %
                    ', '.join(error_text))
        if self.encoding is not None:
            new_content = []
            for item in self._content:
                if isinstance(item, str):
                    item = item.decode(self.encoding)
                new_content.append(item)
            self._content = new_content
        self._text = self._get_text()

    def skip_output(self):
        return (self.in_textarea and self.skip_textarea) or self.skip_error

    def add_key(self, key):
        self.used_keys[key] = 1

    def handle_starttag(self, tag, attrs, startend=False):
        self.write_pos()
        if tag == 'input':
            self.handle_input(attrs, startend)
        elif tag == 'textarea':
            self.handle_textarea(attrs)
        elif tag == 'select':
            self.handle_select(attrs)
        elif tag == 'option':
            self.handle_option(attrs)
            return
        elif tag == 'form:error':
            self.handle_error(attrs)
            return
        elif tag == 'form:iferror':
            self.handle_iferror(attrs)
            return
        else:
            return
        if self.listener:
            self.listener.listen_input(self, tag, attrs)

    def handle_endtag(self, tag):
        self.write_pos()
        if tag == 'textarea':
            self.handle_end_textarea()
        elif tag == 'select':
            self.handle_end_select()
        elif tag == 'form:iferror':
            self.handle_end_iferror()

    def handle_startendtag(self, tag, attrs):
        return self.handle_starttag(tag, attrs, True)

    def handle_iferror(self, attrs):
        name = self.get_attr(attrs, 'name')
        notted = False
        if name.startswith('not '):
            notted = True
            name = name.split(None, 1)[1]
        assert name, "Name attribute in <iferror> required (%s)" % self.getpos()
        self.in_error = name
        ok = self.errors.get(name)
        if notted:
            ok = not ok
        if not ok:
            self.skip_error = True
        self.skip_next = True

    def handle_end_iferror(self):
        self.in_error = None
        self.skip_error = False
        self.skip_next = True

    def handle_error(self, attrs):
        name = self.get_attr(attrs, 'name')
        formatter = self.get_attr(attrs, 'format') or 'default'
        if name is None:
            name = self.in_error
        assert name is not None, (
            "Name attribute in <form:error> required if not contained in "
            "<form:iferror> (%i:%i)" % self.getpos())
        error = self.errors.get(name, '')
        if error:
            error = self.error_formatters[formatter](error)
            self.write_text(error)
        self.skip_next = True
        self.used_errors[name] = 1

    def handle_input(self, attrs, startend):
        t = (self.get_attr(attrs, 'type') or 'text').lower()
        name = self.get_attr(attrs, 'name')
        if self.prefix_error:
            self.write_marker(name)
        value = self.defaults.get(name)
        if isinstance(name, unicode) and isinstance(value, str):
            value = value.decode(self.encoding or self.default_encoding)
        if name in self.add_attributes:
            for attr_name, attr_value in self.add_attributes[name].iteritems():
                if attr_name.startswith('+'):
                    attr_name = attr_name[1:]
                    self.set_attr(attrs, attr_name,
                        self.get_attr(attrs, attr_name, '') + attr_value)
                else:
                    self.set_attr(attrs, attr_name, attr_value)
        if (self.error_class
                and self.errors.get(self.get_attr(attrs, 'name'))):
            self.add_class(attrs, self.error_class)
        if t in ('text', 'hidden'):
            if value is None and not self.force_defaults:
                value = self.get_attr(attrs, 'value', '')
            self.set_attr(attrs, 'value', value)
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif t == 'checkbox':
            if self.force_defaults:
                selected = False
            else:
                selected = self.get_attr(attrs, 'checked')
            if not self.get_attr(attrs, 'value'):
                selected = value
            elif self.selected_multiple(value,
                                        self.get_attr(attrs, 'value', '')):
                selected = True
            if selected:
                self.set_attr(attrs, 'checked', 'checked')
            else:
                self.del_attr(attrs, 'checked')
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif t == 'radio':
            if self.str_compare(value, self.get_attr(attrs, 'value', '')):
                self.set_attr(attrs, 'checked', 'checked')
            elif self.force_defaults or name in self.defaults:
                self.del_attr(attrs, 'checked')
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif t == 'password':
            if value is None and not self.force_defaults:
                value = value or self.get_attr(attrs, 'value', '')
            self.set_attr(attrs, 'value', value)
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif t in ('file', 'image'):
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif t in ('submit', 'reset', 'button'):
            self.set_attr(attrs, 'value', value or
                          self.get_attr(attrs, 'value', ''))
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        elif self.text_as_default:
            if value is None:
                value = self.get_attr(attrs, 'value', '')
            self.set_attr(attrs, 'value', value)
            self.write_tag('input', attrs, startend)
            self.skip_next = True
            self.add_key(name)
        else:
            assert 0, "I don't know about this kind of <input>: %s (pos: %s)" \
                   % (t, self.getpos())
        if not self.prefix_error:
            self.write_marker(name)

    def handle_textarea(self, attrs):
        name = self.get_attr(attrs, 'name')
        if self.prefix_error:
            self.write_marker(name)
        if (self.error_class
            and self.errors.get(name)):
            self.add_class(attrs, self.error_class)
        value = self.defaults.get(name, '')
        if value or self.force_defaults:
            self.write_tag('textarea', attrs)
            self.write_text(html_quote(value))
            self.write_text('</textarea>')
            self.skip_textarea = True
        self.in_textarea = True
        self.last_textarea_name = name
        self.add_key(name)

    def handle_end_textarea(self):
        if self.skip_textarea:
            self.skip_textarea = False
        else:
            self.write_text('</textarea>')
        self.in_textarea = False
        self.skip_next = True
        if not self.prefix_error:
            self.write_marker(self.last_textarea_name)
        self.last_textarea_name = None

    def handle_select(self, attrs):
        name = self.get_attr(attrs, 'name', False)
        if name and self.prefix_error:
            self.write_marker(name)
        if (self.error_class
            and self.errors.get(name)):
            self.add_class(attrs, self.error_class)
        self.in_select = self.get_attr(attrs, 'name', False)
        self.write_tag('select', attrs)
        self.skip_next = True
        self.add_key(self.in_select)

    def handle_end_select(self):
        self.write_text('</select>')
        self.skip_next = True
        if not self.prefix_error and self.in_select:
            self.write_marker(self.in_select)
        self.in_select = None

    def handle_option(self, attrs):
        assert self.in_select is not None, (
            "<option> outside of <select>: line %i, column %i"
            % self.getpos())
        if self.in_select != False:
            if self.force_defaults or self.in_select in self.defaults:
                if self.selected_multiple(self.defaults.get(self.in_select, ''),
                                          self.get_attr(attrs, 'value', '')):
                    self.set_attr(attrs, 'selected', 'selected')
                    self.add_key(self.in_select)
                else:
                    self.del_attr(attrs, 'selected')
        self.write_tag('option', attrs)
        self.skip_next = True

    def selected_multiple(self, obj, value):
        """
        Returns true/false if obj indicates that value should be
        selected.  If obj has a __contains__ method it is used, otherwise
        identity is used.
        """
        if obj is None:
            return value == ""
        if isinstance(obj, (str, unicode)):
            return obj == value
        if hasattr(obj, '__contains__'):
            if value in obj:
                return True
        if hasattr(obj, '__iter__'):
            for inner in obj:
                if self.str_compare(inner, value):
                    return True
        return self.str_compare(obj, value)

    def write_marker(self, marker):
        self._content.append((marker,))

    def insert_at_marker(self, marker, text):
        for i, item in enumerate(self._content):
            if item == (marker,):
                self._content.insert(i, text)
                break
        else:
            self._content.insert(0, text)

# This can potentially be extended globally
default_formatter_dict = dict(
    default=default_formatter,
    none=none_formatter,
    escape=escape_formatter,
    escapenl=escapenl_formatter,
    ignore=ignore_formatter)