text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.gwtvisualizationwrappers</groupId>
    <artifactId>gwtvisualizationwrappers-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0-gwt-2.7.0</version>

    <name>gwt visualization wrappers - parent</name>
    <description>GWT wrappers for popular JS libraries</description>

    <prerequisites>
        <maven>3.0.5</maven>
    </prerequisites>

    <licenses>
        <license>
            <name>Apache License Version 2</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>jay-hodgson</id>
            <name>Jay Hodgson</name>
            <roles>
                <role>architect</role>
                <role>developer</role>
            </roles>
        </developer>
    </developers>

    <modules>
        <module>gwtvisualizationwrappers</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <source.version>1.6</source.version>
        <gwt.version>2.7.0</gwt.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>1.7</version>
                <configuration>
                    <licenseName>apache_v2</licenseName>
                    <inceptionYear>2015</inceptionYear>
                    <organizationName>GwtCytoscapeJs</organizationName>
                    <projectName>GwtCytoscapeJs</projectName>
                    <includes>
                        <include>**/*.java</include>
                        <include>**/*.xml</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <id>license</id>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>update-file-header</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.8.1</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <locale>en</locale>
                    <linksource>true</linksource>
                    <validateLinks>true</validateLinks>
                    <links>
                        <link>http://google-web-toolkit.googlecode.com/svn/javadoc/2.5.1</link>
                    </links>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>gwt-maven-plugin</artifactId>
                    <version>${gwt.version}</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>compile</goal>
                                <goal>test</goal>
                                <goal>resources</goal>
                            </goals>
                            <configuration>
                                <mode>htmlunit</mode>
                                <testTimeOut>240</testTimeOut>
                                <failOnError>true</failOnError>
                                <jsInteropMode>JS</jsInteropMode>
                            </configuration>
                        </execution>
                    </executions>
                    <inherited>true</inherited>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>${source.version}</source>
                        <target>${source.version}</target>
                        <compilerArgument>-Xlint:all</compilerArgument>
                        <showWarnings>true</showWarnings>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.codehaus.mojo</groupId>
                                        <artifactId>gwt-maven-plugin</artifactId>
                                        <versionRange>[0,)</versionRange>
                                        <goals>
                                            <goal>resources</goal>
                                            <goal>i18n</goal>
                                            <goal>generateAsync</goal>
                                            <goal>css</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute />
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.codehaus.mojo</groupId>
                                        <artifactId>license-maven-plugin</artifactId>
                                        <versionRange>[0,)</versionRange>
                                        <goals>
                                            <goal>update-file-header</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <distributionManagement>
        <repository>
            <id>sagebionetworks</id>
            <name>sagebionetworks-releases</name>
            <url>http://sagebionetworks.artifactoryonline.com/sagebionetworks/libs-releases-local
            </url>
        </repository>
        <snapshotRepository>
            <id>sagebionetworks</id>
            <name>sagebionetworks-snapshots</name>
            <url>http://sagebionetworks.artifactoryonline.com/sagebionetworks/libs-snapshots-local
            </url>
            <uniqueVersion>false</uniqueVersion>
        </snapshotRepository>
    </distributionManagement>

</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:deviceIds="wear_square">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <Button
                android:id="@+id/btn1"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn2"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn3"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <Button
                android:id="@+id/btn4"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn5"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn6"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <Button
                android:id="@+id/btn7"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn8"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
            <Button
                android:id="@+id/btn9"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="@drawable/play_btn"
                android:layout_margin="2dp"
                />
        </LinearLayout>
    </LinearLayout>

    <include layout="@layout/include_count"/>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.11.10 at 04:43:16 PM CET
//

package net.sll_mdilab.t5;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

/**
 *
Java class for EquipmentIdentifier complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="EquipmentIdentifier">
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *       <attribute name="nameSpaceID" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EquipmentIdentifier", propOrder = {
    "value"
})
public class EquipmentIdentifier {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "nameSpaceID")
    protected String nameSpaceID;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the nameSpaceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNameSpaceID() {
        return nameSpaceID;
    }

    /**
     * Sets the value of the nameSpaceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNameSpaceID(String value) {
        this.nameSpaceID = value;
    }

}


text:
package com.sjcqs.rawlauncher.items;

import android.content.Intent;
import android.graphics.drawable.Drawable;

import com.sjcqs.rawlauncher.utils.interfaces.Shortcutable;

import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;

/**
 * Created by satyan on 8/24/17.
 */

public abstract class Item implements Shortcutable {

    public static final Comparator<? super Item> ALPHA_COMPARATOR = new Comparator<Item>() {
        private final Collator COLLATOR = Collator.getInstance(Locale.getDefault());

        @Override
        public int compare(Item app1, Item app2) {
            return (COLLATOR.compare(app1.getLabel(), app2.getLabel()));
        }
    };
    public static final Comparator<? super Item> REVERSE_ALPHA_COMPARATOR = new Comparator<Item>() {
        private final Collator COLLATOR = Collator.getInstance(Locale.getDefault());

        @Override
        public int compare(Item app1, Item app2) {
            return -(COLLATOR.compare(app1.getLabel(), app2.getLabel()));
        }
    };
    protected final Drawable icon;
    protected final Intent intent;
    protected CharSequence label;

    protected Item(String label, Drawable drawable, Intent intent){
        this.label = label;
        this.icon = drawable;
        this.intent = intent;
    }

    public String getLabel(){
        return label.toString();
    }

    public Drawable getIcon(){
        return icon;
    }

    public Intent getIntent() {
        return intent;
    }

    public String getInput() {
        return label.toString();
    }

    @Override
    public String toString() {
        return label + ": " + icon.toString();
    }

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

    public String getDiscriminator() {
        return getLabel();
    }

    public boolean canBeUninstalled() {
        return false;
    }

    public Intent getUninstallIntent() {
        return null;
    }
}


text:
"""Test the pre-kill hook on Darwin."""
from __future__ import print_function

# system imports
from multiprocessing import Process, Queue
import platform
import re
from unittest import main, TestCase

# third party
from six import StringIO

def do_child_process(child_work_queue, parent_work_queue, verbose):
    import os

    pid = os.getpid()
    if verbose:
        print("child: pid {} started, sending to parent".format(pid))
    parent_work_queue.put(pid)
    if verbose:
        print("child: waiting for shut-down request from parent")
    child_work_queue.get()
    if verbose:
        print("child: received shut-down request.  Child exiting.")

