text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    app:contentPaddingLeft="@dimen/dimen_10"
    app:contentPaddingRight="@dimen/dimen_10"
    app:cardBackgroundColor="@color/primary"
    android:layout_gravity="center_vertical"
    app:cardElevation="0dp"
    tools:context=".ui.module.main.UserDetailActivity">

    <LinearLayout
        android:id="@+id/fo_info"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/dimen_10"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/fo_info_avatar"
                android:layout_width="@dimen/dimen_60"
                android:layout_height="@dimen/dimen_60"
                android:layout_gravity="center_vertical"
                android:scaleType="fitXY"
                tools:src="@drawable/ic_github"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="@dimen/dimen_5">

                <TextView
                    android:id="@+id/fo_info_login"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/dimen_30"
                    android:textSize="@dimen/text_size_18"
                    android:textColor="@color/md_white_1000"
                    android:gravity="center_vertical"
                    tools:text="jbm758599"/>

                <TextView
                    android:id="@+id/fo_info_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_size_12"
                    android:textColor="@color/md_white_1000"
                    android:gravity="center_vertical"
                    tools:text="蒋柏铭"/>

                <TextView
                    android:id="@+id/fo_info_bio"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/text_size_12"
                    android:textColor="@color/md_white_1000"
                    android:maxLines="1"
                    tools:text="aaaa风蛋"/>

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/fo_info_company_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="@dimen/dimen_2"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_14"
                android:textColor="@color/white"
                android:text="{gmi_accounts_alt}"/>

            <TextView
                android:id="@+id/fo_info_company"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_12"
                android:textColor="@color/white"
                android:layout_marginLeft="@dimen/dimen_10"
                android:gravity="center_vertical"
                android:maxLines="1"
                android:text="not set"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/fo_info_location_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="@dimen/dimen_2"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_14"
                android:textColor="@color/white"
                android:text="{oct_location}"/>

            <TextView
                android:id="@+id/fo_info_location"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_12"
                android:layout_marginLeft="@dimen/dimen_10"
                android:textColor="@color/white"
                android:maxLines="1"
                android:text="not set"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/fo_info_blog_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="@dimen/dimen_2"
            android:gravity="center_vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_14"
                android:textColor="@color/white"
                android:text="{oct_link}"/>

            <TextView
                android:id="@+id/fo_info_blog"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dimen_10"
                android:maxLines="1"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_12"
                android:text="not set"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/fo_info_email_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_marginLeft="@dimen/dimen_2"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/fo_info_email_ic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_14"
                android:text="{oct_mail}"/>
            <TextView
                android:id="@+id/fo_info_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_12"
                android:layout_marginLeft="@dimen/dimen_10"
                android:maxLines="1"
                android:text="not set"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/fo_info_join_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_marginLeft="@dimen/dimen_2"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/fo_info_join_ic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_14"
                android:text="{oct_clock}"/>
            <TextView
                android:id="@+id/fo_info_join"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_12"
                android:layout_marginLeft="@dimen/dimen_10"
                android:maxLines="1"
                android:text="not set"/>

        </LinearLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="@dimen/dimen_30"
            android:gravity="center_vertical"
            android:text="Organizations"
            android:visibility="gone"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/fo_info_orglist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"/>

    </LinearLayout>

</android.support.v7.widget.CardView>


text:
#include "application_manager/commands/hmi/ui_delete_submenu_response.h"
#include "application_manager/event_engine/event.h"

#include "interfaces/HMI_API.h"

namespace application_manager {

namespace commands {

UIDeleteSubmenuResponse::UIDeleteSubmenuResponse(
    const MessageSharedPtr& message, ApplicationManager& application_manager)
    : ResponseFromHMI(message, application_manager) {}

UIDeleteSubmenuResponse::~UIDeleteSubmenuResponse() {}

void UIDeleteSubmenuResponse::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  event_engine::Event event(hmi_apis::FunctionID::UI_DeleteSubMenu);
  event.set_smart_object(*message_);
  event.raise(application_manager_.event_dispatcher());
}

}  // namespace commands

}  // namespace application_manager

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>PowerManager.WakeLock - Android SDK | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../')"
onkeyup="return search_changed(event, false, '../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  android

  android.accessibilityservice

  android.accounts

  android.animation

  android.app

  android.app.admin

  android.app.backup

  android.appwidget

  android.bluetooth

  android.content

  android.content.pm

  android.content.res

  android.database

  android.database.sqlite

  android.drm

  android.gesture

  android.graphics

  android.graphics.drawable

  android.graphics.drawable.shapes

  android.graphics.pdf

  android.hardware

  android.hardware.display

  android.hardware.input

  android.hardware.location

  android.hardware.usb

  android.inputmethodservice

  android.location

  android.media

  android.media.audiofx

  android.media.effect

  android.mtp

  android.net

  android.net.http

  android.net.nsd

  android.net.rtp

  android.net.sip

  android.net.wifi

  android.net.wifi.p2p

  android.net.wifi.p2p.nsd

  android.nfc

  android.nfc.cardemulation

  android.nfc.tech

  android.opengl

  android.os

  android.os.storage

  android.preference

  android.print

  android.print.pdf

  android.printservice

  android.provider

  android.renderscript

  android.sax

  android.security

  android.service.dreams

  android.service.notification

  android.service.textservice

  android.service.wallpaper

  android.speech

  android.speech.tts

  android.support.v13.app

  android.support.v4.accessibilityservice

  android.support.v4.app

  android.support.v4.content

  android.support.v4.content.pm

  android.support.v4.database

  android.support.v4.graphics.drawable

  android.support.v4.hardware.display

  android.support.v4.media

  android.support.v4.net

  android.support.v4.os

  android.support.v4.print

  android.support.v4.text

  android.support.v4.util

  android.support.v4.view

  android.support.v4.view.accessibility

  android.support.v4.widget

  android.support.v7.app

  android.support.v7.appcompat

  android.support.v7.gridlayout

  android.support.v7.media

  android.support.v7.mediarouter

  android.support.v7.view

  android.support.v7.widget

  android.support.v8.renderscript

  android.telephony

  android.telephony.cdma

  android.telephony.gsm

  android.test

  android.test.mock

  android.test.suitebuilder

  android.text

  android.text.format

  android.text.method

  android.text.style

  android.text.util

  android.transition

  android.util

  android.view

  android.view.accessibility

  android.view.animation

  android.view.inputmethod

  android.view.textservice

  android.webkit

  android.widget

  dalvik.bytecode

  dalvik.system

  java.awt.font

  java.beans

  java.io

  java.lang

  java.lang.annotation

  java.lang.ref

  java.lang.reflect

  java.math

  java.net

  java.nio

  java.nio.channels

  java.nio.channels.spi

  java.nio.charset

  java.nio.charset.spi

  java.security

  java.security.acl

  java.security.cert

  java.security.interfaces

  java.security.spec

  java.sql

  java.text

  java.util

  java.util.concurrent

  java.util.concurrent.atomic

  java.util.concurrent.locks

  java.util.jar

  java.util.logging

  java.util.prefs

  java.util.regex

  java.util.zip

  javax.crypto

  javax.crypto.interfaces

  javax.crypto.spec

  javax.microedition.khronos.egl

  javax.microedition.khronos.opengles

  javax.net

  javax.net.ssl

  javax.security.auth

  javax.security.auth.callback

  javax.security.auth.login

  javax.security.auth.x500

  javax.security.cert

  javax.sql

  javax.xml

  javax.xml.datatype

  javax.xml.namespace

  javax.xml.parsers

  javax.xml.transform

  javax.xml.transform.dom

  javax.xml.transform.sax

  javax.xml.transform.stream

  javax.xml.validation

  javax.xml.xpath

  junit.framework

  junit.runner

  org.apache.http

  org.apache.http.auth

  org.apache.http.auth.params

  org.apache.http.client

  org.apache.http.client.entity

  org.apache.http.client.methods

  org.apache.http.client.params

  org.apache.http.client.protocol

  org.apache.http.client.utils

  org.apache.http.conn

  org.apache.http.conn.params

  org.apache.http.conn.routing

  org.apache.http.conn.scheme

  org.apache.http.conn.ssl

  org.apache.http.conn.util

  org.apache.http.cookie

  org.apache.http.cookie.params

  org.apache.http.entity

  org.apache.http.impl

  org.apache.http.impl.auth

  org.apache.http.impl.client

  org.apache.http.impl.conn

  org.apache.http.impl.conn.tsccm

  org.apache.http.impl.cookie

  org.apache.http.impl.entity

  org.apache.http.impl.io

  org.apache.http.io

  org.apache.http.message

  org.apache.http.params

  org.apache.http.protocol

  org.apache.http.util

  org.json

  org.w3c.dom

  org.w3c.dom.ls

  org.xml.sax

  org.xml.sax.ext

  org.xml.sax.helpers

  org.xmlpull.v1

  org.xmlpull.v1.sax2

Interfaces

CancellationSignal.OnCancelListener

Handler.Callback

IBinder

IBinder.DeathRecipient

IInterface

MessageQueue.IdleHandler

Parcelable

