text:
"""
NMA (Notify My Android) notification service.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.nma/
"""
import logging
import xml.etree.ElementTree as ET

import requests
import voluptuous as vol

from homeassistant.components.notify import (
    ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService)
from homeassistant.const import CONF_API_KEY
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
_RESOURCE = 'https://www.notifymyandroid.com/publicapi/'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_API_KEY): cv.string,
})

def get_service(hass, config, discovery_info=None):
    """Get the NMA notification service."""
    parameters = {
        'apikey': config[CONF_API_KEY],
    }
    response = requests.get(
        '{}{}'.format(_RESOURCE, 'verify'), params=parameters, timeout=5)
    tree = ET.fromstring(response.content)

    if tree[0].tag == 'error':
        _LOGGER.error("Wrong API key supplied. %s", tree[0].text)
        return None

    return NmaNotificationService(config[CONF_API_KEY])

class NmaNotificationService(BaseNotificationService):
    """Implement the notification service for NMA."""

    def __init__(self, api_key):
        """Initialize the service."""
        self._api_key = api_key

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        data = {
            'apikey': self._api_key,
            'application': 'home-assistant',
            'event': kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT),
            'description': message,
            'priority': 0,
        }

        response = requests.get(
            '{}{}'.format(_RESOURCE, 'notify'), params=data, timeout=5)
        tree = ET.fromstring(response.content)

        if tree[0].tag == 'error':
            _LOGGER.exception(
                "Unable to perform request. Error: %s", tree[0].text)

redpajama_set_name: RedPajamaGithub


text:
class cBlockLilypadHandler :
	public cClearMetaOnDrop<cBlockHandler>
{
	typedef cClearMetaOnDrop<cBlockHandler> super;
public:

	cBlockLilypadHandler(BLOCKTYPE a_BlockType) :
		super(a_BlockType)
	{
	}
};


text:
package com.facebook.litho.sections.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Every class that is annotated with {@link GroupSectionSpec} requires a method that is annotated
 * with {@link OnCreateChildren}.
 *
 *