class DarwinPreKillTestCase(TestCase):

    def __init__(self, methodName):
        super(DarwinPreKillTestCase, self).__init__(methodName)
        self.process = None
        self.child_work_queue = None
        self.verbose = False

    def tearDown(self):
        if self.verbose:
            print("parent: sending shut-down request to child")
        if self.process:
            self.child_work_queue.put("hello, child")
            self.process.join()
        if self.verbose:
            print("parent: child is fully shut down")

    def test_sample(self):
        # Ensure we're Darwin.
        if platform.system() != 'Darwin':
            self.skipTest("requires a Darwin-based OS")

        # Start the child process.
        self.child_work_queue = Queue()
        parent_work_queue = Queue()
        self.process = Process(target=do_child_process,
                               args=(self.child_work_queue, parent_work_queue,
                                     self.verbose))
        if self.verbose:
            print("parent: starting child")
        self.process.start()

        # Wait for the child to report its pid.  Then we know we're running.
        if self.verbose:
            print("parent: waiting for child to start")
        child_pid = parent_work_queue.get()

        # Sample the child process.
        from darwin import do_pre_kill
        context_dict = {
            "archs": [platform.machine()],
            "platform_name": None,
            "platform_url": None,
            "platform_working_dir": None
        }

        if self.verbose:
            print("parent: running pre-kill action on child")
        output_io = StringIO()
        do_pre_kill(child_pid, context_dict, output_io)
        output = output_io.getvalue()

        if self.verbose:
            print("parent: do_pre_kill() wrote the following output:", output)
        self.assertIsNotNone(output)

        # We should have a line with:
        # Process:  .* [{pid}]
        process_re = re.compile(r"Process:[^[]+\[([^]]+)\]")
        match = process_re.search(output)
        self.assertIsNotNone(match, "should have found process id for "
                             "sampled process")
        self.assertEqual(1, len(match.groups()))
        self.assertEqual(child_pid, int(match.group(1)))

        # We should see a Call graph: section.
        callgraph_re = re.compile(r"Call graph:")
        match = callgraph_re.search(output)
        self.assertIsNotNone(match, "should have found the Call graph section"
                             "in sample output")

        # We should see a Binary Images: section.
        binary_images_re = re.compile(r"Binary Images:")
        match = binary_images_re.search(output)
        self.assertIsNotNone(match, "should have found the Binary Images "
                             "section in sample output")

if __name__ == "__main__":
    main()


text:
package com.elation.demo;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;

public class ElationDebugEventsAdapter extends ArrayAdapter<ElationEvent> {

    private Context context;

    public ElationDebugEventsAdapter(Context context, int textViewResourceId, ArrayList<ElationEvent> items) {
        super(context, textViewResourceId, items);
        this.context = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.debug_events_message, null);
        }

        ElationEvent event = getItem(position);
        if (event != null) {
            // My layout has only one TextView
            TextView eventType = (TextView) view.findViewById(R.id.event_type);
            if (eventType != null) {
                eventType.setText(event.type);
            }
            TextView eventTarget = (TextView) view.findViewById(R.id.event_target);
            if (eventTarget != null) {
                if (event.target != null) {
                  eventTarget.setText(event.target);
                }
            }
            TextView eventData = (TextView) view.findViewById(R.id.event_data);
            if (eventData != null) {
                if (event.hasData()) {
                  eventData.setText(event.dataRaw);
                } else {
                  eventData.setText("(no data)");
                }
            }
         }

        return view;
    }
}