Parcelable.ClassLoaderCreator

Parcelable.Creator

ParcelFileDescriptor.OnCloseListener

RecoverySystem.ProgressListener

Classes

AsyncTask

BatteryManager

Binder

Build

Build.VERSION

Build.VERSION_CODES

Bundle

CancellationSignal

ConditionVariable

CountDownTimer

Debug

Debug.InstructionCount

Debug.MemoryInfo

DropBoxManager

DropBoxManager.Entry

Environment

FileObserver

Handler

HandlerThread

Looper

MemoryFile

Message

MessageQueue

Messenger

Parcel

ParcelFileDescriptor

ParcelFileDescriptor.AutoCloseInputStream

ParcelFileDescriptor.AutoCloseOutputStream

ParcelUuid

PatternMatcher

PowerManager

PowerManager.WakeLock

Process

RecoverySystem

RemoteCallbackList

ResultReceiver

StatFs

StrictMode

StrictMode.ThreadPolicy

StrictMode.ThreadPolicy.Builder

StrictMode.VmPolicy

StrictMode.VmPolicy.Builder

SystemClock

TokenWatcher

Trace

UserHandle

UserManager

Vibrator

WorkSource

Enums

AsyncTask.Status

Exceptions

BadParcelableException

DeadObjectException

NetworkOnMainThreadException

OperationCanceledException

ParcelFileDescriptor.FileDescriptorDetachedException

ParcelFormatException

RemoteException

TransactionTooLargeException

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Methods

  | Protected Methods

  | Inherited Methods

| [Expand All]

  Added in API level 1

    public

    final

    class

PowerManager.WakeLock

    extends Object

        java.lang.Object

               ↳

        android.os.PowerManager.WakeLock

Class Overview

A wake lock is a mechanism to indicate that your application needs
 to have the device stay on.

 Any application using a WakeLock must request the android.permission.WAKE_LOCK
 permission in an <uses-permission> element of the application's manifest.
 Obtain a wake lock by calling newWakeLock(int, String).

 Call acquire() to acquire the wake lock and force the device to stay
 on at the level that was requested when the wake lock was created.

 Call release() when you are done and don't need the lock anymore.
 It is very important to do this as soon as possible to avoid running down the
 device's battery excessively.

Summary

Public Methods

        <nobr>

            void</nobr>

        <nobr>
        acquire()</nobr>

Acquires the wake lock.

        <nobr>

            void</nobr>

        <nobr>
        acquire(long timeout)</nobr>

Acquires the wake lock with a timeout.

        <nobr>

            boolean</nobr>

        <nobr>
        isHeld()</nobr>

Returns true if the wake lock has been acquired but not yet released.

        <nobr>

            void</nobr>

        <nobr>
        release()</nobr>

Releases the wake lock.

        <nobr>

            void</nobr>

        <nobr>
        setReferenceCounted(boolean value)</nobr>

Sets whether this WakeLock is reference counted.

        <nobr>

            void</nobr>

        <nobr>
        setWorkSource(WorkSource ws)</nobr>

Sets the work source associated with the wake lock.

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

Returns a string containing a concise, human-readable description of this
 object.

Protected Methods

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

Invoked when the garbage collector has detected that this instance is no longer reachable.

  [Expand]

Inherited Methods

From class

  java.lang.Object

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

Creates and returns a copy of this Object.

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object o)</nobr>

Compares this instance with the specified object and indicates if they
 are equal.

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

Invoked when the garbage collector has detected that this instance is no longer reachable.

        <nobr>

            final

            Class<?></nobr>

        <nobr>
        getClass()</nobr>

Returns the unique instance of Class that represents this
 object's class.

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

Returns an integer hash code for this object.

        <nobr>

            final

            void</nobr>

        <nobr>
        notify()</nobr>

Causes a thread which is waiting on this object's monitor (by means of
 calling one of the wait() methods) to be woken up.

        <nobr>

            final

            void</nobr>

        <nobr>
        notifyAll()</nobr>

Causes all threads which are waiting on this object's monitor (by means
 of calling one of the wait() methods) to be woken up.

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

Returns a string containing a concise, human-readable description of this
 object.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait()</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long millis, int nanos)</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
 specified timeout expires.

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long millis)</nobr>

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
 specified timeout expires.

Public Methods

        public

        void

      acquire
      ()

  Added in API level 1

Acquires the wake lock.

 Ensures that the device is on at the level requested when
 the wake lock was created.

        public

        void

      acquire
      (long timeout)

  Added in API level 1

Acquires the wake lock with a timeout.

 Ensures that the device is on at the level requested when
 the wake lock was created.  The lock will be released after the given timeout
 expires.

Parameters

          timeout
          The timeout after which to release the wake lock, in milliseconds.

        public

        boolean

      isHeld
      ()

  Added in API level 1

Returns true if the wake lock has been acquired but not yet released.

Returns

True if the wake lock is held.

        public

        void

      release
      ()

  Added in API level 1

Releases the wake lock.

 This method releases your claim to the CPU or screen being on.
 The screen may turn off shortly after you release the wake lock, or it may
 not if there are other wake locks still held.

        public

        void

      setReferenceCounted
      (boolean value)

  Added in API level 1

Sets whether this WakeLock is reference counted.

 Wake locks are reference counted by default.  If a wake lock is
 reference counted, then each call to acquire() must be
 balanced by an equal number of calls to release().  If a wake
 lock is not reference counted, then one call to release() is
 sufficient to undo the effect of all previous calls to acquire().

Parameters

          value
          True to make the wake lock reference counted, false to
 make the wake lock non-reference counted.

        public

        void

      setWorkSource
      (WorkSource ws)

  Added in API level 9

Sets the work source associated with the wake lock.

 The work source is used to determine on behalf of which application
 the wake lock is being held.  This is useful in the case where a
 service is performing work on behalf of an application so that the
 cost of that work can be accounted to the application.

Parameters

          ws
          The work source, or null if none.

        public

        String

      toString
      ()

  Added in API level 1

Returns a string containing a concise, human-readable description of this
 object. Subclasses are encouraged to override this method and provide an
 implementation that takes into account the object's type and data. The
 default implementation is equivalent to the following expression:

   getClass().getName() + '@' + Integer.toHexString(hashCode())

See Writing a useful
 toString method
 if you intend implementing your own toString method.

Returns

a printable representation of this object.

Protected Methods

        protected

        void

      finalize
      ()

  Added in API level 1

Invoked when the garbage collector has detected that this instance is no longer reachable.
 The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that override finalize are significantly more expensive than
 objects that don't. Finalizers may be run a long time after the object is no longer
 reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
 Note also that finalizers are run on a single VM-wide finalizer thread,
 so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
 for a class that has a native peer and needs to call a native method to destroy that peer.
 Even then, it's better to provide an explicit close method (and implement
 Closeable), and insist that callers manually dispose of instances. This
 works well for something like files, but less well for something like a BigInteger
 where typical calling code would have to deal with lots of temporaries. Unfortunately,
 code that creates lots of temporaries is the worst kind of code from the point of view of
 the single finalizer thread.

If you must use finalizers, consider at least providing your own
 ReferenceQueue and having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for
 calling super.finalize() yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
 thread.

 See Effective Java Item 7, "Avoid finalizers" for more.

Throws

            Throwable

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android 4.4 r1 —

    About Android  |
    Legal  |
    Support


text:
Social Builder
==============

## [Use it Live](https://mojotech.github.io/social-builder/)

### Why should you use this?
 - For those times when you want some social buttons, that look nice, but don't want to scrape the internet for how.
 - For those times when you want some markup that you can hack and not iframes.
 - For those times you want to be awesome, because you are!

### Dev
 - `npm install roots@2.1.0 -g`
 - `roots watch`

### Deployment
 - `roots deploy --gh-pages`

### Adding a new display type
 - create a new file like `_list-bar.coffee`
 - add said file to main.coffee
 - add new style to supported styles in application.coffee
 - add a new stylesheet in layout.jade with the contained styles

### License
See the [LICENSE](/LICENSE) file.


text:
<?php

class Google_Service_Pagespeedonline_PagespeedApiPagespeedResponseV4LoadingExperience extends Google_Model
{
  protected $internal_gapi_mappings = array(
        "initialUrl" => "initial_url",
        "overallCategory" => "overall_category",
  );
  public $id;
  public $initialUrl;
  protected $metricsType = 'Google_Service_Pagespeedonline_PagespeedApiPagespeedResponseV4LoadingExperienceMetricsElement';
  protected $metricsDataType = 'map';
  public $overallCategory;

  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setInitialUrl($initialUrl)
  {
    $this->initialUrl = $initialUrl;
  }
  public function getInitialUrl()
  {
    return $this->initialUrl;
  }
  /**
   * @param Google_Service_Pagespeedonline_PagespeedApiPagespeedResponseV4LoadingExperienceMetricsElement
   */
  public function setMetrics($metrics)
  {
    $this->metrics = $metrics;
  }
  /**
   * @return Google_Service_Pagespeedonline_PagespeedApiPagespeedResponseV4LoadingExperienceMetricsElement
   */
  public function getMetrics()
  {
    return $this->metrics;
  }
  public function setOverallCategory($overallCategory)
  {
    $this->overallCategory = $overallCategory;
  }
  public function getOverallCategory()
  {
    return $this->overallCategory;
  }
}


