text:
#pragma once
#include <aws/storagegateway/StorageGateway_EXPORTS.h>
#include <aws/storagegateway/StorageGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace StorageGateway
{
namespace Model
{

  /**
   *
CreateTapeWithBarcodeInput

See Also:
   AWS
   * API Reference

   */
  class AWS_STORAGEGATEWAY_API CreateTapeWithBarcodeRequest : public StorageGatewayRequest
  {
  public:
    CreateTapeWithBarcodeRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateTapeWithBarcode"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline const Aws::String& GetGatewayARN() const{ return m_gatewayARN; }

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline void SetGatewayARN(const Aws::String& value) { m_gatewayARNHasBeenSet = true; m_gatewayARN = value; }

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline void SetGatewayARN(Aws::String&& value) { m_gatewayARNHasBeenSet = true; m_gatewayARN = std::move(value); }

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline void SetGatewayARN(const char* value) { m_gatewayARNHasBeenSet = true; m_gatewayARN.assign(value); }

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline CreateTapeWithBarcodeRequest& WithGatewayARN(const Aws::String& value) { SetGatewayARN(value); return *this;}

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline CreateTapeWithBarcodeRequest& WithGatewayARN(Aws::String&& value) { SetGatewayARN(std::move(value)); return *this;}

    /**
     *
The unique Amazon Resource Name (ARN) that represents the gateway to
     * associate the virtual tape with. Use the ListGateways operation to return
     * a list of gateways for your account and region.

     */
    inline CreateTapeWithBarcodeRequest& WithGatewayARN(const char* value) { SetGatewayARN(value); return *this;}

    /**
     *
The size, in bytes, of the virtual tape that you want to create.
 <note>
     *
The size must be aligned by gigabyte (1024*1024*1024 byte).
 </note>
     */
    inline long long GetTapeSizeInBytes() const{ return m_tapeSizeInBytes; }

    /**
     *
The size, in bytes, of the virtual tape that you want to create.
 <note>
     *
The size must be aligned by gigabyte (1024*1024*1024 byte).
 </note>
     */
    inline void SetTapeSizeInBytes(long long value) { m_tapeSizeInBytesHasBeenSet = true; m_tapeSizeInBytes = value; }

    /**
     *
The size, in bytes, of the virtual tape that you want to create.
 <note>
     *
The size must be aligned by gigabyte (1024*1024*1024 byte).
 </note>
     */
    inline CreateTapeWithBarcodeRequest& WithTapeSizeInBytes(long long value) { SetTapeSizeInBytes(value); return *this;}

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline const Aws::String& GetTapeBarcode() const{ return m_tapeBarcode; }

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline void SetTapeBarcode(const Aws::String& value) { m_tapeBarcodeHasBeenSet = true; m_tapeBarcode = value; }

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline void SetTapeBarcode(Aws::String&& value) { m_tapeBarcodeHasBeenSet = true; m_tapeBarcode = std::move(value); }

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline void SetTapeBarcode(const char* value) { m_tapeBarcodeHasBeenSet = true; m_tapeBarcode.assign(value); }

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline CreateTapeWithBarcodeRequest& WithTapeBarcode(const Aws::String& value) { SetTapeBarcode(value); return *this;}

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline CreateTapeWithBarcodeRequest& WithTapeBarcode(Aws::String&& value) { SetTapeBarcode(std::move(value)); return *this;}

    /**
     *
The barcode that you want to assign to the tape.
 <note>
Barcodes
     * cannot be reused. This includes barcodes used for tapes that have been
     * deleted.
 </note>
     */
    inline CreateTapeWithBarcodeRequest& WithTapeBarcode(const char* value) { SetTapeBarcode(value); return *this;}

    /**
     *
True to use Amazon S3 server side encryption with your own AWS KMS key, or
     * false to use a key managed by Amazon S3. Optional.

     */
    inline bool GetKMSEncrypted() const{ return m_kMSEncrypted; }

    /**
     *
True to use Amazon S3 server side encryption with your own AWS KMS key, or
     * false to use a key managed by Amazon S3. Optional.

     */
    inline void SetKMSEncrypted(bool value) { m_kMSEncryptedHasBeenSet = true; m_kMSEncrypted = value; }

    /**
     *
True to use Amazon S3 server side encryption with your own AWS KMS key, or
     * false to use a key managed by Amazon S3. Optional.

     */
    inline CreateTapeWithBarcodeRequest& WithKMSEncrypted(bool value) { SetKMSEncrypted(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline const Aws::String& GetKMSKey() const{ return m_kMSKey; }

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline void SetKMSKey(const Aws::String& value) { m_kMSKeyHasBeenSet = true; m_kMSKey = value; }

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline void SetKMSKey(Aws::String&& value) { m_kMSKeyHasBeenSet = true; m_kMSKey = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline void SetKMSKey(const char* value) { m_kMSKeyHasBeenSet = true; m_kMSKey.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline CreateTapeWithBarcodeRequest& WithKMSKey(const Aws::String& value) { SetKMSKey(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline CreateTapeWithBarcodeRequest& WithKMSKey(Aws::String&& value) { SetKMSKey(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS KMS Key used for Amazon S3 server
     * side encryption. This value can only be set when KMSEncrypted is true.
     * Optional.

     */
    inline CreateTapeWithBarcodeRequest& WithKMSKey(const char* value) { SetKMSKey(value); return *this;}

  private:

    Aws::String m_gatewayARN;
    bool m_gatewayARNHasBeenSet;

    long long m_tapeSizeInBytes;
    bool m_tapeSizeInBytesHasBeenSet;

    Aws::String m_tapeBarcode;
    bool m_tapeBarcodeHasBeenSet;

    bool m_kMSEncrypted;
    bool m_kMSEncryptedHasBeenSet;

    Aws::String m_kMSKey;
    bool m_kMSKeyHasBeenSet;
  };

} // namespace Model
} // namespace StorageGateway
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
    <item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/abc_list_selector_disabled_holo_dark"/>
    <item android:state_focused="true" android:state_enabled="false" android:drawable="@drawable/abc_list_selector_disabled_holo_dark"/>
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/abc_list_selector_background_transition_holo_dark"/>
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/abc_list_selector_background_transition_holo_dark"/>
    <item android:state_focused="true" android:drawable="@drawable/abc_list_focused_holo"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8" ?>
<testSuite name="Ranking TestSuite" xmlns="http://NBi/TestSuite">
  <test name="With ranking top" uid="0000">
    <system-under-test>
      <resultSet>
        <query name="Select first departments">
          select row_count as DeptId, [Name], [GroupName] from [HumanResources].[Department] order by Name
        </query>
        <alteration>
          <filter>
            <ranking operand="#1">
              <top/>
            </ranking>
          </filter>
        </alteration>
      </resultSet>
    </system-under-test>
    <assert>
      <all-rows>
        <predicate name="ModDepId">
          <more-than or-equal="true">10</more-than>
        </predicate>
      </all-rows>
    </assert>
  </test>
  <test name="With ranking bottom, count and group-by with operand" uid="0001">
    <system-under-test>
      <resultSet>
        <query name="Select first departments">
          select row_count as DeptId, [Name], [GroupName] from [HumanResources].[Department] order by Name
        </query>
        <alteration>
          <filter>
            <ranking operand="#2">
              <bottom count="3"/>
              <group-by>
                <column identifier="#0" type="dateTime"/>
                <column identifier="#1"/>
              </group-by>
            </ranking>
          </filter>
        </alteration>
      </resultSet>
    </system-under-test>
    <assert>
      <all-rows>
        <predicate operand="ModDepId">
          <more-than or-equal="true">10</more-than>
        </predicate>
      </all-rows>
    </assert>
  </test>
  <test name="With ranking top, count and group-by case" uid="0002">
    <system-under-test>
      <result-set>
        <query name="Select first departments">
          select row_count as DeptId, [Name], [GroupName] from [HumanResources].[Department] order by Name
        </query>
        <alteration>
          <filter>
            <ranking operand="#2">
              <top count="3"/>
              <group-by>
                <case>
                  <predicate operand="#1">
                    <lower-case/>
                  </predicate>
                </case>
                <case>
                  <combination operator="and">
                    <predicate operand="#1">
                      <upper-case/>
                    </predicate>
                    <predicate operand="#0">
                      <less-than>10</less-than>
                    </predicate>
                  </combination>
                </case>
              </group-by>
            </ranking>
          </filter>
        </alteration>
      </result-set>
    </system-under-test>
    <assert>
      <all-rows>
        <predicate operand="ModDepId">
          <more-than or-equal="true">10</more-than>
        </predicate>
      </all-rows>
    </assert>
  </test>
</testSuite>


text:
package org.apache.maven.plugin.announcement;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.changes.ChangesXML;
import org.apache.maven.plugin.changes.IssueAdapter;
import org.apache.maven.plugin.changes.ProjectUtils;
import org.apache.maven.plugin.changes.ReleaseUtils;
import org.apache.maven.plugin.github.GitHubDownloader;
import org.apache.maven.plugin.github.GitHubIssueManagementSystem;
import org.apache.maven.plugin.issues.Issue;
import org.apache.maven.plugin.issues.IssueManagementSystem;
import org.apache.maven.plugin.issues.IssueUtils;
import org.apache.maven.plugin.jira.AbstractJiraDownloader;
import org.apache.maven.plugin.jira.AdaptiveJiraDownloader;
import org.apache.maven.plugin.jira.JIRAIssueManagmentSystem;
import org.apache.maven.plugin.trac.TracDownloader;
import org.apache.maven.plugin.trac.TracIssueManagmentSystem;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.changes.model.Release;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.tools.ToolManager;
import org.codehaus.plexus.util.ReaderFactory;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.velocity.VelocityComponent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Goal which generate an announcement from the announcement template.
 *
 * @author aramirez@exist.com
 * @version $Id$
 * @since 2.0-beta-2
 */
@Mojo( name = "announcement-generate", threadSafe = true )
public class AnnouncementMojo
    extends AbstractAnnouncementMojo
{
    private static final String CHANGES_XML = "changes.xml";

    private static final String JIRA = "JIRA";

    private static final String TRAC = "Trac";

    private static final String GIT_HUB = "GitHub";

    /**
     * The name of the file which will contain the generated announcement. If no value is specified the plugin will use
     * the name of the template.
     *
     * @since 2.4
     */
    @Parameter( property = "changes.announcementFile" )
    private String announcementFile;

    /**
     * Map of custom parameters for the announcement. This Map will be passed to the template.
     *
     * @since 2.1
     */
    @Parameter
    private Map announceParameters;

    /**
     */
    @Parameter( property = "project.artifactId", readonly = true )
    private String artifactId;

    /**
     * Name of the team that develops the artifact. This parameter will be passed to the template.
     */
    @Parameter( property = "changes.developmentTeam", defaultValue = "${project.name} team", required = true )
    private String developmentTeam;

    /**
     * The name of the artifact to be used in the announcement.
     */
    @Parameter( property = "changes.finalName", defaultValue = "${project.build.finalName}", required = true )
    private String finalName;

    /**
     */
    @Parameter( property = "project.groupId", readonly = true )
    private String groupId;

    /**
     * Short description or introduction of the released artifact. This parameter will be passed to the template.
     */
    @Parameter( defaultValue = "${project.description}" )
    private String introduction;

    /**
     * A list of issue management systems to fetch releases from. This parameter replaces the parameters
     * generateJiraAnnouncement and jiraMerge.
     *

     * Valid values are: changes.xml and JIRA.
     *

     * Note: Only one issue management system that is configured in
     * <project>/<issueManagement> can be used. This currently means that you can combine a changes.xml file
     * with one other issue management system.
     *
     * @since 2.4
     */
    @Parameter
    private List<String> issueManagementSystems;

    /**
     * Maps issues types to action types for grouping issues in announcements. If issue types are not defined for a
     * action type then the default issue type will be applied.
     *

     * Valid action types: add, fix and update.
     *

     *
     * @since 2.6
     */
    @Parameter
    private Map<String, String> issueTypes;

    /**
     * Directory where the announcement file will be generated.
     *
     * @since 2.10
     */
    @Parameter( defaultValue = "${project.build.directory}/announcement", required = true )
    private File announcementDirectory;

    /**
     * Directory where the announcement file will be generated.
     *
     * @deprecated Starting with version 2.10 this parameter is no longer used. You must use
     *             {@link #announcementDirectory} instead.
     */
    @Parameter
    private File outputDirectory;

    /**
     * Packaging structure for the artifact.
     */
    @Parameter( property = "project.packaging", readonly = true )
    private String packaging;

    /**
     * The Maven Project.
     */
    @Parameter( defaultValue = "${project}", readonly = true, required = true )
    private MavenProject project;

    /**
     * The Velocity template used to format the announcement.
     */
    @Parameter( property = "changes.template", defaultValue = "announcement.vm", required = true )
    private String template;

    /**
     * Directory that contains the template.
     *

     * Note: This directory must be a subdirectory of
     * /src/main/resources/ or current project base directory.
     *

     */
    // CHECKSTYLE_OFF: LineLength
    @Parameter( property = "changes.templateDirectory", defaultValue = "org/apache/maven/plugin/announcement", required = true )
    private String templateDirectory;
    // CHECKSTYLE_ON: LineLength

    /**
     * The template encoding.
     *
     * @since 2.1
     */
    @Parameter( property = "changes.templateEncoding", defaultValue = "${project.build.sourceEncoding}" )
    private String templateEncoding;

    /**
     * Use the JIRA query language instead of the JIRA query based on HTTP parameters. From JIRA 5.1 and up only JQL is
     * supported. JIRA 4.4 supports both JQL and URL parameter based queries. From 5.1.1 this is obsolete, since REST
     * queries only use JQL.
     *
     * @since 2.10
     */
    @Parameter( property = "changes.useJql", defaultValue = "false" )
    private boolean useJql;

    /**
     * Distribution URL of the artifact. This parameter will be passed to the template.
     */
    @Parameter( property = "project.url" )
    private String url;

    /**
     * URL where the artifact can be downloaded. If not specified, no URL is used. This parameter will be passed to the
     * template.
     */
    @Parameter
    private String urlDownload;

    /**
     * Velocity Component.
     */
    @Component( role = VelocityComponent.class, hint = "maven-changes-plugin" )
    private VelocityComponent velocity;

    /**
     * Version of the artifact.
     */
    @Parameter( property = "changes.version", defaultValue = "${project.version}", required = true )
    private String version;

    /**
     * The path of the changes.xml file.
     *
     * @parameter expression="${basedir}/src/changes/changes.xml"
     * @required
     */
    @Parameter( defaultValue = "${basedir}/src/changes/changes.xml" )
    private File xmlPath;

    // =======================================//
    // JIRA-Announcement Needed Parameters //
    // =======================================//

    /**
     * Defines the filter parameters to restrict which issues are retrieved from JIRA. The filter parameter uses the
     * same format of url parameters that is used in a JIRA search.
     *
     * @since 2.4
     */
    @Parameter( defaultValue = "" )
    private String filter;

    /**
     * Flag to determine if the plugin will generate a JIRA announcement.
     *
     * @deprecated Since version 2.4 this parameter has been deprecated. Please use the issueManagementSystems parameter
     *             instead.
     */
    @Parameter( property = "generateJiraAnnouncement", defaultValue = "false", required = true )
    private boolean generateJiraAnnouncement;

    /**
     * If releases from JIRA should be merged with the releases from a changes.xml file.
     *
     * @since 2.1
     * @deprecated Since version 2.4 this parameter has been deprecated. Please use the issueManagementSystems parameter
     *             instead.
     */
    @Parameter( property = "changes.jiraMerge", defaultValue = "false" )
    private boolean jiraMerge;

    /**
     * Defines the JIRA password for authentication into a private JIRA installation.
     *
     * @since 2.1
     */
    @Parameter( property = "changes.jiraPassword", defaultValue = "" )
    private String jiraPassword;

    /**
     * Defines the JIRA username for authentication into a private JIRA installation.
     *
     * @since 2.1
     */
    @Parameter( property = "changes.jiraUser", defaultValue = "" )
    private String jiraUser;

    /**
     * Path to the JIRA XML file, which will be parsed.
     */
    @Parameter( defaultValue = "${project.build.directory}/jira-announcement.xml", required = true, readonly = true )
    private File jiraXML;

    /**
     * The maximum number of issues to fetch from JIRA.
     *

     * Note: In versions 2.0-beta-3 and earlier this parameter was called "nbEntries".
     *

     */
    @Parameter( property = "changes.maxEntries", defaultValue = "25", required = true )
    private int maxEntries;

    /**
     * Include issues from JIRA with these resolution ids. Multiple resolution ids can be specified as a comma separated
     * list of ids.
     *

     * Note: In versions 2.0-beta-3 and earlier this parameter was called "resolutionId".
     *

     */
    @Parameter( property = "changes.resolutionIds", defaultValue = "Fixed" )
    private String resolutionIds;

    /**
     * Settings XML configuration.
     */
    @Parameter( defaultValue = "${settings}", readonly = true, required = true )
    private Settings settings;

    /**
     * Include issues from JIRA with these status ids. Multiple status ids can be specified as a comma separated list of
     * ids.
     *

     * Note: In versions 2.0-beta-3 and earlier this parameter was called "statusId".
     *

     */
    @Parameter( property = "changes.statusIds", defaultValue = "Closed" )
    private String statusIds;

    /**
     * Defines the http user for basic authentication into the JIRA webserver.
     *
     * @since 2.4
     */
    @Parameter( property = "changes.webUser", defaultValue = "" )
    private String webUser;

    /**
     * Defines the http password for basic authentication into the JIRA webserver.
     *
     * @since 2.4
     */
    @Parameter( property = "changes.webPassword", defaultValue = "" )
    private String webPassword;

    /**
     * The prefix used when naming versions in JIRA.
     *

     * If you have a project in JIRA with several components that have different release cycles, it is an often used
     * pattern to prefix the version with the name of the component, e.g. maven-filtering-1.0 etc. To fetch issues from
     * JIRA for a release of the "maven-filtering" component you would need to set this parameter to "maven-filtering-".
     *

     *
     * @since 2.5
     */
    @Parameter( property = "changes.versionPrefix", defaultValue = "" )
    private String versionPrefix;

    /**
     * Defines the connection timeout in milliseconds when accessing JIRA's REST-API.
     *

     * Might help when you have a lot of different resolutions in your JIRA instance.
     *

     *
     * @since 2.11
     */
    @Parameter( property = "changes.jiraConnectionTimeout", defaultValue = "36000" )
    private int jiraConnectionTimeout;

    /**
     * Defines the receive timeout in milliseconds when accessing JIRA's REST-API.
     *

     * Might help when you have a lot of different resolutions in your JIRA instance.
     *

     *
     * @since 2.11
     */
    @Parameter( property = "changes.jiraReceiveTimout", defaultValue = "32000" )
    private int jiraReceiveTimout;

    // =======================================//
    // Trac Parameters //
    // =======================================//

    /**
     * Defines the Trac password for authentication into a private Trac installation.
     *
     * @since 2.4
     */
    @Parameter( property = "changes.tracPassword", defaultValue = "" )
    private String tracPassword;

    /**
     * Defines the Trac query for searching for tickets.
     *
     * @since 2.4
     */
    @Parameter( defaultValue = "order=id" )
    private String tracQuery;

    /**
     * Defines the Trac username for authentication into a private Trac installation.
     *
     * @since 2.4
     */
    @Parameter( property = "changes.tracUser", defaultValue = "" )
    private String tracUser;

    // =======================================//
    // Github Parameters //
    // =======================================//

    /**
     * The scheme of your github api domain. Only use if using github enterprise.
     *
     * @since 2.9
     */
    @Parameter( defaultValue = "http", property = "changes.githubAPIScheme" )
    private String githubAPIScheme;

    /**
     * The port of your github api domain. Only use if using github enterprise.
     *
     * @since 2.9
     */
    @Parameter( defaultValue = "80", property = "changes.githubAPIPort" )
    private int githubAPIPort;

    /**
     * The settings.xml server id to be used to authenticate into github api domain. Only use if using github
     * enterprise.
     *
     * @since 2.12
     */
    @Parameter( defaultValue = "github" )
    private String githubAPIServerId;

    private ReleaseUtils releaseUtils = new ReleaseUtils( getLog() );

    private ChangesXML xml;

    // =======================================//
    // announcement-generate execution //
    // =======================================//

    /**
     * Generate the template
     *
     * @throws MojoExecutionException
     */
    public void execute()
        throws MojoExecutionException
    {
        // Fail build fast if it is using deprecated parameters
        if ( outputDirectory != null )
        {
            throw new MojoExecutionException( "You are using the old parameter 'outputDirectory'. "
                + "You must use 'announcementDirectory' instead." );
        }

        // Run only at the execution root
        if ( runOnlyAtExecutionRoot && !isThisTheExecutionRoot() )
        {
            getLog().info( "Skipping the announcement generation in this project because it's not the Execution Root" );
        }
        else
        {
            if ( issueManagementSystems == null )
            {
                issueManagementSystems = new ArrayList<String>();
            }

            // Handle deprecated parameters, in a backward compatible way
            if ( issueManagementSystems.isEmpty() )
            {
                if ( this.jiraMerge )
                {
                    issueManagementSystems.add( CHANGES_XML );
                    issueManagementSystems.add( JIRA );
                }
                else if ( generateJiraAnnouncement )
                {
                    issueManagementSystems.add( JIRA );
                }
                else
                {
                    issueManagementSystems.add( CHANGES_XML );
                }
            }

            // Fetch releases from the configured issue management systems
            List<Release> releases = null;
            if ( issueManagementSystems.contains( CHANGES_XML ) )
            {
                if ( getXmlPath().exists() )
                {
                    ChangesXML changesXML = new ChangesXML( getXmlPath(), getLog() );
                    List<Release> changesReleases = releaseUtils.convertReleaseList( changesXML.getReleaseList() );
                    releases = releaseUtils.mergeReleases( null, changesReleases );
                    getLog().info( "Including issues from file " + getXmlPath() + " in announcement..." );
                }
                else
                {
                    getLog().warn( "changes.xml file " + getXmlPath().getAbsolutePath() + " does not exist." );
                }
            }

            if ( issueManagementSystems.contains( JIRA ) )
            {
                if ( ProjectUtils.validateIfIssueManagementComplete( project, JIRA, "JIRA announcement", getLog() ) )
                {
                    List<Release> jiraReleases = getJiraReleases();
                    releases = releaseUtils.mergeReleases( releases, jiraReleases );
                    getLog().info( "Including issues from JIRA in announcement..." );
                }
                else
                {
                    throw new MojoExecutionException( "Something is wrong with the Issue Management section. "
                        + "See previous error messages." );
                }
            }

            if ( issueManagementSystems.contains( TRAC ) )
            {
                if ( ProjectUtils.validateIfIssueManagementComplete( project, TRAC, "Trac announcement", getLog() ) )
                {
                    List<Release> tracReleases = getTracReleases();
                    releases = releaseUtils.mergeReleases( releases, tracReleases );
                    getLog().info( "Including issues from Trac in announcement..." );
                }
                else
                {
                    throw new MojoExecutionException( "Something is wrong with the Issue Management section. "
                        + "See previous error messages." );
                }
            }

            if ( issueManagementSystems.contains( GIT_HUB ) )
            {
                if ( ProjectUtils.validateIfIssueManagementComplete( project, GIT_HUB, "GitHub announcement",
                                                                     getLog() ) )
                {
                    List<Release> gitHubReleases = getGitHubReleases();
                    releases = releaseUtils.mergeReleases( releases, gitHubReleases );
                    getLog().info( "Including issues from GitHub in announcement..." );
                }
                else
                {
                    throw new MojoExecutionException( "Something is wrong with the Issue Management section. "
                        + "See previous error messages." );
                }
            }

            // @todo Add more issue management systems here.

            // Follow these steps:
            // 1. Add a constant for the name of the issue management system
            // 2. Add the @parameters needed to configure the issue management system
            // 3. Add a protected List get<IMSname>Releases() method that retrieves a list of releases
            // 4. Merge those releases into the "releases" variable
            // For help with these steps, you can have a look at how this has been done for JIRA or Trac

            // Generate the report
            if ( releases == null || releases.isEmpty() )
            {
                throw new MojoExecutionException( "No releases found in any of the "
                    + "configured issue management systems." );
            }
            else
            {
                doGenerate( releases );
            }
        }
    }

    /**
     * Add the parameters to velocity context
     *
     * @param releases A List of Releases
     * @throws MojoExecutionException
     */
    public void doGenerate( List<Release> releases )
        throws MojoExecutionException
    {
        String version = ( versionPrefix == null ? "" : versionPrefix ) + getVersion();

        getLog().debug( "Generating announcement for version [" + version + "]. Found these releases: "
            + ReleaseUtils.toString( releases ) );

        doGenerate( releases, releaseUtils.getLatestRelease( releases, version ) );
    }

    protected void doGenerate( List<Release> releases, Release release )
        throws MojoExecutionException
    {
        try
        {
            ToolManager toolManager = new ToolManager( true );
            Context context = toolManager.createContext();

            if ( getIntroduction() == null || getIntroduction().equals( "" ) )
            {
                setIntroduction( getUrl() );
            }

            context.put( "releases", releases );

            context.put( "groupId", getGroupId() );

            context.put( "artifactId", getArtifactId() );

            context.put( "version", getVersion() );

            context.put( "packaging", getPackaging() );

            context.put( "url", getUrl() );

            context.put( "release", release );

            context.put( "introduction", getIntroduction() );

            context.put( "developmentTeam", getDevelopmentTeam() );

            context.put( "finalName", getFinalName() );

            context.put( "urlDownload", getUrlDownload() );

            context.put( "project", project );

            if ( announceParameters == null )
            {
                // empty Map to prevent NPE in velocity execution
                context.put( "announceParameters", Collections.EMPTY_MAP );
            }
            else
            {
                context.put( "announceParameters", announceParameters );
            }

            processTemplate( context, announcementDirectory, template, announcementFile );
        }
        catch ( ResourceNotFoundException rnfe )
        {
            throw new MojoExecutionException( "Resource not found.", rnfe );
        }
        catch ( VelocityException ve )
        {
            throw new MojoExecutionException( ve.toString(), ve );
        }
    }

    /**
     * Create the velocity template
     *
     * @param context velocity context that has the parameter values
     * @param outputDirectory directory where the file will be generated
     * @param template velocity template which will the context be merged
     * @param announcementFile The file name of the generated announcement
     * @throws ResourceNotFoundException, VelocityException, IOException
     */
    public void processTemplate( Context context, File outputDirectory, String template, String announcementFile )
        throws VelocityException, MojoExecutionException
    {
        File f;

        // Use the name of the template as a default value
        if ( StringUtils.isEmpty( announcementFile ) )
        {
            announcementFile = template;
        }

        try
        {
            f = new File( outputDirectory, announcementFile );

            if ( !f.getParentFile().exists() )
            {
                f.getParentFile().mkdirs();
            }

            VelocityEngine engine = velocity.getEngine();

            engine.setApplicationAttribute( "baseDirectory", basedir );

            if ( StringUtils.isEmpty( templateEncoding ) )
            {
                templateEncoding = ReaderFactory.FILE_ENCODING;
                getLog().warn( "File encoding has not been set, using platform encoding " + templateEncoding
                    + ", i.e. build is platform dependent!" );
            }

            Writer writer = new OutputStreamWriter( new FileOutputStream( f ), templateEncoding );

            Template velocityTemplate = engine.getTemplate( templateDirectory + "/" + template, templateEncoding );

            velocityTemplate.merge( context, writer );

            writer.flush();

            writer.close();

            getLog().info( "Created template " + f );
        }

        catch ( ResourceNotFoundException rnfe )
        {
            throw new ResourceNotFoundException( "Template not found. ( " + templateDirectory + "/" + template + " )" );
        }
        catch ( VelocityException ve )
        {
            throw new VelocityException( ve.toString() );
        }

        catch ( Exception e )
        {
            if ( e.getCause() != null )
            {
                getLog().warn( e.getCause() );
            }
            throw new MojoExecutionException( e.toString(), e.getCause() );
        }
    }

    protected List<Release> getJiraReleases()
        throws MojoExecutionException
    {
        AbstractJiraDownloader jiraDownloader = new AdaptiveJiraDownloader();

        File jiraXMLFile = jiraXML;

        jiraDownloader.setLog( getLog() );

        jiraDownloader.setOutput( jiraXMLFile );

        jiraDownloader.setStatusIds( statusIds );

        jiraDownloader.setResolutionIds( resolutionIds );

        jiraDownloader.setMavenProject( project );

        jiraDownloader.setSettings( settings );

        jiraDownloader.setNbEntries( maxEntries );

        jiraDownloader.setFilter( filter );

        jiraDownloader.setJiraUser( jiraUser );

        jiraDownloader.setJiraPassword( jiraPassword );

        jiraDownloader.setUseJql( useJql );

        jiraDownloader.setWebUser( webUser );

        jiraDownloader.setWebPassword( webPassword );

        jiraDownloader.setConnectionTimeout( jiraConnectionTimeout );

        jiraDownloader.setReceiveTimout( jiraReceiveTimout );

        try
        {
            jiraDownloader.doExecute();

            List<Issue> issueList = jiraDownloader.getIssueList();

            if ( StringUtils.isNotEmpty( versionPrefix ) )
            {
                int originalNumberOfIssues = issueList.size();
                issueList = IssueUtils.filterIssuesWithVersionPrefix( issueList, versionPrefix );
                getLog().debug( "Filtered out " + issueList.size() + " issues of " + originalNumberOfIssues
                    + " that matched the versionPrefix '" + versionPrefix + "'." );
            }

            return getReleases( issueList, new JIRAIssueManagmentSystem() );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( "Failed to extract issues from JIRA.", e );
        }
    }

    private List<Release> getReleases( List<Issue> issues, IssueManagementSystem ims )
        throws MojoExecutionException
    {
        if ( issueTypes != null )
        {
            ims.applyConfiguration( issueTypes );
        }
        if ( issues.isEmpty() )
        {
            return Collections.emptyList();
        }
        else
        {
            IssueAdapter adapter = new IssueAdapter( ims );
            return adapter.getReleases( issues );
        }
    }

    protected List<Release> getTracReleases()
        throws MojoExecutionException
    {
        TracDownloader issueDownloader = new TracDownloader();

        issueDownloader.setProject( project );

        issueDownloader.setQuery( tracQuery );

        issueDownloader.setTracPassword( tracPassword );

        issueDownloader.setTracUser( tracUser );

        try
        {
            return getReleases( issueDownloader.getIssueList(), new TracIssueManagmentSystem() );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( "Failed to extract issues from Trac.", e );
        }
    }

    protected List<Release> getGitHubReleases()
        throws MojoExecutionException
    {
        try
        {
            GitHubDownloader issueDownloader =
                new GitHubDownloader( project, githubAPIScheme, githubAPIPort, false, true );

            issueDownloader.configureAuthentication( githubAPIServerId, settings, getLog() );

            return getReleases( issueDownloader.getIssueList(), new GitHubIssueManagementSystem() );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( "Failed to extract issues from GitHub.", e );
        }
    }

    /*
     * accessors
     */

    public String getArtifactId()
    {
        return artifactId;
    }

    public void setArtifactId( String artifactId )
    {
        this.artifactId = artifactId;
    }

    public String getDevelopmentTeam()
    {
        return developmentTeam;
    }

    public void setDevelopmentTeam( String developmentTeam )
    {
        this.developmentTeam = developmentTeam;
    }

    public String getFinalName()
    {
        return finalName;
    }

    public void setFinalName( String finalName )
    {
        this.finalName = finalName;
    }

    public String getGroupId()
    {
        return groupId;
    }

    public void setGroupId( String groupId )
    {
        this.groupId = groupId;
    }

    public String getIntroduction()
    {
        return introduction;
    }

    public void setIntroduction( String introduction )
    {
        this.introduction = introduction;
    }

    public void setIssueTypes( Map<String, String> issueTypes )
    {
        this.issueTypes = issueTypes;
    }

    public Map<String, String> getIssueTypes()
    {
        return issueTypes;
    }

    public File getAnnouncementDirectory()
    {
        return announcementDirectory;
    }

    public void setAnnouncementDirectory( File announcementDirectory )
    {
        this.announcementDirectory = announcementDirectory;
    }

    public String getPackaging()
    {
        return packaging;
    }

    public void setPackaging( String packaging )
    {
        this.packaging = packaging;
    }

    public String getUrl()
    {
        return url;
    }

    public void setUrl( String url )
    {
        this.url = url;
    }

    public String getUrlDownload()
    {
        return urlDownload;
    }

    public void setUrlDownload( String urlDownload )
    {
        this.urlDownload = urlDownload;
    }

    public VelocityComponent getVelocity()
    {
        return velocity;
    }

    public void setVelocity( VelocityComponent velocity )
    {
        this.velocity = velocity;
    }

    public String getVersion()
    {
        return version;
    }

    public void setVersion( String version )
    {
        this.version = version;
    }

    public ChangesXML getXml()
    {
        return xml;
    }

    public void setXml( ChangesXML xml )
    {
        this.xml = xml;
    }

    public File getXmlPath()
    {
        return xmlPath;
    }

    public void setXmlPath( File xmlPath )
    {
        this.xmlPath = xmlPath;
    }
}


text:
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Controllers for the form builder test page.
 */

oppia.directive('formOverlay', ['recursionHelper', function(recursionHelper) {
  return {
    scope: {
      definition: '=',
      isDisabled: '&',
      savedValue: '='
    },
    templateUrl: 'formOverlay/entryPoint',
    restrict: 'E',
    compile: recursionHelper.compile,
    controller: ['$scope', function($scope) {
      $scope.$watch('savedValue', function() {
        $scope.localValue = angular.copy($scope.savedValue);
      });

      $scope.submitValue = function() {
        $scope.savedValue = angular.copy($scope.localValue);
        alert($scope.savedValue);
      };
      $scope.cancelEdit = function() {
        $scope.localValue = angular.copy($scope.savedValue);
      };
    }]
  };
}]);

oppia.controller('FormBuilderTests', [
  '$scope', function($scope) {
    $scope.testText = 'abc{{paramUnicode1}}';

    $scope.unicodeForm = {
      schema: {
        type: 'unicode'
      },
      value: 'aab{{paramUnicode1}}'
    };

    $scope.booleanForms = [{
      name: 'Boolean form',
      schema: {
        type: 'bool'
      },
      value: true
    }];

    $scope.intForms = [{
      name: 'Integer form (value must be greater than 2)',
      schema: {
        type: 'int',
        validators: [{
          id: 'is_at_least',
          min_value: 2
        }]
      },
      value: 3
    }];

    $scope.floatForms = [{
      name: 'Float form (value must be between -3 and 6)',
      schema: {
        type: 'float',
        validators: [{
          id: 'is_at_least',
          min_value: -3.0
        }, {
          id: 'is_at_most',
          max_value: 6.0
        }]
      },
      value: 3.14
    }];

    $scope.unicodeForms = [{
      name: 'Restricted unicode form; the value must be either a or b.',
      schema: {
        type: 'unicode',
        choices: ['a', 'b']
      },
      value: 'a'
    }];

    $scope.htmlForms = [{
      name: 'HTML form',
      schema: {
        type: 'html'
      },
      value: 'Some HTML'
    }];

    $scope.compositeForms = [{
      name: (
        'Dict with a bool, a unicode string and a list of ints. ' +
        'The string must be either \'abc\' or \'def\'.'),
      schema: {
        type: 'dict',
        properties: [{
          name: 'a_unicode_string_appearing_first',
          description: 'First field.',
          schema: {
            type: 'unicode',
            choices: ['abc', 'def']
          }
        }, {
          name: 'a_list_appearing_second',
          description: 'Second field.',
          schema: {
            type: 'list',
            items: {
              type: 'int'
            }
          }
        }, {
          name: 'a_boolean_appearing_last',
          description: 'Third field.',
          schema: {
            type: 'bool'
          }
        }]
      },
      value: {
        a_boolean_appearing_last: false,
        a_unicode_string_appearing_first: 'abc',
        a_list_appearing_second: [2, 3]
      }
    }, {
      name: 'List of code areas with custom \'add element\' text',
      schema: {
        type: 'list',
        items: {
          type: 'unicode',
          ui_config: {
            coding_mode: 'python'
          }
        },
        ui_config: {
          add_element_text: '[Custom \'add element\' text]'
        }
      },
      value: ['abc', 'def', 'ghi']
    }, {
      name: 'Fixed-length list of 2 multiple-choice floats',
      schema: {
        type: 'list',
        items: {
          type: 'float',
          choices: [1.0, 0.0, -1.0, -2.0, -3.0]
        },
        len: 2
      },
      value: [1.0, -3.0]
    }, {
      name: 'List of complex items (no descriptions in the dicts)',
      schema: {
        type: 'list',
        items: {
          type: 'dict',
          properties: [{
            name: 'intField',
            schema: {
              type: 'int'
            }
          }, {
            name: 'htmlField',
            schema: {
              type: 'html'
            }
          }]
        }
      },
      value: [{
        intField: 5,
        htmlField: 'def'
      }]
    }, {
      name: 'Nested lists',
      schema: {
        type: 'list',
        items: {
          type: 'list',
          items: {
            type: 'unicode'
          }
        }
      },
      value: [['abc'], ['def', 'ghi']]
    }];

    $scope.formsets = [{
      name: 'Boolean editors',
      forms: $scope.booleanForms
    }, {
      name: 'Integer editors',
      forms: $scope.intForms
    }, {
      name: 'Float editors',
      forms: $scope.floatForms
    }, {
      name: 'Unicode editors',
      forms: $scope.unicodeForms
    }, {
      name: 'HTML editors',
      forms: $scope.htmlForms
    }, {
      name: 'Composite editors',
      forms: $scope.compositeForms
    }];
  }
]);


text:
<?php
namespace Vispanlab\UserBundle\Security\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;

class TEIUserToken extends AbstractToken
{
    public $created;
    public $digest;
    public $nonce;

    public function __construct(array $roles = array())
    {
        parent::__construct($roles);

        // If the user has roles, consider it authenticated
        $this->setAuthenticated(count($roles) > 0);
    }

    public function getCredentials()
    {
        return '';
    }
}


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/ReentrantMonitor.h"

#include "ImageLayers.h"
#include "BasicLayers.h"
#include "gfxImageSurface.h"

#ifdef XP_MACOSX
#include "gfxQuartzImageSurface.h"
#endif

#include "cairo.h"

#include "gfxUtils.h"

#include "gfxPlatform.h"

using mozilla::ReentrantMonitor;

namespace mozilla {
namespace layers {

class BasicPlanarYCbCrImage : public PlanarYCbCrImage
{
public:
  BasicPlanarYCbCrImage(const gfxIntSize& aScaleHint, gfxImageFormat aOffscreenFormat, BufferRecycleBin *aRecycleBin)
    : PlanarYCbCrImage(aRecycleBin)
    , mScaleHint(aScaleHint)
    , mDelayedConversion(false)
  {
    SetOffscreenFormat(aOffscreenFormat);
  }

  ~BasicPlanarYCbCrImage()
  {
    if (mDecodedBuffer) {
      // Right now this only happens if the Image was never drawn, otherwise
      // this will have been tossed away at surface destruction.
      mRecycleBin->RecycleBuffer(mDecodedBuffer.forget(), mSize.height * mStride);
    }
  }

  virtual void SetData(const Data& aData);
  virtual void SetDelayedConversion(bool aDelayed) { mDelayedConversion = aDelayed; }

  already_AddRefed<gfxASurface> GetAsSurface();

private:
  nsAutoArrayPtr<uint8_t> mDecodedBuffer;
  gfxIntSize mScaleHint;
  int mStride;
  bool mDelayedConversion;
};

class BasicImageFactory : public ImageFactory
{
public:
  BasicImageFactory() {}

  virtual already_AddRefed<Image> CreateImage(const ImageFormat* aFormats,
                                              uint32_t aNumFormats,
                                              const gfxIntSize &aScaleHint,
                                              BufferRecycleBin *aRecycleBin)
  {
    if (!aNumFormats) {
      return nullptr;
    }

    nsRefPtr<Image> image;
    if (aFormats[0] == PLANAR_YCBCR) {
      image = new BasicPlanarYCbCrImage(aScaleHint, gfxPlatform::GetPlatform()->GetOffscreenFormat(), aRecycleBin);
      return image.forget();
    }

    return ImageFactory::CreateImage(aFormats, aNumFormats, aScaleHint, aRecycleBin);
  }
};

void
BasicPlanarYCbCrImage::SetData(const Data& aData)
{
  PlanarYCbCrImage::SetData(aData);

  if (mDelayedConversion) {
    return;
  }

  // Do some sanity checks to prevent integer overflow
  if (aData.mYSize.width > PlanarYCbCrImage::MAX_DIMENSION ||
      aData.mYSize.height > PlanarYCbCrImage::MAX_DIMENSION) {
    NS_ERROR("Illegal image source width or height");
    return;
  }

  gfxASurface::gfxImageFormat format = GetOffscreenFormat();

  gfxIntSize size(mScaleHint);
  gfxUtils::GetYCbCrToRGBDestFormatAndSize(aData, format, size);
  if (size.width > PlanarYCbCrImage::MAX_DIMENSION ||
      size.height > PlanarYCbCrImage::MAX_DIMENSION) {
    NS_ERROR("Illegal image dest width or height");
    return;
  }

  mStride = gfxASurface::FormatStrideForWidth(format, size.width);
  mDecodedBuffer = AllocateBuffer(size.height * mStride);
  if (!mDecodedBuffer) {
    // out of memory
    return;
  }

  gfxUtils::ConvertYCbCrToRGB(aData, format, size, mDecodedBuffer, mStride);
  SetOffscreenFormat(format);
  mSize = size;
}

static cairo_user_data_key_t imageSurfaceDataKey;

static void
DestroyBuffer(void* aBuffer)
{
  delete[] static_cast<uint8_t*>(aBuffer);
}

already_AddRefed<gfxASurface>
BasicPlanarYCbCrImage::GetAsSurface()
{
  NS_ASSERTION(NS_IsMainThread(), "Must be main thread");

  if (mSurface) {
    nsRefPtr<gfxASurface> result = mSurface.get();
    return result.forget();
  }

  if (!mDecodedBuffer) {
    return PlanarYCbCrImage::GetAsSurface();
  }

  gfxASurface::gfxImageFormat format = GetOffscreenFormat();

  nsRefPtr<gfxImageSurface> imgSurface =
      new gfxImageSurface(mDecodedBuffer, mSize, mStride, format);
  if (!imgSurface || imgSurface->CairoStatus() != 0) {
    return nullptr;
  }

  // Pass ownership of the buffer to the surface
  imgSurface->SetData(&imageSurfaceDataKey, mDecodedBuffer.forget(), DestroyBuffer);

  nsRefPtr<gfxASurface> result = imgSurface.get();
#if defined(XP_MACOSX)
  nsRefPtr<gfxQuartzImageSurface> quartzSurface =
    new gfxQuartzImageSurface(imgSurface);
  if (quartzSurface) {
    result = quartzSurface.forget();
  }
#endif

  mSurface = result;

  return result.forget();
}

ImageFactory*
BasicLayerManager::GetImageFactory()
{
  if (!mFactory) {
    mFactory = new BasicImageFactory();
  }

  return mFactory.get();
}

}
}


text:
require File.expand_path('../../spec_helper', __FILE__)

describe "Exportable Formats" do

  before(:each) do
    class User
      make_exportable
    end
    clean_database!
    User.create(:first_name => "user_1", :last_name => "Doe", :created_at => Time.at(0), :updated_at => Time.at(0))
    User.create(:first_name => "user_2", :last_name => "Doe", :created_at => Time.at(0), :updated_at => Time.at(0))
  end

  context "csv format" do

    it "should export the columns as csv" do
      User.to_export( "csv", :only => [:first_name, "is_admin"]).should ==  ["First Name,Is Admin\nuser_1,false\nuser_2,false\n", "text/csv; charset=utf-8; header=present"]
    end

    it "should export the columns as csv and detect that there is no header" do
      User.to_export( "csv", :only => [:first_name, "is_admin"], :headers => false).should ==  ["user_1,false\nuser_2,false\n", "text/csv; charset=utf-8; header=absent"]
    end

  end

  context "excel format" do

    it "should export the columns as xls" do
      User.to_export( "xls", :only =>  [:first_name, "is_admin"]).should == ["
\n\t
\n\t\tFirst Name	\n\t\tIs Admin	\n\t
\n\t
\n\t\tuser_1	\n\t\tfalse	\n\t
\n\t
\n\t\tuser_2	\n\t\tfalse	\n\t
\n
\n", "application/vnd.ms-excel; charset=utf-8; header=present"]
    end

    it "should export the columns as xls and detect no header" do
      User.to_export( "xls", :only =>  [:first_name, "is_admin"], :headers => false).should == ["
\n\t
\n\t\tuser_1	\n\t\tfalse	\n\t
\n\t
\n\t\tuser_2	\n\t\tfalse	\n\t
\n
\n", "application/vnd.ms-excel; charset=utf-8; header=absent"]
    end

  end

  context "tsv format" do

    it "should export the columns as tsv" do
      User.to_export( "tsv", :only => [:first_name, "is_admin"]).should == ["First Name\tIs Admin\nuser_1\tfalse\nuser_2\tfalse\n", "text/tab-separated-values; charset=utf-8; header=present"]
    end

    it "should export the columns as tsv  and detect no header" do
      User.to_export( "tsv", :only => [:first_name, "is_admin"], :headers => false).should == ["user_1\tfalse\nuser_2\tfalse\n", "text/tab-separated-values; charset=utf-8; header=absent"]
    end

  end

  context "html format" do

    it "should export the columns as html" do
      User.to_export( "html", :only => [:first_name, "is_admin"]).should == ["
\n\t
\n\t\tFirst Name	\n\t\tIs Admin	\n\t
\n\t
\n\t\tuser_1	\n\t\tfalse	\n\t
\n\t
\n\t\tuser_2	\n\t\tfalse	\n\t
\n
\n", "text/html; charset=utf-8; header=present"]
    end

    it "should export the columns as html and detect no header" do
      User.to_export( "html", :only => [:first_name, "is_admin"], :headers => false).should == ["
\n\t
\n\t\tuser_1	\n\t\tfalse	\n\t
\n\t
\n\t\tuser_2	\n\t\tfalse	\n\t
\n
\n", "text/html; charset=utf-8; header=absent"]
    end

  end

  context "xml format" do

    it "should export the columns as xml" do
      User.to_export( "xml", :only => [:first_name, "is_admin"]).should == ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<records>\n\t<record>\n\t\t<first-name>user_1</first-name>\n\t\t<is-admin>false</is-admin>\n\t</record>\n\t<record>\n\t\t<first-name>user_2</first-name>\n\t\t<is-admin>false</is-admin>\n\t</record>\n</records>\n", "application/xml; header=present"]
    end

    it "should export the columns as xml and detect no header" do
      User.to_export( "xml", :only => [:first_name, "is_admin"], :headers => false).should == ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<records>\n\t<record>\n\t\t<attribute_0>user_1</attribute_0>\n\t\t<attribute_1>false</attribute_1>\n\t</record>\n\t<record>\n\t\t<attribute_0>user_2</attribute_0>\n\t\t<attribute_1>false</attribute_1>\n\t</record>\n</records>\n", "application/xml; header=absent"]
    end

  end

  context "json format" do
    it "should export the columns as json" do
      User.to_export( "json", :only => [:first_name]).should ==["[{\"first_name\":\"user_1\"},{\"first_name\":\"user_2\"}]", "application/json; charset=utf-8;"]
    end

  end

end


text:
<?php

namespace ONGR\ElasticsearchBundle\ORM;

use ONGR\ElasticsearchBundle\Client\Connection;
use ONGR\ElasticsearchBundle\Document\DocumentInterface;
use ONGR\ElasticsearchBundle\Event\ElasticsearchCommitEvent;
use ONGR\ElasticsearchBundle\Event\ElasticsearchPersistEvent;
use ONGR\ElasticsearchBundle\Event\Events;
use ONGR\ElasticsearchBundle\Mapping\ClassMetadata;
use ONGR\ElasticsearchBundle\Mapping\ClassMetadataCollection;
use ONGR\ElasticsearchBundle\Result\Converter;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Manager class.
 */
class Manager
{
    /**
     * @var Connection Elasticsearch connection.
     */
    private $connection;

    /**
     * @var ClassMetadataCollection
     */
    private $classMetadataCollection;

    /**
     * @var Converter
     */
    private $converter;

    /**
     * @var EventDispatcher
     */
    private $eventDispatcher;

    /**
     * @param Connection              $connection
     * @param ClassMetadataCollection $classMetadataCollection
     */
    public function __construct($connection, $classMetadataCollection)
    {
        $this->connection = $connection;
        $this->classMetadataCollection = $classMetadataCollection;
    }

    /**
     * Returns Elasticsearch connection.
     *
     * @return Connection
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * @param EventDispatcher $eventDispatcher
     */
    public function setEventDispatcher($eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Returns repository with one or several active selected type.
     *
     * @param string|string[] $type
     *
     * @return Repository
     */
    public function getRepository($type)
    {
        $type = is_array($type) ? $type : [$type];

        foreach ($type as &$selectedType) {
            $this->checkRepositoryType($selectedType);
        }

        return $this->createRepository($type);
    }

    /**
     * Creates a repository.
     *
     * @param array $types
     *
     * @return Repository
     */
    private function createRepository(array $types)
    {
        return new Repository($this, $types);
    }

    /**
     * Adds document to next flush.
     *
     * @param DocumentInterface $document
     */
    public function persist(DocumentInterface $document)
    {
        $this->dispatchEvent(
            Events::PRE_PERSIST,
            new ElasticsearchPersistEvent($this->getConnection(), $document)
        );

        $mapping = $this->getDocumentMapping($document);
        $documentArray = $this->getConverter()->convertToArray($document);

        $this->getConnection()->bulk(
            'index',
            $mapping->getType(),
            $documentArray
        );

        $this->dispatchEvent(
            Events::POST_PERSIST,
            new ElasticsearchPersistEvent($this->getConnection(), $document)
        );
    }

    /**
     * Commits bulk batch to elasticsearch index.
     */
    public function commit()
    {
        $this->dispatchEvent(
            Events::PRE_COMMIT,
            new ElasticsearchCommitEvent($this->getConnection())
        );

        $this->getConnection()->commit();

        $this->dispatchEvent(
            Events::POST_COMMIT,
            new ElasticsearchCommitEvent($this->getConnection())
        );
    }

    /**
     * Flushes elasticsearch index.
     */
    public function flush()
    {
        $this->getConnection()->flush();
    }

    /**
     * Refreshes elasticsearch index.
     */
    public function refresh()
    {
        $this->getConnection()->refresh();
    }

    /**
     * Returns repository metadata for document.
     *
     * @param object $document
     *
     * @return ClassMetadata|null
     */
    public function getDocumentMapping($document)
    {
        foreach ($this->getBundlesMapping() as $repository) {
            if (in_array(get_class($document), [$repository->getNamespace(), $repository->getProxyNamespace()])) {
                return $repository;
            }
        }

        return null;
    }

    /**
     * Returns bundles mapping.
     *
     * @param array $repositories
     *
     * @return ClassMetadata[]
     */
    public function getBundlesMapping($repositories = [])
    {
        return $this->classMetadataCollection->getMetadata($repositories);
    }

    /**
     * @return array
     */
    public function getTypesMapping()
    {
        return $this->classMetadataCollection->getTypesMap();
    }

    /**
     * Checks if specified repository and type is defined, throws exception otherwise.
     *
     * @param string $type
     *
     * @throws \InvalidArgumentException
     */
    private function checkRepositoryType(&$type)
    {
        $mapping = $this->getBundlesMapping();

        if (array_key_exists($type, $mapping)) {
            return;
        }

        if (array_key_exists($type . 'Document', $mapping)) {
            $type .= 'Document';

            return;
        }

        $exceptionMessage = "Undefined repository `{$type}`, valid repositories are: `" .
            join('`, `', array_keys($this->getBundlesMapping())) . '`.';
        throw new \InvalidArgumentException($exceptionMessage);
    }

    /**
     * Returns converter instance.
     *
     * @return Converter
     */
    private function getConverter()
    {
        if (!$this->converter) {
            $this->converter = new Converter($this->getTypesMapping(), $this->getBundlesMapping());
        }

        return $this->converter;
    }

    /**
     * Dispatches an event, if eventDispatcher is set.
     *
     * @param string $eventName
     * @param Event  $event
     */
    private function dispatchEvent($eventName, Event $event)
    {
        if ($this->eventDispatcher != null) {
            $this->eventDispatcher->dispatch($eventName, $event);
        }
    }
}


text:
class LispSyntaxError(RuntimeError):
    """
    Exception raised when a Lisp syntax error is met.
    """
    pass

class LispRuntimeError(RuntimeError):
    pass

class LispMissingParameterError(LispRuntimeError):
    """
    Raised when there miss a parameter to a lambda call.
    """
    pass

class Identifier(str):
    """
    Class used to differentiate identifiers and keywords from strings.
    """

class Environment(dict):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent = parent

    def __getitem__(self, key):
        if key in self:
            return super().__getitem__(key)

        scope = self.find(key)

        if scope is None:
            raise LispRuntimeError('Unknown identifier : {}'.format(key))

        return scope[key]

    def __setitem__(self, key, val):
        scope = self.find(key)

        if scope == self:
            super().__setitem__(key, val)
        elif scope == None:
            super().__setitem__(key, val)
        else:
            scope[key] = val

    def find(self, key):
        if key in self:
            return self

        if self.parent is not None:
            return self.parent.find(key)

        return None

def create_base_env():
    env = Environment()

    # Support for basic boolean operators
    for op in ['+', '-', '*', '/', '%', '<', '>', '<=', '>=', 'and', 'or']:
        env[op] = eval('lambda x, y: x {} y'.format(op))

    env['='] = lambda x, y: x == y

    # Boolean constants
    env['#t'] = True
    env['#f'] = False
    env['not'] = lambda b: not b

    # List operations
    env['list'] = lambda *args: list(args)
    env['car'] = lambda l: l[0]
    env['cdr'] = lambda l: l[1:]
    env['len'] = len
    env['cons'] = lambda car, cdr: [car] + cdr

    env['display'] = lambda l: print(l, end='')
    env['displayln'] = lambda l: print(l)

    return env

def atom(string):
    """
    Creates an Atom from a string.
    """
    try:
        return int(string)
    except ValueError:
        try:
            return float(string)
        except ValueError:
            return Identifier(string)

def tokenize(prog):
    """
    Cuts a program into a list of list of atoms.
    """
    def inner_parser(prog):
        result = []
        while len(prog) > 0:
            val = prog.pop(0)

            if val == '(':
                result.append(inner_parser(prog))

            elif val == ')':
                return result

            elif val.startswith('"'):
                while not val.endswith('"') or len(val) == 1:
                    val = val + " " + prog.pop(0)
                result.append(val[1:-1])

            else:
                result.append(atom(val))

        # If we reach here, it means we have a non terminated list.
        raise LispSyntaxError('Non terminated list')

    # Converts the string into a flat list
    prog = prog.replace("(", " ( ").replace(")", " ) ").split()
    prog.pop(0) # Drops the initial '('
    return inner_parser(prog)

def create_prog(prog_content):
    """
    This function creates a program from the given content by preprocessing it.
    It starts by wrapping the whole program in a begin expression
    """
    prog_content = prog_content.splitlines()
    prog_content = [l for l in prog_content if not l.lstrip().startswith(";")]
    prog_content = "\n".join(prog_content)
    prog_content = "(begin {})".format(prog_content)
    return tokenize(prog_content)

def eval_prog(prog, env=None):

    if env is None:
        env = Environment()

    if isinstance(prog, int) or isinstance(prog, float):
        return prog

    if isinstance(prog, Identifier):
        return env[prog]

    # String literals
    if isinstance(prog, str):
        return prog

    if prog[0] == 'set!':
        varname = prog[1]
        varvalue = eval_prog(prog[2], env)
        env[varname] = varvalue
        return

    if prog[0] == 'lambda':
        argument_names = prog[1]
        expression = prog[2]
        def f(*args):
            if len(args) < len(argument_names):
                raise LispMissingParameterError
            updated_env = Environment(env, zip(argument_names, args))
            return eval_prog(expression, updated_env)

        return f

    if prog[0] == 'quote':
        return prog[1]

    if prog[0] == 'begin':
        val = None
        for expr in prog[1:]:
            val = eval_prog(expr, env)

        return val

    if prog[0] == 'if':
        cond = eval_prog(prog[1], env)
        if cond:
            return eval_prog(prog[2], env)
        else:
            return eval_prog(prog[3], env)

    # If we get there it means that we have a function call
    args = [eval_prog(v, env) for v in prog]
    func = args.pop(0)

    return func(*args)

def input_expression():
    """
    Allows the user to input a multi line expression.
    """
    level = 0

    s = input(">>> ")
    level += s.count('(')
    level -= s.count(')')

    result = [s]

    while level:
        prompt = "... " + "  " * level
        s = input(prompt)
        level += s.count('(')
        level -= s.count(')')
        result.append(s)

    return ' '.join(result)


text:
namespace Telerik.UI.Xaml.Controls.Input
{
    /// <summary>
    /// Defines the possible text filter modes provided by <see cref="RadAutoCompleteBox"/>.
    /// </summary>
    public enum AutoCompleteBoxFilterMode
    {
        /// <summary>
        /// In this mode <see cref="RadAutoCompleteBox"/> filters
        /// the items based on whether the starting sequence of each candidate
        /// matches the current user input.
        /// </summary>
        StartsWith,

        /// <summary>
        /// In this mode <see cref="RadAutoCompleteBox"/> filters
        /// the items based on whether the input sequence is contained in each
        /// candidate.
        /// </summary>
        Contains
    }
}


text:
package org.dylanfoundry.deft.filetypes.dylan.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface DylanTemplate extends DylanCompositeElement {

  @NotNull
  List<DylanTemplateElement> getTemplateElementList();

}


text:
    <bx_repeat:submenu_items>

                <bx_include_auto:menu_icon.html />

__title__

    </bx_repeat:submenu_items>


text:
#import <Foundation/Foundation.h>

typedef NS_OPTIONS(NSUInteger, UIPopoverArrowDirection) {
    UIPopoverArrowDirectionUp = 1UL << 0,
    UIPopoverArrowDirectionDown = 1UL << 1,
    UIPopoverArrowDirectionLeft = 1UL << 2,
    UIPopoverArrowDirectionRight = 1UL << 3,
    UIPopoverArrowDirectionAny = UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown |
    UIPopoverArrowDirectionLeft | UIPopoverArrowDirectionRight,
    UIPopoverArrowDirectionUnknown = NSUIntegerMax
};

@class UIView, UIViewController, UIPopoverController, UIBarButtonItem, UIPopoverView;

@protocol UIPopoverControllerDelegate <NSObject>
@optional
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController;
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController;
@end

@interface UIPopoverController : NSObject
- (id)initWithContentViewController:(UIViewController *)viewController;

- (void)setContentViewController:(UIViewController *)controller animated:(BOOL)animated;
- (void)setPopoverContentSize:(CGSize)size animated:(BOOL)animated;

- (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;
- (void)presentPopoverFromBarButtonItem:(UIBarButtonItem *)item permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;
- (void)dismissPopoverAnimated:(BOOL)animated;

@property (nonatomic, assign) id <UIPopoverControllerDelegate> delegate;
@property (nonatomic, strong) UIViewController *contentViewController;
@property (nonatomic, readonly, getter=isPopoverVisible) BOOL popoverVisible;
@property (nonatomic, copy) NSArray *passthroughViews;
@property (nonatomic, readonly) UIPopoverArrowDirection popoverArrowDirection;
@property (nonatomic) CGSize popoverContentSize;
@end


text:
from collections import defaultdict
import numpy as np
import math
from scipy.sparse import csr_matrix
from eden import fast_hash_vec_char, fast_hash_2, fast_hash_4
from eden import AbstractVectorizer
import logging
logger = logging.getLogger(__name__)

class Vectorizer(AbstractVectorizer):

    """Transform strings into sparse vectors."""

    def __init__(self,
                 complexity=None,
                 r=3,
                 d=3,
                 min_r=0,
                 min_d=0,
                 nbits=20,
                 normalization=True,
                 inner_normalization=True):
        if complexity is not None:
            self.r = complexity + 1
            self.d = complexity + 1
        else:
            self.r = r + 1
            self.d = d + 1
        self.min_r = min_r
        self.min_d = min_d
        self.nbits = nbits
        self.normalization = normalization
        self.inner_normalization = inner_normalization
        self.bitmask = pow(2, nbits) - 1
        self.feature_size = self.bitmask + 2

    def __repr__(self):
        representation = """path_graph.Vectorizer(r = %d, d = %d, min_r = %d, min_d = %d, nbits = %d, \
            normalization = %s, inner_normalization = %s)""" % (
            self.r - 1,
            self.d - 1,
            self.min_r,
            self.min_d,
            self.nbits,
            self.normalization,
            self. inner_normalization)
        return representation

    def transform(self, seq_list):
        """
        Args:
            seq_list: list of strings
        """

        feature_dict = {}
        for instance_id, seq in enumerate(seq_list):
            feature_dict.update(self._transform(instance_id, seq))
        return self._convert_dict_to_sparse_matrix(feature_dict)

    def transform_iter(self, seq_list):
        for instance_id, seq in enumerate(seq_list):
            yield self._convert_dict_to_sparse_matrix(self._transform(instance_id, seq))

    def _convert_dict_to_sparse_matrix(self, feature_dict):
        if len(feature_dict) == 0:
            raise Exception('ERROR: something went wrong, empty feature_dict.')
        data = feature_dict.values()
        row, col = [], []
        for i, j in feature_dict.iterkeys():
            row.append(i)
            col.append(j)
        data_matrix = csr_matrix((data, (row, col)), shape=(max(row) + 1, self.feature_size))
        return data_matrix

    def _transform(self, instance_id, seq):
        if seq is None or len(seq) == 0:
            raise Exception('ERROR: something went wrong, empty instance # %d.' % instance_id)
        if len(seq) == 2 and len(seq[1]) > 0:
            # assume the instance is a pair (header,seq) and extract only seq
            seq = seq[1]
        # extract kmer hash codes for all kmers up to r in all positions in seq
        seq_len = len(seq)
        neighborhood_hash_cache = [self._compute_neighborhood_hash(seq, pos) for pos in range(seq_len)]
        # construct features as pairs of kmers up to distance d for all radii up to r
        feature_list = defaultdict(lambda: defaultdict(float))
        for pos in range(seq_len):
            for radius in range(self.min_r, self.r + 1):
                if radius < len(neighborhood_hash_cache[pos]):
                    for distance in range(self.min_d, self.d + 1):
                        second_endpoint = pos + distance
                        if second_endpoint + radius < seq_len:
                            feature_code = fast_hash_4(neighborhood_hash_cache[pos][radius],
                                                       radius,
                                                       distance,
                                                       neighborhood_hash_cache[second_endpoint][radius],
                                                       self.bitmask)
                            key = fast_hash_2(radius, distance, self.bitmask)
                            feature_list[key][feature_code] += 1
        return self._normalization(feature_list, instance_id)

    def _normalization(self, feature_list, instance_id):
        # inner normalization per radius-distance
        feature_vector = {}
        total_norm = 0.0
        for features in feature_list.itervalues():
            norm = 0
            for count in features.itervalues():
                norm += count * count
            sqrt_norm = math.sqrt(norm)
            for feature, count in features.iteritems():
                feature_vector_key = (instance_id, feature)
                if self.inner_normalization:
                    feature_vector_value = float(count) / sqrt_norm
                else:
                    feature_vector_value = count
                feature_vector[feature_vector_key] = feature_vector_value
                total_norm += feature_vector_value * feature_vector_value
        # global normalization
        if self.normalization:
            normalization_feature_vector = {}
            sqrt_total_norm = math.sqrt(float(total_norm))
            for feature, value in feature_vector.iteritems():
                normalization_feature_vector[feature] = value / sqrt_total_norm
            return normalization_feature_vector
        else:
            return feature_vector

    def _compute_neighborhood_hash(self, seq, pos):
        """
        Given the seq and the pos, extract all kmers up to size r in a vector
        at position 0 in the vector there will be the hash of a single char, in position 1 of 2 chars, etc
        """

        subseq = seq[pos:pos + self.r]
        return fast_hash_vec_char(subseq, self.bitmask)

    def predict(self, seqs, estimator):
        """
        Takes an iterator over graphs and a fit estimator, and returns an iterator over predictions.
        """

        for seq in seqs:
            if len(seq) == 0:
                raise Exception('ERROR: something went wrong, empty instance.')
            # extract feature vector
            x = self._convert_dict_to_sparse_matrix(self._transform(0, seq))
            margins = estimator.decision_function(x)
            yield margins[0]

    def similarity(self, seqs, ref_instance=None):
        """Takes an iterator over graphs and a reference graph, and returns an iterator
        over similarity evaluations."""

        reference_vec = self._convert_dict_to_sparse_matrix(self._transform(0, ref_instance))
        for seq in seqs:
            if len(seq) == 0:
                raise Exception('ERROR: something went wrong, empty instance.')
            # extract feature vector
            x = self._convert_dict_to_sparse_matrix(self._transform(0, seq))
            res = reference_vec.dot(x.T).todense()
            yield res[0, 0]

    def annotate(self, seqs, estimator=None, relabel=False):
        """
        Given a list of sequences, and a fitted estimator, it computes a vector
        of importance values for each char in the sequence. The importance
        corresponds to the part of the score that is imputable  to the features
        that involve the specific char.

        Args:
            sequences: iterable lists of strings

            estimator: scikit-learn predictor trained on data sampled from the same distribution.
            If None only relabeling is used.

            relabel: bool. If True replace the label attribute of each vertex with the
            sparse vector encoding of all features that have that vertex as root.

        Returns:
            If relabel is False: for each input sequence a pair: 1) the input
            string, 2) a list of real  numbers with size equal to the number of
            characters in each input sequence.

            If relabel is True: for each input sequence a triplet: 1) the input
            string, 2) a list of real  numbers with size equal to the number of
            characters in each input sequence, 3) a list with  size equal to the
            number of characters in each input sequence, of sparse vectors each
            corresponding to the vertex induced features.
        """

        self.estimator = estimator
        self.relabel = relabel

        for seq in seqs:
            yield self._annotate(seq)

    def _annotate(self, seq):
        # extract per vertex feature representation
        data_matrix = self._compute_vertex_based_features(seq)
        # extract importance information
        score, vec = self._annotate_importance(seq, data_matrix)
        # extract list of chars
        out_sequence = [c for c in seq]
        # add or update label information
        if self.relabel:
            return out_sequence, score, vec
        else:
            return out_sequence, score

    def _annotate_importance(self, seq, data_matrix):
        # compute distance from hyperplane as proxy of vertex importance
        if self.estimator is None:
            # if we do not provide an estimator then consider default margin of
            # 1 for all vertices
            margins = np.array([1] * data_matrix.shape[0])
        else:
            margins = self.estimator.decision_function(data_matrix)
        # compute the list of sparse vectors representation
        vec = []
        for i in range(data_matrix.shape[0]):
            vec.append(data_matrix.getrow(i))
        return margins, vec

    def _compute_vertex_based_features(self, seq):
        if seq is None or len(seq) == 0:
            raise Exception('ERROR: something went wrong, empty instance.')
        # extract kmer hash codes for all kmers up to r in all positions in seq
        feature_dict = {}
        seq_len = len(seq)
        neighborhood_hash_cache = [self._compute_neighborhood_hash(seq, pos) for pos in range(seq_len)]
        for pos in range(seq_len):
            # construct features as pairs of kmers up to distance d for all radii up to r
            feature_list = defaultdict(lambda: defaultdict(float))
            for radius in range(self.min_r, self.r + 1):
                if radius < len(neighborhood_hash_cache[pos]):
                    for distance in range(self.min_d, self.d + 1):
                        if pos + distance + radius < seq_len:
                            feature_code = fast_hash_4(neighborhood_hash_cache[pos][radius],
                                                       radius,
                                                       distance,
                                                       neighborhood_hash_cache[pos + distance][radius],
                                                       self.bitmask)
                            key = fast_hash_2(radius, distance, self.bitmask)
                            feature_list[key][feature_code] += 1
            feature_dict.update(self._normalization(feature_list, pos))
        data_matrix = self._convert_dict_to_sparse_matrix(feature_dict)
        return data_matrix


text:
import { Component, OnInit } from '@angular/core';
import { LoginService } from '../../services/api/login.service';
import { Router } from '@angular/router';

@Component({
	selector   : 's-login-pg',
	templateUrl: './login.component.html',
    styleUrls  : [ './login.scss'],
})

export class LoginComponent implements OnInit {
    model: any = {};
    errMsg:string = '';
    constructor(
        private router: Router,
        private loginService: LoginService) { }

    ngOnInit() {
        // reset login status
        this.loginService.logout(false);
    }

    login() {
        this.loginService.getToken(this.model.username, this.model.password)
            .subscribe(resp => {
                    if (resp.user === undefined || resp.user.token === undefined || resp.user.token === "INVALID" ){
                        this.errMsg = 'Username or password is incorrect';
                        return;
                    }
                    this.router.navigate([resp.landingPage]);
                },
                errResponse => {
                  switch(errResponse.status){
                    case 401:
                      this.errMsg = 'Username or password is incorrect';
                      break;
                    case 404:
                      this.errMsg = 'Service not found';
                    case 408:
                      this.errMsg = 'Request Timedout';
                    case 500:
                      this.errMsg = 'Internal Server Error';
                    default:
                      this.errMsg = 'Server Error';
                  }
                }
            );
    }

    onSignUp(){
      this.router.navigate(['signup']);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;

namespace MsgPack.Serialization
{
	/// <summary>
	///		Build serializer for <typeparamref name="TObject"/>.
	/// </summary>
	/// <typeparam name="TObject">Object to be serialized/deserialized.</typeparam>
	internal abstract class SerializerBuilder<TObject>
	{
		private readonly SerializationContext _context;

		/// <summary>
		///		Gets the <see cref="SerializationContext"/>.
		/// </summary>
		/// <value>
		///		The <see cref="SerializationContext"/>.
		/// </value>
		public SerializationContext Context
		{
			get
			{
				Contract.Ensures( Contract.Result<SerializationContext>() != null );

				return this._context;
			}
		}

		/// <summary>
		///		Initializes a new instance of the <see cref="SerializerBuilder<TObject>"/> class.
		/// </summary>
		/// <param name="context">The <see cref="SerializationContext"/>.</param>
		protected SerializerBuilder( SerializationContext context )
		{
			Contract.Requires( context != null );

			this._context = context;
		}

		/// <summary>
		///		Creates serializer for <typeparamref name="TObject"/>.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
		/// </returns>
		public MessagePackSerializer<TObject> CreateSerializer()
		{
			Contract.Ensures( Contract.Result<MessagePackSerializer<TObject>>() != null );

			var entries = GetTargetMembers().OrderBy( item => item.Contract.Id ).ToArray();

            //if ( entries.Length == 0 )
            //{
            //    throw SerializationExceptions.NewNoSerializableFieldsException( typeof( TObject ) );
            //}

			if ( entries.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
			{
				// Alphabetical order.
				return this.CreateSerializer( entries.OrderBy( item => item.Contract.Name ).ToArray() );
			}
			else
			{
				// ID order.

				Contract.Assert( entries[ 0 ].Contract.Id >= 0 );

				if ( this.Context.CompatibilityOptions.OneBoundDataMemberOrder && entries[ 0 ].Contract.Id == 0 )
				{
					throw new NotSupportedException( "Cannot specify order value 0 on DataMemberAttribute when SerializationContext.CompatibilityOptions.OneBoundDataMemberOrder is set to true." );
				}

				var maxId = entries.Max( item => item.Contract.Id );
				var result = new List<SerializingMember>( maxId + 1 );
				for ( int source = 0, destination = this.Context.CompatibilityOptions.OneBoundDataMemberOrder ? 1 : 0; source < entries.Length; source++, destination++ )
				{
					Contract.Assert( entries[ source ].Contract.Id >= 0 );

					if ( entries[ source ].Contract.Id < destination )
					{
						throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The member ID '{0}' is duplicated in the '{1}' type.", entries[ source ].Contract.Id, typeof( TObject ) ) );
					}

					while ( entries[ source ].Contract.Id > destination )
					{
						result.Add( new SerializingMember() );
						destination++;
					}

					result.Add( entries[ source ] );
				}

				return this.CreateSerializer( result.ToArray() );
			}
		}

		private static IEnumerable<SerializingMember> GetTargetMembers()
		{
#if !NETFX_CORE
			var members =
				typeof( TObject ).FindMembers(
					MemberTypes.Field | MemberTypes.Property,
					BindingFlags.Public | BindingFlags.Instance,
					( member, criteria ) => true,
					null
				);
			var filtered = members.Where( item => Attribute.IsDefined( item, typeof( MessagePackMemberAttribute ) ) ).ToArray();
#else
			var members =
				typeof( TObject ).GetRuntimeFields().Where( f => f.IsPublic && !f.IsStatic ).OfType<MemberInfo>().Concat( typeof( TObject ).GetRuntimeProperties().Where( p => p.GetMethod != null && p.GetMethod.IsPublic && !p.GetMethod.IsStatic ) );
			var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();
#endif

			if ( filtered.Length > 0 )
			{
				return
					filtered.Select( member =>
						new SerializingMember(
							member,
							new DataMemberContract( member, member.GetCustomAttribute<MessagePackMemberAttribute>() )
						)
					);
			}

			if ( typeof( TObject ).IsDefined( typeof( DataContractAttribute ) ) )
			{
				return
					members.Where( item => item.IsDefined( typeof( DataMemberAttribute ) ) )
					.Select( member =>
						new SerializingMember(
							member,
							new DataMemberContract( member, member.GetCustomAttribute<DataMemberAttribute>() )
						)
					);
			}

#if SILVERLIGHT || NETFX_CORE
			return members.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#else
			return
				members.Where( item => !Attribute.IsDefined( item, typeof( NonSerializedAttribute ) ) )
				.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#endif
		}

		/// <summary>
		///		Creates serializer for <typeparamref name="TObject"/>.
		/// </summary>
		/// <param name="entries">Serialization target members. This will not be <c>null</c> nor empty.</param>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
		/// </returns>
		protected abstract MessagePackSerializer<TObject> CreateSerializer( SerializingMember[] entries );

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is array type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public abstract MessagePackSerializer<TObject> CreateArraySerializer();

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is map type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public abstract MessagePackSerializer<TObject> CreateMapSerializer();

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is tuple type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public abstract MessagePackSerializer<TObject> CreateTupleSerializer();
	}

	internal abstract class SerializerBuilderContract<T> : SerializerBuilder<T>
	{
		protected SerializerBuilderContract() : base( null ) { }

		protected override MessagePackSerializer<T> CreateSerializer( SerializingMember[] entries )
		{
			Contract.Requires( entries != null );
			Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
			return null;
		}

		public override MessagePackSerializer<T> CreateArraySerializer()
		{
			Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
			return null;
		}

		public override MessagePackSerializer<T> CreateMapSerializer()
		{
			Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
			return null;
		}

		public override MessagePackSerializer<T> CreateTupleSerializer()
		{
			Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
			return null;
		}
	}
}


text:
package adaptors

import (
	"net/http"

	"github.com/codegangsta/negroni"
)

func FromNegroni(handler negroni.Handler) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		n := negroni.New()
		n.Use(handler)
		n.UseHandler(next)
		return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
			n.ServeHTTP(rw, req)
		})
	}
}

func HandlerFromNegroni(handler negroni.Handler) http.Handler {
	n := negroni.New()
	n.Use(handler)
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		n.ServeHTTP(rw, req)
	})
}


text:
fn last_char_of_first_line(text: &str) -> Option<char> {
    text.lines().next()?.chars().last()
}
// ANCHOR_END: here

fn main() {
    assert_eq!(
        last_char_of_first_line("Hello, world\nHow are you today?"),
        Some('d')
    );

    assert_eq!(last_char_of_first_line(""), None);
    assert_eq!(last_char_of_first_line("\nhi"), None);
}


text:
public class Player {
	private int deviceID;
	public Player(int deviceID){
		this.deviceID = deviceID;
	}

	public int getDeviceId(){
		return deviceID;
	}
}


text:
@interface FKGetAgentController : BaseTableViewController

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/>
      <title>
SVG 1.1 2nd Edition Test (svgweb): svgdom-over-01-f.svg
      </title>

      <link rel="prev" href="styling-pres-05-f.html" />
      <link rel="index" href="index.html" />
      <link rel="next" href="text-align-01-b.html" />

Specification link:

    styling-pres-05-f ←
    index
    → text-align-01-b

    Tests that contain the draft-watermark are under development and may be incorrectly testing a feature.

svgdom-over-01-f.svg

            SVG Image

            PNG Image

              <object data="../../svg/svgdom-over-01-f.svg" width="480" height="360" type="image/svg+xml">
FAIL

              </object>

      Operator Script

        Run the test. No interaction required.

    Pass Criteria

      	The test has passed if there is a line of text saying "Test status: PASSED", and there is a green rectangle to the left of that text.

    Test Description

      	This tests how unspecified attributes affect the return values from the
      	SVG DOM methods related to attributes.

      	After loading the test, you should see a list of red or green rectangles followed by some text describing each subtest.

    styling-pres-05-f ←
    index
    → text-align-01-b