text:
using Openpay.Entities;
using Openpay.Entities.Request;
using Openpay.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Openpay
{
	/**
	 * <summary>
	 * Clase base que contiene las operaciones disponibles para la administracion de los webhooks
	 * </summary>
	 */
	public class WebhookService : OpenpayResourceService<Webhook, Webhook>
	{

		public WebhookService(string api_key, string merchant_id, bool production = false)
			: base(api_key, merchant_id, production)
		{
			ResourceName = "webhooks";
		}

		internal WebhookService(OpenpayHttpClient opHttpClient)
			: base(opHttpClient)
		{
			ResourceName = "webhooks";
		}

		public Webhook Create(Webhook webhook)
		{
			return base.Create(null, webhook);
		}

		public void Verify(string webhook_id, string verification_code)
		{
			string url = GetEndPoint(null, webhook_id) + "/verify" + "/" + verification_code;
			this.httpClient.Post<Webhook>(url);
		}

		public Webhook Get(string webhook_id)
		{
			return base.Get(null, webhook_id);
		}

		public void Delete(string webhook_id)
		{
			base.Delete(null, webhook_id);
		}

		public List<Webhook> List()
		{
			return base.List(null, null);
		}

	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 2: 82 (1863)

#### Original name
Agaricus loscosii Rabenh.

### Remarks
null


text:
.. Licensed to the Apache Software Foundation (ASF) under one
.. or more contributor license agreements.  See the NOTICE file
.. distributed with this work for additional information
.. regarding copyright ownership.  The ASF licenses this file
.. to you under the Apache License, Version 2.0 (the
.. "License"); you may not use this file except in compliance
.. with the License.  You may obtain a copy of the License at

..   http://www.apache.org/licenses/LICENSE-2.0

.. Unless required by applicable law or agreed to in writing,
.. software distributed under the License is distributed on an
.. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
.. KIND, either express or implied.  See the License for the
.. specific language governing permissions and limitations
.. under the License.

.. SCOPE OF THIS SECTION
.. This section should include all necessary steps to set up
.. the forked Arrow repository locally in order to be able to
.. proceed toward building the library.

.. _set-up:

******
Set up
******

Install and set up Git
======================

The Arrow project is developed using `Git <https://git-scm.com/>`_
for version control which is easily available for all common
operating systems.

You can follow the instructions to install Git from GitHub
where Arrow repository is hosted, following
`the quickstart instructions <https://docs.github.com/en/get-started/quickstart/set-up-git>`_.

When Git is set up do not forget to configure your name and email

.. code:: console

   $ git config --global user.name "Your Name"
   $ git config --global user.email your.email@example.com

and `authenticate with GitHub <https://docs.github.com/en/get-started/quickstart/set-up-git#next-steps-authenticating-with-github-from-git>`_
as this will allow you to interact with GitHub without typing
a username and password each time you execute a git command.

.. note::

   This guide assumes you are comfortable working from the command line.
   Some IDEs allow you to manage a Git repository, but may implicitly run
   unwanted operations when doing so (such as creating project files).

   For example, cloning it in RStudio assumes the whole repository is an
   RStudio project and will create a ``.Rproj`` file in the root directory.
   For this reason it is *highly recommended* to clone the repository using
   the command line or a Git client.

Get the source code
===================

.. _fork-repo-guide:

Fork the repository
-------------------

The Arrow GitHub repository contains both the Arrow C++ library plus
libraries for other languages such as Go, Java, Matlab, Python, R, etc.
The first step to contributing is to create a fork of the repository
in your own GitHub account.

1. Go to `<https://github.com/apache/arrow>`_.

2. Press Fork in the top right corner.

   .. figure:: /developers/images/github_fork.jpeg
      :scale: 50 %
      :alt: Fork the Apache Arrow repository on GitHub.

      The icon to fork the Apache Arrow repository on GitHub.

3. Choose to fork the repository to your username so the fork will be
   created at ``https://github.com/<your username>/arrow``.

Clone the repository
--------------------

Next you need to clone the repository

.. code:: console

   $ git clone https://github.com/<your username>/arrow.git

and add Apache Arrow repository as a remote called ``upstream``.

.. code:: console

   $ cd arrow
   $ git remote add upstream https://github.com/apache/arrow

Verify your upstream
--------------------

Your upstream should be pointing at the Arrow GitHub repo.

Running in the shell:

.. code:: console

   $ git remote -v

Should give you a result similar to this:

.. code:: console

   origin	https://github.com/<your username>/arrow.git (fetch)
   origin	https://github.com/<your username>/arrow.git (push)
   upstream	https://github.com/apache/arrow (fetch)
   upstream	https://github.com/apache/arrow (push)

If you did everything correctly, you should now have a copy of the code
in the ``arrow`` directory and two remotes that refer to your own GitHub
fork (``origin``) and the official Arrow repository (``upstream``).


text:
import * as actions from 'app/actions/channels';

const initialState = {
  channels: [],
  page: 0,
  per_page: 30,
  total: 0,
  isFetching: false,
}

export default function channels(state=initialState, action) {
  switch (action.type) {
    case actions.CHANNELS_REQUESTED:
      return {
        ...state,
        isFetching: true,
        page: action.payload.page,
      };

    case actions.CHANNELS_INFO_REQUESTED:
      return {
        ...state,
        isFetching: true,
        page: action.payload.page,
      };

    case actions.CHANNELS_FETCH_SUCCESS:
      let { channels, total } = action.payload;
      return {
        ...state,
        isFetching: false,
        channels: channels,
        total: parseInt(total || channels.length),
      };

    case actions.CHANNELS_INFO_FETCH_SUCCESS:
      const channel = action.payload;
      return {
        ...state,
        isFetching: false,
        channels: [ channel ], // Shame, its should has its own reducer for channel info
      };

    default:
      return state;
  }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="appraisal">
        <roleset framnet="" id="appraisal.01" name="set a price, value" source="verb-appraise.01" vncls="54.4 34.1">
            <roles>

                <role descr="seller" f="" n="0">
                    <vnrole vncls="54.4" vntheta="agent"/>
                    <vnrole vncls="34.1" vntheta="agent"/>
                </role>

                <role descr="commodity" f="" n="1">
                    <vnrole vncls="54.4" vntheta="theme"/>
                    <vnrole vncls="34.1" vntheta="theme"/>
                </role>

                <role descr="price" f="" n="2">
                    <vnrole vncls="54.4" vntheta="value"/>
                    <vnrole vncls="34.1" vntheta="attribute"/>
                </role>

                <note/>
            </roles>

            <example name="Arg 1 and TMP" src="NomBank Frames" type="">
                <text>Firms are offering prepurchase house appraisals to deter overpaying.</text>

                <arg f="tmp" n="m">prepurchase</arg>
                <arg f="" n="1">house</arg>
                <rel f="">appraisals</rel>
                <note/>
            </example>

            <example name="Arg 1 and MNR" src="ON sense 1" type="">
                <text>The antique experts had a harsh appraisal of the value of my lunchbox collection.</text>
                <arg f="mnr" n="m">harsh</arg>
                <rel f="">appraisal</rel>
                <note/>
                <arg f="" n="1">of the value of my lunchbox collection.</arg>
            </example>

            <note>Roleset based on verb appraise.01, OntoNotes grouping appraisal-n sense 1; maps to VN classes assessment-34.1 and price-54.4. Framed by Claire.</note>
            <example name="All arguments" src="invented" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Mary's $279,000 appraisal of the house was reasonable.</text>
                <note/>
                <arg f="" n="0">Mary's</arg>
                <arg f="" n="2">$279,000</arg>
                <rel f="">appraisal</rel>
                <arg f="" n="1">of the house</arg>
            </example>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>


text:
@import UIKit;
#import "CDAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([CDAppDelegate class]));
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M15,16.05 L11.275,12.3H3.45V11.675H11.275L15,7.925L19.075,12Z"/>
</vector>


text:
Shindo.tests('Fog::Compute[:libvirt] | servers collection', ['libvirt']) do

  servers = Fog::Compute[:libvirt].servers

  tests('The servers collection') do
    test('should not be empty') { not servers.empty? }
    test('should be a kind of Fog::Compute::Libvirt::Servers') { servers.kind_of? Fog::Compute::Libvirt::Servers }
    tests('should be able to reload itself').succeeds { servers.reload }
    tests('should be able to get a model') do
      tests('by instance uuid').succeeds { servers.get servers.first.id }
    end
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:orientation="vertical"
        android:padding="?attr/standardPadding">

    <RelativeLayout
            android:id="@+id/navigationCircle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/navigation_circle">

        <View
                android:id="@+id/destinationCircle"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:background="@drawable/navigation_destination"
                android:visibility="invisible"
        />

        <TextView
                android:id="@+id/navigationN"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="N"
                android:visibility="invisible"
        />

        <TextView
                android:id="@+id/navigationE"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="E"
                android:visibility="invisible"
        />

        <TextView
                android:id="@+id/navigationS"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="S"
                android:visibility="invisible"
        />

        <TextView
                android:id="@+id/navigationW"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="W"
                android:visibility="invisible"
        />

        <View
                android:id="@+id/currentLocationCircle"
                android:layout_width="4dp"
                android:layout_height="4dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:background="@drawable/navigation_center"
        />
    </RelativeLayout>

    <TableLayout
            android:id="@+id/navigationData"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="*"
            android:shrinkColumns="*"
            android:paddingTop="?attr/standardPadding">

        <TableRow>

            <TextView
                    android:id="@+id/navigationDestinationDistanceLabel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_distance"
            />

            <TextView
                    android:id="@+id/navigationAccuracyLabel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_accuracy"
            />

            <TextView
                    android:id="@+id/navigationDestinationBearingLabel"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_destination"
            />

        </TableRow>

        <TableRow>

            <TextView
                    android:id="@+id/navigationDestinationDistance"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_empty"
            />

            <TextView
                    android:id="@+id/navigationAccuracy"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_empty"
            />

            <TextView
                    android:id="@+id/navigationDestinationBearing"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/label_empty"
            />

        </TableRow>
    </TableLayout>

</LinearLayout>


text:
@extends(layout.defaultLayout, title: "Examples")

Examples

Ninja can do a lot for you. In the following some
		code samples that show the power of Ninja.

Standard behavior

A default route like this one: /

A parameterized route like: /user/{id}/{name}/userDashboard

A redirect at /redirects back to index... /redirect

... and some code in the future ;)

Rendering jsons

As seen here GET /person

As seen here POST /person parses the
		body and displays the result.

Rendering Post form directly to object

As seen here form /contactForm

Filtering

A working security filter can be found at: /filter

A filter that generates output, changes the status and
		disallows further execution of the filter chain:/teapot

Injection

Injection of services is important and can be done easily.
		Check out: Not yet completed. /injection

Session support

The default mode of Ninja is to store the session as signed
		cookie on the client side. Check out /session

Flash cookie support

To transmit small bits of information from one request to
		another Ninja supports so called flash cookies. They transmit eg a
		error message from one request to another. Usually flash cookies only
		live for one request.

Success message via flash cookie: /flash_success

Error message via flash cookie: /flash_error

An arbitrary flash message: /flash_any

Internationalization

To transmit small bits of information from one request to
		another Ninja supports so called flash cookies. They transmit eg a
		error message from one request to another. Usually flash cookies only
		live for one request: /i18n

Html Escaping

By default all html templates are escaped. This eliminates a
		lot of vulnerabilities due to javascript injection attacks. Check out
		the following page and have a look in the source code. The html stuff
		is escaped in the source... /htmlEscaping

Upload demo:

Uploading is straight forward using Ninja. Check out the demo at: /upload


text:
#import <Foundation/Foundation.h>
#import "cocos2d.h"

@class CCStoredMessages;

/** @class CCSendMessages CCActionInstant that sends messsages to a target when it is run.
 *
 * It is different than the CCCallFunc classes in that any message can be sent
 * to a target regardless of the number/type of arguments.
 *
 * NOTE: Any selector in the NSObject class and any selector in the NSObject and
 * NSCopying protocals cannot be added via -addMessage.
 * If you need to call one of those selectors, create an NSInvocation and add it
 * via -addInvocation:.
 *
 * Usage:
 *	Create a CCSendMessages instance with a target using -initWithTarget: or
 *	+actionWithTarget:
 *
 *	Add message call(s) to it:
 *		(assuming sendMessages is your CCSendMessages object)
 *		[[sendMessages addMessage] setOpacity:0.5];
 *		[[sendMessages addMessage] long:0.5 selector:obj example:ccp(3,3)];
 *
 *	Run it on a CCNode with -runAction:, or add it to a
 *	CCSequence to run it later on!
 *
 *	Also, arguments don't have to be Objective-C objects.
 *
 * @version 0.2.1
 */
@interface CCSendMessages : CCActionInstant {

@private
    id messagesTarget_;
    CCStoredMessages *messages_;

}

/** Creates CCSendMessages action with given target. @see initWithTarget: */
+ (id)actionWithTarget:(id)t;

/** Init CCSendMessages action with given target
 * @param t Target, which will receive messages.
 */
- (id)initWithTarget:(id)t;

/** Returns CCStoredMessages that is stored internally to capture Objective-C messages. */
- (id)addMessage;

/** Adds NSInvocation to internal CCStoredMessages, use this method to send NSObject
 * & NSCopying selectors to a target.
 */
- (void)addInvocation:(NSInvocation *)invocation;

/** Sends all captured messages to a target.
 *
 * You don't need to use this method directly - use CCNode#runAction: instead.
 */
- (void)execute;

@end

// CCStoredMessages
// Simply a class to capture messages sent to it
//
// Public ivars are used instead of properties so
// that a wider range of selectors can be used
// (because this class cannot capture selectors it
// responds to).  Also, because of this, most logic
// is handled in CCSendMessages

@interface CCStoredMessages : NSObject {

@public
	id target_;
    NSMutableArray *invocations_;

}

@end


text:
require 'forwardable'

module Honeybadger
  # +Honeybadger::Plugin+ defines the API for registering plugins with
  # Honeybadger. Each plugin has requirements which must be satisfied before
  # executing the plugin's execution block(s). This allows us to detect
  # optional dependencies and load the plugin for each dependency only if it's
  # present in the application.
  #
  # See the plugins/ directory for examples of official plugins. If you're
  # interested in developing a plugin for Honeybadger, see the Integration
  # Guide: https://docs.honeybadger.io/ruby/gem-reference/integration.html
  #
  # @example
  #
  #   require 'honeybadger/plugin'
  #   require 'honeybadger/ruby'
  #
  #   module Honeybadger
  #     module Plugins
  #       # Register your plugin with an optional name. If the name (such as
  #       # "my_framework") is not provided, Honeybadger will try to infer the name
  #       # from the current file.
  #       Plugin.register 'my_framework' do
  #         requirement do
  #           # Check to see if the thing you're integrating with is loaded. Return true
  #           # if it is, or false if it isn't. An exception in this block is equivalent
  #           # to returning false. Multiple requirement blocks are supported.
  #           defined?(MyFramework)
  #         end
  #
  #         execution do
  #           # Write your integration. This code will be executed only if all requirement
  #           # blocks return true. An exception in this block will disable the plugin.
  #           # Multiple execution blocks are supported.
  #           MyFramework.on_exception do |exception|
  #             Honeybadger.notify(exception)
  #           end
  #         end
  #       end
  #     end
  #   end
  class Plugin
    # @api private
    CALLER_FILE = Regexp.new('\A(?:\w:)?([^:]+)(?=(:\d+))').freeze

    class << self
      # @api private
      @@instances = {}

      # @api private
      def instances
        @@instances
      end

      # Register a new plugin with Honeybadger. See {#requirement} and {#execution}.
      #
      # @example
      #
      #   Honeybadger::Plugin.register 'my_framework' do
      #     requirement { }
      #     execution { }
      #   end
      #
      # @param [String, Symbol] name The optional name of the plugin. Should use
      #   +snake_case+. The name is inferred from the current file name if omitted.
      #
      # @return nil
      def register(name = nil, &block)
        name ||= name_from_caller(caller) or
          raise(ArgumentError, 'Plugin name is required, but was nil.')
        instances[key = name.to_sym] and fail("Already registered: #{name}")
        instances[key] = new(name).tap { |d| d.instance_eval(&block) }
      end

      # @api private
      def load!(config)
        instances.each_pair do |name, plugin|
          if config.load_plugin?(name)
            plugin.load!(config)
          else
            config.logger.debug(sprintf('skip plugin name=%s reason=disabled', name))
          end
        end
      end

      # @api private
      def name_from_caller(caller)
        caller && caller[0].match(CALLER_FILE) or
          fail("Unable to determine name from caller: #{caller.inspect}")
        File.basename($1)[/[^\.]+/]
      end
    end

    # @api private
    class Execution
      extend Forwardable

      def initialize(config, &block)
        @config = config
        @block = block
      end

      def call
        instance_eval(&block)
      end

      private

      attr_reader :config, :block
      def_delegator :@config, :logger
    end

    # @api private
    def initialize(name)
      @name         = name
      @loaded       = false
      @requirements = []
      @executions   = []
    end

    # Define a requirement. All requirement blocks must return +true+ for the
    # plugin to be executed.
    #
    # @example
    #
    #   Honeybadger::Plugin.register 'my_framework' do
    #     requirement { defined?(MyFramework) }
    #
    #     # Honeybadger's configuration object is available inside
    #     # requirement blocks. It should generally not be used outside of
    #     # internal plugins. See +Config+.
    #     requirement { config[:'my_framework.enabled'] }
    #
    #     execution { }
    #   end
    #
    # @return nil
    def requirement(&block)
      @requirements << block
    end

    # Define an execution block. Execution blocks will be executed if all
    # requirement blocks return +true+.
    #
    # @example
    #
    #   Honeybadger::Plugin.register 'my_framework' do
    #     requirement { defined?(MyFramework) }
    #
    #     execution do
    #       MyFramework.on_exception {|err| Honeybadger.notify(err) }
    #     end
    #
    #     execution do
    #       # Honeybadger's configuration object is available inside
    #       # execution blocks. It should generally not be used outside of
    #       # internal plugins. See +Config+.
    #       MyFramework.use_middleware(MyMiddleware) if config[:'my_framework.use_middleware']
    #     end
    #   end
    #
    # @return nil
    def execution(&block)
      @executions << block
    end

    # @api private
    def ok?(config)
      @requirements.all? {|r| Execution.new(config, &r).call }
    rescue => e
      config.logger.error(sprintf("plugin error name=%s class=%s message=%s\n\t%s", name, e.class, e.message.dump, Array(e.backtrace).join("\n\t")))
      false
    end

    # @api private
    def load!(config)
      if @loaded
        config.logger.debug(sprintf('skip plugin name=%s reason=loaded', name))
        return false
      elsif ok?(config)
        config.logger.debug(sprintf('load plugin name=%s', name))
        @executions.each {|e| Execution.new(config, &e).call }
        @loaded = true
      else
        config.logger.debug(sprintf('skip plugin name=%s reason=requirement', name))
      end

      @loaded
    rescue => e
      config.logger.error(sprintf("plugin error name=%s class=%s message=%s\n\t%s", name, e.class, e.message.dump, Array(e.backtrace).join("\n\t")))
      @loaded = true
      false
    end

    # @api private
    def loaded?
      @loaded
    end

    # @private
    # Used for testing only; don't normally call this. :)
    def reset!
      @loaded = false
    end

    # @api private
    attr_reader :name, :requirements, :executions
  end
end


text:
require 'rails_helper'

RSpec.describe Admin::TrainersController do
  shared_examples 'access denied' do
    describe 'GET #index' do
      subject(:request) { get :index }

      it { expect { request }.to require_admin_privileges }
    end

    describe 'GET #new' do
      subject(:request) { get :new }

      it { expect { request }.to require_admin_privileges }
    end

    describe 'GET #edit' do
      subject(:request) { get :edit, id: create(:trainer) }

      it { expect { request }.to require_admin_privileges }
    end

    describe 'POST #create' do
      subject(:request) { post :create, trainer: build(:trainer) }

      it { expect { request }.to require_admin_privileges }
    end

    describe 'PUT #update' do
      subject(:request) { put :update, id: create(:trainer), trainer: attributes_for(:trainer) }

      it { expect { request }.to require_admin_privileges }
    end

    describe 'DELETE #destroy' do
      subject(:request) { delete :destroy, id: create(:trainer) }

      it { expect { request }.to require_admin_privileges }
    end
  end

  describe 'guest access' do
    it_behaves_like 'access denied'
  end

  describe 'user access' do
    let(:user) { create :user }

    before { sign_in user }

    it_behaves_like 'access denied'
  end

  describe 'admin access' do
    let(:admin) { create :admin_user }

    before { sign_in admin }

    describe 'GET #index' do
      let!(:trainers) { create_list :trainer, 3 }
      subject { get :index }

      it { is_expected.to render_template :index }
      it { is_expected.to expose :trainers, trainers }
    end

    describe 'GET #new' do
      subject { get :new }

      it { is_expected.to render_template :new }
    end

    describe 'GET #edit' do
      let!(:trainer) { create :trainer }
      subject { get :edit, id: trainer.id }

      it { is_expected.to render_template :edit }
      it { is_expected.to expose :trainer, trainer }
    end

    describe 'PUT #update' do
      let!(:trainer) { create :trainer, first_name: 'Ann' }

      context 'with valid attributes' do

        before :each do
          put :update, id: trainer.id, trainer: { first_name: 'Mary' }
        end

        it { expect(trainer.reload.first_name).to eq 'Mary' }

        it 'redirects to index with a notice' do
          is_expected.to redirect_to action: :index, anchor: Trainer.last.decorate.css_id
          expect(controller).to set_flash[:notice].to 'Trainer has been updated!'
        end
      end

      context 'with invalid attributes' do
        before :each do
          put :update, id: trainer.id, trainer: { first_name: '' }
        end

        it { expect(trainer.reload.first_name).to eq 'Ann' }
        it { is_expected.to render_template :edit }
      end
    end

    describe 'POST #create' do
      context 'with valid attributes' do
        subject { post :create, trainer: attributes_for(:trainer) }

        it { expect { subject }.to change(Trainer, :count).by(1) }

        it 'redirects to index with a notice' do
          is_expected.to redirect_to action: :index, anchor: Trainer.last.decorate.css_id
          expect(controller).to set_flash[:notice].to 'Trainer has been created!'
        end
      end

      context 'with invalid attributes' do
        subject { post :create, trainer: { first_name: '', description: ''} }

        it { expect { subject }.not_to change(Trainer, :count) }
        it { is_expected.to render_template :new }
      end
    end

    describe 'DELETE #destroy' do
      let!(:trainer) { create :trainer }
      subject { xhr :delete, :destroy, id: trainer.id }

      it { expect { subject }.to change(Trainer, :count).by(-1) }
      it { is_expected.to render_template :destroy }

      it 'sets notice' do
        subject
        expect(controller).to set_flash.now[:notice].to 'Trainer has been deleted!'
        end
    end
  end
end


text:
package org.waveprotocol.box.server.persistence.mongodb;

import org.waveprotocol.box.common.comms.WaveClientRpc.WaveletSnapshot;
import org.waveprotocol.box.server.common.SnapshotSerializer;
import org.waveprotocol.box.server.persistence.PersistenceException;
import org.waveprotocol.box.server.waveserver.DeltaStore;
import org.waveprotocol.wave.model.id.InvalidIdException;
import org.waveprotocol.wave.model.id.ModernIdSerialiser;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.operation.OperationException;
import org.waveprotocol.wave.model.util.Preconditions;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.data.ReadableWaveletData;
import org.waveprotocol.wave.model.wave.data.WaveletData;
import org.waveprotocol.wave.util.logging.Log;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

/**
 * A MongoDB-backed store of Wavelet snapshots.
 * The aim is to avoid the whole processing of deltas when a
 * wavelet is loaded into server's memory for the first time.
 *
 * This class is not thread-safe.
 *
 * @author pablojan@gmail.com (Pablo Ojanguren)
 *
 */
public class MongoDBSnapshotStore {

  private static final Log LOG = Log.get(MongoDBSnapshotStore.class);

  protected static final String WAVE_ID_FIELD  = "waveid";
  protected static final String WAVELET_ID_FIELD = "waveletid";
  protected static final String VERSION_FIELD = "version";
  protected static final String VERSION_HASH_FIELD = "versionhash";
  protected static final String LASTMOD_FIELD = "lastmod";

  protected static final String SNAPSHOT_DATA = "data";

  /** Name of the MongoDB collection to store Deltas */
  protected static final String SNAPSHOT_COLLECTION = "snapshots";

  private final MongoCollection<BasicDBObject> collection;

  /**
   * Get a reference to the snapshots store.
   *
   * @param database
   * @return
   */
  public static MongoDBSnapshotStore create(MongoDatabase database) {
      Preconditions.checkArgument(database != null, "Unable to get reference to mongoDB snapshots collection");
    MongoCollection<BasicDBObject> collection = database.getCollection(SNAPSHOT_COLLECTION,
        BasicDBObject.class);
      return new MongoDBSnapshotStore(collection);
  }

  /**
   * Construct a new snapshots store.
   *
   * @param database the database connection object
   */
  protected MongoDBSnapshotStore(MongoCollection<BasicDBObject> collection) {
    this.collection = collection;
  }

  protected void deleteSnapshot(WaveletName waveletName) throws PersistenceException {

    BasicDBObject criteria = new BasicDBObject();
    criteria.put(WAVE_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletName.waveId));
    criteria.put(WAVELET_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletName.waveletId));

    try {
      // Using Journaled Write Concern
      // (http://docs.mongodb.org/manual/core/write-concern/#journaled)
      collection.withWriteConcern(WriteConcern.JOURNALED).deleteMany(criteria);
    } catch (MongoException e) {
      throw new PersistenceException(e);
    }
  }

  /**
   * Store a snapshot
   *
   * @param waveletData
   * @param hashedVersion
   * @throws PersistenceException
   */
  public void store(ReadableWaveletData waveletData) throws PersistenceException {

    String waveId = ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletData.getWaveId());
    String waveletId = ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletData.getWaveletId());

    // store new snapshot
    BasicDBObject dbo = new BasicDBObject();
    dbo.put(WAVE_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletData.getWaveId()));
    dbo.put(WAVELET_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletData.getWaveletId()));

    dbo.put(VERSION_FIELD, waveletData.getHashedVersion().getVersion());
    dbo.put(VERSION_HASH_FIELD, waveletData.getHashedVersion().getHistoryHash());
    dbo.put(LASTMOD_FIELD,waveletData.getLastModifiedTime());

    WaveletSnapshot snapshot = SnapshotSerializer.serializeWavelet(waveletData, waveletData.getHashedVersion());
    dbo.put(SNAPSHOT_DATA,snapshot.toByteArray());

    try {
      collection.insertOne(dbo);
    } catch (MongoException e) {
      LOG.warning("Error storing wavelet snapshot for "+waveId+"/"+waveletId, e);
      throw new PersistenceException(e);
    }

    try {
        collection.deleteMany(Filters.and(
            Filters.eq(WAVE_ID_FIELD,
                ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletData.getWaveId())),
            Filters.eq(WAVELET_ID_FIELD,
                ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletData.getWaveletId())),
            Filters.lt(VERSION_FIELD, waveletData.getHashedVersion().getVersion())));

    } catch (MongoException e) {
      LOG.warning("Error deleting outdated wavelet snapshots for "+waveId+"/"+waveletId, e);
      throw new PersistenceException(e);
    }

    LOG.fine("Stored snaphost for "+waveId+"/"+waveletId+" version "+ waveletData.getHashedVersion().getVersion());
  }

  public DeltaStore.Snapshot load(WaveletName waveletName) throws PersistenceException {

    String waveId = ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletName.waveId);
    String waveletId = ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletName.waveletId);

    // find last snapshot stored
    DBObject query = new BasicDBObject();
    query.put(WAVE_ID_FIELD, waveId);
    query.put(WAVELET_ID_FIELD, waveletId);

    BasicDBObject snapshotDBObject = null;

    try {
      snapshotDBObject = collection.find(Filters.and(
          Filters.eq(WAVE_ID_FIELD, waveId),
          Filters.eq(WAVELET_ID_FIELD, waveletId))).first();
    } catch (MongoException e) {
      LOG.warning("Error querying wavelet snapshots for "+waveId+"/"+waveletId, e);
      throw new PersistenceException(e);
    }

    if (snapshotDBObject == null)
      return null;

    WaveletSnapshot snapshot = null;
    try {
      snapshot = WaveletSnapshot.parseFrom((byte[]) snapshotDBObject.get(SNAPSHOT_DATA));
    } catch (InvalidProtocolBufferException e) {
      throw new PersistenceException(e);
    }

    try {

      final WaveletData waveletData = SnapshotSerializer.deserializeWavelet(snapshot, waveletName.waveId);

      return new DeltaStore.Snapshot() {

        @Override
        public WaveletData getWaveletData() {

          return waveletData;
        }

      };

    } catch (OperationException e) {
      throw new PersistenceException(e);
    } catch (InvalidParticipantAddress e) {
      throw new PersistenceException(e);
    } catch (InvalidIdException e) {
      throw new PersistenceException(e);
    }
  }
}