text:
class CQCheckBox : public QCheckBox {
  Q_OBJECT

 public:
  CQCheckBox(QWidget *parent=nullptr);
  CQCheckBox(const QString &text, QWidget *parent=nullptr);

 private slots:
  void stateSlot(int b);
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;

public static class VariableLengthQuantity
{
    private const uint SevenBitsMask = 0x7fu;
    private const uint EightBitMask = 0x80u;

    public static uint[] Encode(uint[] numbers) => numbers.SelectMany(EncodeSingle).ToArray();

    private static IEnumerable<uint> EncodeSingle(uint number)
    {
        if (number == 0)
        {
            return new[] { 0u };
        }

        var bytes = new List<uint>(4);

        while (number > 0)
        {
            var tmp = number & SevenBitsMask;
            number >>= 7;

            if (bytes.Any())
            {
                tmp |= EightBitMask;
            }

            bytes.Add(tmp);
        }

        bytes.Reverse();
        return bytes;
    }

    public static uint[] Decode(uint[] bytes)
    {
        var numbers = new List<uint>();
        var tmp = 0u;

        for (var index = 0; index < bytes.Length; index++)
        {
            if ((tmp & 0xfe000000u) > 0)
            {
                throw new InvalidOperationException("Overflow exception.");
            }

            var b = bytes[index];
            tmp = (tmp << 7) | (b & 0x7fu);

            if ((b & 0x80) == 0)
            {
                numbers.Add(tmp);
                tmp = 0;
            }
            else if (index == bytes.Length - 1)
            {
                throw new InvalidOperationException("Incomplete byte sequence.");
            }
        }

        return numbers.ToArray();
    }
}


text:
package org.duvin.dsa;

import java.util.Iterator;

/**
 *
 * @author Johannes Verwijnen <duvin@duvin.org>
 */
public abstract class AbstractLinkedList<T> {

    protected Node first;
    protected int size;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public Iterator<T> iterator() {
        return new ListIterator();
    }

    protected class Node<T> {

        T item;
        Node next;
    }

    protected class ListIterator<T> implements Iterator<T> {

        private Node p = first;

        public boolean hasNext() {
            return p != null;
        }

        public T next() {
            T t = (T) p.item;
            p = p.next;
            return t;
        }

