text:
package org.javaz.copse.oauth;

import com.google.api.client.auth.oauth2.*;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.MemoryDataStoreFactory;
import org.javaz.copse.logic.iface.*;
import org.javaz.copse.logic.impl.AbstractHandler;
import org.javaz.copse.logic.impl.AnswerData;
import org.javaz.copse.model.iface.MenuItemI;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 */
public class OauthHandler extends AbstractHandler<OauthDescriptor> {
    @Override
    public AbstractHandler createNewInstance() {
        return new OauthHandler();
    }

    private static final Lock lock = new ReentrantLock();
    private static AuthorizationCodeFlow flow;
    private boolean replaceHttpWithHttps = false;

    @Override
    public void init(String config) {
        JacksonFactory instance = JacksonFactory.getDefaultInstance();
        try {
            JsonParser parser = instance.createJsonParser(config);
            Map configData = parser.parse(HashMap.class);
            OAUTH_CLIENT_ID = (String) configData.get("OAUTH_CLIENT_ID");
            OAUTH_SECRET = (String) configData.get("OAUTH_SECRET");
            if (configData.containsKey("successRedirect")) {
                successRedirect = (String) configData.get("successRedirect");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String OAUTH_CLIENT_ID = "";
    private String OAUTH_SECRET = "";
    // todo make it configurable
    private String phase1Marker = "os";
    private String phase2Marker = "oc";
    private String successRedirect = "/copse/";
    private String noSuchAccRedirect = "/copse/auth/nosuchacc.jsp";

    protected AuthorizationCodeFlow initializeFlow() throws IOException {
        return new GoogleAuthorizationCodeFlow.Builder(
                new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                OAUTH_CLIENT_ID, OAUTH_SECRET,
                Collections.singleton("email")).setDataStoreFactory(
                new MemoryDataStoreFactory()).setAccessType("offline").build();
    }

    protected String getRedirectUri(ParameterProviderI req, Integer menuId) throws IOException {
        String requestUrl = req.getRequestURL();
        if (replaceHttpWithHttps) {
            requestUrl = requestUrl.replace("http://", "https://");
        }
        GenericUrl url = new GenericUrl(requestUrl + "?m=" + menuId + "&a=" + phase2Marker);
        return url.build();
    }

    @Override
    public AnswerDataI handleRequest(String action, MenuItemI menuItem, UserProfileI profile,
                                     OauthDescriptor descriptor, ParameterProviderI provider) {
        AnswerData answerData = new AnswerData();
        if (profile == null) {
            lock.lock();
            try {
                if(flow == null) {
                    flow = this.initializeFlow();
                }

                String sessionKey = provider.getSessionKey();
                Credential credential = flow.loadCredential(sessionKey);
                if(credential != null && credential.getAccessToken() != null) {
                    // todo investigate here, why we didn't have UserProfile in session here.
                    onSuccess(provider, getData(), credential);
                    return null;
                }
                // check if we at init page or at call-back
                // url is
                if (action.equalsIgnoreCase(phase1Marker)) {
                    // phase 1, generate links
                    try {
                        AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl();
                        authorizationUrl.setRedirectUri(getRedirectUri(provider, menuItem.getId()));
                        provider.sendRedirect(authorizationUrl.build());
                    } catch (IOException e) {
                        e.printStackTrace();
                        //todo check what could be wrong here
                    }
                    return null;
                }

                if (action.equalsIgnoreCase(phase2Marker)) {
                    // phase 2, get things from parameters, authenticate user.
                    String code = provider.getParameter("code");
                    if (code != null)
                    {
                        String redirectUri = getRedirectUri(provider, menuItem.getId());
                        TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
                        //todo check what could be wrong here
                        credential = flow.createAndStoreCredential(response, provider.getSessionKey());
                        onSuccess(provider, getData(), credential);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        return answerData;
    }

    protected void onSuccess(ParameterProviderI providerI, DataProviderI dataProviderI, Credential credential)
            throws IOException {

        InputStream in = null;
        try {
            URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + credential.getAccessToken());
            JacksonFactory instance = JacksonFactory.getDefaultInstance();
            in = url.openStream();
            JsonParser parser = instance.createJsonParser(in);
            Map userInfo = parser.parse(HashMap.class);
            if (userInfo != null && userInfo.get("email") != null) {
                String email = (String) userInfo.get("email");
                UserProfileI profileI = dataProviderI.authorizeProfile(email, providerI);
                if (profileI != null) {
                    providerI.sendRedirect(successRedirect);
                } else {
                    providerI.sendRedirect(noSuchAccRedirect);
                }
                //todo unknown user handling
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}


text:
        <form role="form" name="testDetails" ng-submit="addTag(steps.testDetails.tag)">

                <input id="tag-input" class="form-control" name="testDetailsTag" ng-model="steps.testDetails.tag" type="text" placeholder="choose a tag">

                <input id="add-details" class="form-control btn btn-success" type="submit" value="Add">

        </form>

        <form role="form" name="backgrounds" ng-submit="addStep(steps.back)">

                <input class="form-control" name="backGround" ng-model="steps.back.background" type="text" value="" ng-required="true" placeholder="add a bacgkround. see help for more details">

                <input class="form-control btn btn-success" type="submit" value="Add">

 {{ steps.back.background }}

                    <button type="button" class="btn btn-danger" ng-click="saveTest(test_content)">save test</button>

                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                            clone
                        </button>

{{site.title}}

        </form>

            <input class="form-control" name="search-steps" ng-model="search" ng-change="searchForms(search)" type="text" placeholder="search for steps">

Starting Points

            <form role="form" name="scenarioForm" ng-submit="addStep(steps.scenarioForm)" ng-model="form_tags.scenarioForm" ng-init="form_tags.scenarioForm='Scenario'" ng-show="showForm(form_tags.scenarioForm)" class="">

Scenario:

                    <input class="form-control" name="scenarioFormTarget" ng-model="steps.scenarioForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.scenarioForm.arg_1='Testing the page has a link'">

                    <input class="form-control btn btn-success" name="scenarioFormAdd" type="submit" value="Add">

 {{ steps.scenarioForm.intro }} "{{ steps.scenarioForm.arg_1 }}"

            </form>

            <form role="form" name="givenForm" ng-submit="addStep(steps.givenForm)" ng-model="form_tags.given" ng-init="form_tags.given='URL on Visit'" ng-show="showForm(form_tags.given)" class="">

Given I am on

                    <input class="form-control" name="givenFormTarget" ng-model="steps.givenForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.givenForm.arg_1='/some/relative/path'">

                    <input class="form-control btn btn-success" name="givenFormAdd" type="submit" value="Add">

 {{ steps.givenForm.intro }} "{{ steps.givenForm.arg_1 }}"

            </form>

General Interactions

            <form role="form" name="hoverForm" ng-submit="addStep(steps.hoverForm)" ng-model="form_tags.hoverForm" ng-init="form_tags.hoverForm='Menu Hover'" ng-show="showForm(form_tags.hoverForm)" class="ng-hide animate-hide">

And I hover over

                    <select class="form-control" name="hoverFormAction" ng-model="steps.hoverForm.action" ng-required="true" ng-init="steps.hoverForm.action='the menu item named'">
                        <option value="a non link menu item named">a non menu link item eg list item or div</option>
                        <option value="the menu item named">the menu item</option>
                    </select>

                    <input class="form-control" name="hoverFormTarget" ng-model="steps.hoverForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.hoverForm.arg_1='id|name|class'">

                    <input class="form-control btn btn-success" type="submit" name="hoverFormAdd"  value="Add">

 {{ steps.hoverForm.intro }} {{ steps.hoverForm.action }} "{{ steps.hoverForm.arg_1 }}"

            </form>

            <form role="form" name="visibleForm" ng-submit="addStep(steps.visibleForm)" ng-model="form_tags.visibleForm" ng-init="form_tags.visibleForm='Hidden See Not See'" ng-show="showForm(form_tags.visibleForm)" class="ng-hide animate-hide">

Then element

                    <input class="form-control" name="visibleFormTarget" ng-model="steps.visibleForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.visibleForm.arg_1='id|name|class'">
                    <select class="form-control" name="visibleFormAction" ng-model="steps.visibleForm.action" ng-required="true" ng-init="steps.visibleForm.action='is visible'">
                        <option value="is visible">is visible</option>
                        <option value="is not visible">is not visible</option>
                    </select>

                    <input class="form-control btn btn-success" type="submit" name="visibleFormAdd"  value="Add">

 {{ steps.visibleForm.intro }} "{{ steps.visibleForm.arg_1 }}" {{ steps.visibleForm.action }}

            </form>

            <form role="form" name="cfpForm" ng-submit="addStep(steps.cfp)" ng-model="form_tags.cfp" ng-init="form_tags.cfp='Click Press Follow Link'" ng-show="showForm(form_tags.cfp)" class="ng-hide animate-hide">

And I

                    <select class="form-control" name="cfpAction" ng-model="steps.cfp.action" ng-required="true" ng-init="steps.cfp.action='follow'">
                        <option value="follow">follow</option>
                        <option value="press">press</option>
                        <option value="click">click</option>
                    </select>
                    <select class="form-control" name="cfpType" ng-model="steps.cfp.type" ng-required="true" ng-init="steps.cfp.type='the element'">
                        <option value="the element" selected>the element (css path)</option>
                        <option value="">name|label|id</option>
                        <option value="the xpath">xpath</option>
                    </select>

                    <input class="form-control" name="cfpTarget" ng-model="steps.cfp.arg_1" type="textarea" value="" ng-required="true" ng-init="steps.cfp.arg_1='some text'" placeholder="enter the target either a css path or name|label|id">

                    <input class="form-control btn btn-success" type="submit" name="cfpFormAdd"  value="Add">

 {{ steps.cfp.intro }} {{ steps.cfp.action }} {{ steps.cfp.type }} "{{ steps.cfp.arg_1 }}"

            </form>

            <form role="form" name="seeForm" ng-submit="addStep(steps.seeForm)" ng-model="form_tags.see" ng-init="form_tags.see='See on page'" ng-show="showForm(form_tags.see)" class="ng-hide animate-hide">

Then I should

                    <select class="form-control" name="seeFormAction" ng-model="steps.seeForm.action" ng-required="true" ng-init="steps.seeForm.action='see'">
                        <option value="see">see</option>
                        <option value="not see">not see</option>
                    </select>

                    <input class="form-control" name="seeFormTarget" ng-model="steps.seeForm.arg_1" type="textarea" value="" ng-required="true" ng-init="steps.seeForm.arg_1='some text'" placeholder="some text on the page">

                    <input class="form-control btn btn-success" name="seeFormAdd" type="submit" value="Add">

 {{ steps.seeForm.intro }} {{ steps.seeForm.action }} {{ steps.seeForm.type }} "{{ steps.seeForm.arg_1 }}"

            </form>

Form fields & elements

            <form role="form" name="checkUncheckForm" ng-submit="addStep(steps.checkUncheckForm)" ng-model="form_tags.checkUncheckForm" ng-init="form_tags.checkUncheckForm='Check Un UnCheck'" ng-show="showForm(form_tags.checkUncheckForm)" class="ng-hide animate-hide">

And I

                    <select class="form-control" name="checkUncheckFormAction" ng-model="steps.checkUncheckForm.action" ng-required="true" ng-init="steps.checkUncheckForm.action='check'">
                        <option value="check">check</option>
                        <option value="uncheck">uncheck</option>
                    </select>

                    <input class="form-control" name="checkUncheckFormTarget" ng-model="steps.checkUncheckForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.checkUncheckForm.arg_1='id|name|class|value'">

                    <input class="form-control btn btn-success" type="submit" name="checkUncheckFormAdd"  value="Add">

 {{ steps.checkUncheckForm.intro }} {{ steps.checkUncheckForm.action }} "{{ steps.checkUncheckForm.arg_1 }}"

            </form>

            <form role="form" name="checkedOrNotForm" ng-submit="addStep(steps.checkedOrNotForm)" ng-model="form_tags.checkedOrNotForm" ng-init="form_tags.checkedOrNotForm='Check Un UnCheck Checked Not'" ng-show="showForm(form_tags.checkedOrNotForm)" class="ng-hide animate-hide">

Then the

                    <input class="form-control" name="checkedOrNotFormTarget" ng-model="steps.checkedOrNotForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.checkedOrNotForm.arg_1='id|name|class|value'">
                    <select class="form-control" name="checkedOrNotFormAction" ng-model="steps.checkedOrNotForm.action" ng-required="true" ng-init="steps.checkedOrNotForm.action='checkbox should be checked'">
                        <option value="checkbox should be checked">checkbox should be checked</option>
                        <option value="checkbox should not be checked">checkbox should not be checked</option>
                    </select>

                    <input class="form-control btn btn-success" type="submit" name="checkedOrNotFormAdd"  value="Add">

 {{ steps.checkedOrNotForm.intro }} "{{ steps.checkedOrNotForm.arg_1 }}" {{ steps.checkedOrNotForm.action }}

            </form>

            <form role="form" name="selectForm" ng-submit="addStep(steps.selectForm)" ng-model="form_tags.select" ng-init="form_tags.select='Select'" ng-show="showForm(form_tags.select)" class="ng-hide animate-hide animate-show">

And I select

                    <input class="form-control" name="selectFormSelected" ng-model="steps.selectForm.arg_1" type="textarea" value="" ng-required="true" ng-init="steps.selectForm.arg_1='select?'">

from

                    <input class="form-control" name="selectFormTarget" ng-model="steps.selectForm.arg_2" type="textarea" value="" ng-required="true" ng-init="steps.selectForm.arg_2='from name | label or id of select list'">

                    <input class="form-control btn btn-success" name="selectFormAdd" type="submit" value="Add">

 {{ steps.selectForm.intro }} "{{ steps.selectForm.arg_1 }}" {{ steps.selectForm.from }} "{{ steps.selectForm.arg_2 }}"

            </form>

            <form role="form" name="inputForm" ng-submit="addStep(steps.inputForm)" ng-model="form_tags.inputForm" ng-init="form_tags.inputForm='Fill in Input enter'" ng-show="showForm(form_tags.inputForm)" class="ng-hide animate-hide animate-show">

And I fill in

                    <input class="form-control" name="inputFormSelected" ng-model="steps.inputForm.arg_1" type="textarea" value="" ng-required="true" ng-init="steps.inputForm.arg_1='a form field name'">

with

                    <input class="form-control" name="inputFormTarget" ng-model="steps.inputForm.arg_2" type="textarea" value="" ng-required="true" ng-init="steps.inputForm.arg_2='value to put into form field'">

                    <input class="form-control btn btn-success" name="inputFormAdd" type="submit" value="Add">

 {{ steps.inputForm.intro }} "{{ steps.inputForm.arg_1 }}" {{ steps.inputForm.with }} "{{ steps.inputForm.arg_2 }}"

            </form>

            <form role="form" name="shouldContain" ng-submit="addStep(steps.shouldContain)" ng-model="form_tags.shouldContain" ng-init="form_tags.shouldContain='value should input'" ng-show="showForm(form_tags.shouldContain)" class="ng-hide animate-hide animate-show">

Then the

                    <input class="form-control" name="shouldContainTarget" ng-model="steps.shouldContain.arg_1" type="textarea" value="" ng-required="true" ng-init="steps.shouldContain.arg_1='name|label|id'">

                    <select class="form-control" name="shouldContainAction" ng-model="steps.shouldContain.action" ng-required="true" ng-init="steps.shouldContain.action='field should contain'">
                        <option value="field should contain">field should contain</option>
                        <option value="field should not contain">field should not contain</option>
                    </select>

                    <input class="form-control" name="shouldContainTarget2" ng-model="steps.shouldContain.arg_2" type="textarea" value="" ng-required="true" ng-init="steps.shouldContain.arg_2='value to look for'">

                    <input class="form-control btn btn-success" type="submit" name="shouldContainAdd"  value="Add">

 {{ steps.shouldContain.intro }} "{{ steps.shouldContain.arg_1 }}" {{ steps.shouldContain.action }} "{{ steps.shouldContain.arg_2 }}"

            </form>

CSS and DOM

            <form role="form" name="elemExistsForm" ng-submit="addStep(steps.elemExistsForm)" ng-model="form_tags.elemExistsForm" ng-init="form_tags.elemExistsForm='exists'" ng-show="showForm(form_tags.elemExistsForm)" class="ng-hide animate-hide">

Then I see this element

                    <select class="form-control" name="shouldContainAction" ng-model="steps.elemExistsForm.action" ng-required="true" ng-init="steps.elemExistsForm.action='exists'">
                        <option value="exists">exists</option>
                        <option value="not exists">not exists</option>
                    </select>

                    <input class="form-control" name="elemExistsFormTarget" ng-model="steps.elemExistsForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.elemExistsForm.arg_1='css name eg a.menu would be menu'">

                    <input class="form-control btn btn-success" name="elemExistsFormAdd" type="submit" value="Add">

 {{ steps.elemExistsForm.intro }} {{ steps.elemExistsForm.action }} "{{ steps.elemExistsForm.arg_1 }}"

Check to see if class exists eg a.menu would be "menu"

            </form>

            <form role="form" name="onClickForm" ng-submit="addStep(steps.onClickForm)" ng-model="form_tags.onClickForm" ng-init="form_tags.onClickForm='click Popup'" ng-show="showForm(form_tags.onClickForm)" class="ng-hide animate-hide">

Given I click on element which has onclick handler located at

                    <input class="form-control" name="onClickFormTarget" ng-model="steps.onClickForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.onClickForm.arg_1='css path eg div.formRow:nth-child(32)'">

                    <input class="form-control btn btn-success" name="onClickFormAdd" type="submit" value="Add">

 {{ steps.onClickForm.intro }} "{{ steps.onClickForm.arg_1 }}"

            </form>

Navigation Windows iFrames Modals

            <form role="form" name="switchPopupForm" ng-submit="addStep(steps.switchPopupForm)" ng-model="form_tags.switchPopupForm" ng-init="form_tags.switchPopupForm='Popup switch'" ng-show="showForm(form_tags.switchPopupForm)" class="ng-hide animate-hide">

I switch to popup by

                    <select class="form-control" name="shouldContainAction" ng-model="steps.switchPopupForm.action" ng-required="true" ng-init="steps.switchPopupForm.action='clicking'">
                        <option value="clicking">clicking</option>
                        <option value="pressing">pressing</option>
                    </select>

                    <input class="form-control" name="switchPopupFormTarget" ng-model="steps.switchPopupForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.switchPopupForm.arg_1='link or button to act on'">

                    <input class="form-control btn btn-success" name="switchPopupFormAdd" type="submit" value="Add">

 {{ steps.switchPopupForm.intro }} {{ steps.switchPopupForm.action }} "{{ steps.switchPopupForm.arg_1 }}"

            </form>

            <form role="form" name="switchBackForm" ng-submit="addStep(steps.switchBackForm)" ng-model="form_tags.switchBackForm" ng-init="form_tags.switchBackForm='Switch Back'" ng-show="showForm(form_tags.switchBackForm)" class="ng-hide animate-hide">

Then I switch back to the original window

                    <input class="form-control btn btn-success" name="switchBackFormAdd" type="submit" value="Add">

            </form>

            <form role="form" name="iframeSetIdForm" ng-submit="addStep(steps.iframeSetIdForm)" ng-model="form_tags.iframeSetIdForm" ng-init="form_tags.iframeSetIdForm='Iframe name'" ng-show="showForm(form_tags.iframeSetIdForm)" class="ng-hide animate-hide">

Given I set the name of the iframe located in element with an id of

                    <input class="form-control" name="iframeSetIdFormTarget" ng-model="steps.iframeSetIdForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.iframeSetIdForm.arg_1='id of iframe'">

                    <input class="form-control btn btn-success" name="iframeSetIdFormAdd" type="submit" value="Add">

 {{ steps.iframeSetIdForm.intro }} "{{ steps.iframeSetIdForm.arg_1 }}"

 Sets an iFrame ID to no_name_iframe if there is no ID so you can then add a Switch to iFrame step after it using the na_name_iframe ID. You must use an ID but do not pass the #

            </form>

            <form role="form" name="iframeSwitchForm" ng-submit="addStep(steps.iframeSwitchForm)" ng-model="form_tags.iframeSwitchForm" ng-init="form_tags.iframeSwitchForm='Iframe switch name'" ng-show="showForm(form_tags.iframeSwitchForm)" class="ng-hide animate-hide">

Given I switch to iframe with name

                    <input class="form-control" name="iframeSwitchFormTarget" ng-model="steps.iframeSwitchForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.iframeSwitchForm.arg_1='id of iframe'">

                    <input class="form-control btn btn-success" name="iframeSwitchFormAdd" type="submit" value="Add">

 {{ steps.iframeSwitchForm.intro }} "{{ steps.iframeSwitchForm.arg_1 }}"

            </form>

Custom

            <form role="form" name="checkSizeForm" ng-submit="addStep(steps.checkSizeForm)" ng-model="form_tags.checkSizeForm" ng-init="form_tags.checkSizeForm='size'" ng-show="showForm(form_tags.checkSizeForm)" class="ng-hide animate-hide animate-show">

Then the element

                    <input class="form-control" name="checkSizeFormTarget" ng-model="steps.checkSizeForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.checkSizeForm.arg_1='name|label|id'">

should be

                    <input class="form-control" name="checkSizeFormTarget2" ng-model="steps.checkSizeForm.arg_2" type="text" value="" ng-required="true" ng-init="steps.checkSizeForm.arg_2='% it should be'">

percent or greater than the window

                    <input class="form-control btn btn-success" type="submit" name="checkSizeFormAdd"  value="Add">

 {{ steps.checkSizeForm.intro }} "{{ steps.checkSizeForm.arg_1 }}" {{ steps.checkSizeForm.second }} "{{ steps.checkSizeForm.arg_2 }}" See if the element (name|label|id) is greater than the % of the window

            </form>

Low level features

            <form role="form" name="cookiesDestForm" ng-submit="addStep(steps.cookiesDestForm)" ng-model="form_tags.cookiesDestForm" ng-init="form_tags.cookiesDestForm='Cookies'" ng-show="showForm(form_tags.cookiesDestForm)" class="ng-hide animate-hide">

Then I destroy my cookies

                    <input class="form-control btn btn-success" name="cookiesDestFormAdd" type="submit" value="Add">

            </form>

            <form role="form" name="cookiesSeeForm" ng-submit="addStep(steps.cookiesSeeForm)" ng-model="form_tags.cookiesSeeForm" ng-init="form_tags.cookiesSeeForm='Cookies'" ng-show="showForm(form_tags.cookiesSeeForm)" class="ng-hide animate-hide">

Then I should

                    <select class="form-control" name="cookiesSeeFormAction" ng-model="steps.cookiesSeeForm.action" ng-required="true" ng-init="steps.cookiesSeeForm.action='see cookie'">
                        <option value="see cookie">see cookie</option>
                        <option value="not see cookie">not see cookie</option>
                    </select>

                    <input class="form-control" name="cookiesSeeFormArg" ng-model="steps.cookiesSeeForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.cookiesSeeForm.arg_1='monster'">

                    <input class="form-control btn btn-success" name="cookiesSeeFormAdd" type="submit" value="Add">

 {{ steps.cookiesSeeForm.intro }} {{ steps.cookiesSeeForm.action }} "{{ steps.cookiesSeeForm.arg_1 }}"

            </form>

            <form role="form" name="iWaitForm" ng-submit="addStep(steps.iWaitForm)" ng-model="form_tags.iWaitForm" ng-init="form_tags.iWaitForm='Wait'" ng-show="showForm(form_tags.iWaitForm)" class="ng-hide animate-hide">

And I wait

                    <input class="form-control btn btn-success" name="iWaitFormAdd" type="submit" value="Add">

            </form>

            <form role="form" name="iWaitForSecondsForm" ng-submit="addStep(steps.iWaitForSecondsForm)" ng-model="form_tags.iWaitForSecondsForm" ng-init="form_tags.iWaitForSecondsForm='Wait'" ng-show="showForm(form_tags.iWaitForSecondsForm)" class="ng-hide animate-hide animate-show">

And I wait for

                    <input class="form-control" name="iWaitForSecondsFormTarget" ng-model="steps.iWaitForSecondsForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.iWaitForSecondsForm.arg_1='seconds'">

seconds

                    <input class="form-control btn btn-success" type="submit" name="iWaitForSecondsFormAdd"  value="Add">

 {{ steps.iWaitForSecondsForm.intro }} "{{ steps.iWaitForSecondsForm.arg_1 }}"

            </form>

            <form role="form" name="urlMatchForm" ng-submit="addStep(steps.urlMatchForm)" ng-model="form_tags.urlMatchForm" ng-init="form_tags.urlMatchForm='url'" ng-show="showForm(form_tags.urlMatchForm)" class="ng-hide animate-hide animate-show">

Then the url should match

                    <input class="form-control" name="urlMatchFormTarget" ng-model="steps.urlMatchForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.urlMatchForm.arg_1='http://google.com'">

                    <input class="form-control btn btn-success" type="submit" name="urlMatchFormAdd"  value="Add">

 {{ steps.urlMatchForm.intro }} "{{ steps.urlMatchForm.arg_1 }}"

            </form>

            <form role="form" name="iWaitForElementForm" ng-submit="addStep(steps.iWaitForElementForm)" ng-model="form_tags.iWaitForElementForm" ng-init="form_tags.iWaitForElementForm='Wait'" ng-show="showForm(form_tags.iWaitForElementForm)" class="ng-hide animate-hide animate-show">

Then I wait for the element

                    <input class="form-control" name="iWaitForElementFormTarget" ng-model="steps.iWaitForElementForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.iWaitForElementForm.arg_1='Use the full css tag eg #form .class etc'">

                    <select class="form-control" name="iWaitForElementFormAction" ng-model="steps.iWaitForElementForm.action" ng-required="true" ng-init="steps.iWaitForElementForm.action='to appear'">
                        <option value="to appear">to appear</option>
                        <option value="to not be there">to not be there</option>
                    </select>

                    <input class="form-control btn btn-success" type="submit" name="iWaitForElementFormAdd"  value="Add">

 {{ steps.iWaitForElementForm.intro }} "{{ steps.iWaitForElementForm.arg_1 }}" {{ steps.iWaitForElementForm.action }}

            </form>

            <form role="form" name="responseCodeForm" ng-submit="addStep(steps.responseCodeForm)" ng-model="form_tags.responseCodeForm" ng-init="form_tags.responseCodeForm='Response Code'" ng-show="showForm(form_tags.responseCodeForm)" class="ng-hide animate-hide">

Then the response status code should be

                    <input class="form-control" name="responseCodeFormTarget" ng-model="steps.responseCodeForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.responseCodeForm.arg_1='200|404|403'">

                    <input class="form-control btn btn-success" type="submit" name="responseCodeFormAdd"  value="Add">

 {{ steps.responseCodeForm.intro }} "{{ steps.responseCodeForm.arg_1 }}"

            </form>

            <form role="form" name="clickAlertForm" ng-submit="addStep(steps.clickAlertForm)" ng-model="form_tags.clickAlertForm" ng-init="form_tags.clickAlertForm='Alert'" ng-show="showForm(form_tags.clickAlertForm)" class="ng-hide animate-hide">

Then I click on the alert window

                    <input class="form-control btn btn-success" name="clickAlertFormAdd" type="submit" value="Add">

Click on the Javascript Alert Window

            </form>

            <form role="form" name="removeElemForm" ng-submit="addStep(steps.removeElemForm)" ng-model="form_tags.removeElemForm" ng-init="form_tags.removeElemForm='Alert'" ng-show="showForm(form_tags.removeElemForm)" class="ng-hide animate-hide">

Then I remove the element located at

                    <input class="form-control" name="removeElemFormTarget" ng-model="steps.removeElemForm.arg_1" type="text" value="" ng-required="true" ng-init="steps.removeElemForm.arg_1='#ID or .class or div.class etc'">

                    <input class="form-control btn btn-success" name="removeElemFormAdd" type="submit" value="Add">

get an element out of your way

            </form>

Tokens coming soon...

            <button type="button" class="btn btn-danger" data-ng-click="runTest()">run</button>

                    Test Results

redpajama_set_name: RedPajamaGithub


text:
package org.apache.batik.ext.awt.g2d;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
import java.util.Map;

/**
 * This extension of the java.awt.Graphics2D abstract class
 * is still abstract, but it implements a lot of the Graphics2D
 * method in a way that concrete implementations can reuse.
 *
 * This class uses a GraphicContext to store the state of
 * its various attributes that control the rendering, such as the
 * current Font, Paint or clip.
 *
 * Concrete implementations can focus on implementing the rendering
 * methods, such as drawShape. As a convenience, rendering
 * methods that can be expressed with other rendering methods (e.g.,
 * drawRect can be expressed as draw(new Rectangle(..))),
 * are implemented by AbstractGraphics2D
 *
 * @author Vincent Hardy
 * @version $Id$
 * @see org.apache.batik.ext.awt.g2d.GraphicContext
 */
public abstract class AbstractGraphics2D extends Graphics2D implements Cloneable {
    /**
     * Current state of the Graphic Context. The GraphicsContext
     * class manages the state of this Graphics2D graphic context
     * attributes.
     */
    protected GraphicContext gc;

    /**
     * Text handling strategy.
     */
    protected boolean textAsShapes = false;

    /**
     * @param textAsShapes if true, all text is turned into shapes in the
     *        convertion. No text is output.
     *
     */
    public AbstractGraphics2D(boolean textAsShapes) {
        this.textAsShapes = textAsShapes;
    }

    /**
     * Creates a new AbstractGraphics2D from an existing instance.
     * @param g the AbstractGraphics2D whose properties should be copied
     */
    public AbstractGraphics2D(AbstractGraphics2D g) {
        this.gc = (GraphicContext)g.gc.clone();
        this.gc.validateTransformStack();
        this.textAsShapes = g.textAsShapes;
    }

    /**
     * Translates the origin of the graphics context to the point
     * (x, y) in the current coordinate system.
     * Modifies this graphics context so that its new origin corresponds
     * to the point (x, y) in this graphics context's
     * original coordinate system.  All coordinates used in subsequent
     * rendering operations on this graphics context will be relative
     * to this new origin.
     * @param  x   the x coordinate.
     * @param  y   the y coordinate.
     */
    public void translate(int x, int y){
        gc.translate(x, y);
    }

    /**
     * Gets this graphics context's current color.
     * @return    this graphics context's current color.
     * @see       java.awt.Color
     * @see       java.awt.Graphics#setColor
     */
    public Color getColor(){
        return gc.getColor();
    }

    /**
     * Sets this graphics context's current color to the specified
     * color. All subsequent graphics operations using this graphics
     * context use this specified color.
     * @param     c   the new rendering color.
     * @see       java.awt.Color
     * @see       java.awt.Graphics#getColor
     */
    public void setColor(Color c){
        gc.setColor(c);
    }

    /**
     * Sets the paint mode of this graphics context to overwrite the
     * destination with this graphics context's current color.
     * This sets the logical pixel operation function to the paint or
     * overwrite mode.  All subsequent rendering operations will
     * overwrite the destination with the current color.
     */
    public void setPaintMode(){
        gc.setComposite(AlphaComposite.SrcOver);
    }

    /**
     * Gets the current font.
     * @return    this graphics context's current font.
     * @see       java.awt.Font
     * @see       java.awt.Graphics#setFont
     */
    public Font getFont(){
        return gc.getFont();
    }

    /**
     * Sets this graphics context's font to the specified font.
     * All subsequent text operations using this graphics context
     * use this font.
     * @param  font   the font.
     * @see     java.awt.Graphics#getFont
     */
    public void setFont(Font font){
        gc.setFont(font);
    }

    /**
     * Returns the bounding rectangle of the current clipping area.
     * This method refers to the user clip, which is independent of the
     * clipping associated with device bounds and window visibility.
     * If no clip has previously been set, or if the clip has been
     * cleared using setClip(null), this method returns
     * null.
     * The coordinates in the rectangle are relative to the coordinate
     * system origin of this graphics context.
     * @return      the bounding rectangle of the current clipping area,
     *              or null if no clip is set.
     * @see         java.awt.Graphics#getClip
     * @see         java.awt.Graphics#clipRect
     * @see         java.awt.Graphics#setClip(int, int, int, int)
     * @see         java.awt.Graphics#setClip(Shape)
     * @since       JDK1.1
     */
    public Rectangle getClipBounds(){
        return gc.getClipBounds();
    }

    /**
     * Intersects the current clip with the specified rectangle.
     * The resulting clipping area is the intersection of the current
     * clipping area and the specified rectangle.  If there is no
     * current clipping area, either because the clip has never been
     * set, or the clip has been cleared using setClip(null),
     * the specified rectangle becomes the new clip.
     * This method sets the user clip, which is independent of the
     * clipping associated with device bounds and window visibility.
     * This method can only be used to make the current clip smaller.
     * To set the current clip larger, use any of the setClip methods.
     * Rendering operations have no effect outside of the clipping area.
     * @param x the x coordinate of the rectangle to intersect the clip with
     * @param y the y coordinate of the rectangle to intersect the clip with
     * @param width the width of the rectangle to intersect the clip with
     * @param height the height of the rectangle to intersect the clip with
     * @see #setClip(int, int, int, int)
     * @see #setClip(Shape)
     */
    public void clipRect(int x, int y, int width, int height){
        gc.clipRect(x, y, width, height);
    }

    /**
     * Sets the current clip to the rectangle specified by the given
     * coordinates.  This method sets the user clip, which is
     * independent of the clipping associated with device bounds
     * and window visibility.
     * Rendering operations have no effect outside of the clipping area.
     * @param       x the x coordinate of the new clip rectangle.
     * @param       y the y coordinate of the new clip rectangle.
     * @param       width the width of the new clip rectangle.
     * @param       height the height of the new clip rectangle.
     * @see         java.awt.Graphics#clipRect
     * @see         java.awt.Graphics#setClip(Shape)
     * @since       JDK1.1
     */
    public void setClip(int x, int y, int width, int height){
        gc.setClip(x, y, width, height);
    }

    /**
     * Gets the current clipping area.
     * This method returns the user clip, which is independent of the
     * clipping associated with device bounds and window visibility.
     * If no clip has previously been set, or if the clip has been
     * cleared using setClip(null), this method returns
     * null.
     * @return      a Shape object representing the
     *              current clipping area, or null if
     *              no clip is set.
     * @see         java.awt.Graphics#getClipBounds()
     * @see         java.awt.Graphics#clipRect(int, int, int, int)
     * @see         java.awt.Graphics#setClip(int, int, int, int)
     * @see         java.awt.Graphics#setClip(Shape)
     * @since       JDK1.1
     */
    public Shape getClip(){
        return gc.getClip();
    }

    /**
     * Sets the current clipping area to an arbitrary clip shape.
     * Not all objects that implement the Shape
     * interface can be used to set the clip.  The only
     * Shape objects that are guaranteed to be
     * supported are Shape objects that are
     * obtained via the getClip method and via
     * Rectangle objects.  This method sets the
     * user clip, which is independent of the clipping associated
     * with device bounds and window visibility.
     * @param clip the Shape to use to set the clip
     * @see         java.awt.Graphics#getClip()
     * @see         java.awt.Graphics#clipRect
     * @see         java.awt.Graphics#setClip(int, int, int, int)
     * @since       JDK1.1
     */
    public void setClip(Shape clip){
        gc.setClip(clip);
    }

    /**
     * Draws a line, using the current color, between the points
     * (x1, y1) and (x2, y2)
     * in this graphics context's coordinate system.
     * @param   x1  the first point's x coordinate.
     * @param   y1  the first point's y coordinate.
     * @param   x2  the second point's x coordinate.
     * @param   y2  the second point's y coordinate.
     */
    public void drawLine(int x1, int y1, int x2, int y2){
        Line2D line = new Line2D.Float(x1, y1, x2, y2);
        draw(line);
    }

    /**
     * Fills the specified rectangle.
     * The left and right edges of the rectangle are at
     * x and x + width - 1.
     * The top and bottom edges are at
     * y and y + height - 1.
     * The resulting rectangle covers an area
     * width pixels wide by
     * height pixels tall.
     * The rectangle is filled using the graphics context's current color.
     * @param         x   the x coordinate
     *                         of the rectangle to be filled.
     * @param         y   the y coordinate
     *                         of the rectangle to be filled.
     * @param         width   the width of the rectangle to be filled.
     * @param         height   the height of the rectangle to be filled.
     * @see           java.awt.Graphics#clearRect
     * @see           java.awt.Graphics#drawRect
     */
    public void fillRect(int x, int y, int width, int height){
        Rectangle rect = new Rectangle(x, y, width, height);
        fill(rect);
    }

    public void drawRect(int x, int y, int width, int height){
        Rectangle rect = new Rectangle(x, y, width, height);
        draw(rect);
    }

    /**
     * Clears the specified rectangle by filling it with the background
     * color of the current drawing surface. This operation does not
     * use the current paint mode.
     *

     * Beginning with Java 1.1, the background color
     * of offscreen images may be system dependent. Applications should
     * use setColor followed by fillRect to
     * ensure that an offscreen image is cleared to a specific color.
     * @param       x the x coordinate of the rectangle to clear.
     * @param       y the y coordinate of the rectangle to clear.
     * @param       width the width of the rectangle to clear.
     * @param       height the height of the rectangle to clear.
     * @see         java.awt.Graphics#fillRect(int, int, int, int)
     * @see         java.awt.Graphics#drawRect
     * @see         java.awt.Graphics#setColor(java.awt.Color)
     * @see         java.awt.Graphics#setPaintMode
     * @see         java.awt.Graphics#setXORMode(java.awt.Color)
     */
    public void clearRect(int x, int y, int width, int height){
        Paint paint = gc.getPaint();
        gc.setColor(gc.getBackground());
        fillRect(x, y, width, height);
        gc.setPaint(paint);
    }

    /**
     * Draws an outlined round-cornered rectangle using this graphics
     * context's current color. The left and right edges of the rectangle
     * are at x and x + width,
     * respectively. The top and bottom edges of the rectangle are at
     * y and y + height.
     * @param      x the x coordinate of the rectangle to be drawn.
     * @param      y the y coordinate of the rectangle to be drawn.
     * @param      width the width of the rectangle to be drawn.
     * @param      height the height of the rectangle to be drawn.
     * @param      arcWidth the horizontal diameter of the arc
     *                    at the four corners.
     * @param      arcHeight the vertical diameter of the arc
     *                    at the four corners.
     * @see        java.awt.Graphics#fillRoundRect
     */
    public void drawRoundRect(int x, int y, int width, int height,
                              int arcWidth, int arcHeight){
        RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight);
        draw(rect);
    }

    /**
     * Fills the specified rounded corner rectangle with the current color.
     * The left and right edges of the rectangle
     * are at x and x + width - 1,
     * respectively. The top and bottom edges of the rectangle are at
     * y and y + height - 1.
     * @param       x the x coordinate of the rectangle to be filled.
     * @param       y the y coordinate of the rectangle to be filled.
     * @param       width the width of the rectangle to be filled.
     * @param       height the height of the rectangle to be filled.
     * @param       arcWidth the horizontal diameter
     *                     of the arc at the four corners.
     * @param       arcHeight the vertical diameter
     *                     of the arc at the four corners.
     * @see         java.awt.Graphics#drawRoundRect
     */
    public void fillRoundRect(int x, int y, int width, int height,
                              int arcWidth, int arcHeight){
        RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight);
        fill(rect);
    }

    /**
     * Draws the outline of an oval.
     * The result is a circle or ellipse that fits within the
     * rectangle specified by the x, y,
     * width, and height arguments.
     *

     * The oval covers an area that is
     * width + 1 pixels wide
     * and height + 1 pixels tall.
     * @param       x the x coordinate of the upper left
     *                     corner of the oval to be drawn.
     * @param       y the y coordinate of the upper left
     *                     corner of the oval to be drawn.
     * @param       width the width of the oval to be drawn.
     * @param       height the height of the oval to be drawn.
     * @see         java.awt.Graphics#fillOval
     */
    public void drawOval(int x, int y, int width, int height){
        Ellipse2D oval = new Ellipse2D.Float(x, y, width, height);
        draw(oval);
    }

    /**
     * Fills an oval bounded by the specified rectangle with the
     * current color.
     * @param       x the x coordinate of the upper left corner
     *                     of the oval to be filled.
     * @param       y the y coordinate of the upper left corner
     *                     of the oval to be filled.
     * @param       width the width of the oval to be filled.
     * @param       height the height of the oval to be filled.
     * @see         java.awt.Graphics#drawOval
     */
    public void fillOval(int x, int y, int width, int height){
        Ellipse2D oval = new Ellipse2D.Float(x, y, width, height);
        fill(oval);
    }

    /**
     * Draws the outline of a circular or elliptical arc
     * covering the specified rectangle.
     *

     * The resulting arc begins at startAngle and extends
     * for arcAngle degrees, using the current color.
     * Angles are interpreted such that 0 degrees
     * is at the 3 o'clock position.
     * A positive value indicates a counter-clockwise rotation
     * while a negative value indicates a clockwise rotation.
     *

     * The center of the arc is the center of the rectangle whose origin
     * is (x, y) and whose size is specified by the
     * width and height arguments.
     *

     * The resulting arc covers an area
     * width + 1 pixels wide
     * by height + 1 pixels tall.
     *

     * The angles are specified relative to the non-square extents of
     * the bounding rectangle such that 45 degrees always falls on the
     * line from the center of the ellipse to the upper right corner of
     * the bounding rectangle. As a result, if the bounding rectangle is
     * noticeably longer in one axis than the other, the angles to the
     * start and end of the arc segment will be skewed farther along the
     * longer axis of the bounds.
     * @param        x the x coordinate of the
     *                    upper-left corner of the arc to be drawn.
     * @param        y the y  coordinate of the
     *                    upper-left corner of the arc to be drawn.
     * @param        width the width of the arc to be drawn.
     * @param        height the height of the arc to be drawn.
     * @param        startAngle the beginning angle.
     * @param        arcAngle the angular extent of the arc,
     *                    relative to the start angle.
     * @see         java.awt.Graphics#fillArc
     */
    public void drawArc(int x, int y, int width, int height,
                        int startAngle, int arcAngle){
        Arc2D arc = new Arc2D.Float(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN);
        draw(arc);
    }

    /**
     * Fills a circular or elliptical arc covering the specified rectangle.
     *

     * The resulting arc begins at startAngle and extends
     * for arcAngle degrees.
     * Angles are interpreted such that 0 degrees
     * is at the 3 o'clock position.
     * A positive value indicates a counter-clockwise rotation
     * while a negative value indicates a clockwise rotation.
     *

     * The center of the arc is the center of the rectangle whose origin
     * is (x, y) and whose size is specified by the
     * width and height arguments.
     *

     * The resulting arc covers an area
     * width + 1 pixels wide
     * by height + 1 pixels tall.
     *

     * The angles are specified relative to the non-square extents of
     * the bounding rectangle such that 45 degrees always falls on the
     * line from the center of the ellipse to the upper right corner of
     * the bounding rectangle. As a result, if the bounding rectangle is
     * noticeably longer in one axis than the other, the angles to the
     * start and end of the arc segment will be skewed farther along the
     * longer axis of the bounds.
     * @param        x the x coordinate of the
     *                    upper-left corner of the arc to be filled.
     * @param        y the y  coordinate of the
     *                    upper-left corner of the arc to be filled.
     * @param        width the width of the arc to be filled.
     * @param        height the height of the arc to be filled.
     * @param        startAngle the beginning angle.
     * @param        arcAngle the angular extent of the arc,
     *                    relative to the start angle.
     * @see         java.awt.Graphics#drawArc
     */
    public void fillArc(int x, int y, int width, int height,
                        int startAngle, int arcAngle){
        Arc2D arc = new Arc2D.Float(x, y, width, height, startAngle, arcAngle, Arc2D.PIE);
        fill(arc);
    }

    /**
     * Draws a sequence of connected lines defined by
     * arrays of x and y coordinates.
     * Each pair of (x, y) coordinates defines a point.
     * The figure is not closed if the first point
     * differs from the last point.
     * @param       xPoints an array of x points
     * @param       yPoints an array of y points
     * @param       nPoints the total number of points
     * @see         java.awt.Graphics#drawPolygon(int[], int[], int)
     * @since       JDK1.1
     */
    public void drawPolyline(int[] xPoints, int[] yPoints,
                             int nPoints){
        if(nPoints > 0){
            GeneralPath path = new GeneralPath();
            path.moveTo(xPoints[0], yPoints[0]);
            for(int i=1; i<nPoints; i++)
                path.lineTo(xPoints[i], yPoints[i]);

            draw(path);
        }
    }

    /**
     * Draws a closed polygon defined by
     * arrays of x and y coordinates.
     * Each pair of (x, y) coordinates defines a point.
     *

     * This method draws the polygon defined by nPoint line
     * segments, where the first nPoint - 1
     * line segments are line segments from
     * (xPoints[i - 1], yPoints[i - 1])
     * to (xPoints[i], yPoints[i]), for
     * 1 ≤ i ≤ nPoints.
     * The figure is automatically closed by drawing a line connecting
     * the final point to the first point, if those points are different.
     * @param        xPoints   a an array of x coordinates.
     * @param        yPoints   a an array of y coordinates.
     * @param        nPoints   a the total number of points.
     * @see          java.awt.Graphics#fillPolygon(int[],int[],int)
     * @see          java.awt.Graphics#drawPolyline
     */
    public void drawPolygon(int[] xPoints, int[] yPoints,
                            int nPoints){
        Polygon polygon = new Polygon(xPoints, yPoints, nPoints);
        draw(polygon);
    }

    /**
     * Fills a closed polygon defined by
     * arrays of x and y coordinates.
     *

     * This method draws the polygon defined by nPoint line
     * segments, where the first nPoint - 1
     * line segments are line segments from
     * (xPoints[i - 1], yPoints[i - 1])
     * to (xPoints[i], yPoints[i]), for
     * 1 ≤ i ≤ nPoints.
     * The figure is automatically closed by drawing a line connecting
     * the final point to the first point, if those points are different.
     *

     * The area inside the polygon is defined using an
     * even-odd fill rule, also known as the alternating rule.
     * @param        xPoints   a an array of x coordinates.
     * @param        yPoints   a an array of y coordinates.
     * @param        nPoints   a the total number of points.
     * @see          java.awt.Graphics#drawPolygon(int[], int[], int)
     */
    public void fillPolygon(int[] xPoints, int[] yPoints,
                            int nPoints){
        Polygon polygon = new Polygon(xPoints, yPoints, nPoints);
        fill(polygon);
    }

    /**
     * Draws the text given by the specified string, using this
     * graphics context's current font and color. The baseline of the
     * first character is at position (x, y) in this
     * graphics context's coordinate system.
     * @param       str      the string to be drawn.
     * @param       x        the x coordinate.
     * @param       y        the y coordinate.
     * @see         java.awt.Graphics#drawBytes
     * @see         java.awt.Graphics#drawChars
     */
    public void drawString(String str, int x, int y){
        drawString(str, (float)x, (float)y);
    }

    /**
     * Draws the text given by the specified iterator, using this
     * graphics context's current color. The iterator has to specify a font
     * for each character. The baseline of the
     * first character is at position (x, y) in this
     * graphics context's coordinate system.
     * @param       iterator the iterator whose text is to be drawn
     * @param       x        the x coordinate.
     * @param       y        the y coordinate.
     * @see         java.awt.Graphics#drawBytes
     * @see         java.awt.Graphics#drawChars
     */
    public void drawString(AttributedCharacterIterator iterator,
                           int x, int y){
        drawString(iterator, (float)x, (float)y);
    }

    /**
     * Draws as much of the specified image as is currently available.
     * The image is drawn with its top-left corner at
     * (x, y) in this graphics context's coordinate
     * space.  Transparent pixels are drawn in the specified
     * background color.
     *

     * This operation is equivalent to filling a rectangle of the
     * width and height of the specified image with the given color and then
     * drawing the image on top of it, but possibly more efficient.
     *

     * This method returns immediately in all cases, even if the
     * complete image has not yet been loaded, and it has not been dithered
     * and converted for the current output device.
     *

     * If the image has not yet been completely loaded, then
     * drawImage returns false. As more of
     * the image becomes available, the process that draws the image notifies
     * the specified image observer.
     * @param    img    the specified image to be drawn.
     * @param    x      the x coordinate.
     * @param    y      the y coordinate.
     * @param    bgcolor the background color to paint under the
     *                         non-opaque portions of the image.
     * @param    observer    object to be notified as more of
     *                          the image is converted.
     * @see      java.awt.Image
     * @see      java.awt.image.ImageObserver
     * @see      java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
     */
    public boolean drawImage(Image img, int x, int y,
                             Color bgcolor,
                             ImageObserver observer){
        return drawImage(img, x, y, img.getWidth(null), img.getHeight(null),
                         bgcolor, observer);
    }

    /**
     * Draws as much of the specified image as has already been scaled
     * to fit inside the specified rectangle.
     *

     * The image is drawn inside the specified rectangle of this
     * graphics context's coordinate space, and is scaled if
     * necessary. Transparent pixels are drawn in the specified
     * background color.
     * This operation is equivalent to filling a rectangle of the
     * width and height of the specified image with the given color and then
     * drawing the image on top of it, but possibly more efficient.
     *

     * This method returns immediately in all cases, even if the
     * entire image has not yet been scaled, dithered, and converted
     * for the current output device.
     * If the current output representation is not yet complete then
     * drawImage returns false. As more of
     * the image becomes available, the process that draws the image notifies
     * the specified image observer.
     *

     * A scaled version of an image will not necessarily be
     * available immediately just because an unscaled version of the
     * image has been constructed for this output device.  Each size of
     * the image may be cached separately and generated from the original
     * data in a separate image production sequence.
     * @param    img       the specified image to be drawn.
     * @param    x         the x coordinate.
     * @param    y         the y coordinate.
     * @param    width     the width of the rectangle.
     * @param    height    the height of the rectangle.
     * @param    bgcolor   the background color to paint under the
     *                         non-opaque portions of the image.
     * @param    observer    object to be notified as more of
     *                          the image is converted.
     * @see      java.awt.Image
     * @see      java.awt.image.ImageObserver
     * @see      java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
     */
    public boolean drawImage(Image img, int x, int y,
                             int width, int height,
                             Color bgcolor,
                             ImageObserver observer){
        Paint paint = gc.getPaint();
        gc.setPaint(bgcolor);
        fillRect(x, y, width, height);
        gc.setPaint(paint);
        drawImage(img, x, y, width, height, observer);

        return true;
    }

    /**
     * Draws as much of the specified area of the specified image as is
     * currently available, scaling it on the fly to fit inside the
     * specified area of the destination drawable surface. Transparent pixels
     * do not affect whatever pixels are already there.
     *

     * This method returns immediately in all cases, even if the
     * image area to be drawn has not yet been scaled, dithered, and converted
     * for the current output device.
     * If the current output representation is not yet complete then
     * drawImage returns false. As more of
     * the image becomes available, the process that draws the image notifies
     * the specified image observer.
     *

     * This method always uses the unscaled version of the image
     * to render the scaled rectangle and performs the required
     * scaling on the fly. It does not use a cached, scaled version
     * of the image for this operation. Scaling of the image from source
     * to destination is performed such that the first coordinate
     * of the source rectangle is mapped to the first coordinate of
     * the destination rectangle, and the second source coordinate is
     * mapped to the second destination coordinate. The subimage is
     * scaled and flipped as needed to preserve those mappings.
     * @param       img the specified image to be drawn
     * @param       dx1 the x coordinate of the first corner of the
     *                    destination rectangle.
     * @param       dy1 the y coordinate of the first corner of the
     *                    destination rectangle.
     * @param       dx2 the x coordinate of the second corner of the
     *                    destination rectangle.
     * @param       dy2 the y coordinate of the second corner of the
     *                    destination rectangle.
     * @param       sx1 the x coordinate of the first corner of the
     *                    source rectangle.
     * @param       sy1 the y coordinate of the first corner of the
     *                    source rectangle.
     * @param       sx2 the x coordinate of the second corner of the
     *                    source rectangle.
     * @param       sy2 the y coordinate of the second corner of the
     *                    source rectangle.
     * @param       observer object to be notified as more of the image is
     *                    scaled and converted.
     * @see         java.awt.Image
     * @see         java.awt.image.ImageObserver
     * @see         java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
     * @since       JDK1.1
     */
    public boolean drawImage(Image img,
                             int dx1, int dy1, int dx2, int dy2,
                             int sx1, int sy1, int sx2, int sy2,
                             ImageObserver observer){
        BufferedImage src = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = src.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();

        src = src.getSubimage(sx1, sy1, sx2-sx1, sy2-sy1);

        return drawImage(src, dx1, dy1, dx2-dx1, dy2-dy1, observer);
    }

    /**
     * Draws as much of the specified area of the specified image as is
     * currently available, scaling it on the fly to fit inside the
     * specified area of the destination drawable surface.
     *

     * Transparent pixels are drawn in the specified background color.
     * This operation is equivalent to filling a rectangle of the
     * width and height of the specified image with the given color and then
     * drawing the image on top of it, but possibly more efficient.
     *

     * This method returns immediately in all cases, even if the
     * image area to be drawn has not yet been scaled, dithered, and converted
     * for the current output device.
     * If the current output representation is not yet complete then
     * drawImage returns false. As more of
     * the image becomes available, the process that draws the image notifies
     * the specified image observer.
     *

     * This method always uses the unscaled version of the image
     * to render the scaled rectangle and performs the required
     * scaling on the fly. It does not use a cached, scaled version
     * of the image for this operation. Scaling of the image from source
     * to destination is performed such that the first coordinate
     * of the source rectangle is mapped to the first coordinate of
     * the destination rectangle, and the second source coordinate is
     * mapped to the second destination coordinate. The subimage is
     * scaled and flipped as needed to preserve those mappings.
     * @param       img the specified image to be drawn
     * @param       dx1 the x coordinate of the first corner of the
     *                    destination rectangle.
     * @param       dy1 the y coordinate of the first corner of the
     *                    destination rectangle.
     * @param       dx2 the x coordinate of the second corner of the
     *                    destination rectangle.
     * @param       dy2 the y coordinate of the second corner of the
     *                    destination rectangle.
     * @param       sx1 the x coordinate of the first corner of the
     *                    source rectangle.
     * @param       sy1 the y coordinate of the first corner of the
     *                    source rectangle.
     * @param       sx2 the x coordinate of the second corner of the
     *                    source rectangle.
     * @param       sy2 the y coordinate of the second corner of the
     *                    source rectangle.
     * @param       bgcolor the background color to paint under the
     *                    non-opaque portions of the image.
     * @param       observer object to be notified as more of the image is
     *                    scaled and converted.
     * @see         java.awt.Image
     * @see         java.awt.image.ImageObserver
     * @see         java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
     * @since       JDK1.1
     */
    public boolean drawImage(Image img,
                             int dx1, int dy1, int dx2, int dy2,
                             int sx1, int sy1, int sx2, int sy2,
                             Color bgcolor,
                             ImageObserver observer){
        Paint paint = gc.getPaint();
        gc.setPaint(bgcolor);
        fillRect(dx1, dy1, dx2-dx1, dy2-dy1);
        gc.setPaint(paint);
        return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer);
    }

    /**
     * Renders an image, applying a transform from image space into user space
     * before drawing.
     * The transformation from user space into device space is done with
     * the current Transform in the Graphics2D.
     * The specified transformation is applied to the image before the
     * transform attribute in the Graphics2D context is applied.
     * The rendering attributes applied include the Clip,
     * Transform, and Composite attributes.
     * Note that no rendering is done if the specified transform is
     * noninvertible.
     * @param img the Image to be rendered
     * @param xform the transformation from image space into user space
     * @param obs the {@link ImageObserver}
     * to be notified as more of the Image
     * is converted
     * @return true if the Image is
     * fully loaded and completely rendered;
     * false if the Image is still being loaded.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip(Shape)
     */
    public boolean drawImage(Image img,
                             AffineTransform xform,
                             ImageObserver obs){
        boolean retVal = true;

        if(xform.getDeterminant() != 0){
            AffineTransform inverseTransform = null;
            try{
                inverseTransform = xform.createInverse();
            }   catch(NoninvertibleTransformException e){
                                // Should never happen since we checked the
                                // matrix determinant
                throw new Error( e.getMessage() );
            }

            gc.transform(xform);
            retVal = drawImage(img, 0, 0, null);
            gc.transform(inverseTransform);
        }
        else{
            AffineTransform savTransform = new AffineTransform(gc.getTransform());
            gc.transform(xform);
            retVal = drawImage(img, 0, 0, null);
            gc.setTransform(savTransform);
        }

        return retVal;

    }

    /**
     * Renders a BufferedImage that is
     * filtered with a
     * {@link BufferedImageOp}.
     * The rendering attributes applied include the Clip,
     * Transform
     * and Composite attributes.  This is equivalent to:
     *

     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     *

     * @param img the BufferedImage to be rendered
     * @param op the filter to be applied to the image before rendering
     * @param x the x coordinate in user space where the image is rendered
     * @param y the y coordinate in user space where the image is rendered
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip(Shape)
     */
    public void drawImage(BufferedImage img,
                          BufferedImageOp op,
                          int x,
                          int y){
        img = op.filter(img, null);
        drawImage(img, x, y, null);
    }

    /**
     * Renders the text of the specified
     * {@link GlyphVector} using
     * the Graphics2D context's rendering attributes.
     * The rendering attributes applied include the Clip,
     * Transform, Paint, and
     * Composite attributes.  The GlyphVector
     * specifies individual glyphs from a {@link Font}.
     * The GlyphVector can also contain the glyph positions.
     * This is the fastest way to render a set of characters to the
     * screen.
     *
     * @param g the GlyphVector to be rendered
     * @param x the x position in user space where the glyphs should be
     *        rendered
     * @param y the y position in user space where the glyphs should be
     *        rendered
     *
     * @see java.awt.Font#createGlyphVector(FontRenderContext, char[])
     * @see java.awt.font.GlyphVector
     * @see #setPaint
     * @see java.awt.Graphics#setColor
     * @see #setTransform
     * @see #setComposite
     * @see #setClip(Shape)
     */
    public void drawGlyphVector(GlyphVector g, float x, float y){
        Shape glyphOutline = g.getOutline(x, y);
        fill(glyphOutline);
    }

    /**
     * Checks whether or not the specified Shape intersects
     * the specified {@link Rectangle}, which is in device
     * space. If onStroke is false, this method checks
     * whether or not the interior of the specified Shape
     * intersects the specified Rectangle.  If
     * onStroke is true, this method checks
     * whether or not the Stroke of the specified
     * Shape outline intersects the specified
     * Rectangle.
     * The rendering attributes taken into account include the
     * Clip, Transform, and Stroke
     * attributes.
     * @param rect the area in device space to check for a hit
     * @param s the Shape to check for a hit
     * @param onStroke flag used to choose between testing the
     * stroked or the filled shape.  If the flag is true, the
     * Stroke oultine is tested.  If the flag is
     * false, the filled Shape is tested.
     * @return true if there is a hit; false
     * otherwise.
     * @see #setStroke
     * @see #fill(Shape)
     * @see #draw(Shape)
     * @see #transform
     * @see #setTransform
     * @see #clip
     * @see #setClip(Shape)
     */
    public boolean hit(Rectangle rect,
                       Shape s,
                       boolean onStroke){
        if (onStroke) {
            s = gc.getStroke().createStrokedShape(s);
        }

        s = gc.getTransform().createTransformedShape(s);

        return s.intersects(rect);
    }

    /**
     * Sets the Composite for the Graphics2D context.
     * The Composite is used in all drawing methods such as
     * drawImage, drawString, draw,
     * and fill.  It specifies how new pixels are to be combined
     * with the existing pixels on the graphics device during the rendering
     * process.
     *
If this Graphics2D context is drawing to a
     * Component on the display screen and the
     * Composite is a custom object rather than an
     * instance of the AlphaComposite class, and if
     * there is a security manager, its checkPermission
     * method is called with an AWTPermission("readDisplayPixels")
     * permission.
     * @param comp the Composite object to be used for rendering
     * @throws SecurityException
     *         if a custom Composite object is being
     *         used to render to the screen and a security manager
     *         is set and its checkPermission method
     *         does not allow the operation.
     * @see java.awt.Graphics#setXORMode
     * @see java.awt.Graphics#setPaintMode
     * @see java.awt.AlphaComposite
     */
    public void setComposite(Composite comp){
        gc.setComposite(comp);
    }

    /**
     * Sets the Paint attribute for the
     * Graphics2D context.  Calling this method
     * with a null Paint object does
     * not have any effect on the current Paint attribute
     * of this Graphics2D.
     * @param paint the Paint object to be used to generate
     * color during the rendering process, or null
     * @see java.awt.Graphics#setColor
     */
    public void setPaint(Paint paint) {
        gc.setPaint(paint);
    }

    /**
     * Sets the Stroke for the Graphics2D context.
     * @param s the Stroke object to be used to stroke a
     * Shape during the rendering process
     */
    public void setStroke(Stroke s){
        gc.setStroke(s);
    }

    /**
     * Sets the value of a single preference for the rendering algorithms.
     * Hint categories include controls for rendering quality and overall
     * time/quality trade-off in the rendering process.  Refer to the
     * RenderingHints class for definitions of some common
     * keys and values.
     * @param hintKey the key of the hint to be set.
     * @param hintValue the value indicating preferences for the specified
     * hint category.
     * @see RenderingHints
     */
    public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){
        gc.setRenderingHint(hintKey, hintValue);
    }

    /**
     * Returns the value of a single preference for the rendering algorithms.
     * Hint categories include controls for rendering quality and overall
     * time/quality trade-off in the rendering process.  Refer to the
     * RenderingHints class for definitions of some common
     * keys and values.
     * @param hintKey the key corresponding to the hint to get.
     * @return an object representing the value for the specified hint key.
     * Some of the keys and their associated values are defined in the
     * RenderingHints class.
     * @see RenderingHints
     */
    public Object getRenderingHint(RenderingHints.Key hintKey){
        return gc.getRenderingHint(hintKey);
    }

    /**
     * Replaces the values of all preferences for the rendering
     * algorithms with the specified hints.
     * The existing values for all rendering hints are discarded and
     * the new set of known hints and values are initialized from the
     * specified {@link Map} object.
     * Hint categories include controls for rendering quality and
     * overall time/quality trade-off in the rendering process.
     * Refer to the RenderingHints class for definitions of
     * some common keys and values.
     * @param hints the rendering hints to be set
     * @see RenderingHints
     */
    public void setRenderingHints(Map hints){
        gc.setRenderingHints(hints);
    }

    /**
     * Sets the values of an arbitrary number of preferences for the
     * rendering algorithms.
     * Only values for the rendering hints that are present in the
     * specified Map object are modified.
     * All other preferences not present in the specified
     * object are left unmodified.
     * Hint categories include controls for rendering quality and
     * overall time/quality trade-off in the rendering process.
     * Refer to the RenderingHints class for definitions of
     * some common keys and values.
     * @param hints the rendering hints to be set
     * @see RenderingHints
     */
    public void addRenderingHints(Map hints){
        gc.addRenderingHints(hints);
    }

    /**
     * Gets the preferences for the rendering algorithms.  Hint categories
     * include controls for rendering quality and overall time/quality
     * trade-off in the rendering process.
     * Returns all of the hint key/value pairs that were ever specified in
     * one operation.  Refer to the
     * RenderingHints class for definitions of some common
     * keys and values.
     * @return a reference to an instance of RenderingHints
     * that contains the current preferences.
     * @see RenderingHints
     */
    public RenderingHints getRenderingHints(){
        return gc.getRenderingHints();
    }

    /**
     * Concatenates the current
     * Graphics2D Transform
     * with a translation transform.
     * Subsequent rendering is translated by the specified
     * distance relative to the previous position.
     * This is equivalent to calling transform(T), where T is an
     * AffineTransform represented by the following matrix:
     *

     *          [   1    0    tx  ]
     *          [   0    1    ty  ]
     *          [   0    0    1   ]
     *

     * @param tx the distance to translate along the x-axis
     * @param ty the distance to translate along the y-axis
     */
    public void translate(double tx, double ty){
        gc.translate(tx, ty);
    }

    /**
     * Concatenates the current Graphics2D
     * Transform with a rotation transform.
     * Subsequent rendering is rotated by the specified radians relative
     * to the previous origin.
     * This is equivalent to calling transform(R), where R is an
     * AffineTransform represented by the following matrix:
     *

     *          [   cos(theta)    -sin(theta)    0   ]
     *          [   sin(theta)     cos(theta)    0   ]
     *          [       0              0         1   ]
     *

     * Rotating with a positive angle theta rotates points on the positive
     * x axis toward the positive y axis.
     * @param theta the angle of rotation in radians
     */
    public void rotate(double theta){
        gc.rotate(theta);
    }

    /**
     * Concatenates the current Graphics2D
     * Transform with a translated rotation
     * transform.  Subsequent rendering is transformed by a transform
     * which is constructed by translating to the specified location,
     * rotating by the specified radians, and translating back by the same
     * amount as the original translation.  This is equivalent to the
     * following sequence of calls:
     *

     *          translate(x, y);
     *          rotate(theta);
     *          translate(-x, -y);
     *

     * Rotating with a positive angle theta rotates points on the positive
     * x axis toward the positive y axis.
     * @param theta the angle of rotation in radians
     * @param x the x coordinate of the origin of the rotation
     * @param y the y coordinate of the origin of the rotation
     */
    public void rotate(double theta, double x, double y){
        gc.rotate(theta, x, y);
    }

    /**
     * Concatenates the current Graphics2D
     * Transform with a scaling transformation
     * Subsequent rendering is resized according to the specified scaling
     * factors relative to the previous scaling.
     * This is equivalent to calling transform(S), where S is an
     * AffineTransform represented by the following matrix:
     *

     *          [   sx   0    0   ]
     *          [   0    sy   0   ]
     *          [   0    0    1   ]
     *

     * @param sx the amount by which X coordinates in subsequent
     * rendering operations are multiplied relative to previous
     * rendering operations.
     * @param sy the amount by which Y coordinates in subsequent
     * rendering operations are multiplied relative to previous
     * rendering operations.
     */
    public void scale(double sx, double sy){
        gc.scale(sx, sy);
    }

    /**
     * Concatenates the current Graphics2D
     * Transform with a shearing transform.
     * Subsequent renderings are sheared by the specified
     * multiplier relative to the previous position.
     * This is equivalent to calling transform(SH), where SH
     * is an AffineTransform represented by the following
     * matrix:
     *

     *          [   1   shx   0   ]
     *          [  shy   1    0   ]
     *          [   0    0    1   ]
     *

     * @param shx the multiplier by which coordinates are shifted in
     * the positive X axis direction as a function of their Y coordinate
     * @param shy the multiplier by which coordinates are shifted in
     * the positive Y axis direction as a function of their X coordinate
     */
    public void shear(double shx, double shy){
        gc.shear(shx, shy);
    }

    /**
     * Composes an AffineTransform object with the
     * Transform in this Graphics2D according
     * to the rule last-specified-first-applied.  If the current
     * Transform is Cx, the result of composition
     * with Tx is a new Transform Cx'.  Cx' becomes the
     * current Transform for this Graphics2D.
     * Transforming a point p by the updated Transform Cx' is
     * equivalent to first transforming p by Tx and then transforming
     * the result by the original Transform Cx.  In other
     * words, Cx'(p) = Cx(Tx(p)).  A copy of the Tx is made, if necessary,
     * so further modifications to Tx do not affect rendering.
     * @param Tx the AffineTransform object to be composed with
     * the current Transform
     * @see #setTransform
     * @see AffineTransform
     */
    public void transform(AffineTransform Tx){
        gc.transform(Tx);
    }

    /**
     * Sets the Transform in the Graphics2D
     * context.
     * @param Tx the AffineTransform object to be used in the
     * rendering process
     * @see #transform
     * @see AffineTransform
     */
    public void setTransform(AffineTransform Tx){
        gc.setTransform(Tx);
    }

    /**
     * Returns a copy of the current Transform in the
     * Graphics2D context.
     * @return the current AffineTransform in the
     *             Graphics2D context.
     * @see #transform
     * @see #setTransform
     */
    public AffineTransform getTransform(){
        return gc.getTransform();
    }

    /**
     * Returns the current Paint of the
     * Graphics2D context.
     * @return the current Graphics2D Paint,
     * which defines a color or pattern.
     * @see #setPaint
     * @see java.awt.Graphics#setColor
     */
    public Paint getPaint(){
        return gc.getPaint();
    }

    /**
     * Returns the current Composite in the
     * Graphics2D context.
     * @return the current Graphics2D Composite,
     *              which defines a compositing style.
     * @see #setComposite
     */
    public Composite getComposite(){
        return gc.getComposite();
    }

    /**
     * Sets the background color for the Graphics2D context.
     * The background color is used for clearing a region.
     * When a Graphics2D is constructed for a
     * Component, the background color is
     * inherited from the Component. Setting the background color
     * in the Graphics2D context only affects the subsequent
     * clearRect calls and not the background color of the
     * Component.  To change the background
     * of the Component, use appropriate methods of
     * the Component.
     * @param color the background color that isused in
     * subsequent calls to clearRect
     * @see #getBackground
     * @see java.awt.Graphics#clearRect
     */
    public void setBackground(Color color){
        gc.setBackground(color);
    }

    /**
     * Returns the background color used for clearing a region.
     * @return the current Graphics2D Color,
     * which defines the background color.
     * @see #setBackground
     */
    public Color getBackground(){
        return gc.getBackground();
    }

    /**
     * Returns the current Stroke in the
     * Graphics2D context.
     * @return the current Graphics2D Stroke,
     *                 which defines the line style.
     * @see #setStroke
     */
    public Stroke getStroke(){
        return gc.getStroke();
    }

    /**
     * Intersects the current Clip with the interior of the
     * specified Shape and sets the Clip to the
     * resulting intersection.  The specified Shape is
     * transformed with the current Graphics2D
     * Transform before being intersected with the current
     * Clip.  This method is used to make the current
     * Clip smaller.
     * To make the Clip larger, use setClip.
     * The user clip modified by this method is independent of the
     * clipping associated with device bounds and visibility.  If no clip has
     * previously been set, or if the clip has been cleared using
     * {@link java.awt.Graphics#setClip(Shape) setClip} with a
     * null argument, the specified Shape becomes
     * the new user clip.
     * @param s the Shape to be intersected with the current
     *          Clip.  If s is null,
     *          this method clears the current Clip.
     */
    public void clip(Shape s){
        gc.clip(s);
    }

    /**
     * Get the rendering context of the Font within this
     * Graphics2D context.
     * The {@link FontRenderContext}
     * encapsulates application hints such as anti-aliasing and
     * fractional metrics, as well as target device specific information
     * such as dots-per-inch.  This information should be provided by the
     * application when using objects that perform typographical
     * formatting, such as Font and
     * TextLayout.  This information should also be provided
     * by applications that perform their own layout and need accurate
     * measurements of various characteristics of glyphs such as advance
     * and line height when various rendering hints have been applied to
     * the text rendering.
     *
     * @return a reference to an instance of FontRenderContext.
     * @see java.awt.font.FontRenderContext
     * @see java.awt.Font#createGlyphVector(FontRenderContext,char[])
     * @see java.awt.font.TextLayout
     * @since     JDK1.2
     */
    public FontRenderContext getFontRenderContext(){
        return gc.getFontRenderContext();
    }

    /**
     * @return the {@link GraphicContext} of this Graphics2D.
     */
    public GraphicContext getGraphicContext() {
        return gc;
    }
}


text:
"""
    djlime.utils.mail
    ~~~~~~~~~~~~~~

    Utilities for mail sending.

    :copyright: (c) 2012 by Andrey Voronov.
    :license: BSD, see LICENSE for more details.
"""

from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail.message import EmailMultiAlternatives

def send_mail(recipients=None, subject_template='', html_template=None,
              text_template=None, context=None, **kwargs):
    subject = render_to_string(subject_template, context)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    html_msg = render_to_string(html_template, context)
    text_msg = render_to_string(text_template, context)
    sender = kwargs.pop('sender', None)
    if not isinstance(recipients, list):
        recipients = [recipients]
    msg = EmailMultiAlternatives(subject, text_msg,
                                 sender or settings.DEFAULT_FROM_EMAIL, recipients)
    msg.attach_alternative(html_msg, "text/html")
    msg.send()


text:
import matlab.engine as mateng
from time import time
import IPython
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from sklearn import (manifold, datasets, decomposition, ensemble, lda, random_projection, preprocessing, covariance)
from scipy import linalg
import argparse
import pickle
import cv2
import utils

def parse():
	eng = mateng.start_matlab()

	[s, X] = eng.read_binary_blob(PATH_TO_DATA + '1.conv5b', nargout = 2)
	i = 17;
	while i <= 1489:
		[s, data] = eng.read_binary_blob(PATH_TO_DATA + str(i) + '.conv5b', nargout = 2)
		data = np.array(data)
		X = np.concatenate((X, data), axis = 0)
		i += 16
	return X

def parse_annotations_pickle(annotations_file, PATH_TO_DATA, layer):
	index_map = {}
	label_map = {}
	eng = mateng.start_matlab()
	map_index_data = pickle.load(open(annotations_file, "rb"))
	X = None
	i = 0
	for index in map_index_data:
		print "Parsing label " + str(index)
		segments = map_index_data[index]
		for seg in segments:
			j = seg[0]
			while j <= seg[1]:
				print j
				if X is None:
					[s, X] = eng.read_binary_blob(PATH_TO_DATA + str(j) + '.' + args.layer, nargout = 2)
				else:
					[s, data] = eng.read_binary_blob(PATH_TO_DATA + str(j) + '.' + args.layer, nargout = 2)
					data = np.array(data)
					X = np.concatenate((X, data), axis = 0)
				index_map[i] = j
				label_map[i] = index
				j += 16
				i += 1
	return X, label_map, index_map

def plot_all(X):
	tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
	#----------------------------------------------------------------------
	# Pre-processing
	print "t-SNE Scaling"
	X_scaled = preprocessing.scale(X) #zero mean, unit variance
	X_tsne_scaled = tsne.fit_transform(X_scaled)

	#normalize the data (scaling individual samples to have unit norm)
	print "t-SNE L2 Norm"
	X_normalized = preprocessing.normalize(X, norm='l2')
	X_tsne_norm = tsne.fit_transform(X_normalized)

	#whiten the data
	print "t-SNE Whitening"
	# the mean computed by the scaler is for the feature dimension.
	# We want the normalization to be in feature dimention.
	# Zero mean for each sample assumes stationarity which is not necessarily true for CNN features.
	# X: NxD where N is number of examples and D is number of features.

	# scaler = preprocessing.StandardScaler(with_std=False).fit(X)
	scaler = preprocessing.StandardScaler().fit(X) #this scales each feature to have std-dev 1
	X_centered = scaler.transform(X)

	# U, s, Vh = linalg.svd(X_centered)
	shapeX = X_centered.shape
	IPython.embed()
	# this is DxD matrix where D is the feature dimension
	# still to figure out: It seems computation is not a problem but carrying around a 50kx50k matrix is memory killer!
	sig = (1/shapeX[0]) * np.dot(X_centered.T, X_centered)
	sig2= covariance.empirical_covariance(X_centered, assume_centered=True) #estimated -- this is better.
	sig3, shrinkage= covariance.oas(X_centered, assume_centered=True) #estimated

	U, s, Vh = linalg.svd(sig, full_matrices=False)
	eps = 1e-2 # this affects how many low- freq eigevalues are eliminated
	invS = np.diag (np.reciprocal(np.sqrt(s+eps)))

	#PCA_whiten
	X_pca = np.dot(invS, np.dot(U.T, X_centered))
	X_tsne_pca = tsne.fit_transform(X_pca)

	#whiten the data (ZCA)
	X_zca = np.dot(U, X_pca)
	X_tsne_zca = tsne.fit_transform(X_zca)

	return X_tsne_scaled, X_tsne_norm, X_tsne_pca, X_tsne_zca

if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("file_name", help = "Please specify MAIN file name")
	parser.add_argument("layer", help = "Please specify layer")
	parser.add_argument("PATH_TO_DATA", help="Please specify the path to the feature data")
	parser.add_argument("--a", help = "Annotated frames")
	parser.add_argument("--PATH_TO_DATA_2", help="Please specify the path to 2nd set of feature data")
	parser.add_argument("--a_2", help="Annotated frames for 2nd set of data")
	parser.add_argument("--image", help="Parse image mode", default = None)
	args = parser.parse_args()
	if args.a_2 and args.PATH_TO_DATA_2 and not args.image:
		X1, label_map_1, index_map_1 = parse_annotations_pickle(args.a, args.PATH_TO_DATA, args.layer)
		X2, label_map_2, index_map_2 = parse_annotations_pickle(args.a_2, args.PATH_TO_DATA_2, args.layer)
		X1_pca = utils.pca(X1)
		X2_pca = utils.pca(X2)
		plot_annotated_joint(X1_pca, X2_pca, label_map_1, index_map_1, label_map_2, index_map_2, figure_name = args.file_name +".png", title = "PCA " + args.layer)
	elif args.image and not args.PATH_TO_DATA_2:
			X, label_map, index_map  = utils.parse_annotations_images(args.a, args.PATH_TO_DATA)
			pickle.dump(X, open(args.file_name + "_allimages.p", "wb"))
			pickle.dump(label_map, open(args.file_name + "_labelmap.p", "wb"))
			pickle.dump(index_map, open(args.file_name + "_indexmap.p", "wb"))
			IPython.embed()
			X_pca = utils.pca(X)
			X_tsne = utils.tsne(X)
			X_tsne_pca = utils.tsne_pca(X)
			utils.plot_annotated_embedding(X_pca, label_map, index_map, args.file_name + '_' + args.layer + '_pca.png', 'PCA ' + args.layer)
			utils.plot_annotated_embedding(X_tsne, label_map, index_map, args.file_name + '_' + args.layer + '_tsne.png', 't-SNE ' + args.layer)
			utils.plot_annotated_embedding(X_tsne_pca, label_map, index_map, args.file_name + '_' + args.layer + '_tsne_pca.png', 't-SNE (PCA Input) ' + args.layer)
	else:
		if args.a:
			X, label_map, index_map  = parse_annotations_pickle(args.a, args.PATH_TO_DATA, args.layer)
		else:
			X, label_map, index_map = parse_annotations(args)

		X_pca = utils.pca(X)
		X_tsne = utils.tsne(X)
		X_tsne_pca = utils.tsne_pca(X)
		utils.plot_annotated_embedding(X_pca, label_map, index_map, args.file_name + '_' + args.layer + '_pca.png', 'PCA - C3D ' + args.layer)
		utils.plot_annotated_embedding(X_tsne, label_map, index_map, args.file_name + '_' + args.layer + '_tsne.png', 't-SNE - C3D ' + args.layer)
		utils.plot_annotated_embedding(X_tsne_pca, label_map, index_map, args.file_name + '_' + args.layer + '_tsne_pca.png', 't-SNE(PCA input) - C3D ' + args.layer)


text:
layout: post
title:  "It's probably a syntax error"
date:   2017-04-01 23:43:05 +0000
---

I was working on the ZHW Shoes Layout lab, tearing my hair out, and wondering why my columns were still at 100% width, even though I was sure that I had made the right changes in the CSS. I looked and looked, and just couldn't figure out what I had done wrong. Eventually, I began wondering if I had understood the concept at all, and was starting to question my life choices...

After far too long, I realized that I had included two class attributes in an element:

![Screenshot of syntax error](http://i.imgur.com/ngNvGOc.jpg)

That'll teach me for completing labs right after waking up. The lab took me much longer than it would have, had I just run my code through a CSS and HTML validator. Here's what I would have seen right away, had I thrown my code into the [W3C HTML Validator](https://validator.w3.org/#validate_by_input):

![Screenshot of results of W3C HTML validator](http://i.imgur.com/sgehjsQ.jpg)

When inspecting the problem element in Chrome Dev Tools, I could see that the browser had ignored the second class attribute altogether, so no wonder I wasn't seeing any of the styles that I thought I had applied:

![Screenshot of the element in Dev Tools](http://i.imgur.com/144k2UL.jpg)

I felt really silly, partly because of the error, but mostly because I had forgotten to use all of the tools at my disposal to help me with debugging.

This was a simple error, and I know that it can (and will!) be much more complicated in the future, so this was a good reminder to take a deep breath, slow down, and follow clear steps to resolve an issue. I still have some work to do in learning what all those steps are, so it's time to stop procrastinating and learn how to use Chrome Dev Tools already.


text:
package com.intel.analytics.bigdl.nn.tf

import com.intel.analytics.bigdl.nn.abstractnn.DataFormat
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.T
import com.intel.analytics.bigdl.utils.serializer.ModuleSerializationTest

class Conv3DBackpropFilterV2SerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val module = Conv3DBackpropFilterV2[Float](1, 2, 3, 0, 0, 0, DataFormat.NHWC)
    val input = Tensor[Float](4, 20, 30, 40, 3).rand()
    val filter = Tensor[Int](Array(2, 3, 4, 3, 4), Array(5))
    val outputBackprop = Tensor[Float](4, 19, 14, 13, 4).rand()

    runSerializationTest(module, T(input, filter, outputBackprop))
  }
}


text:
package org.checkerframework.afu.scenelib.el;

// Gives an index into a class's set of supertypes (-1 = superclass,
// non-negative integers for implemented interfaces) or into a
// method's set of thrown exceptions.
public class TypeIndexLocation {
  public final int typeIndex;

  public TypeIndexLocation(int typeIndex) {
    this.typeIndex = typeIndex;
  }

  public boolean equals(TypeIndexLocation l) {
    return typeIndex == l.typeIndex;
  }

  @Override
  public boolean equals(Object o) {
    return o instanceof TypeIndexLocation && equals((TypeIndexLocation) o);
  }

  @Override
  public int hashCode() {
    return typeIndex;
  }

  @Override
  public String toString() {
    return "TypeIndexLocation(" + typeIndex + ")";
  }
}