text:
import { UserInterfaceActions, UserInterfaceActionTypes } from '../actions/user-interface.actions';

export const userInterfaceFeatureKey = 'userInterface';

export interface State {
  overlay: boolean;
  dialog: boolean;
  width: number;
  height: number;
}

export const initialState: State = {
  overlay: false,
  dialog: false,
  width: 640,
  height: 480,
};

export function reducer(state = initialState, action: UserInterfaceActions): State {
  switch (action.type) {
    case UserInterfaceActionTypes.Resize:
      return state;

    default:
      return state;
  }
}


text:
Rickshaw.namespace('Rickshaw.Graph.Socketio');

Rickshaw.Graph.Socketio = Rickshaw.Class.create( Rickshaw.Graph.Ajax, {
	request: function() {
		var socket = io.connect(this.dataURL);
		var self = this;
		socket.on('rickshaw', function (data) {
			self.success(data);
		});
	}
} );


text:
//Problem 9. Trapezoids

//Write an expression that calculates trapezoid's area by given sides a and b and height h.
//Examples:

//a	        b	    h	    area
//5	        7	    12	    72
//2	        1	    33	    49.5
//8.5	    4.3	    2.7	    17.28
//100	    200	    300	    45000
//0.222	    0.333	0.555	0.1540125

using System;
using System.Threading;