The method onCreateChildren is responsible for generating the children of a {@link
 * GroupSectionSpec}. Both {@link GroupSectionSpec} and {@link DiffSectionSpec} are valid children.
 * OnCreateChildren has access to both {@literal @}Prop and/or {@literal @}State
 *  annotations.
 *
 *

 * {@literal @}OnCreateChildren
 *  static Children onCreateChildren(
 *      final SectionContext c,
 *     {@literal @}State boolean isLoading,
 *     {@literal @}Prop int prop) {
 *    return Children.create()
 *       .child(SingleComponentSection.create(c).component(SomeComponent.create(c).build())
 *       .build();
 *  }
 *

 */
@Retention(RetentionPolicy.RUNTIME)
public @interface OnCreateChildren {}


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Vince Golveo</title>
    <description>Front-End Web Developer Consultant
</description>
    <link>http://localhost:4000/</link>
    <atom:link href="http://localhost:4000/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Mon, 25 Feb 2019 18:13:21 -0500</pubDate>
    <lastBuildDate>Mon, 25 Feb 2019 18:13:21 -0500</lastBuildDate>
    <generator>Jekyll v3.5.2</generator>

      <item>
        <title>Honeycomb Health App</title>
        <description>
A web application built for a health tech agency startup non-profit using Drupal 8, and customizing screens with Drupal WebForm. Created custom theme and modules with PHP, Twig, JavaScript, jQuery, Bootstrap 4, Node, Gulp and SASS.

Technology used: Drupal 8, Drupal WebForm, PHP, TWIG, JavaScript, jQuery, Bootstrap 4, Node, Gulp and SASS

</description>
        <pubDate>Mon, 25 Feb 2019 11:30:00 -0500</pubDate>
        <link>http://localhost:4000/2019/02/25/honeyhealth.html</link>
        <guid isPermaLink="true">http://localhost:4000/2019/02/25/honeyhealth.html</guid>

      </item>

      <item>
        <title>Renegade Marketing</title>
        <description>
A B2B site for a marketing consultancy group. Set up site architecture, staging servers, database, and Git repositories. Customized CMS forms through plugins and Advanced Custom Fields. Infinite scroll implemented on all post listing pages. Responsive design.

Technology used: Wordpress, PHP, MySQL, Advance Custom Fields, Git, Gulp, Node, Bootstrap 4, SASS, JavaScript, jQuery, HTML, CSS

</description>
        <pubDate>Fri, 19 Oct 2018 12:30:00 -0400</pubDate>
        <link>http://localhost:4000/2018/10/19/renegade.html</link>
        <guid isPermaLink="true">http://localhost:4000/2018/10/19/renegade.html</guid>

      </item>

      <item>
        <title>Calligrahy Pack</title>
        <description>
A responsive e-commerce store with hundreds of products built on the Shopify platform with PHP and Liquid, and designed with Sketch and Photoshop.

Technology used: Shopify CMS, Liquid, PHP, JavaScript, jQuery, HTML, CSS, Sketch, Photoshop

</description>
        <pubDate>Fri, 19 Oct 2018 08:30:00 -0400</pubDate>
        <link>http://localhost:4000/2018/10/19/calligraphypack.html</link>
        <guid isPermaLink="true">http://localhost:4000/2018/10/19/calligraphypack.html</guid>

      </item>

      <item>
        <title>Sara Cowlan</title>
        <description>
A responsive website for a nutritionist built with WordPress and designed with Sketch and Photoshop.

Technology used: WordPress, Bootstrap 4, HTML5, CSS, Sketch, Photoshop

</description>
        <pubDate>Fri, 19 Oct 2018 07:30:00 -0400</pubDate>
        <link>http://localhost:4000/2018/10/19/saracowlan.html</link>
        <guid isPermaLink="true">http://localhost:4000/2018/10/19/saracowlan.html</guid>

      </item>

      <item>
        <title>Binzu Digital</title>
        <description>
A responsive corporate website for Binzu Digital built using WordPress with Bootstrap, and designed in Sketch.

Technology used: Wordpress, PHP, MySQL, Bootstrap, Photoshop, Sketch

</description>
        <pubDate>Thu, 18 Oct 2018 22:30:00 -0400</pubDate>
        <link>http://localhost:4000/2018/10/18/binzu.html</link>
        <guid isPermaLink="true">http://localhost:4000/2018/10/18/binzu.html</guid>

      </item>

      <item>
        <title>Marketer Workspace</title>
        <description>
Launched new features on IBM's global marketing platform incorporating multiple APIs, enhancing responsiveness, improving usability and data integrity.

Technology used: API, AngularJS, Typescript, ES6, Node, Karma, Jasmine, Protractor, Grunt, SASS, HTML5, CSS3, Git

</description>
        <pubDate>Sun, 20 Aug 2017 15:00:00 -0400</pubDate>
        <link>http://localhost:4000/2017/08/20/marketerworkspace.html</link>
        <guid isPermaLink="true">http://localhost:4000/2017/08/20/marketerworkspace.html</guid>

      </item>

      <item>
        <title>IBM Cloud Computing</title>
        <description>
Successfully revamped the IBM cloud website to new CMS and responsive layout, and drastically improved SEO and performance through collaboration in an agile development team. Developed maintainable technical documentation and an online CSS style guide, simplifying transfer of knowledge workflow and global deployment processes.

Technology used: CMS, JavaScript, jQuery, HTML5, CSS3, SASS, Grunt, Git

</description>
        <pubDate>Sun, 20 Aug 2017 14:30:00 -0400</pubDate>
        <link>http://localhost:4000/2017/08/20/ibmcloud.html</link>
        <guid isPermaLink="true">http://localhost:4000/2017/08/20/ibmcloud.html</guid>

      </item>

      <item>
        <title>IBM Think Management</title>
        <description>
Prototyped and developed features for an IBM management training tool and customized front-end for a manager forum.

Technology used: IBM ECM, IBM Connections API, Dojo, JavaScript, jQuery, HTML5, CSS3, SASS, Grunt, SVN

</description>
        <pubDate>Sun, 20 Aug 2017 14:00:00 -0400</pubDate>
        <link>http://localhost:4000/2017/08/20/thinkmanagement.html</link>
        <guid isPermaLink="true">http://localhost:4000/2017/08/20/thinkmanagement.html</guid>

      </item>

      <item>
        <title>Coca-Cola Mix'On</title>
        <description>
Spearheaded Coca-Cola's Road to the VMAs digital marketing campaign by building a responsive interactive timeline and questionnaire designed for smartphones and tablets.

Technology used: JavaScript, jQuery, HTML5, CSS3

</description>
        <pubDate>Sun, 20 Aug 2017 13:30:00 -0400</pubDate>
        <link>http://localhost:4000/2017/08/20/mixon.html</link>
        <guid isPermaLink="true">http://localhost:4000/2017/08/20/mixon.html</guid>

      </item>

      <item>
        <title>Qnasl Device Tour</title>
        <description>
Developed an interactive 360° visualization of a nasal spray for a large pharmaceutical industry client.

Technology used: Sencha Animator, JavaScript, jQuery, HTML5, CSS3, Canvas

</description>
        <pubDate>Sun, 20 Aug 2017 13:00:00 -0400</pubDate>
        <link>http://localhost:4000/2017/08/20/qnasl.html</link>
        <guid isPermaLink="true">http://localhost:4000/2017/08/20/qnasl.html</guid>

      </item>

  </channel>
</rss>


text:
"use strict";

let expect = require('chai').expect,
    NS1    = require('../lib'),
    utils  = require('./utils')

utils.setup_context('NS1.NotificationList', function() {

  let existing_obj

  before(function() {
    return new NS1.NS1Request(
      'put',
      '/lists',
      {
        "name": "My Notification List",
        "notify_list": [
          {
            "config": {
              "email": "email+notify@gmail.com"
            },
            "type": "email"
          }
        ]
      }
    ).then((obj) => {
      existing_obj = obj
    })
  })

  after(function() {
    return new NS1.NS1Request(
      'del',
      `/lists/${existing_obj.id}`
    )
  })

  utils.rest_resource_tests.call(this, {
    skip_find_all:  true,
    subject:        NS1.NotificationList,
    existing_val:   () => existing_obj.id,
    existing_obj:   () => existing_obj,
    new_object_obj: () => {
      return {
        "name": "My Other Notification List",
        "notify_list": [
          {
            "config": {
              "email": "email+notify@gmail.com"
            },
            "type": "email"
          }
        ]
      }
    },
    update_val:     "test update",
    update_key:     'name'
  })

  describe('.types', function() {
    it('should return all notify_list types', function() {
      return NS1.NotificationList.types((types) => {
        expect(Array.isArray(types)).to.eq(false)
        expect(types.email.desc).to.eq('Send notification to an email address.')
        expect(typeof types).to.eq('object')
      })
    })
  })
})


text:
title: Spree 1.3.0
section: release_notes
order: 16
---

Spree 1.3.0 is the first release of the 1.3.x branch of Spree. This release contains some major non-breaking changes, which are covered in the release notes below.

Due to the long development cycle of Spree 1.3 in parallel with continuing development of the 1.1 branch, there may be bug fixes released in 1.3 that are already present in the latest release of 1.2.

Here's a quick summary of the major features in this release:

- Admin redesign
- Currency support for variants

## Major changes

### Admin redesign

Alexey Topolyanskiy has done some amazing work performing a makeover for the admin backend for Spree, something that has been long overdue!

### Currency support

Thanks to work by Gregor MacDougall and the team at Free Running Technologies, Spree's Variant model now is able to keep track of a different price for different currencies.

## Minor changes

### Remove child node from API responses

The API has previously returned data with a child node within its responses. Take this example from `/api/products`:

```ruby
{
 [products]() [
 {
   [product]() {
     [id]() 1,
     …
   }
 }]
}
```

This response will now be returned without the child nodes, like this:

```ruby
{
 [products]() [
   {
   [id]() 1,
     …
   }
  ]
}
```

### API requests can now ask for different Rabl templates

If you would like to make a request to the API use a different Rabl template, pass the template's name within the request as an `X-Spree-Template` header or _template_ parameter, and Spree will automatically use that template to render the response.

For instance, if you have a template at `app/views/spree/api/products/special_show.v1.rabl`, to render that template the `X-Spree-Template` header or `template` parameter would need to be simply "special_show". This will allow you to customize the responses from Spree's API extremely easily.

### Jirafe false positive conversions

We've had a number of reports of Jirafe false positive conversions within Spree
([#2273](https://github.com/spree/spree/issues/2273)
[#2211](https://github.com/spree/spree/issues/2211) and
[#2157](https://github.com/spree/spree/issues/2157))

This issue should now be fixed based on [this commit](https://github.com/spree/spree/commit/50bc65f78d07453fea85ae034748007946bd27bd)

## Other changes

- Fix issue where return authorization form would crash if a variant
  had an ID
  with a large value
  [commit](https://github.com/spree/spree/commit/820a1c023d915f9d2c972c04c5641b5d823ab508)
- Don't process payments if payments are not required [#2025](https://github.com/spree/spree/issues/2025)
- Payments are now applied one at a time until the order total is met,
  rather
  than processing all payments at the same time.
  [#1954](https://github.com/spree/spree/issues/1954)
  [#2008](https://github.com/spree/spree/issues/2008)
- Exclude expired promotions from Product#possible_promotions
  [#2058](https://github.com/spree/spree/issues/2058)
- Pass all changes to Variant#count_on_hand to Variant#on_hand=
  to ensure
  backorders are processed correct
  [commit](https://github.com/spree/spree/commit/d6c1183095125a946e8f6f1078ce0ee7487687b9)
- Use select2 for properties and option types on prototype form to
  display
  options better. [#2077](https://github.com/spree/spree/issues/2077)
- Clicking 'Checkout' on the cart page will now update the order and
  redirect to
  the address form, rather than just redirecting to the address form.
  [#2086](https://github.com/spree/spree/issues/2086)
- The searcher class now has access to the current user.
  [#2089](https://github.com/spree/spree/issues)
- Allow anonymous requests to the API.
  [commit](https://github.com/spree/spree/commit/456cadf5ff858ecac75646ca6b592be384a07396)
- Don't clear mail method or payment method passwords if they're not
  included in
  a request. [#2094](https://github.com/spree/spree/issues/2094)
- An order is marked as returned automatically if all return
  authorizations are
  received. [#1714](https://github.com/spree/spree/issues/1714)
  [#2099](https://github.com/spree/spree/issues/2099)
- Added _on_demand_ field for variants, indicating that the variant
  is an "on
  demand" item. [#1940](https://github.com/spree/spree/issues/1940)
  [#2080](https://github.com/spree/spree/issues/2080)
- Product.in_taxons does not return duplicate products
  [commit](https://github.com/spree/spree/commit/75fa3623b61e22fcde395b7f9900e23038361df9)
- Spree::Product.on_hand no longer sums with deleted variants
  [#2112](https://github.com/spree/spree/issues/2112)
- Payment#capture! will no longer work on completed payments.
  [#2119](https://github.com/spree/spree/issues/2119)
- Fix "Order adjustments" translation
  [#2123](https://github.com/spree/spree/issues/2123)
- Order#create_tax_charge! is called whenever a line item is added
  or removed
  from an order. [#1418](https://github.com/spree/spree/issues/1418)
- Don't allow
  void_transaction! to operate on a payment which is already void.
  [#2119](https://github.com/spree/spree/issues/2119)
- Strip EXIF data from images [#2142](https://github.com/spree/spree/issues/2142)
- Display promotion usage data in admin
  [#2193](https://github.com/spree/spree/issues/2193)
- Remove display_on option for Payment Methods.
  [#1918](https://github.com/spree/spree/issues/1981)
- Add Order#variants, to get a list of variants associated with an order.
  [#2195](https://github.com/spree/spree/issues/2195)
- Fix issue when trying to move taxon to the bottom of the tree
  [#2180](https://github.com/spree/spree/issues/2180)
- Show only one validation message for an order's email if left blank on the
  checkout [#2214](https://github.com/spree/spree/issues/2214)
- Taxonomies can now be reordered
  [#2237](https://github.com/spree/spree/issues/2237)
- Order#merge no longer uses Order#add_variant. For an
  explanation, [see this
  commit](https://github.com/spree/spree/commit/8569ed5d98e354285ad6ccbd366444fd31e773f8)
- Orders with promotions that "zero" the order total will no longer
  skip
  delivery step if that step is required.
  [#2191](https://github.com/spree/spree/issues/2191)
- Jirafe analytics can now be edited after registration
  [#2238](https://github.com/spree/spree/issues)
- awesome_nested_set version has been bumped to 2.1.5
  [commit](https://github.com/spree/spree/commit/3bdd22fedda456308f20f0817155590fab231e96)
- Order details page no longer errors if a payment's credit card type
  is blank
  [#2282](https://github.com/spree/spree/issues/2282)
- No longer transition to complete if payment is required and there
  are payments
  due.
  [commit](https://github.com/spree/spree/commit/8639bbcc3b1909a339b0a60da239a49b95baa760)
- Refactored preference fetching from the preference store
  [commit](https://github.com/spree/spree/commit/bfcb5b29b3e29c3d451b14ab39e2b502ea93f6a4)
- Order#checkout_steps will now always include the "Complete" step.
  [commit](https://github.com/spree/spree/commit/227f86ff57735e0e0637a0896006ff79fe8e0a6d)
- Allow "first order for user" promotion to work with guest users as
  well
  [#2306](https://github.com/spree/spree/issues/2306)
- Always show "resend" (email confirmation) button when viewing an
  order in
  admin backend. [#2318](https://github.com/spree/spree/issues/2318)
- Made sure that shipment for resumed order can be set to "ready"
  [#2317](https://github.com/spree/spree/issues/2317)


text:
@echo off
if not exist .logs mkdir .logs
if not exist .output mkdir .output
set PACKER_LOG=1
set PACKER_LOG_PATH=.logs\devops-ol7-aws.log
set PACKER_CACHE_DIR=.cache
set TMPDIR=.tmp
packer build -force boxes\devops-ol7-aws.json
pause


text:
import { computed } from '@ember/object';
import { moduleForComponent, test } from 'ember-qunit';
import PageObject from 'ember-cli-page-object';
import hbs from 'htmlbars-inline-precompile';
import userDropdownComponent from 'code-corps-ember/tests/pages/component/user-dropdown';

let page = PageObject.create(userDropdownComponent);

moduleForComponent('user-dropdown', 'Integration | Component | user dropdown', {
  integration: true,
  beforeEach() {
    page.setContext(this);
  },
  afterEach() {
    page.removeContext();
  }
});

const stubUser = {
  id: 1,
  username: 'tester',
  photoThumbUrl: '/assets/images/twitter.png',

  atUsername: computed('username', function() {
    return `@${this.get('username')}`;
  }),

  twitterUrl: computed('twitter', function() {
    return `https://twitter.com/${this.get('twitter')}`;
  })
};

test('it renders', function(assert) {
  assert.expect(1);

  this.set('user', stubUser);

  this.render(hbs`{{user-dropdown user=user}}`);

  assert.ok(page.isVisible, 'The component renders');
});

test('it triggers the hide action when clicked', function(assert) {
  assert.expect(1);

  this.set('user', stubUser);
  this.on('hide', function() {
    assert.ok(true, 'It triggers the hide action when clicked');
  });

  this.render(hbs`{{user-dropdown user=user action='hide'}}`);

  page.click();

});


text:
.tribute-container {
  position: absolute;
  top: 0;
  left: 0;
  height: auto;
  max-height: 300px;
  max-width: 500px;
  overflow: auto;
  display: block;
  box-shadow: 0px 1px 3px 1px #c7c7c7;
  z-index: 999999; }
  .tribute-container ul {
    margin: 0;
    margin-top: 2px;
    padding: 0;
    list-style: none;
    background: #ffffff; }
  .tribute-container li {
    padding: 8px 12px;
    border-bottom: 1px solid #dcdcdc;
    cursor: pointer; }
    .tribute-container li.highlight, .tribute-container li:hover {
      background: #2185D0;
      color: #ffffff;}
    .tribute-container li img {
      display: inline-block;
      vertical-align: middle;
      width: 28px;
      margin-right: 5px;
    }
    .tribute-container li span {
      font-weight: bold; }
    .tribute-container li span.fullname {
      font-weight: normal;
      font-size: 0.8rem;
      margin-left: 3px;}
    .tribute-container li.no-match {
      cursor: default; }
  .tribute-container .menu-highlighted {
    font-weight: bold; }


text:
package team_policies

import "github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"

// CameraUploadsPolicyState : has no documentation (yet)
type CameraUploadsPolicyState struct {
	dropbox.Tagged
}

// Valid tag values for CameraUploadsPolicyState
const (
	CameraUploadsPolicyStateDisabled = "disabled"
	CameraUploadsPolicyStateEnabled  = "enabled"
	CameraUploadsPolicyStateOther    = "other"
)

// EmmState : has no documentation (yet)
type EmmState struct {
	dropbox.Tagged
}

// Valid tag values for EmmState
const (
	EmmStateDisabled = "disabled"
	EmmStateOptional = "optional"
	EmmStateRequired = "required"
	EmmStateOther    = "other"
)

// GroupCreation : has no documentation (yet)
type GroupCreation struct {
	dropbox.Tagged
}

// Valid tag values for GroupCreation
const (
	GroupCreationAdminsAndMembers = "admins_and_members"
	GroupCreationAdminsOnly       = "admins_only"
)

// OfficeAddInPolicy : has no documentation (yet)
type OfficeAddInPolicy struct {
	dropbox.Tagged
}

// Valid tag values for OfficeAddInPolicy
const (
	OfficeAddInPolicyDisabled = "disabled"
	OfficeAddInPolicyEnabled  = "enabled"
	OfficeAddInPolicyOther    = "other"
)

// PaperDeploymentPolicy : has no documentation (yet)
type PaperDeploymentPolicy struct {
	dropbox.Tagged
}

// Valid tag values for PaperDeploymentPolicy
const (
	PaperDeploymentPolicyFull    = "full"
	PaperDeploymentPolicyPartial = "partial"
	PaperDeploymentPolicyOther   = "other"
)

// PaperEnabledPolicy : has no documentation (yet)
type PaperEnabledPolicy struct {
	dropbox.Tagged
}

// Valid tag values for PaperEnabledPolicy
const (
	PaperEnabledPolicyDisabled    = "disabled"
	PaperEnabledPolicyEnabled     = "enabled"
	PaperEnabledPolicyUnspecified = "unspecified"
	PaperEnabledPolicyOther       = "other"
)

// PasswordStrengthPolicy : has no documentation (yet)
type PasswordStrengthPolicy struct {
	dropbox.Tagged
}

// Valid tag values for PasswordStrengthPolicy
const (
	PasswordStrengthPolicyMinimalRequirements = "minimal_requirements"
	PasswordStrengthPolicyModeratePassword    = "moderate_password"
	PasswordStrengthPolicyStrongPassword      = "strong_password"
	PasswordStrengthPolicyOther               = "other"
)

// RolloutMethod : has no documentation (yet)
type RolloutMethod struct {
	dropbox.Tagged
}

// Valid tag values for RolloutMethod
const (
	RolloutMethodUnlinkAll             = "unlink_all"
	RolloutMethodUnlinkMostInactive    = "unlink_most_inactive"
	RolloutMethodAddMemberToExceptions = "add_member_to_exceptions"
)

// SharedFolderJoinPolicy : Policy governing which shared folders a team member
// can join.
type SharedFolderJoinPolicy struct {
	dropbox.Tagged
}

// Valid tag values for SharedFolderJoinPolicy
const (
	SharedFolderJoinPolicyFromTeamOnly = "from_team_only"
	SharedFolderJoinPolicyFromAnyone   = "from_anyone"
	SharedFolderJoinPolicyOther        = "other"
)

// SharedFolderMemberPolicy : Policy governing who can be a member of a folder
// shared by a team member.
type SharedFolderMemberPolicy struct {
	dropbox.Tagged
}

// Valid tag values for SharedFolderMemberPolicy
const (
	SharedFolderMemberPolicyTeam   = "team"
	SharedFolderMemberPolicyAnyone = "anyone"
	SharedFolderMemberPolicyOther  = "other"
)

// SharedLinkCreatePolicy : Policy governing the visibility of shared links.
// This policy can apply to newly created shared links, or all shared links.
type SharedLinkCreatePolicy struct {
	dropbox.Tagged
}

// Valid tag values for SharedLinkCreatePolicy
const (
	SharedLinkCreatePolicyDefaultPublic   = "default_public"
	SharedLinkCreatePolicyDefaultTeamOnly = "default_team_only"
	SharedLinkCreatePolicyTeamOnly        = "team_only"
	SharedLinkCreatePolicyOther           = "other"
)

// ShowcaseDownloadPolicy : has no documentation (yet)
type ShowcaseDownloadPolicy struct {
	dropbox.Tagged
}

// Valid tag values for ShowcaseDownloadPolicy
const (
	ShowcaseDownloadPolicyDisabled = "disabled"
	ShowcaseDownloadPolicyEnabled  = "enabled"
	ShowcaseDownloadPolicyOther    = "other"
)

// ShowcaseEnabledPolicy : has no documentation (yet)
type ShowcaseEnabledPolicy struct {
	dropbox.Tagged
}

// Valid tag values for ShowcaseEnabledPolicy
const (
	ShowcaseEnabledPolicyDisabled = "disabled"
	ShowcaseEnabledPolicyEnabled  = "enabled"
	ShowcaseEnabledPolicyOther    = "other"
)

// ShowcaseExternalSharingPolicy : has no documentation (yet)
type ShowcaseExternalSharingPolicy struct {
	dropbox.Tagged
}

// Valid tag values for ShowcaseExternalSharingPolicy
const (
	ShowcaseExternalSharingPolicyDisabled = "disabled"
	ShowcaseExternalSharingPolicyEnabled  = "enabled"
	ShowcaseExternalSharingPolicyOther    = "other"
)

// SmartSyncPolicy : has no documentation (yet)
type SmartSyncPolicy struct {
	dropbox.Tagged
}

// Valid tag values for SmartSyncPolicy
const (
	SmartSyncPolicyLocal    = "local"
	SmartSyncPolicyOnDemand = "on_demand"
	SmartSyncPolicyOther    = "other"
)

// SsoPolicy : has no documentation (yet)
type SsoPolicy struct {
	dropbox.Tagged
}

// Valid tag values for SsoPolicy
const (
	SsoPolicyDisabled = "disabled"
	SsoPolicyOptional = "optional"
	SsoPolicyRequired = "required"
	SsoPolicyOther    = "other"
)

// TeamMemberPolicies : Policies governing team members.
type TeamMemberPolicies struct {
	// Sharing : Policies governing sharing.
	Sharing *TeamSharingPolicies `json:"sharing"`
	// EmmState : This describes the Enterprise Mobility Management (EMM) state
	// for this team. This information can be used to understand if an
	// organization is integrating with a third-party EMM vendor to further
	// manage and apply restrictions upon the team's Dropbox usage on mobile
	// devices. This is a new feature and in the future we'll be adding more new
	// fields and additional documentation.
	EmmState *EmmState `json:"emm_state"`
	// OfficeAddin : The admin policy around the Dropbox Office Add-In for this
	// team.
	OfficeAddin *OfficeAddInPolicy `json:"office_addin"`
}

// NewTeamMemberPolicies returns a new TeamMemberPolicies instance
func NewTeamMemberPolicies(Sharing *TeamSharingPolicies, EmmState *EmmState, OfficeAddin *OfficeAddInPolicy) *TeamMemberPolicies {
	s := new(TeamMemberPolicies)
	s.Sharing = Sharing
	s.EmmState = EmmState
	s.OfficeAddin = OfficeAddin
	return s
}

// TeamSharingPolicies : Policies governing sharing within and outside of the
// team.
type TeamSharingPolicies struct {
	// SharedFolderMemberPolicy : Who can join folders shared by team members.
	SharedFolderMemberPolicy *SharedFolderMemberPolicy `json:"shared_folder_member_policy"`
	// SharedFolderJoinPolicy : Which shared folders team members can join.
	SharedFolderJoinPolicy *SharedFolderJoinPolicy `json:"shared_folder_join_policy"`
	// SharedLinkCreatePolicy : Who can view shared links owned by team members.
	SharedLinkCreatePolicy *SharedLinkCreatePolicy `json:"shared_link_create_policy"`
}

// NewTeamSharingPolicies returns a new TeamSharingPolicies instance
func NewTeamSharingPolicies(SharedFolderMemberPolicy *SharedFolderMemberPolicy, SharedFolderJoinPolicy *SharedFolderJoinPolicy, SharedLinkCreatePolicy *SharedLinkCreatePolicy) *TeamSharingPolicies {
	s := new(TeamSharingPolicies)
	s.SharedFolderMemberPolicy = SharedFolderMemberPolicy
	s.SharedFolderJoinPolicy = SharedFolderJoinPolicy
	s.SharedLinkCreatePolicy = SharedLinkCreatePolicy
	return s
}

// TwoStepVerificationPolicy : has no documentation (yet)
type TwoStepVerificationPolicy struct {
	dropbox.Tagged
}

// Valid tag values for TwoStepVerificationPolicy
const (
	TwoStepVerificationPolicyRequireTfaEnable  = "require_tfa_enable"
	TwoStepVerificationPolicyRequireTfaDisable = "require_tfa_disable"
	TwoStepVerificationPolicyOther             = "other"
)


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC 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.

/**
 * @fileoverview A basic example of working with Chrome on Android. Before
 * running this example, you must start adb and connect a device (or start an
 * AVD).
 */

'use strict';

const {Builder, By, Key, promise, until} = require('..');
const {Options} = require('../chrome');

promise.consume(function* () {
  let driver;
  try {
    driver = yield new Builder()
        .forBrowser('chrome')
        .setChromeOptions(new Options().androidChrome())
        .build();
    yield driver.get('http://www.google.com/ncr');
    yield driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);
    yield driver.wait(until.titleIs('webdriver - Google Search'), 1000);
  } finally {
    yield driver && driver.quit();
  }
}).then(_ => console.log('SUCCESS'), err => console.error('ERROR: ' + err));


text:
fastlane documentation
================
# Installation

Make sure you have the latest version of the Xcode command line tools installed:

```
xcode-select --install
```

Install _fastlane_ using
```
[sudo] gem install fastlane -NV
```
or alternatively using `brew install fastlane`

# Available Actions
## iOS
### ios carthage_bootstrap
```
fastlane ios carthage_bootstrap
```
Run carthage bootstrap
### ios test
```
fastlane ios test
```
Run test
### ios lint_podspec
```
fastlane ios lint_podspec
```
Lint podspec
### ios bump_up_version
```
fastlane ios bump_up_version
```
Bump up next version
### ios create_pr_to_public
```
fastlane ios create_pr_to_public
```
Create GitHub PR to `payjp/payjp-ios` from internal repo. (internal only)
### ios check_swift_format
```
fastlane ios check_swift_format
```
Check Swift format with swiftLint
### ios check_objc_format
```
fastlane ios check_objc_format
```
Check Objective-C format with clang-format
### ios create_pr_to_update_docs
```
fastlane ios create_pr_to_update_docs
```
Create PR to update docs
### ios distribute_sample_app
```
fastlane ios distribute_sample_app
```
Distribute sample app with Firebase App Distribution
### ios build_swiftpm
```
fastlane ios build_swiftpm
```
Build with Package.swift
### ios build_carthage_swift_example
```
fastlane ios build_carthage_swift_example
```
Build carthage-swift example app
### ios build_cocoapods_objc_example
```
fastlane ios build_cocoapods_objc_example
```
Build cocoapods-objc example app

----

This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run.
More information about fastlane can be found on [fastlane.tools](https://fastlane.tools).
The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools).


text:
TOPDIR=$(shell cd ../../.. && pwd)
include $(TOPDIR)/Makefile.base

HEADERS=

SOURCES=

# only test_ccmp uses CppUnitTestRunnerLocal, so don't include it here
COMMON_SOURCES=

TESTS=                       \
  acquire_mt                 \
  create_destroy             \
  test_ccmp

MYLIBS =  -L$(TOPDIR)/src/lib/$(OBJDIR) -lmdbm -L$(LIBDIR)
MYLIBS += -lpthread $(LIBRT) -lstdc++ -lreadline -lcppunit
LD_EXTRA += $(MYLIBS) -lcppunit $(LOCAL_LDADD)
CXXFLAGS += -I$(TOPDIR)/src/lib

TESTEXES= $(patsubst %, $(OBJDIR)/%, $(TESTS))

# generate xml test results...
RUN_ARGS= -tall -x $(1).xml

default-make-target: $(TESTEXES)

# Create the per-test targets.
#$(foreach test, $(TESTS), $(eval $(call CppExeTargetRules,$(test),,$(LD_EXTRA))))
$(eval $(call CppExeTargetRules,acquire_mt,,$(LD_EXTRA)))
$(eval $(call CppExeTargetRules,create_destroy,,$(LD_EXTRA)))
$(eval $(call CppExeTargetRules,test_ccmp,,$(LD_EXTRA) CppUnitTestRunnerLocal.cc))

test:: $(TESTEXES)
	@echo "RUNNING HANDLE-POOL TESTS MODE=$(MODE), FAST=$(FAST) !!!!"
	make run-test_ccmp
	make RUN_ARGS=4   run-create_destroy
	make RUN_ARGS=32  run-create_destroy
	make RUN_ARGS=128 run-create_destroy
	make RUN_ARGS="32 16" run-acquire_mt
	make RUN_ARGS="32 32" run-acquire_mt
	make RUN_ARGS="32 48" run-acquire_mt

valg:: $(TESTEXES)
	make valg-test_ccmp
	make RUN_ARGS=4   valg-create_destroy
	make RUN_ARGS=32  valg-create_destroy
	make RUN_ARGS=128 valg-create_destroy
	make RUN_ARGS="32 16" valg-acquire_mt
	make RUN_ARGS="32 32" valg-acquire_mt
	make RUN_ARGS="32 48" valg-acquire_mt

# test_create_destroy:
# 	$(OBJDIR)/create_destroy 4
# 	$(OBJDIR)/create_destroy 32
# 	$(OBJDIR)/create_destroy 128
#
# test_acquire_mt:
# 	$(OBJDIR)/acquire_mt 32 16
# 	$(OBJDIR)/acquire_mt 32 32
# 	$(OBJDIR)/acquire_mt 32 48

clean :: clean-objs $(foreach exe, $(TESTS), clean-exe-$(exe))
#clean :
#	rm -f *.d $(OBJDIR)/*.o $(OBJDIR)/*.lib $(OBJDIR)/*.so *.xml
#	rm -f $(TESTEXES) $(OBJDIR)/CppUnitTestRunner


text:
package query

import (
	"errors"
	"fmt"
	"strings"
	"unicode/utf8"
)

// Based on the talk "Lexical Scanning in Go" by Rob Pike.
// http://talks.golang.org/2011/lex.slide

// character sets
const (
	charAlpha      = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	charAlphanum   = charAlpha + charNumeric
	charDelim      = "(),"
	charGlob       = "[]{}*"
	charDot        = "."
	charIdentifier = charAlphanum + "-_"
	charNumeric    = "0123456789"
	charQuote      = `"'`
	charWhitespace = " \t\r\n\v\f"
)

func is(r int, sets ...string) bool {
	for _, v := range sets {
		if strings.ContainsRune(v, rune(r)) {
			return true
		}
	}
	return false
}

const eof = -1

type item struct {
	typ int // see %token decl in expr.y
	val string
}

type stateFn func(*lexer) stateFn

type lexer struct {
	input      string    // the input string
	start, pos int       // start, end+1 of current item
	width      int       // length of previous utf8 codepoint
	items      chan item // scanned lexemes go here
	err        []string  // errors from yacc
	last       string    // last token emitted
	result     *Query    // yacc puts our result here
}

func lex(input string) *lexer {
	l := lexer{
		input: input,
		items: make(chan item),
	}
	go l.run()
	return &l
}

// implement the yyLex interface
func (l *lexer) Error(e string) {
	s := fmt.Sprintf("%v in %q at column %d", e, l.last, l.pos-len(l.last))
	l.err = append(l.err, s)
}

func (l *lexer) Lex(lval *yySymType) int {
	tok, ok := <-l.items
	if !ok {
		// eof reached
		return 0
	}
	lval.str = tok.val
	if tok.typ == pERROR {
		return 1
	}
	return tok.typ
}

func (l *lexer) Err() error {
	if len(l.err) > 0 {
		return errors.New(strings.Join(l.err, "\n\t"))
	}
	return nil
}

func (l *lexer) dot() string  { return l.input[l.start:l.pos] }
func (l *lexer) rest() string { return l.input[l.pos:] }
func (l *lexer) ignore()      { l.start = l.pos }
func (l *lexer) backup()      { l.pos -= l.width }
func (l *lexer) peek() int    { defer l.backup(); return l.next() }
func (l *lexer) emit(t int) {
	l.last = l.dot()
	l.items <- item{t, l.dot()}
	l.start = l.pos
}

func (l *lexer) errorf(format string, v ...interface{}) stateFn {
	l.items <- item{pERROR, fmt.Sprintf(format, v...)}
	return nil
}

func (l *lexer) run() {
	for state := lexClear; state != nil; state = state(l) {
	}
	close(l.items)
}

// Any call to lex() should be paired with a deferred
// call to l.drain(). This ensures that the lexing goroutine
// finishes.
func (l *lexer) drain() {
	for range l.items {
	}
}

// consumes the next character in the input
func (l *lexer) next() int {
	var r rune
	if l.pos >= len(l.input) {
		l.width = 0
		return eof
	}
	r, l.width = utf8.DecodeRuneInString(l.rest())
	l.pos += l.width
	return int(r)
}

// consume a rune from the valid set
func (l *lexer) accept(valid ...string) bool {
	for _, v := range valid {
		if strings.ContainsRune(v, rune(l.next())) {
			return true
		}
		l.backup()
	}
	return false
}

// consume a run of consecutive runes from the valid set
func (l *lexer) acceptRun(valid ...string) {
Loop:
	for {
		r := rune(l.next())
		for _, v := range valid {
			if strings.ContainsRune(v, r) {
				continue Loop
			}
		}
		break Loop
	}
	l.backup()
}

// starting state, scan for any expression
func lexClear(l *lexer) stateFn {
	for {
		switch r := l.next(); {
		case is(r, charNumeric, "+-"):
			l.backup()
			return lexNumber
		case is(r, charWhitespace):
			l.ignore()
		case is(r, charIdentifier):
			l.backup()
			return lexName
		case is(r, charGlob):
			l.backup()
			return lexMetric
		case is(r, charDelim):
			l.emit(r)
			return lexClear
		case is(r, charQuote):
			// note that quote tokens contain their
			// surrounding tokens. this allows us to
			// preserve the formatting of string literals
			// exactly (this is a proxy, after all).
			l.backup()
			return lexQuote
		case r == eof:
			return nil
		default:
			return l.errorf("unexpected character '%c' (%d)", r)
		}
	}
	panic("not reached")
}

// read a (possibly negative, possibly) number.
// graphite only accepts decimal numbers. No
// scientific notation or imaginary numbers are
// allowed. But note that something like
//
// 	305.mymetric.count
//
// could be a valid name for a metric.
func lexNumber(l *lexer) stateFn {
	l.accept("+-")
	l.acceptRun(charNumeric)
	if l.accept(".") {
		l.acceptRun(charNumeric)
	}
	if l.accept(charWhitespace, charDelim) {
		l.backup()
		l.emit(pNUMBER)
		return lexClear
	}
	if l.accept(charAlphanum, charGlob, ".") {
		l.backup()
		return lexMetric
	}
	return l.errorf("unexpected character '%c' in number", l.peek())
}

// read a simple word, such as a function name
func lexName(l *lexer) stateFn {
	l.acceptRun(charIdentifier)
	if l.accept(charWhitespace, charDelim) {
		l.backup()
		l.emit(pWORD)
		return lexClear
	}
	if l.accept(charGlob, charDot) {
		l.backup()
		return lexMetric
	}
	return l.errorf("unexpected character '%c' in word", l.peek())
}

// read a metric name, which is a series of words
// connected by dots. metrics may contain complex
// patterns, for instance
//
// 	servers.{prod,dev,stage}-sql[1-4].loadavg.*
//
// two additional states ensure the braces and brackets
// are balanced.
func lexMetric(l *lexer) stateFn {
	l.acceptRun(charIdentifier, "*.")
	if l.accept("{") {
		return lexCurlyBrace
	} else if l.accept("[") {
		return lexSquareBracket
	} else if l.accept(charWhitespace, charDelim) {
		l.backup()
		l.emit(pMETRIC)
		return lexClear
	} else if l.peek() == eof {
		l.emit(pMETRIC)
		return lexClear
	}
	return l.errorf("unexpected character '%c' in metric", l.peek())
}

// consume a glob expression of the form {x,y,z} (do not emit it)
// The opening '{' is already consumed. '}' characters may be
// escaped with a backslash.
func lexCurlyBrace(l *lexer) stateFn {
	for {
		switch l.next() {
		case '\\':
			if r := l.next(); r != eof {
				break
			}
			fallthrough
		case eof:
			return l.errorf("unterminated brace list")
		case '}':
			return lexMetric
		}
	}
}

// consume, do not emit, a glob expression of the form [chars]
// The opening '[' is already consumed. characters may be
// escaped with a backslash.
func lexSquareBracket(l *lexer) stateFn {
	for {
		switch l.next() {
		case '\\':
			if r := l.next(); r != eof {
				break
			}
			fallthrough
		case eof:
			return l.errorf("unterminated '[' glob")
		case ']':
			return lexMetric
		}
	}
}

// consume a quoted string. quotation marks within the
// string may be escaped with a backslash.
func lexQuote(l *lexer) stateFn {
	quoteChar := l.next()
Loop:
	for {
		switch l.next() {
		case '\\':
			if r := l.next(); r != eof {
				break
			}
			fallthrough
		case eof:
			return l.errorf("unterminated string")
		case quoteChar:
			break Loop
		}
	}
	l.emit(pSTRING)
	return lexClear
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Trematosphaeria schweinitzii Ellis & Everh.

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Flash terminal screen (visual bell)</title>

ncurses_filter

ncurses_flushinp

Ncurses Functions

PHP Manual

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Flash terminal screen (visual bell)

Description

   bool ncurses_flash
    ( void
   )

Warning
This function is
EXPERIMENTAL. The behaviour of this function, its name, and
surrounding documentation may change without notice in a future release of PHP.
This function should be used at your own risk.

   Flashes the screen, and if its not possible, sends an audible alert
   (bell).

Return Values

   Returns FALSE on success, otherwise TRUE.

See Also

ncurses_beep() - Let the terminal beep

ncurses_filter

ncurses_flushinp

Ncurses Functions

PHP Manual


text:
<?php

use PHPUnit\Framework\TestCase;
use Nimbusec\API;

class AgentTest extends TestCase
{
    private $api;
    private $token;
    private $agentVer;

    public function setUp()
    {
        $this->api = new API(
            getenv("SDK_KEY"),
            getenv("SDK_SECRET"),
            getenv("SDK_URL")
        );

        $this->token = array(
            "name" => "testToken"
        );

        $this->agentVer = getenv("SDK_AGENT_VERSION");
    }

    // ========================================= [ AGENT TOKEN ] =========================================

    public function testFindAgentToken()
    {
        $token = $this->api->findAgentToken();
        $this->assertInternalType("array", $token);
        return $token[0];
    }

    /**
     * @depends testFindAgentToken
     */
    public function testFindValidAgentToken($token)
    {
        $this->assertArrayHasKey("key", $token);
    }

    public function testCreateAgentToken()
    {
        $created = $this->api->createAgentToken($this->token);
        $this->assertArrayHasKey("key", $created);
        return $created;
    }

    /**
     * @depends testCreateAgentToken
     */
    public function testDeleteAgentToken($token)
    {
        $this->assertEquals(null, $this->api->deleteAgentToken($token["id"]));
    }

    // ========================================= [ AGENT ] =========================================

    public function testFindServerAgents()
    {
        $agents = $this->api->findServerAgents();
        $this->assertInternalType("array", $agents);
        return $agents[0];
    }

    /**
     * @depends testFindServerAgents
     */
    public function testFindValidServerAgents($agent)
    {
        $this->assertArrayHasKey("arch", $agent);
    }

    public function testFindSpecificServerAgent()
    {
        $agent = $this->api->findSpecificServerAgent("linux", "64bit", $this->agentVer, "tar.gz");
        $this->assertNotNull($agent);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jb. nassau. Ver. Naturk. 23-24: 101 (1870)

#### Original name
Sphaerella graminicola (Fuckel) Fuckel, 1870

### Remarks
null


text:
This python 3.x script is used to create an `output directory` containing all the
files necessary for a TensorFlow Lite Micro (TFLM) library.  The created TFLM
library is ready for use with the Arduino IDE. The `output directory` can also
be used to update the
[Arduino Examples repository](https://github.com/tensorflow/tflite-micro-arduino-examples)
by the repository maintainers.

The [create_tflm_arduino](create_tflm_arduino.py) script accepts the following
arguments:
* `--output_dir`

    The `output directory` for the TFLM library to be created.
* `--base_dir`

    This is the `base directory` containing a base set of files from the
    [TFLM repository](https://github.com/tensorflow/tflite-micro).
* `--manifest_file`

    Specifies which `manifest` file to use.  The `manifest` uses Windows INI
    format, and [MANIFEST.ini](MANIFEST.ini) is the default.
* `--is_dry_run`

    A debugging flag.  All actions that would have been taken are output, but
    not executed.

The operation of the [create_tflm_arduino](create_tflm_arduino.py) script is
to copy files from the
[Arduino Examples repository](https://github.com/tensorflow/tflite-micro-arduino-examples)
and the `base directory` to the `output directory`.  Depending on file source
and suffix, a content and/or file name transformation is applied.  The `manifest`
contains directives that determine which files are copied to the `output directory`
as well as additional content transforms to apply.

The `base directory` is created using the
[create_tflm_tree](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/tools/project_generation/create_tflm_tree.py) script.  This script allows for a specific
platform target to be chosen, as well as which TFLM example applications are to be
included in the `base directory`.

## Detailed steps of the [create_tflm_arduino](create_tflm_arduino.py) script
1. Parse script arguments

    The script command-line arguments are parsed.

1. Parse `manifest` file

    Generate the following lists from the `manifest` directives:

    * Files that will be copied from the repository to the `output directory`
    * Files that will not be copied from the `base directory` to the `output directory`
    * Files that will be copied from the repository to the `output directory`
        with a changed file name/path
    * Files that will be copied from the `base directory` to the `output directory`
        with a changed file name/path
    * Files in the `output directory` that will be transformed by a `sed`
        regular-expression script

    Each of these lists are used as filters in subsequent path tuple generation
    operations.

1. Clean the `output directory`

    Removes any files or directories in the `output directory`

1. Generate list of tuples of base paths which will be transformed

    Each tuple in the list consists of a source path relative to the `base directory`,
    and a destination path relative to the `output directory`.

    The list is initially all files in the `base directory`,
    and is filtered by the `manifest` directives applicable to source paths
    in the `base directory`.

    The list is again filtered such that only source paths with the following suffixes
    are included: `.c .cc .cpp .h .ino`

    All destination paths with a `.cc` suffix are changed to a `.cpp` suffix.

1. Generate list of tuples of base paths that will not be transformed

    Each tuple in the list consists of a source path relative to the `base directory`,
    and a destination path relative to the `output directory`.

    The list is initially all files in the `base directory`,
    and is filtered by the `manifest` directives applicable to source paths
    in the `base directory`.

    The list is again filtered such that only source paths with the following suffixes
    are excluded: `.c .cc .cpp .h .ino`

1. Generate list of tuples of repository paths which will be transformed

    Each tuple in the list consists of a source path relative to the repository,
    and a destination path relative to the `output directory`.

    The list is generated by the `manifest` directives applicable to source paths
    in the repository.

    The list is filtered such that only source paths with the following suffixes
    are included: `.c .cc .cpp .h .ino`

    The list is again filtered such that it includes only files whose source
    path is within the `src/third_party` directory tree.

1. Generate list of tuples of repository paths that will not be transformed

    Each tuple in the list consists of a source path relative to the repository,
    and a destination path relative to the `output directory`.

    The list is generated by the `manifest` directives applicable to source paths
    in the repository.

    The list is filtered such that only source paths with the following suffixes
    are excluded: `.c .cc .cpp .h .ino`

    The suffix exclusion filter is only applied where the source
    path is within the `src/third_party` directory tree.

1. Create directory tree in `output directory`

    The previously generated lists of paths are used to create the directory
    tree structure in `output directory`.  Only directories are created, in
    preparation for subsequent file copy operations.

1. Generate dictionary of header files

    A dictionary is generated where the keys are the names of the example
    applications. The value for each dictionary entry is a list of header
    file paths.  The list of header file paths represents header files in
    the `output directory`, residing within each example application and
    under the `src/third_party` directory.

    An additional default key entry is also generated.
    The value for this dictionary entry is a list of header
    file paths.  The list of header file paths represents header files in
    the `output directory`,
    under the `src/third_party` directory.

    This dictionary of header files is used as an input parameter to the
    [transform_source](transform_source.py) script.

1. Transform and copy files in the list of base paths

    The list of base paths which will be transformed is used to copy
    files from the `base directory` to the `output directory`.
    Each file to be copied is transformed using the
    [transform_source](transform_source.py) script.

1. Transform and copy files in the list of repository paths

    The list of repository paths which will be transformed is used to copy
    files from the repository to the `output directory`.
    Each file to be copied is transformed using the
    [transform_source](transform_source.py) script.

1. Copy files with no transform in the list of base paths

    The list of base paths that will not be transformed is used to copy
    files from the `base directory` to the `output directory`.

1. Copy files with no transform in the list of repository paths

    The list of repository paths that will not be transformed is used to copy
    files from the repository to the `output directory`.

1. Flatten file tree of the example applications in the `output directory`

    Some example applications have sub-directories.  These sub-directories must
    be flattened to make the example applications compatible with the Arduino
    IDE.  This flatenning causes all sub-directory files to be moved to the
    top-level directories of the example applications.  The script
    [fix_arduino_subfolders](fix_arduino_subfolders.py) performs the flattening
    operation.

1. Patch files in `output directory` using `manifest` directives

    The files in the `output directory` have `sed` regular-expression script
    directives applied as specified in the `manifest`.

1. Remove empty directories in the `output directory`

    Remove any empty directories that are a result of the previous step of
    flattening the example application directories.


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"path"
	"runtime"
	"sort"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/aws/aws-sdk-go/service/rds"

	"github.com/uchimanajet7/rds-try/command"
	"github.com/uchimanajet7/rds-try/config"
	"github.com/uchimanajet7/rds-try/logger"
	"github.com/uchimanajet7/rds-try/utils"
)

var log = logger.GetLogger("main")

func showHelp() func() {
	return func() {
		helpText := fmt.Sprintf("\nUsage: %s [globals] <command> [options]\n\n", utils.GetAppName())
		helpText += "Globals:\n"

		globals := make(map[string]string)

		// list global options
		flag.VisitAll(func(f *flag.Flag) {
			if value, ok := globals[f.Usage]; ok {
				// key exists
				if len(f.Name) > len(value) {
					globals[f.Usage] = fmt.Sprintf("-%s, --%s", value, f.Name)
				} else {
					globals[f.Usage] = fmt.Sprintf("-%s, --%s", f.Name, value)
				}
			} else {
				// key does not exist
				globals[f.Usage] = f.Name
			}
		})

		// to store the keys in slice in sorted order
		var keys []string
		textLength := 0
		for k, v := range globals {
			keys = append(keys, k)

			if len(v) > textLength {
				textLength = len(v)
			}
		}
		sort.Strings(keys)

		// to prepare the output format
		for _, k := range keys {
			optionText := fmt.Sprintf("%s%s", globals[k], strings.Repeat(" ", textLength-len(globals[k])))
			helpText += fmt.Sprintf("  %s  %s\n", optionText, k)
		}

		helpText += "\nCommands:\n"

		// make commad list
		// to-do: want to change the "command name" that has been hard-coded
		commandList := map[string]command.CmdInterface{
			"es": &command.EsCommand{},
			"ls": &command.LsCommand{},
			"rm": &command.RmCommand{},
		}

		// to store the keys in slice in sorted order
		keys = nil
		textLength = 0
		for k := range commandList {
			keys = append(keys, k)

			if len(k) > textLength {
				textLength = len(k)
			}
		}
		sort.Strings(keys)

		// to prepare the output format
		for _, k := range keys {
			commandText := fmt.Sprintf("%s%s", k, strings.Repeat(" ", textLength-len(k)))
			helpText += fmt.Sprintf("  %s  %s\n", commandText, commandList[k].Synopsis())
		}

		helpText += "\nOptions:\n"
		helpText += "  show commands options help <command> -h, --help\n"

		// show a help string
		fmt.Println(helpText)
	}
}

var (
	helpFlag    bool
	versionFlag bool
	configFlag  string
	nameFlag    string
)

func resolveArgs() (*config.Config, int) {
	// register flag name
	flag.BoolVar(&helpFlag, "help", false, "show this help message and exit")
	flag.BoolVar(&helpFlag, "h", false, "show this help message and exit")
	flag.BoolVar(&versionFlag, "version", false, "show version message and exit")
	flag.BoolVar(&versionFlag, "v", false, "show version message and exit")
	flag.StringVar(&configFlag, "config", "", "specify an alternate config file")
	flag.StringVar(&configFlag, "c", "", "specify an alternate config file")
	flag.StringVar(&nameFlag, "name", "default", "specify an alternate rds environment name")
	flag.StringVar(&nameFlag, "n", "default", "specify an alternate rds environment name")

	// set help func
	flag.Usage = showHelp()
	flag.Parse()

	// show help
	if helpFlag {
		flag.Usage()
		return nil, 0
	}
	// show version
	if versionFlag {
		fmt.Printf("%s %s\n", utils.GetAppName(), utils.GetAppVersion())
		return nil, 0
	}
	// show help
	// to-do: want to change the "command name" that has been hard-coded
	if len(flag.Args()) <= 0 || flag.Args()[0] != "es" && flag.Args()[0] != "ls" && flag.Args()[0] != "rm" {
		flag.Usage()
		return nil, 1
	}

	// load config file
	configFile := config.GetDefaultPath()
	if configFlag != "" {
		configFile = configFlag
	}
	conf, err := config.LoadConfig(configFile)
	if err != nil {
		return nil, 1
	}
	log.Debugf("Config: %+v", conf)

	return conf, 0
}

// need to run the caller always "defer log_file.Close()"
func setLogOptions(conf *config.Config) (*os.File, int) {
	// log setting
	if conf.Log.Verbose {
		log.SetLogLevelDebug()
	}
	if conf.Log.JSON {
		log.SetJSONLogFormat()
	}
	logRoot := utils.GetHomeDir()
	if conf.Log.Root != "" {
		logRoot = conf.Log.Root
	}

	logPath := path.Join(logRoot, fmt.Sprintf("%s.log", utils.GetFormatedFileDisplayName()))
	// need to run the caller always "defer log_file.Close()"
	logFile, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Errorf("%s", err.Error())
		return nil, 1
	}

	log.Debugf("Log File: %s", logPath)

	return logFile, 0
}

func getCommandStruct(conf *config.Config) (*command.Command, int) {
	// aws Credentials
	creds, err := conf.GetAWSCreds()
	if err != nil {
		log.Errorf("%s", err.Error())
		return nil, 1
	}
	// aws config init
	awsConfig := aws.NewConfig()
	awsConfig = awsConfig.WithCredentials(creds)
	awsConfig = awsConfig.WithRegion(conf.Rds[nameFlag].Region)

	// new iam
	awsIam := iam.New(awsConfig)

	// IAM info
	iamUsers, err := awsIam.ListUsers(&iam.ListUsersInput{})
	if err != nil {
		log.Errorf("%s", err.Error())
		return nil, 1
	}
	if len(iamUsers.Users) <= 0 {
		log.Errorf("iam user not found")
		return nil, 1
	}

	// edit IAM ARN
	// arn:aws:iam::<account>:user/<username> to arn:aws:rds:<region>:<account>:
	// see also
	// Tagging Amazon RDS Resources - Amazon Relational Database Service
	// http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html#USER_Tagging.ARN
	iamSplit := strings.SplitAfter(*iamUsers.Users[0].Arn, "::")
	iamAccount := iamSplit[len(iamSplit)-1]
	iamSplit = strings.Split(iamAccount, ":")
	iamAccount = iamSplit[0]

	// new rds
	awsRds := rds.New(awsConfig)

	commandStruct := &command.Command{
		OutConfig: conf.Out,
		RDSConfig: conf.Rds[nameFlag],
		RDSClient: awsRds,
		ARNPrefix: "arn:aws:rds:" + conf.Rds[nameFlag].Region + ":" + iamAccount + ":",
	}
	log.Debugf("Command: %+v", commandStruct)

	return commandStruct, 0
}

func main() {
	var exCode int
	defer func() { os.Exit(exCode) }()

	// environment variable is set up in order to correspond to multi-core CPU
	if envvar := os.Getenv("GOMAXPROCS"); envvar == "" {
		runtime.GOMAXPROCS(runtime.NumCPU())
	}

	// resolve command line
	conf, exCode := resolveArgs()
	if exCode != 0 || conf == nil {
		return
	}

	// log setting
	logFile, exCode := setLogOptions(conf)
	if exCode != 0 || logFile == nil {
		return
	}
	defer func() {
		// remove the log file of capacity zero
		fi, err := logFile.Stat()
		logFile.Close()
		if err == nil {
			if fi.Size() <= 0 {
				os.Remove(logFile.Name())
			}
		}
	}()
	log.SetFileOutPut(logFile)

	// check rds env name
	if _, ok := conf.Rds[nameFlag]; !ok {
		log.Errorf("rds environment information name not found:[%s]", nameFlag)
		exCode = 1
		return
	}

	// get base command struct
	commandStruct, exCode := getCommandStruct(conf)
	if exCode != 0 || commandStruct == nil {
		return
	}

	// call commands
	args := flag.Args()
	var commandList command.CmdInterface

	// to-do: want to change the "command name" that has been hard-coded
	switch flag.Args()[0] {
	case "es":
		commandList = &command.EsCommand{
			Command: commandStruct,
		}
	case "ls":
		commandList = &command.LsCommand{
			Command: commandStruct,
		}
	case "rm":
		commandList = &command.RmCommand{
			Command: commandStruct,
		}
	default:
		flag.Usage()
		exCode = 1
		return
	}

	// run commands
	exCode = commandList.Run(args[1:])
	log.Debugf("ex_code: %d", exCode)
}


text:
import json,sys,os

def mergejson(base,addition):
	re = base
	for (key,value) in addition.iteritems():
		if type(value) == type({}):#dict
			re[key] = mergejson(base[key],value)
		elif len(value) == 0 : # None
			re[key] = base[key]
		else:
			re[key] = value
	return re

def getconfig():
	base_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir,os.pardir,os.pardir))
	dir_name = os.path.dirname(os.path.abspath(__file__))
	dcfile = open(dir_name+"/default_config.json","r+")
	default_config = json.loads(dcfile.read())
	dcfile.close()
	userfile = open(base_dir+"/Racpider.json","r+")
	user_config = json.loads(userfile.read())
	user_config["src"] = os.path.abspath(os.path.join(base_dir,"src"))
	user_config["project_root"] = os.path.abspath(os.path.join(base_dir,"src"))
	userfile.close()
	return mergejson(default_config,user_config)

if __name__ == '__main__':
	print json.dumps(getconfig())


text:
package three

import "github.com/gopherjs/gopherjs/js"

type Object3D interface {
	ApplyMatrix(matrix *Matrix4)
	Add(m Object3D)
	ToJSON() interface{}
	// Copy(source Object3D, recursive bool)

	getInternalObject() *js.Object
}

// OnBeforeRender()
// OnAfterRender()
// ApplyMatrix(matrix float64)
// ApplyQuaternion(q Quaternion)
// SetRotationFromAxisAngle(axis Vector3, angle float64)
// SetRotationFromEuler(euler Euler)
// SetRotationFromMatrix(m Matrix4)
// SetRotationFromQuaternion(q Quaternion)
// RotateOnAxis()
// RotateX()
// RotateY()
// RotateZ()
// TranslateOnAxis()
// TranslateX()
// TranslateY()
// TranslateZ()
// LocalToWorld(vector Vector3)
// WorldToLocal()
// LookAt()
// Add(object Object3D)
// Remove(object Object3D)
// GetObjectById(id string)
// GetObjectByName(name string)
// GetObjectByProperty(name, value string)
// GetWorldPosition(optionalTarget Object3D)
// GetWorldQuaternion()
// GetWorldRotation()
// GetWorldScale()
// GetWorldDirection()
// Raycast()
// UpdateMatrix()
// UpdateMatrixWorld(force bool)
// ToJSON(meta interface{})
// Clone(recursive bool)
// Copy(source Object3D, recursive bool)


text:
module ReExport1 where

x = 42


text:
// Copyright 2018 Google LLC
//
// 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.

/**
 * MoveOperation.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201809.mcm;

/**
 * Operation for moving ManagedCustomer links. See {@link ManagedCustomerService#mutateManager}.
 */
public class MoveOperation  extends com.google.api.ads.adwords.axis.v201809.cm.Operation  implements java.io.Serializable {
    private com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerLink operand;

    /* The ID of the old Manager. */
    private java.lang.Long oldManagerCustomerId;

    public MoveOperation() {
    }

    public MoveOperation(
           com.google.api.ads.adwords.axis.v201809.cm.Operator operator,
           java.lang.String operationType,
           com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerLink operand,
           java.lang.Long oldManagerCustomerId) {
        super(
            operator,
            operationType);
        this.operand = operand;
        this.oldManagerCustomerId = oldManagerCustomerId;
    }

    @Override
    public String toString() {
        return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
            .omitNullValues()
            .add("oldManagerCustomerId", getOldManagerCustomerId())
            .add("operand", getOperand())
            .add("operationType", getOperationType())
            .add("operator", getOperator())
            .toString();
    }

    /**
     * Gets the operand value for this MoveOperation.
     *
     * @return operand
     */
    public com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerLink getOperand() {
        return operand;
    }

    /**
     * Sets the operand value for this MoveOperation.
     *
     * @param operand
     */
    public void setOperand(com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerLink operand) {
        this.operand = operand;
    }

    /**
     * Gets the oldManagerCustomerId value for this MoveOperation.
     *
     * @return oldManagerCustomerId   * The ID of the old Manager.
     */
    public java.lang.Long getOldManagerCustomerId() {
        return oldManagerCustomerId;
    }

    /**
     * Sets the oldManagerCustomerId value for this MoveOperation.
     *
     * @param oldManagerCustomerId   * The ID of the old Manager.
     */
    public void setOldManagerCustomerId(java.lang.Long oldManagerCustomerId) {
        this.oldManagerCustomerId = oldManagerCustomerId;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof MoveOperation)) return false;
        MoveOperation other = (MoveOperation) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.operand==null && other.getOperand()==null) ||
             (this.operand!=null &&
              this.operand.equals(other.getOperand()))) &&
            ((this.oldManagerCustomerId==null && other.getOldManagerCustomerId()==null) ||
             (this.oldManagerCustomerId!=null &&
              this.oldManagerCustomerId.equals(other.getOldManagerCustomerId())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getOperand() != null) {
            _hashCode += getOperand().hashCode();
        }
        if (getOldManagerCustomerId() != null) {
            _hashCode += getOldManagerCustomerId().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(MoveOperation.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "MoveOperation"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("operand");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "operand"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "ManagedCustomerLink"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("oldManagerCustomerId");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "oldManagerCustomerId"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
from flask import Blueprint, render_template, redirect, url_for, flash

blueprint = Blueprint('general', __name__)

@blueprint.route('/')
def index():
    return render_template('index.html')

# Error handlers
@blueprint.app_errorhandler(401)
def not_authorized(e):
    return render_template('error_pages/401.html'), 401

@blueprint.app_errorhandler(403)
def not_permitted(e):
    return render_template('error_pages/403.html'), 403

@blueprint.app_errorhandler(404)
def not_found(e):
    return render_template('error_pages/404.html'), 404

@blueprint.app_errorhandler(410)
def no_longer_exists(e):
    return render_template('error_pages/410.html'), 410

@blueprint.app_errorhandler(500)
def internal_server_error(e):
    return render_template('error_pages/500.html'), 500

# flash a welcome message to space travelers
@blueprint.route('/fly_back_to_earth')
def fly_back_to_earth():
    flash("Welcome back to Earth! You're faster than light!", 'success')
    return redirect(url_for('general.index'))


text:
define([
	'intern!object',
	'intern/chai!assert',
	'../../main'
], function (registerSuite, assert, main) {
	registerSuite({
		name: 'intern/main',

		'initial state': function () {
			assert.isFunction(main.load, 'main.load should be a function');
			assert.property(main, 'executor', 'main should have an executor property');
		}
	});
});


text:
from __future__ import print_function

__author__ = 'John Sirois'

import hashlib
import getpass
import os
import pkgutil
import shutil
import subprocess

from collections import defaultdict

from twitter.common.collections import OrderedDict, OrderedSet
from twitter.common.config import Properties
from twitter.common.dirutil import safe_open, safe_rmtree

from twitter.pants import get_buildroot, is_exported as provides, is_internal, is_java, pants
from twitter.pants.base import Address, ParseContext, Target
from twitter.pants.base.generator import Generator, TemplateData
from twitter.pants.targets import InternalTarget, AnnotationProcessor, JavaLibrary, ScalaLibrary
from twitter.pants.tasks import binary_utils, Task, TaskError

class Semver(object):
  @staticmethod
  def parse(version):
    components = version.split('.', 3)
    if len(components) != 3:
      raise ValueError
    major, minor, patch = components
    def to_i(component):
      try:
        return int(component)
      except (TypeError, ValueError):
        raise ValueError('Invalid revision component %s in %s - '
                         'must be an integer' % (component, version))
    return Semver(to_i(major), to_i(minor), to_i(patch))

  def __init__(self, major, minor, patch, snapshot=False):
    self.major = major
    self.minor = minor
    self.patch = patch
    self.snapshot = snapshot

  def bump(self):
    # A bump of a snapshot discards snapshot status
    return Semver(self.major, self.minor, self.patch + 1)

  def make_snapshot(self):
    return Semver(self.major, self.minor, self.patch, snapshot=True)

  def version(self):
    return '%s.%s.%s' % (
      self.major,
      self.minor,
      ('%s-SNAPSHOT' % self.patch) if self.snapshot else self.patch
    )

  def __eq__(self, other):
    return self.__cmp__(other) == 0

  def __cmp__(self, other):
    diff = self.major - other.major
    if not diff:
      diff = self.minor - other.minor
      if not diff:
        diff = self.patch - other.patch
        if not diff:
          if self.snapshot and not other.snapshot:
            diff = 1
          elif not self.snapshot and other.snapshot:
            diff = -1
          else:
            diff = 0
    return diff

  def __repr__(self):
    return 'Semver(%s)' % self.version()

class PushDb(object):
  @staticmethod
  def load(file):
    """Loads a pushdb maintained in a properties file at the given path."""
    with open(file, 'r') as props:
      properties = Properties.load(props)
      return PushDb(properties)

  def __init__(self, props):
    self._props = props

  def as_jar_with_version(self, target):
    """
      Given an internal target, return a JarDependency with the last published revision filled in.
    """
    jar_dep, db_get, _ = self._accessors_for_target(target)

    major = int(db_get('revision.major', '0'))
    minor = int(db_get('revision.minor', '0'))
    patch = int(db_get('revision.patch', '0'))
    snapshot = db_get('revision.snapshot', 'false').lower() == 'true'
    sha = db_get('revision.sha', None)
    fingerprint = db_get('revision.fingerprint', None)
    semver = Semver(major, minor, patch, snapshot=snapshot)
    jar_dep.rev = semver.version()
    return jar_dep, semver, sha, fingerprint

  def set_version(self, target, version, sha, fingerprint):
    version = version if isinstance(version, Semver) else Semver.parse(version)
    _, _, db_set = self._accessors_for_target(target)
    db_set('revision.major', version.major)
    db_set('revision.minor', version.minor)
    db_set('revision.patch', version.patch)
    db_set('revision.snapshot', str(version.snapshot).lower())
    db_set('revision.sha', sha)
    db_set('revision.fingerprint', fingerprint)

  def _accessors_for_target(self, target):
    jar_dep, id, exported = target._get_artifact_info()
    if not exported:
      raise ValueError

    def key(prefix):
      return '%s.%s%%%s' % (prefix, jar_dep.org, jar_dep.name)

    def getter(prefix, default=None):
      return self._props.get(key(prefix), default)

    def setter(prefix, value):
      self._props[key(prefix)] = value

    return jar_dep, getter, setter

  def dump(self, file):
    """Saves the pushdb as a properties file to the given path."""
    with open(file, 'w') as props:
      Properties.dump(self._props, props)

class DependencyWriter(object):
  """
    Builds up a template data representing a target and applies this to a template to produce a
    dependency descriptor.
  """

  def __init__(self, get_db, template_relpath):
    self.get_db = get_db
    self.template_relpath = template_relpath

  def write(self, target, path, confs=None):
    def as_jar(internal_target):
      jar, _, _, _ = self.get_db(internal_target).as_jar_with_version(internal_target)
      return jar

    # TODO(John Sirois): a dict is used here to de-dup codegen targets which have both the original
    # codegen target - say java_thrift_library - and the synthetic generated target (java_library)
    # Consider reworking codegen tasks to add removal of the original codegen targets when rewriting
    # the graph
    dependencies = OrderedDict()
    for dep in target.internal_dependencies:
      jar = as_jar(dep)
      dependencies[(jar.org, jar.name)] = self.internaldep(jar)
    for jar in target.jar_dependencies:
      if jar.rev:
        dependencies[(jar.org, jar.name)] = self.jardep(jar)
    target_jar = self.internaldep(as_jar(target)).extend(dependencies=dependencies.values())

    template_kwargs = self.templateargs(target_jar, confs)
    with safe_open(path, 'w') as output:
      template = pkgutil.get_data(__name__, self.template_relpath)
      Generator(template, **template_kwargs).write(output)

  def templateargs(self, target_jar, confs=None):
    """
      Subclasses must return a dict for use by their template given the target jar template data
      and optional specific ivy configurations.
    """
    raise NotImplementedError()

  def internaldep(self, jar_dependency):
    """
      Subclasses must return a template data for the given internal target (provided in jar
      dependency form).
    """
    raise NotImplementedError()

  def jardep(self, jar_dependency):
    """Subclasses must return a template data for the given external jar dependency."""
    raise NotImplementedError()

  def create_exclude(self, exclude):
    return TemplateData(org=exclude.org, name=exclude.name)

class PomWriter(DependencyWriter):
  def __init__(self, get_db):
    super(PomWriter, self).__init__(get_db, os.path.join('jar_publish', 'pom.mk'))

  def templateargs(self, target_jar, confs=None):
    return dict(artifact=target_jar)

  def jardep(self, jar):
    return TemplateData(
      org=jar.org,
      name=jar.name,
      rev=jar.rev,
      scope='compile',
      excludes=[self.create_exclude(exclude) for exclude in jar.excludes if exclude.name]
    )

  def internaldep(self, jar_dependency):
    return self.jardep(jar_dependency)

class IvyWriter(DependencyWriter):
  def __init__(self, get_db):
    super(IvyWriter, self).__init__(get_db, os.path.join('ivy_resolve', 'ivy.mk'))

  def templateargs(self, target_jar, confs=None):
    return dict(lib=target_jar.extend(
      publications=set(confs) if confs else set(),
    ))

  def _jardep(self, jar, transitive=True, ext=None, url=None, configurations='default'):
    return TemplateData(
      org=jar.org,
      module=jar.name,
      version=jar.rev,
      force=jar.force,
      excludes=[self.create_exclude(exclude) for exclude in jar.excludes],
      transitive=transitive,
      ext=ext,
      url=url,
      configurations=configurations,
    )

  def jardep(self, jar):
    return self._jardep(jar,
      transitive=jar.transitive,
      ext=jar.ext,
      url=jar.url,
      configurations=';'.join(jar._configurations)
    )

  def internaldep(self, jar_dependency):
    return self._jardep(jar_dependency)

def is_exported(target):
  return provides(target) and (
    isinstance(target, AnnotationProcessor)
    or isinstance(target, JavaLibrary)
    or isinstance(target, ScalaLibrary)
  )

def coordinate(org, name, rev=None):
  return '%s#%s;%s' % (org, name, rev) if rev else '%s#%s' % (org, name)

def jar_coordinate(jar, rev=None):
  return coordinate(jar.org, jar.name, rev or jar.rev)

class JarPublish(Task):

  @classmethod
  def setup_parser(cls, option_group, args, mkflag):
    # TODO(John Sirois): Support a preview mode that outputs a file with entries like:
    # artifact id:
    # revision:
    # publish: (true|false)
    # changelog:
    #
    # Allow re-running this goal with the file as input to support forcing an arbitrary set of
    # revisions and supply of hand endited changelogs.

    option_group.add_option(mkflag("dryrun"), mkflag("dryrun", negate=True),
                            dest="jar_publish_dryrun", default=True,
                            action="callback", callback=mkflag.set_bool,
                            help="[%default] Runs through a push without actually pushing "
                                 "artifacts, editing publish dbs or otherwise writing data")

    option_group.add_option(mkflag("commit", negate=True),
                            dest="jar_publish_commit", default=True,
                            action="callback", callback=mkflag.set_bool,
                            help="Turns off commits of the push db for local testing.")

    local_flag = mkflag("local")
    option_group.add_option(local_flag, dest="jar_publish_local",
                            help="Publishes jars to a maven repository on the local filesystem at "
                                 "the specified path.")

    option_group.add_option(mkflag("local-snapshot"), mkflag("local-snapshot", negate=True),
                            dest="jar_publish_local_snapshot", default=True,
                            action="callback", callback=mkflag.set_bool,
                            help="[%%default] If %s is specified, publishes jars with '-SNAPSHOT' "
                                 "revisions." % local_flag)

    option_group.add_option(mkflag("transitive"), mkflag("transitive", negate=True),
                            dest="jar_publish_transitive", default=True,
                            action="callback", callback=mkflag.set_bool,
                            help="[%default] Publishes the specified targets and all their "
                                 "internal dependencies transitively.")

    option_group.add_option(mkflag("force"), mkflag("force", negate=True),
                            dest="jar_publish_force", default=False,
                            action="callback", callback=mkflag.set_bool,
                            help="[%default] Forces pushing jars even if there have been no "
                                 "changes since the last push.")

    flag = mkflag('override')
    option_group.add_option(flag, action='append', dest='jar_publish_overrides',
                            help='''Specifies a published jar revision override in the form:
                            ([org]#[name]|[target spec])=[new revision]

                            For example, to specify 2 overrides:
                            %(flag)s=com.twitter.common#quantity=0.1.2 \\
                            %(flag)s=src/java/com/twitter/common/base=1.0.0 \\
                            ''' % dict(flag=flag))

    flag = mkflag("restart-at")
    option_group.add_option(flag, dest="jar_publish_restart_at",
                            help='''Restart a fail push at the given jar.  Jars can be identified by
                            maven coordinate [org]#[name] or target.

                            For example:
                            %(flag)s=com.twitter.common#quantity

                            Or:
                            %(flag)s=src/java/com/twitter/common/base
                            ''' % dict(flag=flag))

  def __init__(self, context):
    Task.__init__(self, context)

    self.outdir = context.config.get('jar-publish', 'workdir')
    self.cachedir = os.path.join(self.outdir, 'cache')

    if context.options.jar_publish_local:
      local_repo = dict(
        resolver='publish_local',
        path=os.path.abspath(os.path.expanduser(context.options.jar_publish_local)),
        confs=context.config.getlist('jar-publish', 'publish_local_confs', default=['*']),
        auth=None
      )
      self.repos = defaultdict(lambda: local_repo)
      self.commit = False
      self.snapshot = context.options.jar_publish_local_snapshot
    else:
      self.repos = context.config.getdict('jar-publish', 'repos')
      self.commit = context.options.jar_publish_commit
      self.snapshot = False

    self.ivycp = context.config.getlist('ivy', 'classpath')
    self.ivysettings = context.config.get('ivy', 'ivy_settings')

    self.dryrun = context.options.jar_publish_dryrun
    self.transitive = context.options.jar_publish_transitive
    self.force = context.options.jar_publish_force

    def parse_jarcoordinate(coordinate):
      components = coordinate.split('#', 1)
      if len(components) == 2:
        org, name = components
        return org, name
      else:
        try:
          address = Address.parse(get_buildroot(), coordinate)
          try:
            target = Target.get(address)
            if not target:
              siblings = Target.get_all_addresses(address.buildfile)
              prompt = 'did you mean' if len(siblings) == 1 else 'maybe you meant one of these'
              raise TaskError('%s => %s?:\n    %s' % (address, prompt,
                                                      '\n    '.join(str(a) for a in siblings)))
            if not is_exported(target):
              raise TaskError('%s is not an exported target' % coordinate)
            return target.provides.org, target.provides.name
          except (ImportError, SyntaxError, TypeError):
            raise TaskError('Failed to parse %s' % address.buildfile.relpath)
        except IOError:
          raise TaskError('No BUILD file could be found at %s' % coordinate)

    self.overrides = {}
    if context.options.jar_publish_overrides:
      def parse_override(override):
        try:
          coordinate, rev = override.split('=', 1)
          try:
            rev = Semver.parse(rev)
          except ValueError as e:
            raise TaskError('Invalid version %s: %s' % (rev, e))
          return parse_jarcoordinate(coordinate), rev
        except ValueError:
          raise TaskError('Invalid override: %s' % override)

      self.overrides.update(parse_override(o) for o in context.options.jar_publish_overrides)

    self.restart_at = None
    if context.options.jar_publish_restart_at:
      self.restart_at = parse_jarcoordinate(context.options.jar_publish_restart_at)

    context.products.require('jars')
    context.products.require('source_jars')
    context.products.require('javadoc_jars')

  def execute(self, targets):
    self.check_clean_master()

    pushdbs = {}
    def get_db(target):
      if target.provides is None:
        raise TaskError('trying to publish target %r which does not provide an artifact' % target)
      dbfile = target.provides.repo.push_db
      result = pushdbs.get(dbfile)
      if not result:
        db = PushDb.load(dbfile)
        repo = self.repos[target.provides.repo.name]
        result = (db, dbfile, repo)
        pushdbs[dbfile] = result
      return result

    def fingerprint_internal(target):
      if not is_internal(target):
        raise ValueError('Expected an internal target for fingerprinting, got %s' % target)
      pushdb, _, _ = get_db(target)
      _, _, _, fingerprint = pushdb.as_jar_with_version(target)
      return fingerprint or '0.0.0'

    def stage_artifacts(target, jar, version, changelog, confs=None):
      def artifact_path(name=None, suffix='', extension='jar'):
        return os.path.join(self.outdir, jar.org, jar.name,
                            '%s-%s%s.%s' % ((name or jar.name), version, suffix, extension))

      with safe_open(artifact_path(suffix='-CHANGELOG', extension='txt'), 'w') as changelog_file:
        changelog_file.write(changelog)

      def get_pushdb(target):
        return get_db(target)[0]

      PomWriter(get_pushdb).write(target, artifact_path(extension='pom'))

      ivyxml = artifact_path(name='ivy', extension='xml')
      IvyWriter(get_pushdb).write(target, ivyxml, confs)

      def copy(typename, suffix=''):
        genmap = self.context.products.get(typename)
        for basedir, jars in genmap.get(target).items():
          for artifact in jars:
            shutil.copy(os.path.join(basedir, artifact), artifact_path(suffix=suffix))

      copy('jars')
      if is_java(target):
        copy('javadoc_jars', '-javadoc')
      copy('source_jars', '-sources')

      return ivyxml

    if self.overrides:
      print('Publishing with revision overrides:\n  %s' % '\n  '.join(
        '%s=%s' % (coordinate(org, name), rev) for (org, name), rev in self.overrides.items()
      ))

    head_sha = self.check_output(['git', 'rev-parse', 'HEAD']).strip()

    safe_rmtree(self.outdir)
    published = []
    skip = (self.restart_at is not None)
    for target in self.exported_targets():
      pushdb, dbfile, repo = get_db(target)
      jar, semver, sha, fingerprint = pushdb.as_jar_with_version(target)

      published.append(jar)

      if skip and (jar.org, jar.name) == self.restart_at:
        skip = False

      newver = self.overrides.get((jar.org, jar.name)) or semver.bump()
      if self.snapshot:
        newver = newver.make_snapshot()

      if newver <= semver:
        raise TaskError('Requested version %s must be greater than the current version %s' % (
          newver.version(), semver.version()
        ))

      newfingerprint = self.fingerprint(target, fingerprint_internal)
      no_changes = newfingerprint == fingerprint

      if no_changes:
        changelog = 'No changes for %s - forced push.\n' % jar_coordinate(jar, semver.version())
      else:
        changelog = self.changelog(target, sha) or 'Direct dependencies changed.\n'

      if no_changes and not self.force:
        print('No changes for %s' % jar_coordinate(jar, semver.version()))
        stage_artifacts(target, jar, (newver if self.force else semver).version(), changelog)
      elif skip:
        print('Skipping %s to resume at %s' % (
          jar_coordinate(jar, (newver if self.force else semver).version()),
          coordinate(self.restart_at[0], self.restart_at[1])
        ))
        stage_artifacts(target, jar, semver.version(), changelog)
      else:
        if not self.dryrun:
          # Confirm push looks good
          if no_changes:
            print(changelog)
          else:
            print('\nChanges for %s since %s @ %s:\n\n%s' % (
              coordinate(jar.org, jar.name), semver.version(), sha, changelog
            ))
          push = raw_input('Publish %s with revision %s ? [y|N] ' % (
            coordinate(jar.org, jar.name), newver.version()
          ))
          print('\n')
          if push.strip().lower() != 'y':
            raise TaskError('User aborted push')

        pushdb.set_version(target, newver, head_sha, newfingerprint)
        ivyxml = stage_artifacts(target, jar, newver.version(), changelog, confs=repo['confs'])
        if self.dryrun:
          print('Skipping publish of %s in test mode.' % jar_coordinate(jar, newver.version()))
        else:
          resolver = repo['resolver']
          path = repo.get('path')

          # Get authentication for the publish repo if needed
          jvmargs = []
          auth = repo['auth']
          if auth:
            with ParseContext.temp():
              credentials = pants(auth).resolve().next()
              jvmargs.append(credentials.username())
              jvmargs.append(credentials.password())

          # Do the publish
          ivysettings = self.generate_ivysettings(published, publish_local=path)
          args = [
            '-settings', ivysettings,
            '-ivy', ivyxml,
            '-deliverto', '%s/[organisation]/[module]/ivy-[revision].xml' % self.outdir,
            '-publish', resolver,
            '-publishpattern',
              '%s/[organisation]/[module]/[artifact]-[revision](-[classifier]).[ext]' % self.outdir,
            '-revision', newver.version(),
            '-m2compatible',
          ]
          if self.snapshot:
            args.append('-overwrite')

          result = binary_utils.runjava(jvmargs=jvmargs, classpath=self.ivycp, args=args)
          if result != 0:
            raise TaskError('Failed to push %s - ivy failed with %d' % (
              jar_coordinate(jar, newver.version()), result)
            )

          if self.commit:
            pushdb.dump(dbfile)
            self.commit_push(jar.org, jar.name, newver.version(), head_sha)

  def exported_targets(self):
    candidates = set(self.context.targets() if self.transitive else self.context.target_roots)
    def exportable(target):
      return target in candidates and is_exported(target) and is_internal(target)
    return OrderedSet(filter(exportable,
                             reversed(InternalTarget.sort_targets(filter(exportable, candidates)))))

  def fingerprint(self, target, fingerprint_internal):
    sha = hashlib.sha1()

    for source in sorted(target.sources):
      path = os.path.join(target.target_base, source)
      with open(path) as fd:
        sha.update(source)
        sha.update(fd.read())

    # TODO(John Sirois): handle resources and circular dep scala_library java_sources

    for jarsig in sorted([jar_coordinate(j) for j in target.jar_dependencies if j.rev]):
      sha.update(jarsig)

    internal_dependencies = sorted(target.internal_dependencies, key=lambda t: t.id)
    for internal_target in internal_dependencies:
      fingerprint = fingerprint_internal(internal_target)
      sha.update(fingerprint)

    return sha.hexdigest()

  def changelog(self, target, sha):
    cmd = ['git', 'whatchanged', '--stat', '-M', '-C']
    if sha:
      cmd.append('%s..HEAD' % sha)
    cmd.append('--')
    cmd.extend(os.path.join(target.target_base, source) for source in target.sources)
    return self.check_output(cmd)

  def check_clean_master(self):
    if self.dryrun or not self.commit:
      print('Skipping check for a clean master in test mode.')
    else:
      branch = self.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
      if branch != 'master':
        raise TaskError('Can only push from master, currently on branch: %s' % branch)

      self.check_call(['git', 'diff', '--exit-code', '--quiet'],
                      failuremsg='Can only push from a clean master, workspace is dirty')

      self.check_call(['git', 'diff', '--exit-code', '--cached', '--quiet'],
                      failuremsg='Can only push from a clean master, index is dirty')

  def commit_push(self, org, name, rev, sha):
    args = dict(
      org=org,
      name=name,
      rev=rev,
      coordinate=coordinate(org, name, rev),
      user=getpass.getuser(),
      cause='with forced revision' if (org, name) in self.overrides else '(autoinc)'
    )
    self.check_call(['git', 'pull', '--ff-only', '--tags', 'origin', 'master'])
    self.check_call(['git', 'tag' , '-a',
                     '-m', 'Publish of %(coordinate)s initiated by %(user)s %(cause)s' % args,
                     '%(org)s-%(name)s-%(rev)s' % args, sha])

    self.check_call(['git', 'commit' , '-a',
                     '-m', 'pants build committing publish data for push of '
                           '%(coordinate)s' % args])

    self.check_call(['git', 'push' , 'origin', 'master', '--tags'])

  def check_call(self, cmd, failuremsg=None):
    self.log_call(cmd)
    result = subprocess.call(cmd)
    self.check_result(cmd, result, failuremsg)

  def check_output(self, cmd, failuremsg=None):
    self.log_call(cmd)
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    self.check_result(cmd, process.returncode, failuremsg)
    return out

  def log_call(self, cmd):
    self.context.log.debug('Executing: %s' % ' '.join(cmd))

  def check_result(self, cmd, result, failuremsg=None):
    if result != 0:
      raise TaskError(failuremsg or '%s failed with exit code %d' % (' '.join(cmd), result))

  def generate_ivysettings(self, publishedjars, publish_local=None):
    template = pkgutil.get_data(__name__, os.path.join('jar_publish', 'ivysettings.mk'))
    with safe_open(os.path.join(self.outdir, 'ivysettings.xml'), 'w') as wrapper:
      generator = Generator(template,
                            ivysettings=self.ivysettings,
                            dir=self.outdir,
                            cachedir=self.cachedir,
                            published=[TemplateData(org=jar.org, name=jar.name)
                                       for jar in publishedjars],
                            publish_local=publish_local)
      generator.write(wrapper)
      return wrapper.name