        public void remove() {
            throw new UnsupportedOperationException("Not supported.");
        }

    }
}


text:
public class RearrangementTest23
    implements IFace2, IFace1
{
    int method1() { return 4; }
    public boolean getB() { return false; }
    public int getY() { return 6; }
    public int getX() { return getA() ? 5 : 3; }
    public boolean getA() { return true; }
    int method2() { return 7; }
}

interface IFace2
{
    public boolean getA();
    public boolean getB();
}

interface IFace1
{
    public int getY();
    public int getX();
}


text:
'use strict';

var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var glob = require('glob');

module.exports = yeoman.Base.extend({

  initializing: function () {
    this.sourceRoot(path.join(this.sourceRoot(), '../../ruby-starter-kit'));
  },

  prompting: function () {
    this.log(yosay(
            'Welcome to the ' + chalk.green('Ruby Starter Kit') + ' generator!'
    ));
  },

  writing: function () {
    var done = this.async();
    glob('**/*', { cwd: this.sourceRoot(), dot: true }, function (err, files) {
      if (err) {
        this.log('Error:', err.message);
        return done();
      }
      files.forEach(function (file) {
        var dest = file;
        if (file === '.npmignore') {
          dest = '.gitignore';
        }
        this.fs.copy(
            this.templatePath(file),
            this.destinationPath(dest)
        );
      }, this);
      done();
    }.bind(this));
  },

  detectFeature: function (testCommand) {
    if (!testCommand) return;
    var result = this.spawnCommandSync(testCommand, ['--version'], {stdio: 'ignore'});
    return !result.error;
  },

  _promptUserWithGitInit: function() {
    var done = this.async();
    this.prompt({
      type: 'confirm',
      name: 'initGit',
      message: 'Initialize Git repo?',
      default: true
    }, function (answers) {
      if (answers.initGit) {
        this.log("Initializing Git repo..");
        this.spawnCommandSync('git', ['init']);
      }
  //    this._sayGoodbye();
      done();
    }.bind(this));
  },

  _showRvmInstructions: function () {
    this.log("You are using RVM. Please run these commands manually after this installation is complete:");
    this.log();
    this.log("rvm use `cat .ruby-version`");
    this.log("gem install bundler");
    this.log("bundle install");
    this.log();
  },

  _installGems: function () {
    this.log('Installing bundler gem..');
    this.spawnCommandSync('gem', ['install', 'bundler']);
    this.log("Installing dependent gems with 'bundle install'..");
    this.spawnCommandSync('bundle', ['install']);
  },

  install: {

    bundle: function() {
      if (this.detectFeature('rvm')) {
        this._showRvmInstructions();
      } else {
        this._installGems();
      }
    },

    gitInit: function() {
      if (this.detectFeature('git')) {
        var fs = require('fs');
        fs.exists('.git', function (exists) {
          if (!exists) {
            this._promptUserWithGitInit()
          } else {
            this._sayGoodbye();
          }
        }.bind(this));
      } else {
        this._sayGoodbye();
      }
    }
  },

  _sayGoodbye: function() {
    this.log(yosay("That's it. " + chalk.green("Happy hacking!")));
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:minHeight="70dp"
    android:layout_height="70dp">

    <RelativeLayout
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/place_guess"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Place Name"
            android:maxLines="1"
            android:textSize="18sp"
            android:textColor="#000000"
            android:ellipsize="end"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            />

        <com.google.android.flexbox.FlexboxLayout
            android:id="@+id/coordinates"
            android:layout_below="@id/place_guess"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:flexWrap="wrap"
            app:alignItems="stretch"
            app:alignContent="stretch"
            >
            <TextView
                android:id="@+id/latitude"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="12.34567890123"
                android:textSize="12sp"
                android:textColor="#929292"
                android:layout_marginRight="4dp"
                android:layout_marginEnd="4dp"
                android:maxWidth="80dp"
                android:ellipsize="end"
                android:lines="1"
                />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text=", "
                android:textSize="12sp"
                android:textColor="#929292"
                android:layout_marginRight="4dp"
                android:layout_marginEnd="4dp"
                />
            <TextView
                android:id="@+id/longitude"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:textSize="12sp"
                android:textColor="#929292"
                android:layout_marginRight="4dp"
                android:layout_marginEnd="4dp"
                android:text="12.34567890123"
                android:maxWidth="80dp"
                android:ellipsize="end"
                android:lines="1"
                />
            <TextView
                android:id="@+id/accuracy_prefix"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="@string/coordinates_acc"
                android:textSize="12sp"
                android:textColor="#929292"
                android:layout_marginRight="2dp"
                android:layout_marginEnd="2dp"
                />
            <TextView
                android:id="@+id/accuracy"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:textSize="12sp"
                android:textColor="#929292"
                android:text="34567890123"
                android:maxWidth="80dp"
                android:ellipsize="end"
                android:lines="1"
                />
        </com.google.android.flexbox.FlexboxLayout>

        <TextView
            android:id="@+id/geoprivacy"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/geoprivacy_with_value"
            android:layout_below="@id/coordinates"
            android:textSize="12sp"
            android:textColor="#929292"
            android:layout_marginRight="2dp"
            android:layout_marginEnd="2dp"
            />
    </RelativeLayout>
</RelativeLayout>


text:
namespace web_app {

WebAppOriginAssociationManager::WebAppOriginAssociationManager()
    : fetcher_(std::make_unique<webapps::WebAppOriginAssociationFetcher>()) {}

WebAppOriginAssociationManager::~WebAppOriginAssociationManager() = default;

void WebAppOriginAssociationManager::GetWebAppOriginAssociations(
    const GURL& manifest_url,
    apps::UrlHandlers url_handlers,
    OnDidGetWebAppOriginAssociations callback) {
  if (url_handlers.empty()) {
    std::move(callback).Run(apps::UrlHandlers());
    return;
  }

  auto task = std::make_unique<Task>(manifest_url, std::move(url_handlers),
                                     *this, std::move(callback));
  pending_tasks_.push_back(std::move(task));
  MaybeStartNextTask();
}

void WebAppOriginAssociationManager::MaybeStartNextTask() {
  if (task_in_progress_ || pending_tasks_.empty())
    return;

  task_in_progress_ = true;
  pending_tasks_.front().get()->Start();
}

void WebAppOriginAssociationManager::OnTaskCompleted() {
  DCHECK(!pending_tasks_.empty());
  task_in_progress_ = false;
  pending_tasks_.pop_front();
  MaybeStartNextTask();
}

void WebAppOriginAssociationManager::SetFetcherForTest(
    std::unique_ptr<webapps::WebAppOriginAssociationFetcher> fetcher) {
  fetcher_ = std::move(fetcher);
}

const mojo::Remote<webapps::mojom::WebAppOriginAssociationParser>&
WebAppOriginAssociationManager::GetParser() {
  if (!parser_ || !parser_.is_bound()) {
    parser_ = webapps::LaunchWebAppOriginAssociationParser();
    parser_.reset_on_disconnect();
  }

  return parser_;
}

webapps::WebAppOriginAssociationFetcher&
WebAppOriginAssociationManager::GetFetcher() {
  return *fetcher_;
}

}  // namespace web_app


text:
import sys
import os
import argparse

user = password = lunch_msg = idle_msg = ""
cmd = []

parser = argparse.ArgumentParser()
parser.add_argument('-u', help='Harvest username')
parser.add_argument('-p', help='Harvest password')
parser.add_argument('-l', help='Lunch message')
parser.add_argument('-i', help='Idle message')

args = parser.parse_args()

if args.l == None:
	args.l = ""
if args.i == None:
	args.i = ""

if args.u != None and args.p != None:
	cmd.append("./get_harvest_tasks.py -u " + args.u + " -p " + args.p)
	cmd.append("./get_task_notes.py -l '" + args.l + "' -i '" + args.i + "'")
	cmd.append("./set_skype_mood.py")

	os.system(" | ".join(cmd))


text:
package org.accelio.jxio.tests.benchmarks.jxioConnection;

import java.net.URI;
import java.net.URISyntaxException;

import org.accelio.jxio.jxioConnection.JxioConnectionServer;
import org.accelio.jxio.tests.benchmarks.jxioConnection.UserServerCallbacks;

public class StreamServer {

	public static void main(String[] args) {

		try {
			String uriString = String.format("rdma://%s:%s", args[0], args[1]);
			URI uri = null;
			try {
				uri = new URI(uriString);
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}

			JxioConnectionServer conServer = new JxioConnectionServer(uri, Integer.parseInt(args[2]),
			        new UserServerCallbacks());
			conServer.start();
		} catch (Throwable t) {
			t.printStackTrace();
			t.getCause().printStackTrace();
		}
	}
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import datetime
from dateutil import tz as tzutil
import json
import logging
import os
import re
import time
import uuid
from collections import OrderedDict

from botocore.exceptions import ClientError
import boto3
from .common import BaseTest, event_data, TestConfig as Config

from c7n.exceptions import PolicyValidationError
from c7n.executor import MainThreadExecutor
from c7n.resources import rds
from c7n import tags

logger = logging.getLogger(name="c7n.tests")

class RDSTest(BaseTest):

    def test_rds_config_event(self):
        event = event_data("rds-from-rule.json", "config")
        p = self.load_policy({"name": "rds", "resource": "rds"})
        source = p.resource_manager.get_source("config")
        resource_config = json.loads(event["invokingEvent"])["configurationItem"]
        resource = source.load_resource(resource_config)
        self.assertEqual(
            resource["Tags"], [{u"Key": u"workload-type", u"Value": u"other"}]
        )

    def test_rds_stop(self):
        session_factory = self.replay_flight_data("test_rds_stop")
        db_instance_id = "rds-test-instance-1"
        client = session_factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-stop",
                "resource": "rds",
                "filters": [{"DBInstanceIdentifier": db_instance_id}],
                "actions": ["stop"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceStatus"], "available")
        result = client.describe_db_instances(DBInstanceIdentifier=db_instance_id)
        self.assertEqual(result["DBInstances"][0]["DBInstanceStatus"], "stopping")

    def test_rds_start(self):
        session_factory = self.replay_flight_data("test_rds_start")
        db_instance_id = "rds-test-instance-2"
        client = session_factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-start",
                "resource": "rds",
                "filters": [{"DBInstanceIdentifier": db_instance_id}],
                "actions": ["start"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceStatus"], "stopped")
        result = client.describe_db_instances(DBInstanceIdentifier=db_instance_id)
        self.assertEqual(result["DBInstances"][0]["DBInstanceStatus"], "starting")

    def test_rds_autopatch(self):
        session_factory = self.replay_flight_data("test_rds_auto_patch")
        p = self.load_policy(
            {
                "name": "rds-tags",
                "resource": "rds",
                "filters": [{"AutoMinorVersionUpgrade": False}],
                "actions": ["auto-patch"],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_autopatch_with_window(self):
        window = "mon:23:00-tue:01:00"

        session_factory = self.replay_flight_data("test_rds_auto_patch_with_window")
        p = self.load_policy(
            {
                "name": "rds-tags",
                "resource": "rds",
                "filters": [{"AutoMinorVersionUpgrade": False}],
                "actions": [{"type": "auto-patch", "minor": True, "window": window}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        rds = session_factory().client("rds")
        details = rds.describe_db_instances(
            DBInstanceIdentifier=resources[0]["DBInstanceIdentifier"]
        )
        details = details["DBInstances"][0]

        self.assertTrue(details["AutoMinorVersionUpgrade"])
        self.assertEqual(details["PreferredMaintenanceWindow"], window)

    def test_rds_tags(self):
        session_factory = self.replay_flight_data("test_rds_tags")
        p = self.load_policy(
            {
                "name": "rds-tags",
                "resource": "rds",
                "filters": [{"tag:Platform": "postgres"}],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_tag_trim(self):
        self.patch(tags.TagTrim, "max_tag_count", 1)
        session_factory = self.replay_flight_data("test_rds_tag_trim")
        p = self.load_policy(
            {
                "name": "rds-tags",
                "resource": "rds",
                "filters": [{"tag:Platform": "postgres"}],
                "actions": [{"type": "tag-trim", "preserve": ["Name", "Owner"]}],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_tag_and_remove(self):
        self.patch(rds.RDS, "executor_factory", MainThreadExecutor)
        session_factory = self.replay_flight_data("test_rds_tag_and_remove")
        client = session_factory().client("rds")

        p = self.load_policy(
            {
                "name": "rds-tag",
                "resource": "rds",
                "filters": [{"tag:Platform": "postgres"}],
                "actions": [{"type": "tag", "key": "xyz", "value": "hello world"}],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        arn = p.resource_manager.generate_arn(resources[0]["DBInstanceIdentifier"])

        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertTrue("xyz" in tag_map)

        policy = self.load_policy(
            {
                "name": "rds-remove-tag",
                "resource": "rds",
                "filters": [{"tag:xyz": "not-null"}],
                "actions": [{"type": "remove-tag", "tags": ["xyz"]}],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 1)

        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertFalse("xyz" in tag_map)

    def test_rds_mark_and_match(self):
        session_factory = self.replay_flight_data("test_rds_mark_and_match")
        p = self.load_policy(
            {
                "name": "rds-mark",
                "resource": "rds",
                "filters": [{"tag:Platform": "postgres"}],
                "actions": [
                    {
                        "type": "mark-for-op",
                        "tag": "custodian_next",
                        "days": 1,
                        "op": "delete",
                    }
                ],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        policy = self.load_policy(
            {
                "name": "rds-mark-filter",
                "resource": "rds",
                "filters": [
                    {
                        "type": "marked-for-op",
                        "tag": "custodian_next",
                        "op": "delete",
                        "skew": 1,
                    }
                ],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 1)

    def test_rds_mark_hours(self):
        localtz = tzutil.gettz("Etc/UTC")
        dt = datetime.datetime.now(localtz)
        dt = dt.replace(
            year=2018, month=5, day=9, hour=21, minute=20, second=0, microsecond=0
        )
        session_factory = self.replay_flight_data("test_rds_mark_hours")
        session = session_factory(region="us-east-1")
        rds = session.client("rds")

        policy = self.load_policy(
            {
                "name": "rds-mark-5-hours",
                "resource": "rds",
                "filters": [{"tag:CreatorName": "absent"}],
                "actions": [{"type": "mark-for-op", "hours": 5, "op": "delete"}],
            },
            config={"account_id": "123456789012"},
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 1)

        resource = rds.list_tags_for_resource(
            ResourceName=resources[0]["DBInstanceArn"]
        )
        tags = [t["Value"] for t in resource["TagList"] if t["Key"] == "maid_status"]
        result = datetime.datetime.strptime(
            tags[0].strip().split("@", 1)[-1], "%Y/%m/%d %H%M %Z"
        ).replace(
            tzinfo=localtz
        )
        self.assertEqual(result, dt)

    def test_rds_marked_hours(self):
        session_factory = self.replay_flight_data("test_rds_marked_hours")
        policy = self.load_policy(
            {
                "name": "rds-marked-for-op-hours",
                "resource": "rds",
                "filters": [{"type": "marked-for-op", "op": "delete"}],
            },
            config={"account_id": "123456789012"},
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceIdentifier"], "db1")

    def test_rds_default_vpc(self):
        session_factory = self.replay_flight_data("test_rds_default_vpc")
        p = self.load_policy(
            {
                "name": "rds-default-filters",
                "resource": "rds",
                "filters": [{"type": "default-vpc"}],
            },
            config={"region": "us-west-2"},
            session_factory=session_factory,
        )

        resources = p.run()
        self.assertEqual(len(resources), 2)

    def test_rds_kms_alias(self):
        session_factory = self.replay_flight_data("test_rds_kms_alias")
        p = self.load_policy(
            {
                "name": "rds-aws-managed-kms-keys-filters",
                "resource": "rds",
                "filters": [
                    {
                        "type": "kms-alias",
                        "key": "AliasName",
                        "value": "^(alias/aws/)",
                        "op": "regex",
                    }
                ],
            },
            config={"region": "us-west-2"},
            session_factory=session_factory,
        )

        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_snapshot(self):
        session_factory = self.replay_flight_data("test_rds_snapshot")
        dt = datetime.datetime.now().replace(
            year=2017, month=12, day=11, hour=14, minute=9
        )
        suffix = dt.strftime("%Y-%m-%d-%H-%M")
        p = self.load_policy(
            {
                "name": "rds-snapshot",
                "resource": "rds",
                "filters": [{"DBInstanceIdentifier": "c7n-snapshot-test"}],
                "actions": [{"type": "snapshot"}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        client = session_factory(region="us-east-1").client("rds")
        snapshot = client.describe_db_snapshots(
            DBInstanceIdentifier=resources[0]["DBInstanceIdentifier"]
        )[
            "DBSnapshots"
        ][
            0
        ]
        self.assertEqual(
            snapshot["DBSnapshotIdentifier"],
            "backup-%s-%s" % (resources[0]["DBInstanceIdentifier"], suffix),
        )

    def test_rds_retention(self):
        session_factory = self.replay_flight_data("test_rds_retention")
        p = self.load_policy(
            {
                "name": "rds-snapshot",
                "resource": "rds",
                "actions": [{"type": "retention", "days": 21}],
            },
            config={"region": "us-west-2"},
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 5)

    def test_rds_retention_copy_tags(self):
        session_factory = self.replay_flight_data("test_rds_retention")
        p = self.load_policy(
            {
                "name": "rds-snapshot",
                "resource": "rds",
                "actions": [{"type": "retention", "days": 21, "copy-tags": True}],
            },
            config={"region": "us-west-2"},
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 5)

    def test_rds_restore(self):
        self.patch(rds.RestoreInstance, "executor_factory", MainThreadExecutor)
        self.change_environment(AWS_DEFAULT_REGION="us-east-2")
        session_factory = self.replay_flight_data("test_rds_restore")
        client = session_factory().client("rds")
        instance_id = "mxtest"
        self.assertRaises(
            ClientError, client.describe_db_instances, DBInstanceIdentifier=instance_id
        )

        p = self.load_policy(
            {
                "name": "rds-restore",
                "resource": "rds-snapshot",
                "filters": [{"MasterUsername": "mxtester"}, "latest"],
                "actions": [
                    {
                        "type": "restore",
                        "restore_options": {"DBInstanceIdentifier": instance_id},
                    }
                ],
            },
            Config.empty(region="us-east-2"),
            session_factory=session_factory,
        )
        resources = p.run()

        self.assertEqual(len(resources), 1)
        try:
            client.describe_db_instances(DBInstanceIdentifier=instance_id)
        except ClientError:
            self.fail("DB Not found")

    def test_rds_delete_copy(self):
        session_factory = self.replay_flight_data("test_rds_delete_copy_restore")
        client = session_factory().client("rds")
        instance_id = "mxtest"
        db_info = client.describe_db_instances(DBInstanceIdentifier=instance_id)
        self.assertFalse(db_info["DBInstances"][0]["CopyTagsToSnapshot"])
        p = self.load_policy(
            {
                "name": "rds-delete",
                "resource": "rds",
                "filters": [{"DBInstanceIdentifier": instance_id}],
                "actions": [{"type": "delete", "copy-restore-info": True}],
            },
            config=Config.empty(region="us-east-2"),
            session_factory=session_factory,
        )
        p.run()
        db_info = client.describe_db_instances(DBInstanceIdentifier=instance_id)
        self.assertTrue(db_info["DBInstances"][0]["CopyTagsToSnapshot"])
        snaps = p.resource_manager.get_resource_manager("rds-snapshot").get_resources(
            ("final-mxtest-2017-05-25",)
        )
        snap_keys = {t["Key"] for t in snaps[0]["Tags"]}
        self.assertTrue(snap_keys.issuperset(rds.RestoreInstance.restore_keys))

    def test_rds_delete(self):
        session_factory = self.replay_flight_data("test_rds_delete")
        p = self.load_policy(
            {
                "name": "rds-delete",
                "resource": "rds",
                "filters": [{"tag:Owner": "test"}],
                "actions": [{"type": "delete", "skip-snapshot": True}],
            },
            config=Config.empty(region="us-west-2"),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_available_engine_upgrades(self):
        session_factory = self.replay_flight_data(
            "test_rds_available_engine_upgrades", zdata=True
        )
        client = session_factory().client("rds")
        upgrades = rds._get_available_engine_upgrades(client)
        self.assertEqual(upgrades["postgres"]["9.3.1"], "9.3.14")
        self.assertEqual(
            upgrades["sqlserver-ex"]["10.50.6000.34.v1"], "10.50.6529.0.v1"
        )
        upgrades = rds._get_available_engine_upgrades(client, major=True)
        self.assertEqual(upgrades["postgres"]["9.3.1"], "9.4.9")
        self.assertEqual(upgrades["postgres"]["9.4.9"], "9.5.4")
        self.assertEqual(upgrades["sqlserver-ex"]["10.50.2789.0.v1"], "12.00.5000.0.v1")

    def test_rds_upgrade_available(self):
        session_factory = self.replay_flight_data("test_rds_minor_upgrade_available")
        p = self.load_policy(
            {
                "name": "rds-upgrade-available",
                "resource": "rds",
                "filters": [{"type": "upgrade-available", "major": True}],
                "actions": []
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            {r["EngineVersion"]: r.get("c7n-rds-engine-upgrade") for r in resources},
            {u"5.6.27": u"5.7.11"},
        )

    def test_rds_minor_upgrade_unavailable(self):
        session_factory = self.replay_flight_data("test_rds_minor_upgrade_unavailable")
        p = self.load_policy(
            {
                "name": "rds-upgrade-done",
                "resource": "rds",
                "filters": [{"type": "upgrade-available", "value": False}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 3)
        self.assertEqual(
            {r["EngineVersion"]: r.get("c7n-rds-engine-upgrade") for r in resources},
            {u"5.5.41": u"5.5.46", u"5.6.29": None, u"5.7.11": None},
        )

    def test_rds_minor_upgrade_do(self):
        session_factory = self.replay_flight_data("test_rds_minor_upgrade_do")
        p = self.load_policy(
            {
                "name": "rds-upgrade-do",
                "resource": "rds",
                "filters": [
                    {
                        "type": "marked-for-op",
                        "tag": "custodian_upgrade",
                        "op": "upgrade",
                        "skew": 4,
                    }
                ],
                "actions": [{"type": "upgrade", "immediate": False}],
            },
            config=Config.empty(),
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            {r["EngineVersion"]: r.get("c7n-rds-engine-upgrade") for r in resources},
            {u"5.6.29": u"5.6.35"},
        )
        self.assertEqual(resources[0]["DBInstanceIdentifier"], "c7n-mysql-test-03")
        self.assertEqual(resources[0]["EngineVersion"], "5.6.29")
        self.assertEqual(resources[0]["c7n-rds-engine-upgrade"], "5.6.35")

    def test_rds_eligible_start_stop(self):
        resource = {"DBInstanceIdentifier": "ABC",
                    "DBInstanceStatus": "available",
                    "Engine": "mysql"}
        self.assertTrue(rds._eligible_start_stop(resource, "available"))

        resource = {"DBInstanceIdentifier": "ABC",
                    "DBInstanceStatus": "stopped",
                    "Engine": "mysql"}
        self.assertFalse(rds._eligible_start_stop(resource, "available"))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "postgres",
            "MultiAZ": True,
        }
        self.assertTrue(rds._eligible_start_stop(resource))
        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "sqlserver-ee",
            "MultiAZ": True,
        }
        self.assertFalse(rds._eligible_start_stop(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "docdb"
        }
        self.assertFalse(rds._eligible_start_stop(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "postgres",
            "ReadReplicaDBInstanceIdentifiers": ["sbbdevslave"],
        }
        self.assertFalse(rds._eligible_start_stop(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "mysql",
            "ReadReplicaSourceDBInstanceIdentifier": "sbbdev",
        }
        self.assertFalse(rds._eligible_start_stop(resource))

    def test_rds_db_instance_eligible_for_backup(self):
        resource = {"DBInstanceIdentifier": "ABC"}
        self.assertFalse(rds._db_instance_eligible_for_backup(resource))

        resource = {"DBInstanceIdentifier": "ABC", "DBInstanceStatus": "funky"}
        self.assertFalse(rds._db_instance_eligible_for_backup(resource))

        resource = {"DBInstanceIdentifier": "ABC", "DBInstanceStatus": "available"}
        self.assertTrue(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "DBClusterIdentifier": "C1",
        }
        self.assertFalse(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "R1",
            "Engine": "postgres",
        }
        self.assertFalse(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "postgres",
        }
        self.assertTrue(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "Engine": "mysql",
            "EngineVersion": "5.5.1",
        }
        self.assertTrue(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "R1",
            "Engine": "mysql",
            "EngineVersion": "5.5.1",
        }
        self.assertFalse(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "R1",
            "Engine": "mysql",
            "EngineVersion": "5.7.1",
        }
        self.assertTrue(rds._db_instance_eligible_for_backup(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "R1",
            "Engine": "mysql",
            "EngineVersion": "6.1.1",
        }
        self.assertTrue(rds._db_instance_eligible_for_backup(resource))

    def test_rds_db_instance_eligible_for_final_snapshot(self):
        resource = {"DBInstanceIdentifier": "ABC"}
        self.assertTrue(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {"DBInstanceIdentifier": "ABC", "DBInstanceStatus": "available"}
        self.assertTrue(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {"DBInstanceIdentifier": "ABC", "DBInstanceStatus": "creating"}
        self.assertFalse(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {"DBInstanceIdentifier": "ABC", "DBInstanceStatus": "failed"}
        self.assertFalse(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {
            "DBInstanceIdentifier": "ABC", "DBInstanceStatus": "incompatible-restore"
        }
        self.assertFalse(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {
            "DBInstanceIdentifier": "ABC", "DBInstanceStatus": "incompatible-network"
        }
        self.assertFalse(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "R1",
            "Engine": "mysql",
            "EngineVersion": "5.7.1",
        }
        self.assertFalse(rds._db_instance_eligible_for_final_snapshot(resource))

        resource = {
            "DBInstanceIdentifier": "ABC",
            "DBInstanceStatus": "available",
            "ReadReplicaSourceDBInstanceIdentifier": "",
            "Engine": "mysql",
            "EngineVersion": "5.7.1",
        }
        self.assertTrue(rds._db_instance_eligible_for_final_snapshot(resource))

    def test_rds_db_subnetgroup_delete(self):
        session_factory = self.replay_flight_data("test_rdssubnetgroup_delete")

        policy = self.load_policy(
            {
                "name": "db-subnet-group-delete",
                "resource": "rds-subnet-group",
                "actions": [{"type": "delete"}],
            },
            session_factory=session_factory,
        )

        resources = policy.run()

        self.assertGreater(len(resources), 0, "Test should delete db subnetgroup")

    def test_rds_db_subnetgroup_unused(self):
        session_factory = self.replay_flight_data("test_rdssubnetgroup_unused")

        policy = self.load_policy(
            {
                "name": "db-subnet-group-unused",
                "resource": "rds-subnet-group",
                "filters": [{"type": "unused"}],
            },
            session_factory=session_factory,
        )

        resources = policy.run()

        self.assertEqual(len(resources), 1, "Resources should be unused")

    def test_rds_modify_db(self):
        session_factory = self.replay_flight_data("test_rds_modify_db")
        p = self.load_policy(
            {
                "name": "rds-modify-db",
                "resource": "rds",
                "filters": [
                    {"DeletionProtection": True},
                    {"MasterUsername": "testtest"}
                ],
                "actions": [
                    {
                        "type": "modify-db",
                        "update": [
                            {
                                "property": 'DeletionProtection',
                                "value": False
                            }
                        ],
                        "immediate": True
                    }
                ],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        client = session_factory().client("rds")
        db_info = client.describe_db_instances(DBInstanceIdentifier="testtest")
        self.assertFalse(db_info["DBInstances"][0]["DeletionProtection"])

class RDSSnapshotTest(BaseTest):

    def test_rds_snapshot_copy_tags_enable(self):
        session_factory = self.replay_flight_data("test_rds_snapshot_copy_tags_enable")
        client = session_factory(region="us-east-1").client("rds")
        self.assertFalse(
            client.describe_db_instances(DBInstanceIdentifier="mydbinstance")[
                "DBInstances"
            ][
                0
            ][
                "CopyTagsToSnapshot"
            ]
        )

        p = self.load_policy(
            {
                "name": "rds-enable-snapshot-tag-copy",
                "resource": "rds",
                "filters": [
                    {"type": "value", "key": "Engine", "value": "mysql", "op": "eq"}
                ],
                "actions": [{"type": "set-snapshot-copy-tags", "enable": True}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertTrue(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceIdentifier"], "mydbinstance")

        self.assertTrue(
            client.describe_db_instances(DBInstanceIdentifier="mydbinstance")[
                "DBInstances"
            ][
                0
            ][
                "CopyTagsToSnapshot"
            ]
        )

    def test_rds_snapshot_copy_tags_disable(self):
        session_factory = self.replay_flight_data("test_rds_snapshot_copy_tags_disable")
        client = session_factory(region="us-east-1").client("rds")
        self.assertTrue(
            client.describe_db_instances(DBInstanceIdentifier="mydbinstance")[
                "DBInstances"
            ][
                0
            ][
                "CopyTagsToSnapshot"
            ]
        )

        p = self.load_policy(
            {
                "name": "rds-enable-snapshot-tag-copy",
                "resource": "rds",
                "filters": [
                    {"type": "value", "key": "Engine", "value": "mysql", "op": "eq"}
                ],
                "actions": [{"type": "set-snapshot-copy-tags", "enable": False}],
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertTrue(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceIdentifier"], "mydbinstance")

        self.assertFalse(
            client.describe_db_instances(DBInstanceIdentifier="mydbinstance")[
                "DBInstances"
            ][
                0
            ][
                "CopyTagsToSnapshot"
            ]
        )

    def test_rds_snapshot_access(self):
        factory = self.replay_flight_data("test_rds_snapshot_access")
        p = self.load_policy(
            {
                "name": "rds-snap-access",
                "resource": "rds-snapshot",
                "filters": ["cross-account"],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 2)
        self.assertEqual(
            {
                r["DBSnapshotIdentifier"]: r["c7n:CrossAccountViolations"]
                for r in resources
            },
            {"tidx-pub": ["all"], "tidx-rdx": ["619193117841"]},
        )

    def test_rds_latest_manual(self):
        # preconditions
        # one db with manual and automatic snapshots
        factory = self.replay_flight_data("test_rds_snapshot_latest")
        p = self.load_policy(
            {
                "name": "rds-latest-snaps",
                "resource": "rds-snapshot",
                "filters": [{"type": "latest", "automatic": False}],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["DBSnapshotIdentifier"], "originb")

    def test_rds_latest(self):
        # preconditions
        # one db with manual and automatic snapshots
        factory = self.replay_flight_data("test_rds_snapshot_latest")
        p = self.load_policy(
            {
                "name": "rds-latest-snaps",
                "resource": "rds-snapshot",
                "filters": ["latest"],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            resources[0]["DBSnapshotIdentifier"], "rds:originb-2016-12-28-09-15"
        )

    def test_rds_cross_region_copy_lambda(self):
        self.assertRaises(
            PolicyValidationError,
            self.load_policy,
            {
                "name": "rds-copy-fail",
                "resource": "rds-snapshot",
                "mode": {"type": "config-rule"},
                "actions": [{"type": "region-copy", "target_region": "us-east-2"}],
            },
        )

    def test_rds_cross_region_copy_skip_same_region(self):
        self.change_environment(AWS_DEFAULT_REGION="us-east-2")
        factory = self.replay_flight_data("test_rds_snapshot_latest")
        output = self.capture_logging("custodian.actions")
        p = self.load_policy(
            {
                "name": "rds-copy-skip",
                "resource": "rds-snapshot",
                "actions": [{"type": "region-copy", "target_region": "us-east-2"}],
            },
            Config.empty(region="us-east-2"),
            session_factory=factory,
        )
        resources = p.run()
        self.assertFalse([r for r in resources if "c7n:CopiedSnapshot" in r])
        self.assertIn("Source and destination region are the same", output.getvalue())

    def test_rds_cross_region_copy_many(self):
        # preconditions
        # rds snapshot, encrypted in region with kms, and tags
        # in this scenario we have 9 snapshots in source region,
        # 3 snaps already in target region, 6 to copy, which means
        # we will hit transfer limits.
        factory = self.replay_flight_data("test_rds_snapshot_region_copy_many")

        # no sleep till, beastie boys ;-)
        def brooklyn(delay):
            return

        output = self.capture_logging("c7n.worker", level=logging.DEBUG)
        self.patch(time, "sleep", brooklyn)
        self.change_environment(AWS_DEFAULT_REGION="us-east-1")
        p = self.load_policy(
            {
                "name": "rds-snapshot-region-copy",
                "resource": "rds-snapshot",
                "filters": [{"DBInstanceIdentifier": "originb"}],
                "actions": [
                    {
                        "type": "region-copy",
                        "target_region": "us-east-2",
                        "tags": {"migrated_from": "us-east-1"},
                        "target_key": "cb291f53-f3ab-4e64-843e-47b0a7c9cf61",
                    }
                ],
            },
            Config.empty(region="us-east-1"),
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 9)
        self.assertEqual(6, len([r for r in resources if "c7n:CopiedSnapshot" in r]))
        self.assertEqual(output.getvalue().count("retrying"), 2)

    def test_rds_cross_region_copy(self):
        # preconditions
        # rds snapshot, encrypted in region with kms, and tags
        factory = self.replay_flight_data("test_rds_snapshot_region_copy")
        client = factory().client("rds", region_name="us-east-2")
        self.change_environment(AWS_DEFAULT_REGION="us-east-1")
        p = self.load_policy(
            {
                "name": "rds-snapshot-region-copy",
                "resource": "rds-snapshot",
                "filters": [{"DBSnapshotIdentifier": "rds:originb-2016-12-28-09-15"}],
                "actions": [
                    {
                        "type": "region-copy",
                        "target_region": "us-east-2",
                        "tags": {"migrated_from": "us-east-1"},
                        "target_key": "cb291f53-f3ab-4e64-843e-47b0a7c9cf61",
                    }
                ],
            },
            Config.empty(region="us-east-1"),
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

        snapshots = client.describe_db_snapshots(
            DBSnapshotIdentifier=resources[0]["c7n:CopiedSnapshot"].rsplit(":", 1)[1]
        )[
            "DBSnapshots"
        ]
        self.assertEqual(len(snapshots), 1)
        self.assertEqual(snapshots[0]["DBInstanceIdentifier"], "originb")
        tags = {
            t["Key"]: t["Value"]
            for t in client.list_tags_for_resource(
                ResourceName=resources[0]["c7n:CopiedSnapshot"]
            )[
                "TagList"
            ]
        }
        self.assertEqual(
            {
                "migrated_from": "us-east-1",
                "app": "mgmt-portal",
                "env": "staging",
                "workload-type": "other",
            },
            tags,
        )

    def test_rds_snapshot_tag_filter(self):
        factory = self.replay_flight_data("test_rds_snapshot_tag_filter")
        client = factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-snapshot-tag-filter",
                "resource": "rds-snapshot",
                "filters": [{"type": "marked-for-op", "op": "delete"}],
            },
            config=Config.empty(),
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        arn = p.resource_manager.generate_arn(resources[0]["DBSnapshotIdentifier"])
        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertTrue("maid_status" in tag_map)
        self.assertTrue("delete@" in tag_map["maid_status"])

    def test_rds_snapshot_age_filter(self):
        factory = self.replay_flight_data("test_rds_snapshot_age_filter")
        p = self.load_policy(
            {
                "name": "rds-snapshot-age-filter",
                "resource": "rds-snapshot",
                "filters": [{"type": "age", "days": 7}],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_snapshot_trim(self):
        factory = self.replay_flight_data("test_rds_snapshot_delete")
        p = self.load_policy(
            {
                "name": "rds-snapshot-trim",
                "resource": "rds-snapshot",
                "actions": ["delete"],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_rds_snapshot_tag(self):
        factory = self.replay_flight_data("test_rds_snapshot_mark")
        client = factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-snapshot-tag",
                "resource": "rds-snapshot",
                "actions": [{"type": "tag", "key": "test-key", "value": "test-value"}],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        arn = p.resource_manager.generate_arn(resources[0]["DBSnapshotIdentifier"])
        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertTrue("test-key" in tag_map)
        self.assertTrue("test-value" in tag_map["test-key"])

    def test_rds_snapshot_mark(self):
        factory = self.replay_flight_data("test_rds_snapshot_mark")
        client = factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-snapshot-mark",
                "resource": "rds-snapshot",
                "actions": [{"type": "mark-for-op", "op": "delete", "days": 1}],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        arn = p.resource_manager.generate_arn(resources[0]["DBSnapshotIdentifier"])
        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertTrue("maid_status" in tag_map)

    def test_rds_snapshot_unmark(self):
        factory = self.replay_flight_data("test_rds_snapshot_unmark")
        client = factory().client("rds")
        p = self.load_policy(
            {
                "name": "rds-snapshot-unmark",
                "resource": "rds-snapshot",
                "actions": [{"type": "unmark"}],
            },
            session_factory=factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        arn = p.resource_manager.generate_arn(resources[0]["DBSnapshotIdentifier"])
        tags = client.list_tags_for_resource(ResourceName=arn)
        tag_map = {t["Key"]: t["Value"] for t in tags["TagList"]}
        self.assertFalse("maid_status" in tag_map)

    def test_rds_public_accessible_disable(self):
        session_factory = self.replay_flight_data("test_rds_public_accessible_disable")
        client = session_factory(region="us-east-1").client("rds")
        policy = self.load_policy(
            {
                "name": "disable-publicly-accessibility",
                "resource": "rds",
                "filters": [
                    {"DBInstanceIdentifier": "c7n-test-pa"},
                    {"PubliclyAccessible": True},
                ],
                "actions": [{"type": "set-public-access", "state": False}],
            },
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["DBInstanceIdentifier"], "c7n-test-pa")
        self.assertFalse(
            client.describe_db_instances(DBInstanceIdentifier="c7n-test-pa")[
                "DBInstances"
            ][
                0
            ][
                "PubliclyAccessible"
            ]
        )

class TestModifyVpcSecurityGroupsAction(BaseTest):

    def test_rds_remove_matched_security_groups(self):
        #
        # Test conditions:
        #    - running 2 Aurora DB clusters in default VPC with 2 instances
        #      each.
        #        - translates to 4 actual instances
        #    - a default security group with id 'sg-7a3fcb13' exists
        #    - security group named PROD-ONLY-Test-Security-Group exists in
        #      VPC and is attached to one set of DB instances
        #        - translates to 2 instances marked non-compliant
        #
        # Results in 4 DB Instances with default Security Group attached

        session_factory = self.replay_flight_data(
            "test_rds_remove_matched_security_groups"
        )
        p = self.load_policy(
            {
                "name": "rds-remove-matched-security-groups",
                "resource": "rds",
                "filters": [
                    {
                        "type": "security-group",
                        "key": "GroupName",
                        "value": "(.*PROD-ONLY.*)",
                        "op": "regex",
                    }
                ],
                "actions": [
                    {
                        "type": "modify-security-groups",
                        "remove": "matched",
                        "isolation-group": "sg-7a3fcb13",
                    }
                ],
            },
            session_factory=session_factory,
        )
        clean_p = self.load_policy(
            {
                "name": "rds-verify-remove-matched-security-groups",
                "resource": "rds",
                "filters": [
                    {"type": "security-group", "key": "GroupName", "value": "default"}
                ],
            },
            session_factory=session_factory,
        )

        resources = p.run()
        clean_resources = clean_p.run()

        # clusters autoscale across AZs, so they get -001, -002, etc appended
        self.assertIn("test-sg-fail", resources[0]["DBInstanceIdentifier"])

        self.assertEqual(len(resources), 2)
        self.assertEqual(len(resources[0]["VpcSecurityGroups"]), 1)
        # show that it was indeed a replacement of security groups
        self.assertEqual(len(clean_resources[0]["VpcSecurityGroups"]), 1)
        self.assertEqual(len(clean_resources), 4)

    def test_rds_add_security_group(self):
        #
        # Test conditions:
        #   - running 2 Aurora DB clusters in default VPC with 2 instances each
        #        - translates to 4 actual instances
        #    - a default security group with id 'sg-7a3fcb13' exists -
        #      attached to all instances
        #    - security group named PROD-ONLY-Test-Security-Group exists in
        #      VPC and is attached to 2/4 instances
        #        - translates to 2 instances marked to get new group attached
        #
        # Results in 4 instances with default Security Group and
        # PROD-ONLY-Test-Security-Group
        session_factory = self.replay_flight_data("test_rds_add_security_group")
        p = self.load_policy(
            {
                "name": "add-sg-to-prod-rds",
                "resource": "rds",
                "filters": [
                    {"type": "security-group", "key": "GroupName", "value": "default"},
                    {
                        "type": "value",
                        "key": "DBInstanceIdentifier",
                        "value": "test-sg-fail.*",
                        "op": "regex",
                    },
                ],
                "actions": [{"type": "modify-security-groups", "add": "sg-6360920a"}],
            },
            session_factory=session_factory,
        )

        clean_p = self.load_policy(
            {
                "name": "validate-add-sg-to-prod-rds",
                "resource": "rds",
                "filters": [
                    {"type": "security-group", "key": "GroupName", "value": "default"},
                    {
                        "type": "security-group",
                        "key": "GroupName",
                        "value": "PROD-ONLY-Test-Security-Group",
                    },
                ],
            },
            session_factory=session_factory,
        )

        resources = p.run()
        clean_resources = clean_p.run()

        self.assertEqual(len(resources), 2)
        self.assertIn("test-sg-fail", resources[0]["DBInstanceIdentifier"])
        self.assertEqual(len(resources[0]["VpcSecurityGroups"]), 1)
        self.assertEqual(len(clean_resources[0]["VpcSecurityGroups"]), 2)
        self.assertEqual(len(clean_resources), 4)

class TestHealthEventsFilter(BaseTest):

    def test_rds_health_events_filter(self):
        session_factory = self.replay_flight_data("test_rds_health_events_filter")
        policy = self.load_policy(
            {
                "name": "rds-health-events-filter",
                "resource": "rds",
                "filters": [{"type": "health-event"}],
            },
            session_factory=session_factory,
        )
        resources = policy.run()
        self.assertEqual(len(resources), 0)

class TestRDSParameterGroupFilter(BaseTest):

    PARAMGROUP_PARAMETER_FILTER_TEST_CASES = [
        # filter_struct, test_func, err_message
        (
            {"key": "log_destination", "op": "eq", "value": "stderr"},
            lambda r: len(r) == 1,
            "instances with log_destination == stderr should be 1",
        ),
        (
            {"key": "log_destination", "op": "eq", "value": "s3"},
            lambda r: len(r) == 0,
            "instances with log_destination == s3 should be 0",
        ),
        (
            {"key": "log_destination", "op": "ne", "value": "stderr"},
            lambda r: len(r) == 0,
            "instances with log_destination != stderr should be 0",
        ),
        (
            {"key": "log_destination", "op": "ne", "value": "s3"},
            lambda r: len(r) == 1,
            "instances with log_destination != s3 should be 1",
        ),
        (
            {"key": "full_page_writes", "op": "eq", "value": True},
            lambda r: len(r) == 1,
            "full_page_writes ( a boolean ) should be on",
        ),
    ]

    def test_param_value_cases(self):
        session_factory = self.replay_flight_data("test_rds_param_filter")
        policy = self.load_policy(
            {"name": "rds-pg-filter", "resource": "rds"},
            session_factory=session_factory,
        )
        resources = policy.resource_manager.resources()

        for testcase in self.PARAMGROUP_PARAMETER_FILTER_TEST_CASES:
            fdata, assertion, err_msg = testcase
            f = policy.resource_manager.filter_registry.get("db-parameter")(
                fdata, policy.resource_manager
            )
            f_resources = f.process(resources)
            if not assertion(f_resources):
                print(len(f_resources), fdata, assertion)
                self.fail(err_msg)

class Resize(BaseTest):

    def get_waiting_client(self, session_factory, session, name):
        if session_factory.__name__ == "<lambda>":  # replaying
            return None
        else:  # recording
            return boto3.Session(region_name=session.region_name).client(name)

    def get_dbid(self, recording, flight_data):
        if recording:
            return "test-" + str(uuid.uuid4())
        else:
            pill_path = os.path.join(
                os.path.dirname(__file__),
                "data",
                "placebo",
                flight_data,
                "rds.CreateDBInstance_1.json",
            )
            pill = json.load(open(pill_path))
            return pill["data"]["DBInstance"]["DBInstanceIdentifier"]

    def install_modification_pending_waiter(self, waiters):
        if "DBInstanceModificationPending" in waiters:
            return
        pattern = waiters["DBInstanceAvailable"]
        acceptors = [OrderedDict(eg) for eg in pattern["acceptors"][1:]]
        acceptors.insert(
            0,
            OrderedDict(
                expected=True,
                matcher="path",
                state="success",
                argument="!!length(DBInstances[].PendingModifiedValues)",
            ),
        )
        waiter = OrderedDict(pattern)
        waiter["acceptors"] = acceptors
        waiters["DBInstanceModificationPending"] = waiter

    def install_modifying_waiter(self, waiters):
        if "DBInstanceModifying" in waiters:
            return
        pattern = waiters["DBInstanceAvailable"]
        acceptors = [OrderedDict(eg) for eg in pattern["acceptors"]]
        acceptors[0]["expected"] = "modifying"
        waiter = OrderedDict(pattern)
        waiter["acceptors"] = acceptors
        waiters["DBInstanceModifying"] = waiter

    def install_waiters(self, client):
        # Not provided by boto otb.
        client._get_waiter_config()  # primes cache if needed
        waiters = client._cache["waiter_config"]["waiters"]
        self.install_modification_pending_waiter(waiters)
        self.install_modifying_waiter(waiters)

    def wait_until(self, client, dbid, status):
        if client is None:
            return  # We're in replay mode. Don't bother waiting.
        self.install_waiters(client)
        waiter = client.get_waiter("db_instance_" + status)
        waiter.wait(Filters=[{"Name": "db-instance-id", "Values": [dbid]}])

    def create_instance(self, client, dbid, gb=5):
        client.create_db_instance(
            Engine="mariadb",
            DBInstanceIdentifier=dbid,
            DBInstanceClass="db.r3.large",
            MasterUsername="eric",
            MasterUserPassword="cheese42",
            StorageType="gp2",
            AllocatedStorage=gb,
            BackupRetentionPeriod=0,
        )  # disable automatic backups

        def delete():
            client.delete_db_instance(DBInstanceIdentifier=dbid, SkipFinalSnapshot=True)

        self.addCleanup(delete)
        return dbid

    @staticmethod
    def get_window_now():
        start = datetime.datetime.utcnow()
        end = start + datetime.timedelta(seconds=60 * 60)  # hour long
        fmt = "%a:%H:%M"
        return "{}-{}".format(start.strftime(fmt), end.strftime(fmt))

    def test_can_get_a_window_now(self):
        assert re.match(r"[A-Za-z]{3}:\d\d:\d\d", self.get_window_now())

    def start(self, flight_data):
        session_factory = self.replay_flight_data(flight_data)
        session = session_factory(region="us-west-2")
        client = session.client("rds")
        waiting_client = self.get_waiting_client(session_factory, session, "rds")
        dbid = self.get_dbid(bool(waiting_client), flight_data)
        self.create_instance(client, dbid)

        wait_until = lambda state: self.wait_until(waiting_client, dbid, state) # NOQA
        wait_until("available")

        describe = lambda: client.describe_db_instances(DBInstanceIdentifier=dbid)[ # NOQA
            "DBInstances"
        ][
            0
        ]

        def resize(**kw):
            action = {"type": "resize", "percent": 10}
            action.update(kw)
            policy = self.load_policy(
                {
                    "name": "rds-resize-up",
                    "resource": "rds",
                    "filters": [
                        {"type": "value", "key": "DBInstanceIdentifier", "value": dbid}
                    ],
                    "actions": [action],
                },
                config={"region": "us-west-2"},
                session_factory=session_factory,
            )
            policy.run()

        return client, dbid, resize, wait_until, describe

    def test_can_resize_up_asynchronously(self):
        flight = "test_rds_resize_up_asynchronously"
        client, dbid, resize, wait_until, describe = self.start(flight)
        resize()
        wait_until("modification_pending")
        client.modify_db_instance(
            DBInstanceIdentifier=dbid, PreferredMaintenanceWindow=self.get_window_now()
        )
        wait_until("modifying")
        wait_until("available")
        self.assertEqual(describe()["AllocatedStorage"], 6)  # nearest gigabyte

    def test_can_resize_up_immediately(self):
        flight = "test_rds_resize_up_immediately"
        _, _, resize, wait_until, describe = self.start(flight)
        resize(immediate=True)
        wait_until("modifying")
        wait_until("available")
        self.assertEqual(describe()["AllocatedStorage"], 6)  # nearest gigabyte

class TestReservedRDSInstance(BaseTest):
    def test_reserved_rds_instance_query(self):
        session_factory = self.replay_flight_data("test_reserved_rds_instance_query")
        p = self.load_policy(
            {
                "name": "filter-rds-reserved-instances",
                "resource": "aws.rds-reserved"
            },
            session_factory=session_factory,
        )
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(resources[0]["ReservedDBInstanceId"], "ri-2019-05-06-14-19-06-332")


text:
{% load url from future %}

<form method="get" action="{% url 'article_history' %}">
  Find article by full URL: <input type="text" name="url" style="width: 40em"></input>
  <input type="submit" value="Go" style="margin-bottom: 9px" />
</form>


text:
package com.yahoo.dtf.actions.selenium.commands.mouse;

import com.yahoo.dtf.actions.selenium.commands.SeleniumLocatorAtTag;
import com.yahoo.dtf.exception.DTFException;

/**
 * @dtf.tag mouseMoveAt
 * @dtf.skip.index
 *
 * @dtf.since 1.0
 * @dtf.author Rodney Gomes
 *
 * @dtf.tag.desc <p>
 *               This command simulates a mouse move event at the location
 *               specified by the locator attribute using the
 *               {@dtf.link Element Locator} syntax. The location of the click
 *               can also be influenced by using the coordString to identify the
 *               specific position within the element identified by the locator.
 *               </p>
 *
 * @dtf.tag.example
 *  <selenium baseurl="http://www.google.com" browser="*firefox">
 *      <open url="/"/>
 *      <mouseMoveAt locator="//input[@value='q']" coordString="0,0"/>
 *  </selenium>
 */
public class Mousemoveat extends SeleniumLocatorAtTag {

    @Override
    public void execute() throws DTFException {
        getSelenium().mouseMoveAt(getLocator(), getCoordString());
    }
}


text:
SYNONYM

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

#### Published in
L. Choris, Voy. pittor. aut. monde 5, t. 5. 1822 (Flora 6:226. 1823)

#### Original name
null

### Remarks
null