class Trapezoids
{
    static void Main()
    {
        string str;
        double a;
        double b;
        double h;
        Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

        do
        {
            Console.Write("Please enter a value for a: ");
            str = Console.ReadLine();
            Console.Clear();

        } while (!double.TryParse(str, out a));

        do
        {
            Console.Write("Please enter a value for b: ");
            str = Console.ReadLine();
            Console.Clear();

        } while (!double.TryParse(str, out b));

        do
        {
            Console.Write("Please enter a value for h: ");
            str = Console.ReadLine();
            Console.Clear();

        } while (!double.TryParse(str, out h));

        double area = ((a + b) / 2) * h;

        Console.WriteLine("The area of a trapezoid with sides {0}, {1} and height {2}, is: {3}", a, b, h, area);
    }
}


text:
#pragma once

#include <boost/endian/buffers.hpp>
#include <span>
#include <string>
#include <vector>

// sizeof 0x18
struct MetadataBlockHeader {
  // Flags:
  // 0x00400000 - Area header
  // 0x00800000 - Root area
  // 0x20000000 - leaf directory tree
  // 0x40000000 - ?
  // 0x80000000 - Directory?
  enum Flags {
    AREA = 0x00400000,
    ROOT_AREA = 0x00800000,
    EXTERNAL_DIRECTORY_TREE = 0x20000000,
    DIRECTORY = 0x80000000,
  };
  boost::endian::big_uint32_buf_t block_flags;  // 20 least bits ignored
  boost::endian::big_uint8_buf_t hash[20];
};
static_assert(sizeof(MetadataBlockHeader) == 0x18, "Incorrect sizeof MetadataBlockHeader");

