text:
#include <gtest/gtest.h>

#include <geode/AuthenticatedView.hpp>
#include <geode/Cache.hpp>
#include <geode/PoolManager.hpp>
#include <geode/RegionFactory.hpp>
#include <geode/RegionShortcut.hpp>

using apache::geode::client::CacheClosedException;
using apache::geode::client::CacheFactory;
using apache::geode::client::RegionAttributesFactory;
using apache::geode::client::RegionShortcut;

/**
 * Cache should close and throw exceptions on methods called after close.
 */
TEST(LocalRegionTest, subRegions) {
  auto cache = CacheFactory{}.set("log-level", "none").create();

  auto rootRegions = cache.rootRegions();
  EXPECT_TRUE(rootRegions.empty());

  auto rootRegion1 =
      cache.createRegionFactory(RegionShortcut::LOCAL).create("rootRegion1");
  EXPECT_NE(nullptr, rootRegion1);

  auto subRegion11 = rootRegion1->createSubregion(
      "subRegion11", RegionAttributesFactory().create());
  EXPECT_NE(nullptr, subRegion11);

  auto subRegion12 = rootRegion1->createSubregion(
      "subRegion12", RegionAttributesFactory().create());
  EXPECT_NE(nullptr, subRegion12);

  auto subRegions1 = rootRegion1->subregions(true);
  EXPECT_EQ(2, subRegions1.size());

  auto rootRegion2 =
      cache.createRegionFactory(RegionShortcut::LOCAL).create("rootRegion2");
  EXPECT_NE(nullptr, rootRegion2);

  auto subRegion21 = rootRegion2->createSubregion(
      "subRegion21", RegionAttributesFactory().create());
  EXPECT_NE(nullptr, subRegion21);

  auto subRegion211 = subRegion21->createSubregion(
      "subRegion211", RegionAttributesFactory().create());
  EXPECT_NE(nullptr, subRegion211);

  auto subRegions2 = rootRegion2->subregions(true);
  EXPECT_EQ(2, subRegions2.size());

  auto subRegions2NonRecursive = rootRegion2->subregions(false);
  EXPECT_EQ(1, subRegions2NonRecursive.size());

  auto rootRegion3 =
      cache.createRegionFactory(RegionShortcut::LOCAL).create("rootRegion3");
  EXPECT_NE(nullptr, rootRegion3);

  auto subRegions3 = rootRegion3->subregions(true);
  EXPECT_EQ(0, subRegions3.size());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.nifi</groupId>
        <artifactId>nifi-framework</artifactId>
        <version>1.2.0-SNAPSHOT</version>
    </parent>
    <artifactId>nifi-file-authorizer</artifactId>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/xsd</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>authorizations</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                        <configuration>
                            <schemaDirectory>src/main/xsd</schemaDirectory>
                            <schemaFiles>authorizations.xsd</schemaFiles>
                            <packageName>org.apache.nifi.authorization.file.generated</packageName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>tenants</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                        <configuration>
                            <schemaDirectory>src/main/xsd</schemaDirectory>
                            <schemaFiles>tenants.xsd</schemaFiles>
                            <packageName>org.apache.nifi.authorization.file.tenants.generated</packageName>
                            <clearOutputDir>false</clearOutputDir>
                        </configuration>
                    </execution>
                    <execution>
                        <id>users</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                        <configuration>
                            <schemaDirectory>src/main/xsd</schemaDirectory>
                            <schemaFiles>legacy-users.xsd</schemaFiles>
                            <packageName>org.apache.nifi.user.generated</packageName>
                            <clearOutputDir>false</clearOutputDir>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <outputDirectory>${project.build.directory}/generated-sources/jaxb</outputDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <configuration>
                    <excludes>**/authorization/file/generated/*.java,**/authorization/file/tenants/generated/*.java,**/user/generated/*.java</excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-framework-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-properties</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-framework-authorization</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-framework-core</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-expression-language</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-containeranalysis-parent</artifactId>
  <packaging>pom</packaging>
  <version>2.8.0-SNAPSHOT</version><!-- {x-version-update:google-cloud-containeranalysis:current} -->
  <name>Google Cloud Container Analysis Parent</name>
  <description>
    Java idiomatic client for Google Cloud Platform services.
  </description>

  <parent>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-jar-parent</artifactId>
    <version>1.1.0-SNAPSHOT</version><!-- {x-version-update:google-cloud-java:current} -->
    <relativePath>../google-cloud-jar-parent/pom.xml</relativePath>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <github.global.server>github</github.global.server>
    <site.installationModule>google-cloud-containeranalysis-parent</site.installationModule>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.api.grpc</groupId>
        <artifactId>proto-google-cloud-containeranalysis-v1</artifactId>
        <version>2.8.0-SNAPSHOT</version><!-- {x-version-update:proto-google-cloud-containeranalysis-v1:current} -->
      </dependency>
      <dependency>
        <groupId>com.google.api.grpc</groupId>
        <artifactId>proto-google-cloud-containeranalysis-v1beta1</artifactId>
        <version>0.98.0-SNAPSHOT</version><!-- {x-version-update:proto-google-cloud-containeranalysis-v1beta1:current} -->
      </dependency>
      <dependency>
        <groupId>com.google.api.grpc</groupId>
        <artifactId>grpc-google-cloud-containeranalysis-v1beta1</artifactId>
        <version>0.98.0-SNAPSHOT</version><!-- {x-version-update:grpc-google-cloud-containeranalysis-v1beta1:current} -->
      </dependency>
      <dependency>
        <groupId>com.google.api.grpc</groupId>
        <artifactId>grpc-google-cloud-containeranalysis-v1</artifactId>
        <version>2.8.0-SNAPSHOT</version><!-- {x-version-update:grpc-google-cloud-containeranalysis-v1:current} -->
      </dependency>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-containeranalysis</artifactId>
        <version>2.8.0-SNAPSHOT</version><!-- {x-version-update:google-cloud-containeranalysis:current} -->
      </dependency>
      <!-- TODO: This should maybe eventually be moved into this repo -->
      <dependency>
        <groupId>io.grafeas</groupId>
        <artifactId>grafeas</artifactId>
        <version>2.8.0-SNAPSHOT</version><!-- {x-version-update:grafeas:current} -->
      </dependency>
      <!-- TODO: Until gax-grpc && grafeas align  -->
    </dependencies>
  </dependencyManagement>

  <modules>
    <module>google-cloud-containeranalysis</module>
    <module>grpc-google-cloud-containeranalysis-v1beta1</module>
    <module>grpc-google-cloud-containeranalysis-v1</module>
    <module>proto-google-cloud-containeranalysis-v1</module>
    <module>proto-google-cloud-containeranalysis-v1beta1</module>
    <module>google-cloud-containeranalysis-bom</module>
  </modules>

  </project>


text:
<bill session="111" type="h" number="810" updated="2009-03-07T11:23:18-05:00">
	<status><introduced date="1233637200" datetime="2009-02-03"/></status>

	<introduced date="1233637200" datetime="2009-02-03"/>
	<titles>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to provide a tax credit to employers for the value of the service not performed during the period employees are performing service as members of the Ready Reserve or the National Guard.</title>
	</titles>
	<sponsor id="412250"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1233637200" datetime="2009-02-03"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>
		<committee name="House Ways and Means" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	2/3/2009--Introduced.
Amends the Internal Revenue Code to provide employers a business tax credit for up to ten percent of compensation not paid to their employees who were members of the Ready Reserve or National Guard absent from work to perform active duty. Limits such credit to $2,000 for any one Ready Reserve-National Guard employee per year.

</bill>


text:
title: Our minds can be hijacked - the tech insiders who fear a smartphone dystopia
date: 2017-10-09
articleauthor: Paul Lewis
articleurl: https://www.theguardian.com/technology/2017/oct/05/smartphone-addiction-silicon-valley-dystopia
site: The Guardian
siteurl: https://www.theguardian.com
pubdt: Thursday October 05, 2017
---

> Justin Rosenstein had tweaked his laptop's operating system to block Reddit, banned himself from Snapchat, which he compares to heroin, and imposed limits on his use of Facebook. But even that wasn't enough.

One interesting take on in discussing with people who built these systems is both funny and eye opening.

> It is revealing that many of these younger technologists are weaning themselves off their own products, sending their children to elite Silicon Valley schools where iPhones, iPads and even laptops are banned. They appear to be abiding by a Biggie Smalls lyric from their own youth about the perils of dealing crack cocaine: never get high on your own supply.


text:
use strict;

use lib "../../../lib";

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201406::ManagedCustomer;
use Google::Ads::AdWords::v201406::ManagedCustomerOperation;

use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);

# Example main subroutine.
sub create_account {
  my $client = shift;

  # Force to use the MCC credentials.
  $client->set_client_id(undef);

  # Create an account object with a currencyCode and a dateTimeZone
  # See https://developers.google.com/adwords/api/docs/appendix/currencycodes
  # and https://developers.google.com/adwords/api/docs/appendix/timezones
  my $account = Google::Ads::AdWords::v201406::ManagedCustomer->new({
    name => "Managed Account #" . uniqid(),
    currencyCode => "USD",
    dateTimeZone => "America/New_York",
  });

  # Create the operation
  my $operation = Google::Ads::AdWords::v201406::ManagedCustomerOperation->new({
    operator        => "ADD",
    operand         => $account
  });

  # Perform the operation. It is possible to create multiple accounts with one
  # request by sending multiple operations.
  my $response = $client->ManagedCustomerService->mutate({
    operations => [$operation],
  });

  if ($response) {
    my $new_account = $response->get_value();
    print "Account with customer ID ", $new_account->get_customerId(),
          " was created.\n";
  } else {
    print "No account was created.\n";
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201406"});

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
create_account($client);


text:
Identity Matching
#################

Basic Idea

.. graphviz::

    digraph Identity {
        linkedin -> google;
        facebook -> google;
        google -> github;
        github -> twitter;
        github -> hackernews;
    }

Another example

.. graphviz::

    digraph Email {
        twitter -> "someone@foo.com";
        facebook -> "someone@foo.com";
        google -> "someone@foo.com";
        linkedin -> "someone@foo.com";
        linkedin -> "someone@work.com";
    }


text:
<?xml version="1.0"?>

<iati-activities version="xx">
  <iati-activity>
    <iati-identifier></iati-identifier>
    <reporting-org type="xx" ref="xx">
      <narrative>Organisation name</narrative>
    </reporting-org>
    <title>
      <narrative>Xxxxxxx</narrative>
    </title>
    <description>
      <narrative>Xxxxxxx</narrative>
    </description>
    <participating-org role="xx"></participating-org>
    <activity-status code="xx"/>
    <activity-date type="xx" iso-date="2013-11-27"/>
    <activity-date type="xx" iso-date="2013-11-27">
      <narrative>Some stuff ere</narrative>
    </activity-date>
    <result type="xx">
      <title>
        <narrative>Sample text</narrative>
      </title>
      <indicator measure="xx" ascending="0">
        <title>
          <narrative>Sample text</narrative>
        </title>
        <period>
          <period-start iso-date="2017-11-22"/>
          <period-end iso-date="2017-11-23"/>
          <actual value="xx">
            <document-link url="xx" format="xx">
              <title/><!-- FAIL: Required `title` element added, but without the required 'narrative' child element. -->
              <category code="xx"/>
            </document-link>
          </actual>
        </period>
      </indicator>
    </result>
  </iati-activity>
</iati-activities>


text:
.. _httpapi_plugins:

Httpapi Plugins
===============

.. contents::
   :local:
   :depth: 2

Httpapi plugins tell Ansible how to interact with a remote device's HTTP-based API and execute tasks on the
device.

Each plugin represents a particular dialect of API. Some are platform-specific (Arista eAPI, Cisco NXAPI), while
others might be usable on a variety of platforms (RESTCONF).

.. _enabling_httpapi:

Adding httpapi plugins
-------------------------

You can extend Ansible to support other APIs by dropping a custom plugin into the ``httpapi_plugins`` directory. See :ref:`developing_plugins_httpapi` for details.

.. _using_httpapi:

Using httpapi plugins
------------------------

The httpapi plugin to use is determined automatically from the ``ansible_network_os`` variable.

Most httpapi plugins can operate without configuration. Additional options may be defined by each plugin.

Plugins are self-documenting. Each plugin should document its configuration options.

.. _httpapi_plugin_list:

Plugin List
-----------

You can use ``ansible-doc -t httpapi -l`` to see the list of available plugins.
Use ``ansible-doc -t httpapi <plugin name>`` to see detailed documentation and examples.

.. toctree:: :maxdepth: 1
    :glob:

    httpapi/*

.. seealso::

   :ref:`Ansible for Network Automation<network_guide>`
       An overview of using Ansible to automate networking devices.
   :ref:`Developing network modules<developing_modules_network>`
       How to develop network modules.
   `User Mailing List <https://groups.google.com/group/ansible-devel>`_
       Have a question?  Stop by the google group!
   `irc.freenode.net <http://irc.freenode.net>`_
       #ansible-network IRC chat channel


text:
use std::error::Error;

use diesel::result::Error::NotFound;

use super::data_structures::*;
use super::table_data::*;
use crate::database::InferConnection;
use crate::print_schema::ColumnSorting;

static RESERVED_NAMES: &[&str] = &[
    "abstract",
    "alignof",
    "as",
    "become",
    "box",
    "break",
    "const",
    "continue",
    "crate",
    "do",
    "else",
    "enum",
    "extern",
    "false",
    "final",
    "fn",
    "for",
    "if",
    "impl",
    "in",
    "let",
    "loop",
    "macro",
    "match",
    "mod",
    "move",
    "mut",
    "offsetof",
    "override",
    "priv",
    "proc",
    "pub",
    "pure",
    "ref",
    "return",
    "Self",
    "self",
    "sizeof",
    "static",
    "struct",
    "super",
    "trait",
    "true",
    "type",
    "typeof",
    "unsafe",
    "unsized",
    "use",
    "virtual",
    "where",
    "while",
    "yield",
    "bool",
    "columns",
    "is_nullable",
];

fn is_reserved_name(name: &str) -> bool {
    RESERVED_NAMES.contains(&name)
        || (
            // Names ending in an underscore are not considered reserved so that we
            // can always just append an underscore to generate an unreserved name.
            name.starts_with("__") && !name.ends_with('_')
        )
}

fn contains_unmappable_chars(name: &str) -> bool {
    // Rust identifier names are restricted to [a-zA-Z0-9_].
    !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

pub fn rust_name_for_sql_name(sql_name: &str) -> String {
    if is_reserved_name(sql_name) {
        format!("{}_", sql_name)
    } else if contains_unmappable_chars(sql_name) {
        // Map each non-alphanumeric character ([^a-zA-Z0-9]) to an underscore.
        let mut rust_name: String = sql_name
            .chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
            .collect();

        // Iteratively remove adjoining underscores ("__").
        let mut last_len = rust_name.len();
        'remove_adjoining: loop {
            rust_name = rust_name.replace("__", "_");
            if rust_name.len() == last_len {
                // No more underscore pairs left.
                break 'remove_adjoining;
            }
            last_len = rust_name.len();
        }

        rust_name
    } else {
        sql_name.to_string()
    }
}

pub fn load_table_names(
    database_url: &str,
    schema_name: Option<&str>,
) -> Result<Vec<TableName>, Box<dyn Error + Send + Sync + 'static>> {
    let mut connection = InferConnection::establish(database_url)?;

    match connection {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(ref mut c) => super::sqlite::load_table_names(c, schema_name),
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut c) => {
            super::information_schema::load_table_names(c, schema_name)
        }
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(ref mut c) => {
            super::information_schema::load_table_names(c, schema_name)
        }
    }
}

fn get_table_comment(
    conn: &mut InferConnection,
    table: &TableName,
) -> Result<Option<String>, Box<dyn Error + Send + Sync + 'static>> {
    let table_comment = match *conn {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(_) => Ok(None),
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut c) => super::pg::get_table_comment(c, table),
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(ref mut c) => super::mysql::get_table_comment(c, table),
    };
    if let Err(NotFound) = table_comment {
        Err(format!("no table exists named {}", table).into())
    } else {
        table_comment.map_err(Into::into)
    }
}

fn get_column_information(
    conn: &mut InferConnection,
    table: &TableName,
    column_sorting: &ColumnSorting,
) -> Result<Vec<ColumnInformation>, Box<dyn Error + Send + Sync + 'static>> {
    let column_info = match *conn {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(ref mut c) => {
            super::sqlite::get_table_data(c, table, column_sorting)
        }
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut c) => super::pg::get_table_data(c, table, column_sorting),
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(ref mut c) => super::mysql::get_table_data(c, table, column_sorting),
    };
    if let Err(NotFound) = column_info {
        Err(format!("no table exists named {}", table).into())
    } else {
        column_info.map_err(Into::into)
    }
}

fn determine_column_type(
    attr: &ColumnInformation,
    conn: &mut InferConnection,
) -> Result<ColumnType, Box<dyn Error + Send + Sync + 'static>> {
    match *conn {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(_) => super::sqlite::determine_column_type(attr),
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut conn) => {
            use crate::infer_schema_internals::information_schema::DefaultSchema;

            super::pg::determine_column_type(attr, diesel::pg::Pg::default_schema(conn)?)
        }
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(_) => super::mysql::determine_column_type(attr),
    }
}

pub(crate) fn get_primary_keys(
    conn: &mut InferConnection,
    table: &TableName,
) -> Result<Vec<String>, Box<dyn Error + Send + Sync + 'static>> {
    let primary_keys: Vec<String> = match *conn {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(ref mut c) => super::sqlite::get_primary_keys(c, table),
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut c) => super::information_schema::get_primary_keys(c, table),
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(ref mut c) => super::information_schema::get_primary_keys(c, table),
    }?;
    if primary_keys.is_empty() {
        Err(format!(
            "Diesel only supports tables with primary keys. \
             Table {} has no primary key",
            table,
        )
        .into())
    } else {
        Ok(primary_keys)
    }
}

pub fn load_foreign_key_constraints(
    database_url: &str,
    schema_name: Option<&str>,
) -> Result<Vec<ForeignKeyConstraint>, Box<dyn Error + Send + Sync + 'static>> {
    let mut connection = InferConnection::establish(database_url)?;

    let constraints = match connection {
        #[cfg(feature = "sqlite")]
        InferConnection::Sqlite(ref mut c) => {
            super::sqlite::load_foreign_key_constraints(c, schema_name)
        }
        #[cfg(feature = "postgres")]
        InferConnection::Pg(ref mut c) => {
            super::information_schema::load_foreign_key_constraints(c, schema_name)
                .map_err(Into::into)
        }
        #[cfg(feature = "mysql")]
        InferConnection::Mysql(ref mut c) => {
            super::mysql::load_foreign_key_constraints(c, schema_name).map_err(Into::into)
        }
    };

    constraints.map(|mut ct| {
        ct.sort();
        ct.iter_mut().for_each(|foreign_key_constraint| {
            if is_reserved_name(&foreign_key_constraint.foreign_key_rust_name) {
                foreign_key_constraint.foreign_key_rust_name =
                    format!("{}_", foreign_key_constraint.foreign_key_rust_name);
            }
        });
        ct
    })
}

macro_rules! doc_comment {
    ($($token:tt)*) => {
        format!($($token)*)
            .lines()
            .map(str::trim)
            .collect::<Vec<_>>()
            .join("\n")
    };
}

pub fn load_table_data(
    database_url: &str,
    name: TableName,
    column_sorting: &ColumnSorting,
) -> Result<TableData, Box<dyn Error + Send + Sync + 'static>> {
    let mut connection = InferConnection::establish(database_url)?;

    let table_comment = get_table_comment(&mut connection, &name)?;
    let docs = table_comment.unwrap_or_else(|| {
        doc_comment!(
            "Representation of the `{}` table.

            (Automatically generated by Diesel.)",
            name.full_sql_name(),
        )
    });
    let primary_key = get_primary_keys(&mut connection, &name)?;
    let primary_key = primary_key
        .iter()
        .map(|k| rust_name_for_sql_name(k))
        .collect();

    let column_data = get_column_information(&mut connection, &name, column_sorting)?
        .into_iter()
        .map(|c| {
            let ty = determine_column_type(&c, &mut connection)?;

            let ColumnInformation {
                column_name,
                comment,
                ..
            } = c;
            let rust_name = rust_name_for_sql_name(&column_name);

            let docs = comment.unwrap_or_else(|| {
                doc_comment!(
                    "The `{}` column of the `{}` table.

                    Its SQL type is `{}`.

                    (Automatically generated by Diesel.)",
                    column_name,
                    name.full_sql_name(),
                    ty
                )
            });
            Ok(ColumnDefinition {
                docs,
                sql_name: column_name,
                ty,
                rust_name,
            })
        })
        .collect::<Result<_, Box<dyn Error + Send + Sync + 'static>>>()?;

    Ok(TableData {
        name,
        primary_key,
        column_data,
        docs,
    })
}


text:
package org.eclipse.php.internal.core.util.preferences;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.core.runtime.Preferences;
import org.eclipse.php.internal.core.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * XML preferences reader for reading XML structures from the prefernces store.
 * This class works in combination with IXMLPreferencesStorable.
 */
public class XMLPreferencesReader {

	public static final char DELIMITER = (char) 5;
	protected static final Pattern LT_PATTERN = Pattern.compile("<"); //$NON-NLS-1$
	protected static final Pattern GT_PATTERN = Pattern.compile(">"); //$NON-NLS-1$
	protected static final Pattern QUOT_PATTERN = Pattern.compile("""); //$NON-NLS-1$
	protected static final Pattern APOS_PATTERN = Pattern.compile("'"); //$NON-NLS-1$
	protected static final Pattern AMP_PATTERN = Pattern.compile("&"); //$NON-NLS-1$
	public static final String STRING_DEFAULT = ""; //$NON-NLS-1$

	public static String getUnEscaped(String s) {
		s = LT_PATTERN.matcher(s).replaceAll("<"); //$NON-NLS-1$
		s = GT_PATTERN.matcher(s).replaceAll(">"); //$NON-NLS-1$
		s = QUOT_PATTERN.matcher(s).replaceAll("\""); //$NON-NLS-1$
		s = APOS_PATTERN.matcher(s).replaceAll("'"); //$NON-NLS-1$
		s = AMP_PATTERN.matcher(s).replaceAll("&"); //$NON-NLS-1$
		return s;
	}

	private static HashMap read(NodeList nl) {
		HashMap map = new HashMap(nl.getLength());
		for (int i = 0; i < nl.getLength(); ++i) {
			Node n = nl.item(i);
			if (n.hasChildNodes()) {
				if (n.getFirstChild().getNodeType() == Node.TEXT_NODE) {
					map.put(n.getNodeName(), getUnEscaped(n.getFirstChild()
							.getNodeValue()));
				} else {
					map.put(n.getNodeName(), read(n.getChildNodes()));
				}
			}
		}
		return map;
	}

	protected static HashMap read(String str) {
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			// docBuilderFactory.setValidating(true);
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(new ByteArrayInputStream(str
					.getBytes()));

			return read(doc.getChildNodes());

		} catch (Exception e) {
			Logger.logException(e);
		}
		return null;
	}

	/**
	 * Reads a map of elements from the Preferences by a given key.
	 *
	 * @param store
	 * @param prefsKey
	 * @return
	 */
	public static HashMap[] read(Preferences store, String prefsKey) {
		String storedValue = store.getString(prefsKey);
		return getHashFromStoredValue(storedValue);
	}

	public static HashMap[] getHashFromStoredValue(String storedValue) {

		ArrayList maps = new ArrayList();
		StringTokenizer st = new StringTokenizer(storedValue, new String(
				new char[] { DELIMITER }));
		while (st.hasMoreTokens()) {
			maps.add(read(st.nextToken()));
		}
		return (HashMap[]) maps.toArray(new HashMap[maps.size()]);

	}
}


text:
require "spec_helper"

describe AnswersController do
  describe "routing" do

    it "routes to #create" do
      post("/questions/1/answers").should route_to("answers#create", :question_id => "1" )
    end

    it "routes to #update" do
      put("/questions/1/answers/1").should route_to("answers#update", :id => "1", :question_id => "1")
    end

    it "routes to #destroy" do
      delete("/questions/1/answers/1").should route_to("answers#destroy", :id => "1", :question_id => "1")
    end

  end
end


text:
module.exports = {
  PORT: process.env.PORT || 3000,
  HOSTNAME: process.env.HOSTNAME || 'localhost',
  MONGODB_URL: process.env.MONGODB_URL || 'mongodb://localhost:27017/stripe-demo'
};


text:
package org.ejml.alg.dense.decomposition.bidiagonal;

import org.ejml.alg.dense.decomposition.qr.QrHelperFunctions_D64;
import org.ejml.data.DenseMatrix64F;
import org.ejml.interfaces.decomposition.BidiagonalDecomposition;
import org.ejml.ops.CommonOps;

/**
 * <p>
 * Performs a {@link org.ejml.interfaces.decomposition.BidiagonalDecomposition} using
 * householder reflectors.  This is efficient on wide or square matrices.
 * </p>
 *
 * @author Peter Abeles
 */
public class BidiagonalDecompositionRow_D64
        implements BidiagonalDecomposition<DenseMatrix64F>
{
    // A combined matrix that stores te upper Hessenberg matrix and the orthogonal matrix.
    private DenseMatrix64F UBV;

    // number of rows
    private int m;
    // number of columns
    private int n;
    // the smaller of m or n
    private int min;

    // the first element in the orthogonal vectors
    private double gammasU[];
    private double gammasV[];
    // temporary storage
    private double b[];
    private double u[];

    /**
     * Creates a decompose that defines the specified amount of memory.
     *
     * @param numElements number of elements in the matrix.
     */
    public BidiagonalDecompositionRow_D64(int numElements) {

        UBV = new DenseMatrix64F(numElements);
        gammasU = new double[ numElements ];
        gammasV = new double[ numElements ];
        b = new double[ numElements ];
        u = new double[ numElements ];
    }

    public BidiagonalDecompositionRow_D64() {
        this(1);
    }

    /**
     * Computes the decomposition of the provided matrix.  If no errors are detected then true is returned,
     * false otherwise.
     *
     * @param A  The matrix that is being decomposed.  Not modified.
     * @return If it detects any errors or not.
     */
    @Override
    public boolean decompose( DenseMatrix64F A  )
    {
        init(A);
        return _decompose();
    }

    /**
     * Sets up internal data structures and creates a copy of the input matrix.
     *
     * @param A The input matrix.  Not modified.
     */
    protected void init(DenseMatrix64F A ) {
        UBV = A;

        m = UBV.numRows;
        n = UBV.numCols;

        min = Math.min(m,n);
        int max = Math.max(m,n);

        if( b.length < max+1 ) {
            b = new double[ max+1 ];
            u = new double[ max+1 ];
        }
        if( gammasU.length < m ) {
            gammasU = new double[ m ];
        }
        if( gammasV.length < n ) {
            gammasV = new double[ n ];
        }
    }

    /**
     * The raw UBV matrix that is stored internally.
     *
     * @return UBV matrix.
     */
    public DenseMatrix64F getUBV() {
        return UBV;
    }

    @Override
    public void getDiagonal(double[] diag, double[] off) {
        diag[0] = UBV.get(0);
        for( int i = 1; i < n; i++ ) {
            diag[i] = UBV.unsafe_get(i,i);
            off[i-1] = UBV.unsafe_get(i-1,i);
        }
    }

    /**
     * Returns the bidiagonal matrix.
     *
     * @param B If not null the results are stored here, if null a new matrix is created.
     * @return The bidiagonal matrix.
     */
    @Override
    public DenseMatrix64F getB( DenseMatrix64F B , boolean compact ) {
        B = handleB(B, compact,m,n,min);

        //System.arraycopy(UBV.data, 0, B.data, 0, UBV.getNumElements());

        B.set(0,0,UBV.get(0,0));
        for( int i = 1; i < min; i++ ) {
            B.set(i,i, UBV.get(i,i));
            B.set(i-1,i, UBV.get(i-1,i));
        }
        if( n > m )
            B.set(min-1,min,UBV.get(min-1,min));

        return B;
    }

    public static DenseMatrix64F handleB(DenseMatrix64F B, boolean compact,
                                          int m , int n , int min ) {
        int w = n > m ? min + 1 : min;

        if( compact ) {
            if( B == null ) {
                B = new DenseMatrix64F(min,w);
            } else {
                B.reshape(min,w, false);
                B.zero();
            }
        } else {
            if( B == null ) {
                B = new DenseMatrix64F(m,n);
            } else {
                B.reshape(m,n, false);
                B.zero();
            }
        }
        return B;
    }

    /**
     * Returns the orthogonal U matrix.
     *
     * @param U If not null then the results will be stored here.  Otherwise a new matrix will be created.
     * @return The extracted Q matrix.
     */
    @Override
    public DenseMatrix64F getU( DenseMatrix64F U , boolean transpose , boolean compact ) {
        U = handleU(U, transpose, compact,m,n,min);
        CommonOps.setIdentity(U);

        for( int i = 0; i < m; i++ ) u[i] = 0;

        for( int j = min-1; j >= 0; j-- ) {
            u[j] = 1;
            for( int i = j+1; i < m; i++ ) {
                u[i] = UBV.get(i,j);
            }
            if( transpose )
                QrHelperFunctions_D64.rank1UpdateMultL(U, u, gammasU[j], j, j, m);
            else
                QrHelperFunctions_D64.rank1UpdateMultR(U, u, gammasU[j], j, j, m, this.b);
        }

        return U;
    }

    public static DenseMatrix64F handleU(DenseMatrix64F U,
                                         boolean transpose, boolean compact,
                                         int m, int n , int min ) {
        if( compact ){
            if( transpose ) {
                if( U == null )
                    U = new DenseMatrix64F(min,m);
                else {
                    U.reshape(min,m, false);
                }
            } else {
                if( U == null )
                    U = new DenseMatrix64F(m,min);
                else
                    U.reshape(m,min, false);
            }
        } else  {
            if( U == null )
                U = new DenseMatrix64F(m,m);
            else
                U.reshape(m,m, false);
        }

        return U;
    }

    /**
     * Returns the orthogonal V matrix.
     *
     * @param V If not null then the results will be stored here.  Otherwise a new matrix will be created.
     * @return The extracted Q matrix.
     */
    @Override
    public DenseMatrix64F getV( DenseMatrix64F V , boolean transpose , boolean compact ) {
        V = handleV(V, transpose, compact,m,n,min);
        CommonOps.setIdentity(V);

//        UBV.print();

        // todo the very first multiplication can be avoided by setting to the rank1update output
        for( int j = min-1; j >= 0; j-- ) {
            u[j+1] = 1;
            for( int i = j+2; i < n; i++ ) {
                u[i] = UBV.get(j,i);
            }
            if( transpose )
                QrHelperFunctions_D64.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);
            else
                QrHelperFunctions_D64.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);
        }

        return V;
    }

    public static DenseMatrix64F handleV(DenseMatrix64F V, boolean transpose, boolean compact,
                                   int m , int n , int min ) {
        int w = n > m ? min + 1 : min;

        if( compact ) {
            if( transpose ) {
                if( V == null ) {
                    V = new DenseMatrix64F(w,n);
                } else
                    V.reshape(w,n, false);
            } else {
                if( V == null ) {
                    V = new DenseMatrix64F(n,w);
                } else
                    V.reshape(n,w, false);
            }
        } else {
            if( V == null ) {
                V = new DenseMatrix64F(n,n);
            } else
                V.reshape(n,n, false);
        }

        return V;
    }

    /**
     * Internal function for computing the decomposition.
     */
    private boolean _decompose() {
        for( int k = 0; k < min; k++ ) {
//            UBV.print();
            computeU(k);
//            System.out.println("--- after U");
//            UBV.print();
            computeV(k);
//            System.out.println("--- after V");
//            UBV.print();
        }

        return true;
    }

    protected void computeU( int k) {
        double b[] = UBV.data;

        // find the largest value in this column
        // this is used to normalize the column and mitigate overflow/underflow
        double max = 0;

        for( int i = k; i < m; i++ ) {
            // copy the householder vector to vector outside of the matrix to reduce caching issues
            // big improvement on larger matrices and a relatively small performance hit on small matrices.
            double val = u[i] = b[i*n+k];
            val = Math.abs(val);
            if( val > max )
                max = val;
        }

        if( max > 0 ) {
            // -------- set up the reflector Q_k
            double tau = QrHelperFunctions_D64.computeTauAndDivide(k, m, u, max);

            // write the reflector into the lower left column of the matrix
            // while dividing u by nu
            double nu = u[k] + tau;
            QrHelperFunctions_D64.divideElements_Bcol(k + 1, m, n, u, b, k, nu);
            u[k] = 1.0;

            double gamma = nu/tau;
            gammasU[k] = gamma;

            // ---------- multiply on the left by Q_k
            QrHelperFunctions_D64.rank1UpdateMultR(UBV, u, gamma, k + 1, k, m, this.b);

            b[k*n+k] = -tau*max;
        } else {
            gammasU[k] = 0;
        }
    }

    protected void computeV(int k) {
        double b[] = UBV.data;

        int row = k*n;

        // find the largest value in this column
        // this is used to normalize the column and mitigate overflow/underflow
        double max = QrHelperFunctions_D64.findMax(b, row + k + 1, n - k - 1);

        if( max > 0 ) {
            // -------- set up the reflector Q_k

            double tau = QrHelperFunctions_D64.computeTauAndDivide(k + 1, n, b, row, max);

            // write the reflector into the lower left column of the matrix
            double nu = b[row+k+1] + tau;
            QrHelperFunctions_D64.divideElements_Brow(k + 2, n, u, b, row, nu);

            u[k+1] = 1.0;

            double gamma = nu/tau;
            gammasV[k] = gamma;

            // writing to u could be avoided by working directly with b.
            // requires writing a custom rank1Update function
            // ---------- multiply on the left by Q_k
            QrHelperFunctions_D64.rank1UpdateMultL(UBV, u, gamma, k + 1, k + 1, n);

            b[row+k+1] = -tau*max;
        } else {
            gammasV[k] = 0;
        }
    }

    /**
     * Returns gammas from the householder operations for the U matrix.
     *
     * @return gammas for householder operations
     */
    public double[] getGammasU() {
        return gammasU;
    }

    /**
     * Returns gammas from the householder operations for the V matrix.
     *
     * @return gammas for householder operations
     */
    public double[] getGammasV() {
        return gammasV;
    }

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


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE locale SYSTEM "../../../../../lib/pkp/dtd/locale.dtd">

<!--
  * plugins/importexport/doaj/locale/id_ID/locale.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * Localization strings for the en_US (U.S. English) locale.
  *
  -->

<locale name="id_ID" full_name="Indonesia">
	<message key="plugins.importexport.doaj.displayName">Plugin Ekspor DOAJ</message>
	<message key="plugins.importexport.doaj.description">Ekspor Jurnal untuk DOAJ dan sediakan informasi jurnal untuk pencantuman</message>

	<message key="plugins.importexport.doaj.export">Ekspor Data Jurnal ke DOAJ</message>
	<message key="plugins.importexport.doaj.export.journal">Ekspor Jurnal</message>
	<message key="plugins.importexport.doaj.export.contact">Kontak DOAJ untuk pencantuman</message>
	<message key="plugins.importexport.doaj.export.journalInfo">Ekspor informasi artikel dalam XML untuk pengarsipan dalam DOAJ</message>
	<message key="plugins.importexport.doaj.export.contactInfo">sebagai bahan pertimbangan, silahkan menyerahkan sebagian formulir yang telah diisi ke DOAJ, dan isi informasi yang belum lengkap sebaik yang kamu bisa.</message>

</locale>


text:
"""USB updater tool for servo and similar boards."""

from __future__ import print_function

import argparse
import json
import os
import re
import subprocess
import time

import ecusb.tiny_servo_common as c
import fw_update
from ecusb import tiny_servod

class ServoUpdaterException(Exception):
    """Raised on exceptions generated by servo_updater."""

BOARD_C2D2 = "c2d2"
BOARD_SERVO_MICRO = "servo_micro"
BOARD_SERVO_V4 = "servo_v4"
BOARD_SERVO_V4P1 = "servo_v4p1"
BOARD_SWEETBERRY = "sweetberry"

DEFAULT_BOARD = BOARD_SERVO_V4

# These lists are to facilitate exposing choices in the command-line tool
# below.
BOARDS = [
    BOARD_C2D2,
    BOARD_SERVO_MICRO,
    BOARD_SERVO_V4,
    BOARD_SERVO_V4P1,
    BOARD_SWEETBERRY,
]

# Servo firmware bundles four channels of firmware. We need to make sure the
# user does not request a non-existing channel, so keep the lists around to
# guard on command-line usage.

DEFAULT_CHANNEL = STABLE_CHANNEL = "stable"

PREV_CHANNEL = "prev"

# The ordering here matters. From left to right it's the channel that the user
# is most likely to be running. This is used to inform and warn the user if
# there are issues. e.g. if the all channels are the same, we want to let the
# user know they are running the 'stable' version before letting them know they
# are running 'dev' or even 'alpah' which (while true) might cause confusion.

CHANNELS = [DEFAULT_CHANNEL, PREV_CHANNEL, "dev", "alpha"]

DEFAULT_BASE_PATH = "/usr/"
TEST_IMAGE_BASE_PATH = "/usr/local/"

COMMON_PATH = "share/servo_updater"

FIRMWARE_DIR = "firmware/"
CONFIGS_DIR = "configs/"

RETRIES_COUNT = 10
RETRIES_DELAY = 1

def do_with_retries(func, *args):
    """Try a function several times

    Call function passed as argument and check if no error happened.
    If exception was raised by function,
    it will be retried up to RETRIES_COUNT times.

    Args:
      func: function that will be called
      args: arguments passed to 'func'

    Returns:
      If call to function was successful, its result will be returned.
      If retries count was exceeded, exception will be raised.
    """

    retry = 0
    while retry < RETRIES_COUNT:
        try:
            return func(*args)
        except Exception as e:
            print("Retrying function %s: %s" % (func.__name__, e))
            retry = retry + 1
            time.sleep(RETRIES_DELAY)
            continue

    raise Exception(
        "'{}' failed after {} retries".format(func.__name__, RETRIES_COUNT)
    )

def flash(brdfile, serialno, binfile):
    """Call fw_update to upload to updater USB endpoint.

    Args:
      brdfile: path to board configuration file
      serialno: device serial number
      binfile: firmware file
    """

    p = fw_update.Supdate()
    p.load_board(brdfile)
    p.connect_usb(serialname=serialno)
    p.load_file(binfile)

    # Start transfer and erase.
    p.start()
    # Upload the bin file
    print("Uploading %s" % binfile)
    p.write_file()

    # Finalize
    print("Done. Finalizing.")
    p.stop()

def flash2(vidpid, serialno, binfile):
    """Call fw update via usb_updater2 commandline.

    Args:
      vidpid: vendor id and product id of device
      serialno: device serial number (optional)
      binfile: firmware file
    """

    tool = "usb_updater2"
    cmd = "%s -d %s" % (tool, vidpid)
    if serialno:
        cmd += " -S %s" % serialno
    cmd += " -n"
    cmd += " %s" % binfile

    print(cmd)
    help_cmd = "%s --help" % tool
    with open("/dev/null") as devnull:
        valid_check = subprocess.call(
            help_cmd.split(), stdout=devnull, stderr=devnull
        )
    if valid_check:
        raise ServoUpdaterException(
            "%s exit with res = %d. Make sure the tool "
            "is available on the device." % (help_cmd, valid_check)
        )
    res = subprocess.call(cmd.split())

    if res in (0, 1, 2):
        return res
    else:
        raise ServoUpdaterException("%s exit with res = %d" % (cmd, res))

def select(tinys, region):
    """Jump to specified boot region

    Ensure the servo is in the expected ro/rw region.
    This function jumps to the required region and verify if jump was
    successful by executing 'sysinfo' command and reading current region.
    If response was not received or region is invalid, exception is raised.

    Args:
      tinys: TinyServod object
      region: region to jump to, only "rw" and "ro" is allowed
    """

    if region not in ["rw", "ro"]:
        raise Exception("Region must be ro or rw")

    if region == "ro":
        cmd = "reboot"
    else:
        cmd = "sysjump %s" % region

    tinys.pty._issue_cmd(cmd)

    tinys.close()
    time.sleep(2)
    tinys.reinitialize()

    res = tinys.pty._issue_cmd_get_results("sysinfo", [r"Copy:[\s]+(RO|RW)"])
    current_region = res[0][1].lower()
    if current_region != region:
        raise Exception("Invalid region: %s/%s" % (current_region, region))

def do_version(tinys):
    """Check version via ec console 'pty'.

    Args:
      tinys: TinyServod object

    Returns:
      detected version number

    Commands are:
    # > version
    # ...
    # Build:   tigertail_v1.1.6749-74d1a312e
    """
    cmd = "version"
    regex = r"Build:\s+(\S+)[\r\n]+"

    results = tinys.pty._issue_cmd_get_results(cmd, [regex])[0]

    return results[1].strip(" \t\r\n\0")

def do_updater_version(tinys):
    """Check whether this uses python updater or c++ updater

    Args:
      tinys: TinyServod object

    Returns:
      updater version number. 2 or 6.
    """
    vers = do_version(tinys)

    # Servo versions below 58 are from servo-9040.B. Versions starting with _v2
    # are newer than anything _v1, no need to check the exact number. Updater
    # version is not directly queryable.
    if re.search(r"_v[2-9]\.\d", vers):
        return 6
    m = re.search(r"_v1\.1\.(\d\d\d\d)", vers)
    if m:
        version_number = int(m.group(1))
        if version_number < 5800:
            return 2
        else:
            return 6
    raise ServoUpdaterException(
        "Can't determine updater target from vers: [%s]" % vers
    )

def _extract_version(boardname, binfile):
    """Find the version string from |binfile|.

    Args:
      boardname: the name of the board, eg. "servo_micro"
      binfile: path to the binary to search

    Returns:
      the version string.
    """
    if boardname is None:
        # cannot extract the version if the name is None
        return None
    rawstrings = subprocess.check_output(
        ["cbfstool", binfile, "read", "-r", "RO_FRID", "-f", "/dev/stdout"],
        **c.get_subprocess_args()
    )
    m = re.match(r"%s_v\S+" % boardname, rawstrings)
    if m:
        newvers = m.group(0).strip(" \t\r\n\0")
    else:
        raise ServoUpdaterException(
            "Can't find version from file: %s." % binfile
        )

    return newvers

def get_firmware_channel(bname, version):
    """Find out which channel |version| for |bname| came from.

    Args:
      bname: board name
      version: current version string

    Returns:
      one of the channel names if |version| came from one of those, or None
    """
    for channel in CHANNELS:
        # Pass |bname| as cname to find the board specific file, and pass None as
        # fname to ensure the default directory is searched
        _, _, vers = get_files_and_version(bname, None, channel=channel)
        if version == vers:
            return channel
    # None of the channels matched. This firmware is currently unknown.
    return None

def get_files_and_version(cname, fname=None, channel=DEFAULT_CHANNEL):
    """Select config and firmware binary files.

    This checks default file names and paths.
    In: /usr/share/servo_updater/[firmware|configs]
    check for board.json, board.bin

    Args:
      cname: board name, or config name. eg. "servo_v4" or "servo_v4.json"
      fname: firmware binary name. Can be None to try default.
      channel: the channel requested for servo firmware. See |CHANNELS| above.

    Returns:
      cname, fname, version: validated filenames selected from the path.
    """
    for p in (DEFAULT_BASE_PATH, TEST_IMAGE_BASE_PATH):
        updater_path = os.path.join(p, COMMON_PATH)
        if os.path.exists(updater_path):
            break
    else:
        raise ServoUpdaterException(
            "servo_updater/ dir not found in known spots."
        )

    firmware_path = os.path.join(updater_path, FIRMWARE_DIR)
    configs_path = os.path.join(updater_path, CONFIGS_DIR)

    for p in (firmware_path, configs_path):
        if not os.path.exists(p):
            raise ServoUpdaterException("Could not find required path %r" % p)

    if not os.path.isfile(cname):
        # If not an existing file, try checking on the default path.
        newname = os.path.join(configs_path, cname)
        if os.path.isfile(newname):
            cname = newname
        else:
            # Try appending ".json" to convert board name to config file.
            cname = newname + ".json"
        if not os.path.isfile(cname):
            raise ServoUpdaterException("Can't find config file: %s." % cname)

    # Always retrieve the boardname
    with open(cname) as data_file:
        data = json.load(data_file)
    boardname = data["board"]

    if not fname:
        # If no |fname| supplied, look for the default locations with the board
        # and channel requested.
        binary_file = "%s.%s.bin" % (boardname, channel)
        newname = os.path.join(firmware_path, binary_file)
        if os.path.isfile(newname):
            fname = newname
        else:
            raise ServoUpdaterException(
                "Can't find firmware binary: %s." % binary_file
            )
    elif not os.path.isfile(fname):
        # If a name is specified but not found, try the default path.
        newname = os.path.join(firmware_path, fname)
        if os.path.isfile(newname):
            fname = newname
        else:
            raise ServoUpdaterException("Can't find file: %s." % fname)

    # Lastly, retrieve the version as well for decision making, debug, and
    # informational purposes.
    binvers = _extract_version(boardname, fname)

    return cname, fname, binvers

def main():
    parser = argparse.ArgumentParser(description="Image a servo device")
    parser.add_argument(
        "-p",
        "--print",
        dest="print_only",
        action="store_true",
        default=False,
        help="only print available firmware for board/channel",
    )
    parser.add_argument(
        "-s",
        "--serialno",
        type=str,
        help="serial number to program",
        default=None,
    )
    parser.add_argument(
        "-b",
        "--board",
        type=str,
        help="Board configuration json file",
        default=DEFAULT_BOARD,
        choices=BOARDS,
    )
    parser.add_argument(
        "-c",
        "--channel",
        type=str,
        help="Firmware channel to use",
        default=DEFAULT_CHANNEL,
        choices=CHANNELS,
    )
    parser.add_argument(
        "-f", "--file", type=str, help="Complete ec.bin file", default=None
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Update even if version match",
        default=False,
    )
    parser.add_argument(
        "-v", "--verbose", action="store_true", help="Chatty output"
    )
    parser.add_argument(
        "-r",
        "--reboot",
        action="store_true",
        help="Always reboot, even after probe.",
    )

    args = parser.parse_args()

    brdfile, binfile, newvers = get_files_and_version(
        args.board, args.file, args.channel
    )

    # If the user only cares about the information then just print it here,
    # and exit.
    if args.print_only:
        output = ("board: %s\nchannel: %s\nfirmware: %s") % (
            args.board,
            args.channel,
            newvers,
        )
        print(output)
        return

    serialno = args.serialno

    with open(brdfile) as data_file:
        data = json.load(data_file)
    vid, pid = int(data["vid"], 0), int(data["pid"], 0)
    vidpid = "%04x:%04x" % (vid, pid)
    iface = int(data["console"], 0)
    boardname = data["board"]

    # Make sure device is up.
    print("===== Waiting for USB device =====")
    c.wait_for_usb(vidpid, serialname=serialno)
    # We need a tiny_servod to query some information. Set it up first.
    tinys = tiny_servod.TinyServod(vid, pid, iface, serialno, args.verbose)

    if not args.force:
        vers = do_version(tinys)
        print("Current %s version is   %s" % (boardname, vers))
        print("Available %s version is %s" % (boardname, newvers))

        if newvers == vers:
            print("No version update needed")
            if args.reboot:
                select(tinys, "ro")
            return
        else:
            print("Updating to recommended version.")

    # Make sure the servo MCU is in RO
    print("===== Jumping to RO =====")
    do_with_retries(select, tinys, "ro")

    print("===== Flashing RW =====")
    vers = do_with_retries(do_updater_version, tinys)
    # To make sure that the tiny_servod here does not interfere with other
    # processes, close it out.
    tinys.close()

    if vers == 2:
        flash(brdfile, serialno, binfile)
    elif vers == 6:
        do_with_retries(flash2, vidpid, serialno, binfile)
    else:
        raise ServoUpdaterException("Can't detect updater version")

    # Make sure device is up.
    c.wait_for_usb(vidpid, serialname=serialno)
    # After we have made sure that it's back/available, reconnect the tiny servod.
    tinys.reinitialize()

    # Make sure the servo MCU is in RW
    print("===== Jumping to RW =====")
    do_with_retries(select, tinys, "rw")

    print("===== Flashing RO =====")
    vers = do_with_retries(do_updater_version, tinys)

    if vers == 2:
        flash(brdfile, serialno, binfile)
    elif vers == 6:
        do_with_retries(flash2, vidpid, serialno, binfile)
    else:
        raise ServoUpdaterException("Can't detect updater version")

    # Make sure the servo MCU is in RO
    print("===== Rebooting =====")
    do_with_retries(select, tinys, "ro")
    # Perform additional reboot to free USB/UART resources, taken by tiny servod.
    # See https://issuetracker.google.com/196021317 for background.
    tinys.pty._issue_cmd("reboot")

    print("===== Finished =====")

if __name__ == "__main__":
    main()


text:
from .exporter import Exporter

class TestExporter(Exporter):
    """
    A simple exporter that extracts the test input (or the reduced test input,
    if it exists) from the issue.

    Note: This exporter expects the test input to be a :class:`str` or a
    :class:`bytes` instance.

    **Optional parameters of the exporter:**

      - ``extension``: the filename extension (including the leading period) to
        use when writing exported test inputs to file (default: no extension).

      - ``type``: the MIME (or content) type of the exported test inputs
        (default: no MIME type).

    **Example configuration snippet:**

        .. code-block:: ini

            [sut.foo]
            # see fuzzinator.call.*
            exporter=fuzzinator.exporter.TestExporter

            [sut.foo.exporter]
            extension=.txt
            type=text/plain
    """

    def __init__(self, *, extension=None, type=None, **kwargs):
        self.extension = extension
        self.type = type

    def __call__(self, *, issue):
        return issue.get('reduced') or issue['test']


text:
using System;
using Frapid.DataAccess;
using Frapid.NPoco;

namespace Frapid.Account.Entities
{
    [TableName("account.logins")]
    [PrimaryKey("login_id", AutoIncrement = true)]
    public sealed class Login : IPoco
    {
        public long LoginId { get; set; }
        public int? UserId { get; set; }
        public int? OfficeId { get; set; }
        public string Browser { get; set; }
        public string IpAddress { get; set; }
        public DateTime LoginTimestamp { get; set; }
        public string Culture { get; set; }
    }
}


text:
use Catalyst::ScriptRunner;
Catalyst::ScriptRunner->run('OpenClimateClient', 'CGI');

1;

=head1 NAME

openclimateclient_cgi.pl - Catalyst CGI

=head1 SYNOPSIS

See L<Catalyst::Manual>

=head1 DESCRIPTION

Run a Catalyst application as a CGI script.

=head1 AUTHORS

Catalyst Contributors, see Catalyst.pm

=head1 COPYRIGHT

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut


text:
"""
tunable.py contains a tunable (settings to be changed depending on input data) management class
"""
from __future__ import division, unicode_literals, print_function

import logging

class TunableManager(object):
    """
    TunableManager

    Static object handling tunables (that is, parameters which are user-changeable)

    Tunables have default values, which must be set as a parameter by the function asking for the tunable.
    That way, default configuration is inlined, and does not need to be centrally managed.
    In order to collect all defaults, a typical run of the program has to be performed, and the collected default
    values to be dumped afterwards.

    :cvar defaults: Internal map of defaults
    :vartype defaults: dict
    :cvar current: Current tunables, with possible overrides.
    :vartype current: dict
    :cvar force_default: Whether to force usage of default values (default: `False`)
    :vartype force_default: bool

    """

    defaults = {}

    current = {}

    descriptions = {}

    force_default = False

    logger = logging.getLogger(__name__ + '.' + 'TunableManager')

    @classmethod
    def set_description(cls, what, description):
        """
        Sets a description for a paremeter.

        :param what: parameter to describe
        :param description: description
        :return:
        """
        cls.descriptions[what] = description

    @classmethod
    def get_descriptions(cls):
        """
        Gets descriptions.

        :return: The descriptions.
        :rtype: dict
        """
        return cls.descriptions

    @classmethod
    def get_table(cls):
        descriptions = cls.get_descriptions()

        return [
            {
                'name': k,
                'default': v,
                'type_': type(v).__name__,
                'description': descriptions[k] if k in descriptions else ''
            }
            for k, v in cls.get_defaults().items()
        ]

    @classmethod
    def load_tunables(cls, data):
        """
        Sets the tunables.

        :param data: set of tunables to load
        :type data: dict
        :rtype: None

        >>> TunableManager.load_tunables({'foo': 'bar'})
        >>> tunable('foo', 'not bar')
        'bar'
        """
        cls.current = data

    @classmethod
    def get_defaults(cls):
        """
        Gets the defaults, which were collected during the calls asking for various tunables.

        :return: either the overridden tunable or the default value
        :rtype: dependent on default

        >>> TunableManager.defaults = {}
        >>> value = tunable('my.tunable', 3.1415)
        >>> TunableManager.get_defaults()
        {'my.tunable': 3.1415}
        """
        return cls.defaults

    @classmethod
    def get_tunable(cls, what, default):
        """
        Returns either an overridden tunable, or the default value.
        The result will be casted to the type of default.

        :param what: tunable to look up
        :type what: str
        :param default: default value
        :return: either the overridden tunable or the default value

        >>> tunable('my.tunable', 3.1415)
        3.1415
        """
        cls.defaults[what] = default
        if cls.force_default or what not in cls.current:
            result = default

            if cls.force_default:
                cls.logger.debug("Getting tunable \"%s\", forcing default: %s", what, repr(result))
            else:
                cls.logger.debug("Getting tunable \"%s\", using default: %s", what, repr(result))

        else:
            result = type(default)(cls.current[what])
            cls.logger.debug("Getting tunable \"%s\", using override: %s", what, repr(result))

        return result

def tunable(what, default, description=None):
    """
    Syntactic sugar helper function, to quickly get a tunable.
    Calls: :code:`TunableManager.get_tunable(what, default)`

    :param what: tunable to look up
    :type what: str or unicode
    :param default: default value
    :param description: description
    :return: either the overridden tunable or the default value
    :rtype: type(default)

    >>> tunable('my.tunable', 3.1415)
    3.1415
    """

    if description:
        TunableManager.set_description(what, description)

    return TunableManager.get_tunable(what, default)


text:
Certitude
=========

A small library that makes the OS X keychain-based certificate store available
to OpenSSL in a format that OpenSSL appreciates.

In the future, this library may expand to become a truly cross-platform tool
that pastes over the differences between platforms.

License
-------

OS X Cert Store is provided under the MIT License. See the ``LICENSE`` file for
copyright details.


text:
using System;
using System.Collections.Generic;
using EasyApi.Converting;
using EasyApi.Metadata;
using EasyApi.Metadata.Attributes;
using EasyApi.Values;
using NUnit.Framework;
using static EasyApi.Tests.TestUtils.ExtraPropertyHelpers;
using static EasyApi.Tests.TestUtils.TestCaseHelpers;

namespace EasyApi.Tests.Metadata.Attributes
{
	[TestFixture]
	[TestOf(typeof(MetadataPropertyAttribute))]
	[Parallelizable]
	public class MetadataPropertyAttributeTests : MetadataAttributeTests<MetadataPropertyAttribute>
	{
		protected override MetadataPropertyAttribute DefaultAttribute()
		{
			return new MetadataPropertyAttribute("CustomPropety")
			{
				Value = 42
			};
		}

		protected override IEnumerable<TestCaseData> AddPropertiesToWithInvalidStateTestCases => TestCases(
			TestCase(new MetadataPropertyAttribute("CustomProperty")),
			TestCase(new MetadataPropertyAttribute("CustomPropety")
			{
				Value = 12,
				ValueType = typeof(string)
			})
		);

		protected override object GetPropertyAddingResult(MetadataPropertyAttribute attribute, IExtraPropertyCollection properties)
		{
			Assert.IsTrue(properties.TryGet(attribute.Name, out var extraProperty));
			Assert.AreSame(attribute.Name, extraProperty.Metadata.Name);

			return extraProperty;
		}

		protected override IExtraPropertyMetadata AttributeMetadataProperty => throw new NotSupportedException();

		protected override IEnumerable<TestCaseData> AddPropertiesToTestCases => TestCases(
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.BindingName) { Value = "Body" },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.SameAs(MetadataProperties.BindingName)).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo("Body"))
			),
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.BindingName) { Value = 42 },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.Not.SameAs(MetadataProperties.BindingName).And.InstanceOf<ExtraPropertyMetadata<int>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(42))
			),
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.BindingName) { Value = null, ValueType = typeof(string) },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.Not.SameAs(MetadataProperties.BindingName).And.InstanceOf<ExtraPropertyMetadata<string>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.Null)
			),
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.BindingName) { Value = string.Empty },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.Not.SameAs(MetadataProperties.BindingName).And.InstanceOf<ExtraPropertyMetadata<string>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(string.Empty))
			),
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.BindingName) { Value = "Body", ValueType = typeof(object) },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.Not.SameAs(MetadataProperties.BindingName).And.InstanceOf<ExtraPropertyMetadata<object>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo("Body"))
			),
			TestCase(
				new MetadataPropertyAttribute(MetadataPropertyNames.GeneralTypeConverter) { ValueType = typeof(GeneralTypeConverter) },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.SameAs(MetadataProperties.GeneralTypeConverter).And.InstanceOf<ExtraPropertyMetadata<IGeneralTypeConverter>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.InstanceOf<GeneralTypeConverter>())
			),

			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { Value = 50 },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<int>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(50))
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { ValueType = typeof(int) },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<int>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(0))
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { Value = 50, ValueType = null, ValueConstructorArguments = null },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<int>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(50))
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { ValueType = typeof(int), ValueConstructorArguments = null },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<int>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo(0))
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { ValueType = typeof(string), ValueConstructorArguments = new object[] { 'c', 3 } },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<string>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo("ccc"))
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { Value = null, ValueType = typeof(string) },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<string>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.Null)
			),
			TestCase(
				new MetadataPropertyAttribute("CustomPropety") { Value = null },
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<object>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.Null)
			),

			TestCase(
				new MetadataPropertyAttribute("ExistingPropety") { Value = "test" },
				ExtraProperties(ExtraProperty.From("ExistingProperty", 100)),
				Has.Property(nameof(ExtraProperty.Metadata)).Matches(Is.InstanceOf<ExtraPropertyMetadata<string>>()).And
					.Property(nameof(ExtraProperty.Value)).Matches(Is.EqualTo("test"))
			)
		);
	}
}


text:
namespace CodapaloozaAPI.Areas.HelpPage
{
    /// <summary>
    /// Indicates whether the sample is used for request or response
    /// </summary>
    public enum SampleDirection
    {
        Request = 0,
        Response
    }
}


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/createAttributeNS06";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "hc_staff");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
    	catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*
Document.createAttributeNS with an empty qualified name should cause an INVALID_CHARACTER_ERR.

* @author Curt Arnold
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-DocCrAttrNS
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-DocCrAttrNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='INVALID_CHARACTER_ERR'])
* @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=525
*/
function createAttributeNS06() {
   var success;
    if(checkInitialization(builder, "createAttributeNS06") != null) return;
    var namespaceURI = "http://www.example.com/";
      var qualifiedName;
      var doc;
      var newAttr;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "hc_staff");

	{
		success = false;
		try {
            newAttr = doc.createAttributeNS(namespaceURI,"");
        }
		catch(ex) {
      success = (typeof(ex.code) != 'undefined' && ex.code == 5);
		}
		assertTrue("throw_INVALID_CHARACTER_ERR",success);
	}

}

function runTest() {
   createAttributeNS06();
}


text:
require 'spec_helper'
require 'sequel/schema-sharding'
require 'benchmark'

describe Sequel::SchemaSharding::Finder do

  describe '.lookup' do
    it 'returns an object with a valid connection and schema' do
      result = Sequel::SchemaSharding::Finder.instance.lookup('boof', 60)
      expect(result.connection).to be_a(Sequel::Postgres::Database)
      expect(result.schema).to eq('sequel_logical_boof_01')
      expect(result.shard_number).to eq(1)
    end

    xit 'is fast' do
      TIMES = 150_000
      result = Benchmark.measure do
        TIMES.times do
          Sequel::SchemaSharding::Finder.instance.lookup('boof', 60)
        end
      end
      puts "performed #{TIMES} finder lookups: #{result}"
    end
  end
end


text:
package com.audax.dev.forte;

import java.util.Collection;

import android.app.Dialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.audax.dev.forte.data.Center;
import com.audax.dev.forte.data.Repository;
import com.audax.dev.forte.maps.LocationUtils;
import com.audax.dev.forte.maps.MapsClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.model.LatLng;
public class NearestCenterFragment extends Fragment implements MapsClient.ClientListener, View.OnClickListener {

	private MapsClient mapsClient;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mapsClient = new MapsClient(this.getActivity());

		mapsClient.setClientListener(this);
	}

	private View rootView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.nearest_center_view, container);
		this.rootView = view;
		view.findViewById(R.id.lnk_view_in_map).setOnClickListener(this);
		return view;
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		this.mapsClient.stop();
	}

	// Define a DialogFragment that displays the error dialog
	public static class ErrorDialogFragment extends DialogFragment {
		// Global field to contain the error dialog
		private Dialog mDialog;

		// Default constructor. Sets the dialog field to null
		public ErrorDialogFragment() {
			super();
			mDialog = null;
		}

		// Set the dialog to display
		public void setDialog(Dialog dialog) {
			mDialog = dialog;
		}

		// Return a Dialog to the DialogFragment.
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			return mDialog;
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity());
		if (code == ConnectionResult.SUCCESS) {
			Log.i("Google Play", "Service is available");

			this.mapsClient.start();
		} else {

			 Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
	                    code,
	                    this.getActivity(),
	                    Constants.CONNECTION_FAILURE_RESOLUTION_REQUEST);

	            // If Google Play services can provide an error dialog
	            if (errorDialog != null) {
	                // Create a new DialogFragment for the error dialog
	                ErrorDialogFragment errorFragment =
	                        new ErrorDialogFragment();
	                // Set the dialog in the DialogFragment
	                errorFragment.setDialog(errorDialog);
	                // Show the error dialog in the DialogFragment
	                FragmentActivity fa = (FragmentActivity)this.getActivity();
	                errorFragment.show(fa.getSupportFragmentManager(),
	                        "Location Updates");
	            }
		}
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		this.mapsClient.stop();
	}

	private Center closestCenter;

	public void refreshLocation() {
		this.mapsClient.start();
	}

	@Override
	public void onLocationChanged(MapsClient client) {
		Repository repo = new Repository();
		Collection<Center> centers = repo.getAvailableCenters();
		Location loc = client.getCurrentLocation();
		LatLng ll = new LatLng(loc.getLatitude(), loc.getLongitude());

		try {
			Center closest = LocationUtils.getClosest(ll, centers);

			String distanceText = String.format("%1$.2f%2$s/%3$.2f%4$s", closest.getDistanceInMiles(),
						this.getString(R.string.Mi),
						closest.getDistanceInMiles() * LocationUtils.MILES_TO_KILO,
						this.getActivity().getString(R.string.Km));

			closest.setDistance(distanceText);

			this.closestCenter = closest;
			((TextView)this.rootView
						.findViewById(R.id.lbl_nearest_center_name))
						.setText(closest.getName());
			((TextView)this.rootView
					.findViewById(R.id.lbl_distance_away))
					.setText(distanceText);

			this.rootView.findViewById(R.id.lbl_loading_nearest).setVisibility(View.GONE);
			this.rootView.findViewById(R.id.lbl_nearest_center_name).setVisibility(View.VISIBLE);
			this.rootView.findViewById(R.id.lbl_distance_away).setVisibility(View.VISIBLE);
			this.rootView.findViewById(R.id.lnk_view_in_map).setVisibility(View.VISIBLE);

			client.stop();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.lnk_view_in_map:
			if (this.closestCenter != null) {

				Intent itt = new Intent(this.getActivity(), MapActivity.class);

				itt.putExtra("centerId", closestCenter.getId().toString());

				//itt.putExtra("marker", mo);

				this.startActivity(itt);
			}
			break;
		}
	}

}


text:
namespace ash {

// A subclass of FocusRingLayer that highlights the mouse cursor while it's
// moving, to make it easier to find visually.
class ASH_EXPORT AccessibilityCursorRingLayer : public FocusRingLayer {
 public:
  AccessibilityCursorRingLayer(AccessibilityLayerDelegate* delegate,
                               int red,
                               int green,
                               int blue);

  AccessibilityCursorRingLayer(const AccessibilityCursorRingLayer&) = delete;
  AccessibilityCursorRingLayer& operator=(const AccessibilityCursorRingLayer&) =
      delete;

  ~AccessibilityCursorRingLayer() override;

  // Create the layer and update its bounds and position in the hierarchy.
  void Set(const gfx::Point& location);

 private:
  // ui::LayerDelegate overrides:
  void OnPaintLayer(const ui::PaintContext& context) override;

  // The current location.
  gfx::Point location_;

  int red_;
  int green_;
  int blue_;
};

}  // namespace ash

#endif  // ASH_ACCESSIBILITY_UI_ACCESSIBILITY_CURSOR_RING_LAYER_H_


text:
/**
 * Classes that are normally omitted from public API because they duplicate existing classes,
 * but still temporarily used at XML (un)marshalling time for standards compliance.
 *
 *
Some objects defined in various standards have overlapping functionalities.
 * For example, the Metadata (ISO 19115), Referencing by Coordinates (ISO 19111),
 * Data Quality (ISO 19157) and Web Processing Service (WPS) standards all define their own parameter objects.
 * Another example is ISO 19115 defining basic referencing information, which is clearly ISO 19111 work.
 * GeoAPI tries to provide an uniform API by merging objects, or by omitting an object from one standard
 * in favor of the equivalent object of another standard. However, at XML (un)marshalling time,
 * we still need to temporarily recreate the omitted object as defined in the original standard.
 * This package is used for such replacement.

 *
 * @author  Martin Desruisseaux (Geomatys)
 * @author  Rémi Maréchal (Geomatys)
 * @author  Cullen Rombach (Image Matters)
 * @since   1.3
 * @since   0.5
 * @module
 */
@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED, xmlns = {
    @XmlNs(prefix = "mcc",  namespaceURI = Namespaces.MCC),        // Metadata Common Classes
    @XmlNs(prefix = "mrs",  namespaceURI = Namespaces.MRS),        // Metadata for Reference System
    @XmlNs(prefix = "srv",  namespaceURI = Namespaces.SRV),        // Metadata for Services 2.0
    @XmlNs(prefix = "srv1", namespaceURI = LegacyNamespaces.SRV),  // Metadata for Services 1.0
    @XmlNs(prefix = "gmd",  namespaceURI = LegacyNamespaces.GMD)   // Metadata ISO 19139:2007
})
@XmlAccessorType(XmlAccessType.NONE)
@XmlJavaTypeAdapters({
    @XmlJavaTypeAdapter(GO_Boolean.class),
    @XmlJavaTypeAdapter(MD_Identifier.class),
    @XmlJavaTypeAdapter(DQM_Description.class),

    // Java types, primitive types and basic OGC types handling
    @XmlJavaTypeAdapter(StringAdapter.class),
    @XmlJavaTypeAdapter(InternationalStringAdapter.class),
    @XmlJavaTypeAdapter(value=GO_Boolean.class, type=boolean.class)
})
package org.apache.sis.internal.jaxb.metadata.replace;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import org.apache.sis.internal.xml.LegacyNamespaces;
import org.apache.sis.internal.jaxb.metadata.MD_Identifier;
import org.apache.sis.internal.jaxb.metadata.DQM_Description;
import org.apache.sis.internal.jaxb.gco.*;
import org.apache.sis.xml.Namespaces;


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.macros.BuildTargetMacro;
import com.google.common.collect.ImmutableList;
import java.util.function.Function;

/** Coercer for macros which take a single {@link BuildTarget} arg. */
public final class BuildTargetMacroTypeCoercer<M extends BuildTargetMacro>
    implements MacroTypeCoercer<M> {

  /** Should target be resolved for host platform or target */
  public enum TargetOrHost {
    TARGET,
    HOST,
  }

  private final TypeCoercer<BuildTarget> buildTargetTypeCoercer;
  private final Class<M> mClass;
  private final TargetOrHost targetOrHost;
  private final Function<BuildTarget, M> factory;

  public BuildTargetMacroTypeCoercer(
      TypeCoercer<BuildTarget> buildTargetTypeCoercer,
      Class<M> mClass,
      TargetOrHost targetOrHost,
      Function<BuildTarget, M> factory) {
    this.buildTargetTypeCoercer = buildTargetTypeCoercer;
    this.mClass = mClass;
    this.targetOrHost = targetOrHost;
    this.factory = factory;
  }

  @Override
  public boolean hasElementClass(Class<?>[] types) {
    return buildTargetTypeCoercer.hasElementClass(types);
  }

  @Override
  public void traverse(CellPathResolver cellRoots, M macro, TypeCoercer.Traversal traversal) {
    buildTargetTypeCoercer.traverse(cellRoots, macro.getTarget(), traversal);
  }

  @Override
  public Class<M> getOutputClass() {
    return mClass;
  }

  @Override
  public M coerce(
      CellPathResolver cellRoots,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      TargetConfiguration targetConfiguration,
      TargetConfiguration hostConfiguration,
      ImmutableList<String> args)
      throws CoerceFailedException {
    if (args.size() != 1) {
      throw new CoerceFailedException(
          String.format("expected exactly one argument (found %d)", args.size()));
    }
    BuildTarget target =
        buildTargetTypeCoercer.coerce(
            cellRoots,
            filesystem,
            pathRelativeToProjectRoot,
            targetOrHost == TargetOrHost.TARGET ? targetConfiguration : hostConfiguration,
            hostConfiguration,
            args.get(0));
    return factory.apply(target);
  }
}