// sizeof 0x18
struct DataBlockMetadata {
  boost::endian::big_uint32_buf_t block_number;
  boost::endian::big_uint8_buf_t hash[20];
};
static_assert(sizeof(DataBlockMetadata) == 0x18, "Incorrect sizeof DataBlockMetadata");

// sizeof 0xa4
struct DataBlocksClusterMetadata {
  boost::endian::big_uint32_buf_t block_number;
  boost::endian::big_uint8_buf_t hash[8][20];
};
static_assert(sizeof(DataBlocksClusterMetadata) == 0xa4, "Incorrect sizeof DataBlocksClusterMetadata");

// sizeof 0xc
struct Permissions {
  boost::endian::big_uint32_buf_t owner;
  boost::endian::big_uint32_buf_t group;
  boost::endian::big_uint32_buf_t mode;
};
static_assert(sizeof(Permissions) == 0xc, "Incorrect sizeof Permissions");

// sizeof 0x2c
struct Attributes {
  enum Flags {
    UNENCRYPTED_FILE = 0x2000000,
    LINK = 0x4000000,
    AREA_SIZE_BASIC = 0x10000000,
    AREA_SIZE_REGULAR = 0x20000000,
    QUOTA = 0x40000000,
    DIRECTORY = 0x80000000,
  };
  boost::endian::big_uint32_buf_t flags;
  boost::endian::big_uint32_buf_t size_on_disk;
  boost::endian::big_uint32_buf_t ctime;
  boost::endian::big_uint32_buf_t mtime;
  boost::endian::big_uint32_buf_t unknown;  // TODO: ????
  union {
    boost::endian::big_uint32_buf_t size;          // for file
    boost::endian::big_uint32_buf_t blocks_count;  // for quota
  };
  boost::endian::big_uint32_buf_t directory_block_number;  // in case of directory
  Permissions permissions;
  boost::endian::big_uint8_buf_t entry_log2_size;  // log2 size of the whole entry, including this attributes
  boost::endian::big_uint8_buf_t size_category;    // 0-4, see File.c
  boost::endian::big_uint8_buf_t filename_length;
  boost::endian::big_uint8_buf_t case_bitmap;  // This byte in the struct also behave as padding, it isn't really a
                                               // byte, it is a bitmap of filename_length

  bool IsDirectory() { return !!(flags.value() & Flags::DIRECTORY); }
  bool IsFile() { return !IsDirectory(); }
  bool IsLink() { return !!(flags.value() & Flags::LINK); }

  size_t DataOffset();
};
static_assert(sizeof(Attributes) == 0x2C, "Incorrect sizeof Attributes");

// sizeof 0x48
struct WfsHeader {
  boost::endian::big_uint32_buf_t iv;           // most 2 bits are device type. 1-mlc/3-usb
  boost::endian::big_uint32_buf_t version;      // should be 0x01010800
  boost::endian::big_uint16_buf_t device_type;  // usb - 0x16a2. mlc - 0x136a?
  boost::endian::big_uint16_buf_t _pad;
  Attributes root_area_attributes;
  boost::endian::big_uint32_buf_t
      transactions_area_block_number;  // must be 6 or 12 (6*2, when regular block size used)
  boost::endian::big_uint32_buf_t root_area_blocks_count;
  boost::endian::big_uint32_buf_t unknown[2];  // not used??
};
static_assert(sizeof(WfsHeader) == 0x48, "Incorrect sizeof WfsHeader");

// sizof 0x8
struct WfsAreaFragmentInfo {
  boost::endian::big_uint32_buf_t block_number;
  boost::endian::big_uint32_buf_t blocks_count;
};
static_assert(sizeof(WfsAreaFragmentInfo) == 0x8, "Incorrect sizeof WfsAreaFragmentInfo");

// sizeof 0x60
struct WfsAreaHeader {
  enum class AreaType : uint8_t {
    RootArea = 0,
    QuotaArea = 1,
  };
  boost::endian::big_uint32_buf_t iv;  // used for blocks  encryption
  boost::endian::big_uint32_buf_t blocks_count;
  boost::endian::big_uint32_buf_t root_directory_block_number;  // is 6
  // Those two directories are not used. It was supposed to be some kind of refcount mechansism. not really sure.
  // But nothing uses it in the WiiU
  boost::endian::big_uint32_buf_t shadow_directory_block_number_1;  // is 4
  boost::endian::big_uint32_buf_t shadow_directory_block_number_2;  // is 5
  boost::endian::big_uint8_buf_t depth;                             // how many total parents area this area has
  boost::endian::big_uint8_buf_t log2_block_size;                   // 12/13
  boost::endian::big_uint8_buf_t log2_mega_block_size;              // mega block - 8 blocks. so 15/16
  boost::endian::big_uint8_buf_t log2_mega_blocks_cluster_size;     // mega blocks cluster - 8 mega blocks. so 18/19
  boost::endian::big_uint8_buf_t area_type;          // 0 - root area, 1 - data (not relavent for transactions area)
  boost::endian::big_uint8_buf_t maybe_always_zero;  // init to zero. doesn't seem to be changed by anything
  boost::endian::big_uint16_buf_t
      spare_blocks_count;  // in case of quota, how many spare blocks this area allocated beyond the quota. (parent area
                           // blocks, so in parent area block size)
  WfsAreaFragmentInfo first_fragments[8];  // On which blocks this area is spread on (if there aren't enough free
                                           // sequentials blocks it will framgnet the area). parent area blocks, so in
                                           // parent area block size. This list contains only the first 8 fragments
  boost::endian::big_uint32_buf_t fragments_log2_block_size;  // block size of parent area
};
static_assert(sizeof(WfsAreaHeader) == 0x60, "Incorrect sizeof WfsAreaHeader");

// sizof 0x8
struct WfsAreaFragmentsInfo {
  boost::endian::big_uint16_buf_t max_fragments_count;  // 480
  boost::endian::big_uint16_buf_t
      fragments_log2_block_size;  // block size of parent area. In root area it is the minimum block size (12)
  boost::endian::big_uint32_buf_t fragments_count;
  WfsAreaFragmentInfo fragments[480];  // On which blocks this area is spread on (if there aren't enough free
                                       // sequentials blocks it will framgnet the area). parent area blocks, so in
                                       // parent area block size.
};
static_assert(sizeof(WfsAreaFragmentsInfo) == 0xF08, "Incorrect sizeof WfsAreaFragmentsInfo");

struct WfsQuotaArea {
  WfsAreaHeader header;

  WfsAreaFragmentsInfo framgnets;
};
static_assert(sizeof(WfsQuotaArea) == 0x60 + 0xF08, "Incorrect sizeof WfsQuotaArea");

struct WfsTransactionsArea {
  WfsAreaHeader header;

  // This is the area that responsible for creating transaction when making changes to the file system (until the quota
  // is flushed to the disk).
  // Most of the structures of this area are known, but it isn't interesting since it is cleared every time the WiiU
  // mount the file system. (transactions from previous boot that weren't flushed to the disk are lost)
  boost::endian::big_uint8_buf_t unknown[0x3B4];
};
static_assert(sizeof(WfsTransactionsArea) == 0x60 + 0x3B4, "Incorrect sizeof WfsTransactionsArea");

struct SubBlockAllocatorFreeListEntry {
  boost::endian::big_uint16_buf_t unused;
  boost::endian::big_uint16_buf_t next;
  boost::endian::big_uint16_buf_t prev;
  boost::endian::big_uint16_buf_t log2_block_size;
};
static_assert(sizeof(SubBlockAllocatorFreeListEntry) == 0x8, "Incorrect sizeof SubBlockAllocatorFreeListEntry");

struct SubBlockAllocatorFreeList {
  boost::endian::big_uint16_buf_t free_blocks_count;
  boost::endian::big_uint16_buf_t head;  // head free block
};
static_assert(sizeof(SubBlockAllocatorFreeList) == 0x4, "Incorrect sizeof SubBlockAllocatorFreeList");

struct SubBlockAllocatorStruct {
  SubBlockAllocatorFreeList free_list[8];  // for sizes 1<<3-10
  boost::endian::big_uint16_buf_t root;
  boost::endian::big_uint16_buf_t records_count;
};
static_assert(sizeof(SubBlockAllocatorStruct) == 0x24, "Incorrect sizeof SubBlockAllocatorStruct");

struct DirectoryTreeNode {
  boost::endian::big_uint8_buf_t prefix_length;
  boost::endian::big_uint8_buf_t choices_count;

 public:
  std::string prefix() { return {&reinterpret_cast<char*>(this)[sizeof(*this)], prefix_length.value()}; }
  std::span<std::byte> choices() {
    return {&reinterpret_cast<std::byte*>(this)[sizeof(*this) + prefix_length.value()], choices_count.value()};
  }
};
static_assert(sizeof(DirectoryTreeNode) == 0x2, "Incorrect sizeof DirectoryTreeNode");

struct ExternalDirectoryTreeNode : DirectoryTreeNode {
 private:
  size_t size();

 public:
  boost::endian::big_uint16_buf_t get_item(size_t index) {
    return reinterpret_cast<boost::endian::big_uint16_buf_t*>(reinterpret_cast<std::byte*>(this) +
                                                              size())[-static_cast<int>(index) - 1];
  }
};

struct InternalDirectoryTreeNode : DirectoryTreeNode {
 private:
  size_t size();

 public:
  boost::endian::big_uint16_buf_t get_item(size_t index) {
    return reinterpret_cast<boost::endian::big_uint16_buf_t*>(
        reinterpret_cast<std::byte*>(this) + size() -
        (choices()[0] == std::byte{0} ? 2 : 0))[-static_cast<int>(index) - 1];
  }
  boost::endian::big_uint32_buf_t get_next_allocator_block_number() {
    return reinterpret_cast<boost::endian::big_uint32_buf_t*>(reinterpret_cast<std::byte*>(this) + size())[-1];
  }
};


text:
`web` is the service responsible for serving static content for The Blue Alliance. Although `web` handles the majority of responsibility in The Blue Alliance's stack, it's responsibilities should be limited to serving web pages and read-only actions. Create or update actions should be delegate to other services.

# Configuration

## Setup Javascript Secrets

Components in `web` (GameDay, login, etc.) make calls to Firebase and need to have Firebase keys set in order to work properly. Keys are referenced from a `tba_keys.js` file. This file is not checked in to source control, but an template of the file is. You can copy the template and add your own keys to the file.

```
$ cp src/backend/web/static/javascript/tba_js/tba_keys_template.js src/backend/web/static/javascript/tba_js/tba_keys.js
```

Edit the fields specified in the file and save. If you're using the development container, make sure to sync this file to the container. Finally, [rebuild web resources](https://github.com/the-blue-alliance/the-blue-alliance/wiki/Development-Runbook#rebuilding-web-resources-javascript-css-etc) to compile the secrets file with the Javascript.

## Rebuilding Web Resources (JavaScript, CSS, etc.)

If you make changes to JavaScript or CSS files for the `web` service, you will have to recompile the files in order for the changes to show up in your browser. After syncing changes from your local environment to the development container, run the `run_buildweb.sh` script from inside the development container.

```
$ ./ops/build/run_buildweb.sh
```

# Development

## Redirects

Redirecting to a page via the `next` URL parameter is a pattern used in The Blue Alliance codebase. Since this `next` parameter can be modified by a user, caution should be taken to ensure the `next` parameter is redirecting back to The Blue Alliance as expected before redirecting the user. [`redirect`](https://github.com/the-blue-alliance/the-blue-alliance/blob/py3/src/backend/web/redirect.py) offers some helpful commands for safely redirecting.

| Method | Description |
| --- | --- |
| `is_safe_url` | Given a URL, check that the URL redirects back to the current host and is a HTTP URL. |
| `safe_next_redirect` | Get a redirect Response from the `next` parameter. If the `next` parameter is not valid, the Response will be a redirect to the given fallback URL. |

```python
from backend.web.redirect import is_safe_url

def route() -> Response:
    next = request.args.get("next")
    # Make sure `next` is safe - otherwise drop it
    next = next if is_safe_url(next) else None
    return make_response(render_template(..., next=next))
```

```python
from backend.web.redirect import safe_next_redirect

def logout() -> Response:
    # Do some logout stuff here. Redirect to the `next` page. Fallback to the index page.
    return safe_next_redirect("/")
```

## Passing Data Between Pages

In some cases, data might want to be passed between pages. For example, a form flow with multiple steps or an action that has a failure state might want to use the state from the previous page when loading the next page. This data can be passed using the [Flask session](https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions). Session data is stored cryptographically in cookies and is safe to store secret or privileged information for a given user.

```python
from flask import request, session

def route() -> Response:
    if request.method == "POST":
        error = some_failable_work()
        if error:
            session["route_error"] = "work_failed"

        return redirect(url_for("route"))

    return make_response(
        render_template(
            ..., status=session.pop("route_error", None)
        )
    )
```

## Forms + POST

The `web` service uses [Flask WTF to enable CSRF protection](https://flask-wtf.readthedocs.io/en/stable/csrf.html). Since The Blue Alliance does not leverage `FlaskForm`, the CSRF token must be passed manually via the form. Form POSTs to the `web` service without a CSRF token will throw an exception.

```html
<form method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>
```

## Authentication + User

### Authentication Decorators

Use the [authentication decorators]((https://github.com/the-blue-alliance/the-blue-alliance/blob/py3/src/backend/web/decorators.py)) to ensure proper permission for a user for a given route.

| Method | Description |
| --- | --- |
| `require_login` | Ensures that a user is currently logged in and registered. If the user is not logged in, this method will automatically redirect the user to the login page and after logging in will redirect the user back to the original page. If the user is not registered, this method will automatically redirect the user to the registration page and after registering will redirect the user back to the original page. |
| `require_login_only` | Like `require_login` but does not require that a user is registered. |
| `enforce_login` | Ensures that a user is currently logged in - otherwise, this method will throw a 401. |
| `require_admin` | Ensures that a user is an admin. If the user is not logged in, this method will automatically redirect the user to the login page and after logging in will redirect the user back to the original page. |
| `require_permission` | Ensures that a user has a given permission. If the user is not logged in, this method will automatically redirect the user to the login page and after logging in will redirect the user back to the original page. If the user does not have the given permission, this method will throw a 401. |
| `require_any_permission` | Ensures that a user has any of the given permission. If the user is not logged in, this method will automatically redirect the user to the login page and after logging in will redirect the user back to the original page. If the user does not have any of the given permission, this method will throw a 401. |

```python
from backend.web.decorators import require_login

@require_login
def route() -> str:
    return render_template(...)
```

### Getting a User object

See the [[common|common]] page for details on how to obtain a user object through `current_user()`. The `User` object from `current_user()` is available in the HTML templates via the `user` property. If being used on a page that is not gated behind an authentication decorator, this property may be null. If the route is protected via the authentication decorators, the `current_user()` call can be wrapped in a `none_throws` call to ensure the object is not `None`.

```python
from pyre_extensions import none_throws

from backend.common.auth import current_user
from backend.web.decorators import require_login

@require_login
def route() -> str:
    user = none_throws(current_user())
    return render_template(..., api_read_keys=user.api_read_keys)
```

```html
{% if user %}
    <p>Welcome back, {{ user.display_name }}</p>
{% else %}
    <a href="login">Login</a>
{% endif }
```

### Safe User Actions

Requests that act on user data or on behalf of a user should be careful that the executing user has the proper permissions to perform the requested action. As previously mentioned, POST requests should pass a `csrf_token`. Required information should be fetched for only the currently logged in user. In some cases, a POST request might pass a user ID using the `user.uid` property in the template to ensure that the user is acting upon their own data when the request is made when relying on the currently logged in user is not enough validation (ex: editing account info).

Ex: Consider deleting an API key. A form might POST the API key to delete. The query to fetch the API key to delete should fetch the API key for the passed API key identifier **for the currently logged in user**. Failing to query the API key scoped to the given user would allow any user to delete any API key, regardless of if they're the owner of the API key.

The `User` model exposes several methods and properties that fetch data scoped for the user, and are considered safe. These methods should be preferred as opposed to writing custom queries or logic.

### Stubbing `current_user` + `User` in Tests

A [`login_user`](https://github.com/the-blue-alliance/the-blue-alliance/blob/py3/src/backend/web/handlers/conftest.py#L32) pytest fixture is available for stubbing the `current_user` function. `current_user` will return a `User` [Mock](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock) that can be used for verifying functionality.

```python
def test_register_account(login_user) -> None:
    login_user.is_registered = False

    with patch.object(login_user, "register") as mock_register:
        ...

    mock_register.assert_called_with("Zach")
```


text:
class CommandInfo : public ICommand
{
public:
    CommandInfo();
    void read(char* c);
    bool execute();
};

#endif // COMMANDINFO_H


text:
module Resque
  # Helper for trapping signals.
  #
  #   Trap a signal (accepts same params as Signal#trap):
  #     SignalTrapper.trap('INT') { do_stuff }
  #   Trap a signal, but don't raise exception if unsupported signal:
  #     SignalTrapper.trap_or_warn('INT') { do_stuff }
  module SignalTrapper
    # A wrapper around Signal::trap
    # @see Signal::trap
    def self.trap(*args, &block)
      Signal.trap(*args, &block)
    end

    # Trap a signal, but don't raise exception if unsupported signal:
    # @see Signal::trap
    # @return [void]
    def self.trap_or_warn(*args, &block)
      trap(*args, &block)
    rescue ArgumentError => e
      warn e
    end
  end
end