text:
This example illustrates the concept of data synchronozation using Watermarking.

### Watermarking ###

The concept of Watermark refers to a flood after-match in which you look at the water stains in a wall to figure how high the water got, which is what we want to do in this use case: figure out which was the last item we updated and move from there on.

### Assumptions ###

This document describes the details of the example within the context of **Anypoint™ Studio**, Mule ESB's graphical user interface (GUI). Where appropriate, the XML configuration is provided.

This document assumes that you are familiar with Mule ESB and the [Anypoint Studio interface](http://www.mulesoft.org/documentation/display/current/Anypoint+Studio+Essentials). To increase your familiarity with Mule Studio, consider completing one or more [Anypoint Studio Tutorials](http://www.mulesoft.org/documentation/display/current/Basic+Studio+Tutorial). Further, this example assumes that you have a basic understanding of [Mule flows](http://www.mulesoft.org/documentation/display/current/Mule+Application+Architecture) and [Mule Global Elements](http://www.mulesoft.org/documentation/display/current/Global+Elements).

### Example Use Case ###

In this example, watermarking feature is used to periodically make pull requests to the data store to retrieve only records that were modified since the last request. Specifically, Salesforce CRM is queried for contacts that were recently modified and just prints them in the console.

### Set Up and Run the Example ###

Complete the following procedure to create, then run this example in your own instance of Anypoint Studio. Skip ahead to the next section if you prefer to simply examine this example.

1. Open the Example project in Anypoint Studio from [Anypoint Exchange](http://www.mulesoft.org/documentation/display/current/Anypoint+Exchange). *Do not run the application*.
1. Log in to your Salesforce account. From your account menu (your account is labeled with your name), select **Setup**.
1. In the left navigation bar, under the **Personal Setup** heading, click to expand the **My Personal Information** folder.
1. Click **Reset My Security Token**. Salesforce resets the token and emails you the new one.
1. Access the email that Salesforce sent and copy the new token onto your local clipboard.
1. In your application in Studio, click the **Global Elements** tab.
1. Double-click the Salesforce global element to open its **Global Element Properties** panel. In the **Security Token** field, paste the new Salesforce token you copied from the email. Alternatively, configure the global element in the XML Editor.
1. Change the contents of the **Username** and **Password** fields to your account-specific values, then click **OK** to save your changes.
1. In the **Package Explorer**, right-click the connect-with-salesforce project name, then select **Run As > Mule Application**. Studio runs the application on the embedded server.
1. In your browser, access your Salesforce account, then navigate to the **Contacts** tab.
2. Use the drop-down menu to display** All Contacts**, then select one contact and edit (e.g. change the first name).
3. Go back to Anypoint Studio and click the console view and search for a log similar to this one:

		INFO  2014-07-04 08:17:01,502 [batch-job-watermarkingBatch1-work-manager.05] org.mule.api.processor.LoggerMessageProcessor: contact recently modified: {Name=Avi123 Green, LastModifiedDate=2014-07-04T06:16:54.000Z, Id=0032000001DpkrEAAR, type=Contact}
1. Stop the Mule application by clicking the square, red terminate button in the **Console**.

### How it Works ###

Using a single flow, this application queries Salesforce CRM for recently modified contacts and prints them in the console view.

The [Poll Component](http://www.mulesoft.org/documentation/display/current/Poll+Reference) periodically invokes [Salesforce Connector](http://www.mulesoft.org/documentation/display/current/Salesforce+Connector+Reference) to perform a query in your Salesforce account: to get *Id,Name* and *LastModifiedDate* attributes of Contact objects that were modified since the last polling. The polling is set to be executed every 10 seconds right from the start but can be easily changed by accessing component configuration. The polling is executed in the Input Phase of Batch Processing. To keep the example simple, Process Records Phase only prints the obtained records to the console.

The following steps outline the process to build this application.

1. Drop a Batch Scope in your application.
2. Drop a Poll Component in the Input Phase of the Batch enabling the polling mechanism. Set Frequency and Time units to 10 seconds or any time period you wish. Check the Enable watermarking checkbox, set Variable Name to *timestamp* and Default Expression to:

		YESTERDAY

	or to precise time in the following format:

		2015-06-17T10:00:00.000Z

3. Check the Selector checkbox to be able to select how the watermarking variable will be updated. Select *MAX* so the watermarking process updates it to the latest time value. Set the Selector Expression to #payload.LastModifiedDate].
4. Next, put a Salesforce Connector into the Poll Component. At this point, you can configure the connector with your Salesforce account-specific details and test the connection to Salesforce.
3. When you click Test Connection, Mule tests the connection to Salesforce. With a valid username, password and security token, the connection test results in success and Mule saves your global element configurations. If any of the values are invalid, the connection test results in failure, and Mule does not save the global element, prompting you to correct the invalid configurations.
4. Back in the Salesforce connector properties editor, choose **Query** operation from the dropdown menu and set Query Text to

		SELECT Id,Name,LastModifiedDate FROM Contact WHERE LastModifiedDate > #[flowVars['timestamp']]
3. Add a Logger Component to the Process Records Phase of the batch and set Message to

		Contact recently modified: #[payload]
4. The configuration now complete, you can save, then run the application. Modify an existing contact in your Salesforce account and watch it appear in the console.

### Documentation ###

Studio includes a feature that enables you to easily export all the documentation you have recorded for your project. Whenever you want to share your project with others outside the Studio environment, you can export the project's documentation to print, email or share online. Studio's auto-generated documentation includes:

- A visual diagram of the flows in your application
- The XML configuration which corresponds to each flow in your application
- The text you entered in the Notes tab of any building block in your flow

Follow [the procedure](http://www.mulesoft.org/documentation/display/current/Importing+and+Exporting+in+Studio#ImportingandExportinginStudio-ExportingStudioDocumentation) to export auto-generated Studio documentation.

### Go Further ###

- For more information on the Salesforce Connector, see [Salesforce Connector Reference](http://www.mulesoft.org/documentation/display/current/Salesforce+Connector+Reference).
- For more information on Batch processing, see [Batch processing](http://www.mulesoft.org/documentation/display/current/Batch+Processing+Reference).


text:
<?php
$bp_docs_do_theme_compat = is_buddypress() && bp_docs_do_theme_compat( 'docs-loop.php' );
if ( ! $bp_docs_do_theme_compat ) : ?>

<?php endif; ?>

<div class="<?php bp_docs_container_class(); ?>">

<?php include( apply_filters( 'bp_docs_header_template', bp_docs_locate_template( 'docs-header.php' ) ) ) ?>

<?php if ( current_user_can( 'bp_docs_manage_folders' ) && bp_docs_is_folder_manage_view() ) : ?>
	<?php bp_locate_template( 'docs/manage-folders.php', true ) ?>
<?php else : ?>

		<?php bp_docs_directory_breadcrumb() ?>

		<?php bp_docs_info_header() ?>

	<?php if ( bp_docs_enable_folders_for_current_context() ) : ?>

			<?php if ( current_user_can( 'bp_docs_manage_folders' ) ) : ?>

					<a href="<?php bp_docs_manage_folders_url() ?>"><?php _e( 'Manage Folders', 'bp-docs' ) ?>

			<?php endif ?>

				<?php _e( 'Hide Folders', 'bp-docs' ) ?>
				<?php _e( 'Show Folders', 'bp-docs' ) ?>

	<?php endif; ?>

			<?php if ( bp_docs_enable_attachments() ) : ?>

			<?php endif ?>

			<th scope="column" class="title-cell<?php bp_docs_is_current_orderby_class( 'title' ) ?>">
				<a href="<?php bp_docs_order_by_link( 'title' ) ?>"><?php _e( 'Title', 'bp-docs' ); ?>

			<?php if ( ! bp_docs_is_started_by() ) : ?>
				<th scope="column" class="author-cell<?php bp_docs_is_current_orderby_class( 'author' ) ?>">
					<a href="<?php bp_docs_order_by_link( 'author' ) ?>"><?php _e( 'Author', 'bp-docs' ); ?>

			<?php endif; ?>

			<th scope="column" class="created-date-cell<?php bp_docs_is_current_orderby_class( 'created' ) ?>">
				<a href="<?php bp_docs_order_by_link( 'created' ) ?>"><?php _e( 'Created', 'bp-docs' ); ?>

			<th scope="column" class="edited-date-cell<?php bp_docs_is_current_orderby_class( 'modified' ) ?>">
				<a href="<?php bp_docs_order_by_link( 'modified' ) ?>"><?php _e( 'Last Edited', 'bp-docs' ); ?>

			<?php do_action( 'bp_docs_loop_additional_th' ) ?>

	<?php if ( bp_docs_enable_folders_for_current_context() ) : ?>
		<?php /* The '..' row */ ?>
		<?php if ( ! empty( $_GET['folder'] ) ) : ?>

				<?php /* Just to keep things even */ ?>
				<?php if ( bp_docs_enable_attachments() ) : ?>

						<?php bp_docs_attachment_icon() ?>

				<?php endif ?>

					<a href="<?php echo esc_url( bp_docs_get_parent_folder_url() ) ?>" class="up-one-folder"><?php bp_docs_genericon( 'category', 0 ); ?><?php _e( 'Go up one folder', 'bp-docs' ) ?><?php _ex( '..', 'up one folder', 'bp-docs' ) ?>

		<?php endif ?>

		<?php if ( bp_docs_include_folders_in_loop_view() ) : ?>
			<?php foreach ( bp_docs_get_folders() as $folder ) : ?>

					<?php /* Just to keep things even */ ?>
					<?php if ( bp_docs_enable_attachments() ) : ?>

							<?php bp_docs_attachment_icon() ?>

					<?php endif ?>

						<div class="toggleable <?php bp_docs_toggleable_open_or_closed_class(); ?>">
							<a class="toggle-folder" id="expand-folder-<?php echo $folder->ID; ?>" data-folder-id="<?php echo $folder->ID; ?>" href="<?php echo esc_url( bp_docs_get_folder_url( $folder->ID ) ) ?>"><?php bp_docs_genericon( 'expand', $folder->ID ); ?><?php bp_docs_genericon( 'category', $folder->ID ); ?><?php echo esc_html( $folder->post_title ) ?>

			<?php endforeach ?>
		<?php endif; ?>
	<?php endif; /* bp_docs_enable_folders_for_current_context() */ ?>

	<?php $has_docs = false ?>
	<?php if ( bp_docs_has_docs( array( 'update_attachment_cache' => true ) ) ) : ?>
		<?php $has_docs = true ?>
		<?php while ( bp_docs_has_docs() ) : bp_docs_the_doc() ?>
			<tr<?php bp_docs_doc_row_classes(); ?>>
				<?php if ( bp_docs_enable_attachments() ) : ?>

						<?php bp_docs_attachment_icon() ?>

				<?php endif ?>

					<?php bp_docs_genericon( 'document' ); ?><a href="<?php bp_docs_doc_link() ?>"><?php the_title() ?> <?php bp_docs_doc_trash_notice(); ?>

					<?php if ( bp_docs_get_excerpt_length() ) : ?>

							<?php the_excerpt() ?>

					<?php endif ?>

					<?php do_action( 'bp_docs_loop_after_doc_excerpt' ) ?>

						<?php bp_docs_doc_action_links() ?>

					<div class="bp-docs-attachment-drawer" id="bp-docs-attachment-drawer-<?php echo get_the_ID() ?>">
						<?php bp_docs_doc_attachment_drawer() ?>

				<?php if ( ! bp_docs_is_started_by() ) : ?>

						<a href="<?php echo bp_core_get_user_domain( get_the_author_meta( 'ID' ) ) ?>" title="<?php echo bp_core_get_user_displayname( get_the_author_meta( 'ID' ) ) ?>"><?php echo bp_core_get_user_displayname( get_the_author_meta( 'ID' ) ) ?>

				<?php endif; ?>

					<?php echo get_the_date() ?>

					<?php echo get_the_modified_date() ?>

				<?php do_action( 'bp_docs_loop_additional_td' ) ?>

		<?php endwhile ?>
	<?php endif ?>

	<?php if ( $has_docs ) : ?>

				<?php printf( __( 'Viewing %1$s-%2$s of %3$s docs', 'bp-docs' ), bp_docs_get_current_docs_start(), bp_docs_get_current_docs_end(), bp_docs_get_total_docs_num() ); ?>

				<?php bp_docs_paginate_links(); ?>

	<?php else : ?>
	    <?php if ( bp_docs_current_user_can_create_in_context() ) : ?>

<?php printf( __( 'There are no docs for this view. Why not create one?', 'bp-docs' ), bp_docs_get_create_link() ); ?>
		<?php else : ?>

<?php _e( 'There are no docs for this view.', 'bp-docs' ); ?>

	    <?php endif; ?>
	<?php endif; ?>
<?php endif; ?>
<?php bp_docs_ajax_value_inputs(); ?>

<?php if ( ! $bp_docs_do_theme_compat ) : ?>

<?php endif; ?>

redpajama_set_name: RedPajamaGithub


text:
/**
 * Locale specific code.
 */
package org.dictionary.config.locale;


text:
#ifndef RenderThemeMacShared_h
#define RenderThemeMacShared_h

#import "RenderTheme.h"
#import <wtf/HashMap.h>
#import <wtf/RetainPtr.h>

OBJC_CLASS WebCoreRenderThemeNotificationObserver;

namespace WebCore {

class RenderProgress;
class RenderStyle;

class RenderThemeMacShared : public RenderTheme {
public:
    // A method asking if the control changes its tint when the window has focus or not.
    virtual bool controlSupportsTints(const RenderObject*) const;

    // A general method asking if any control tinting is supported at all.
    virtual bool supportsControlTints() const { return true; }

    virtual void adjustRepaintRect(const RenderObject*, IntRect&) OVERRIDE;

    virtual bool isControlStyled(const RenderStyle*, const BorderData&, const FillLayer&, const Color& backgroundColor) const;

    virtual Color platformActiveSelectionBackgroundColor() const;
    virtual Color platformInactiveSelectionBackgroundColor() const;
    virtual Color platformActiveListBoxSelectionBackgroundColor() const;
    virtual Color platformActiveListBoxSelectionForegroundColor() const;
    virtual Color platformInactiveListBoxSelectionBackgroundColor() const;
    virtual Color platformInactiveListBoxSelectionForegroundColor() const;
    virtual Color platformFocusRingColor() const;

    virtual ScrollbarControlSize scrollbarControlSizeForPart(ControlPart) { return SmallScrollbar; }

    virtual void platformColorsDidChange();

    // System fonts.
    virtual void systemFont(int cssValueId, FontDescription&) const;

    virtual int minimumMenuListSize(RenderStyle*) const;

    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const;

#if ENABLE(DATALIST_ELEMENT)
    virtual IntSize sliderTickSize() const OVERRIDE;
    virtual int sliderTickOffsetFromTrackCenter() const OVERRIDE;
#endif

    virtual int popupInternalPaddingLeft(RenderStyle*) const;
    virtual int popupInternalPaddingRight(RenderStyle*) const;
    virtual int popupInternalPaddingTop(RenderStyle*) const;
    virtual int popupInternalPaddingBottom(RenderStyle*) const;

    virtual bool paintCapsLockIndicator(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;

    virtual bool popsMenuByArrowKeys() const OVERRIDE { return true; }

#if ENABLE(METER_ELEMENT)
    virtual IntSize meterSizeForBounds(const RenderMeter*, const IntRect&) const OVERRIDE;
    virtual bool paintMeter(RenderObject*, const PaintInfo&, const IntRect&);
    virtual bool supportsMeter(ControlPart) const;
#endif

#if ENABLE(PROGRESS_ELEMENT)
    // Returns the repeat interval of the animation for the progress bar.
    virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const;
    // Returns the duration of the animation for the progress bar.
    virtual double animationDurationForProgressBar(RenderProgress*) const;
#endif

    virtual Color systemColor(int cssValueId) const;
    // Controls color values returned from platformFocusRingColor(). systemColor() will be used when false.
    virtual bool usesTestModeFocusRingColor() const;
    // A view associated to the contained document. Subclasses may not have such a view and return a fake.
    virtual NSView* documentViewFor(RenderObject*) const = 0;

protected:
    RenderThemeMacShared();
    virtual ~RenderThemeMacShared();

    virtual bool supportsSelectionForegroundColors() const { return false; }

    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const;

#if ENABLE(PROGRESS_ELEMENT)
    virtual void adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const;
    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
#endif

    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustSliderTrackStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustSliderThumbStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&);
    virtual void adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const;

    virtual void adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
    virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&);

    virtual void adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
    virtual bool paintSearchFieldDecoration(RenderObject*, const PaintInfo&, const IntRect&);

    virtual void adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const;
    virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&);

    virtual void adjustSearchFieldResultsButtonStyle(StyleResolver*, RenderStyle*, Element*) const;
    virtual bool paintSearchFieldResultsButton(RenderObject*, const PaintInfo&, const IntRect&);

#if ENABLE(VIDEO)
    virtual void adjustMediaSliderThumbSize(RenderStyle*) const = 0;
    virtual bool supportsClosedCaptioning() const { return true; }
#endif

    virtual bool shouldShowPlaceholderWhenFocused() const;

private:
    virtual String fileListNameForWidth(const FileList*, const Font&, int width, bool multipleFilesAllowed) const OVERRIDE;

    IntRect inflateRect(const IntRect&, const IntSize&, const int* margins, float zoomLevel = 1.0f) const;

    FloatRect convertToPaintingRect(const RenderObject* inputRenderer, const RenderObject* partRenderer, const FloatRect& inputRect, const IntRect&) const;

    // Get the control size based off the font. Used by some of the controls (like buttons).
    NSControlSize controlSizeForFont(RenderStyle*) const;
    NSControlSize controlSizeForSystemFont(RenderStyle*) const;
    void setControlSize(NSCell*, const IntSize* sizes, const IntSize& minSize, float zoomLevel = 1.0f);
    void setSizeFromFont(RenderStyle*, const IntSize* sizes) const;
    IntSize sizeForFont(RenderStyle*, const IntSize* sizes) const;
    IntSize sizeForSystemFont(RenderStyle*, const IntSize* sizes) const;
    void setFontFromControlSize(StyleResolver*, RenderStyle*, NSControlSize) const;

    void updateCheckedState(NSCell*, const RenderObject*);
    void updateEnabledState(NSCell*, const RenderObject*);
    void updateFocusedState(NSCell*, const RenderObject*);
    void updatePressedState(NSCell*, const RenderObject*);
    // An optional hook for subclasses to update the control tint of NSCell.
    virtual void updateActiveState(NSCell*, const RenderObject*) { }

    // Helpers for adjusting appearance and for painting

    void setPopupButtonCellState(const RenderObject*, const IntRect&);
    const IntSize* popupButtonSizes() const;
    const int* popupButtonMargins() const;
    const int* popupButtonPadding(NSControlSize) const;
    void paintMenuListButtonGradients(RenderObject*, const PaintInfo&, const IntRect&);
    const IntSize* menuListSizes() const;

    const IntSize* searchFieldSizes() const;
    const IntSize* cancelButtonSizes() const;
    const IntSize* resultsButtonSizes() const;
    void setSearchCellState(RenderObject*, const IntRect&);
    void setSearchFieldSize(RenderStyle*) const;

    NSPopUpButtonCell* popupButton() const;
    NSSearchFieldCell* search() const;
    NSMenu* searchMenuTemplate() const;
    NSSliderCell* sliderThumbHorizontal() const;
    NSSliderCell* sliderThumbVertical() const;
    NSTextFieldCell* textField() const;

#if ENABLE(METER_ELEMENT)
    NSLevelIndicatorStyle levelIndicatorStyleFor(ControlPart) const;
    NSLevelIndicatorCell* levelIndicatorFor(const RenderMeter*) const;
#endif

#if ENABLE(PROGRESS_ELEMENT)
    int minimumProgressBarHeight(RenderStyle*) const;
    const IntSize* progressBarSizes() const;
    const int* progressBarMargins(NSControlSize) const;
#endif

private:
    mutable RetainPtr<NSPopUpButtonCell> m_popupButton;
    mutable RetainPtr<NSSearchFieldCell> m_search;
    mutable RetainPtr<NSMenu> m_searchMenuTemplate;
    mutable RetainPtr<NSSliderCell> m_sliderThumbHorizontal;
    mutable RetainPtr<NSSliderCell> m_sliderThumbVertical;
    mutable RetainPtr<NSLevelIndicatorCell> m_levelIndicator;
    mutable RetainPtr<NSTextFieldCell> m_textField;

    bool m_isSliderThumbHorizontalPressed;
    bool m_isSliderThumbVerticalPressed;

    mutable HashMap<int, RGBA32> m_systemColorCache;

    RetainPtr<WebCoreRenderThemeNotificationObserver> m_notificationObserver;
};

} // namespace WebCore

#endif // RenderThemeMacShared_h


text:
require 'rails/generators/base'
module ZapierRestHooks
  class InstallGenerator < Rails::Generators::Base
    include Rails::Generators::Migration
    source_root File.expand_path('templates', __dir__)
    require 'rails/generators/migration'

    desc 'Mounts ZapierRestHooks in routes and copies migrations.'

    def mount_in_routes
      route 'mount ZapierRestHooks::Engine, at: "/hooks"'
    end

    def copy_migrations
      require 'rake'
      Rails.application.load_tasks
      Rake::Task['railties:install:migrations'].reenable
      Rake::Task['zapier_rest_hooks:install:migrations'].invoke
    end
  end
end


text:
.class public abstract Landroid/net/IEthernetManager$Stub;
.super Landroid/os/Binder;
.source "IEthernetManager.java"

# interfaces
.implements Landroid/net/IEthernetManager;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/IEthernetManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Stub"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/net/IEthernetManager$Stub$Proxy;
    }
.end annotation

# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "android.net.IEthernetManager"

.field static final TRANSACTION_addListener:I = 0x4

.field static final TRANSACTION_getConfiguration:I = 0x1

.field static final TRANSACTION_isAvailable:I = 0x3

.field static final TRANSACTION_removeListener:I = 0x5

.field static final TRANSACTION_setConfiguration:I = 0x2

# direct methods
.method public constructor <init>()V
    .registers 2

    .prologue
    .line 17
    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    .line 19
    const-string/jumbo v0, "android.net.IEthernetManager"

    invoke-virtual {p0, p0, v0}, Landroid/net/IEthernetManager$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    .line 17
    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Landroid/net/IEthernetManager;
    .registers 3
    .param p0, "obj"    # Landroid/os/IBinder;

    .prologue
    const/4 v1, 0x0

    .line 27
    if-nez p0, :cond_4

    .line 28
    return-object v1

    .line 30
    :cond_4
    const-string/jumbo v1, "android.net.IEthernetManager"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    .line 31
    .local v0, "iin":Landroid/os/IInterface;
    if-eqz v0, :cond_14

    instance-of v1, v0, Landroid/net/IEthernetManager;

    if-eqz v1, :cond_14

    .line 32
    check-cast v0, Landroid/net/IEthernetManager;

    .end local v0    # "iin":Landroid/os/IInterface;
    return-object v0

    .line 34
    .restart local v0    # "iin":Landroid/os/IInterface;
    :cond_14
    new-instance v1, Landroid/net/IEthernetManager$Stub$Proxy;

    invoke-direct {v1, p0}, Landroid/net/IEthernetManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V

    return-object v1
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .registers 1

    .prologue
    .line 38
    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .registers 12
    .param p1, "code"    # I
    .param p2, "data"    # Landroid/os/Parcel;
    .param p3, "reply"    # Landroid/os/Parcel;
    .param p4, "flags"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v4, 0x0

    const/4 v5, 0x1

    .line 42
    sparse-switch p1, :sswitch_data_86

    .line 104
    invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v4

    return v4

    .line 46
    :sswitch_a
    const-string/jumbo v4, "android.net.IEthernetManager"

    invoke-virtual {p3, v4}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 47
    return v5

    .line 51
    :sswitch_11
    const-string/jumbo v6, "android.net.IEthernetManager"

    invoke-virtual {p2, v6}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 52
    invoke-virtual {p0}, Landroid/net/IEthernetManager$Stub;->getConfiguration()Landroid/net/IpConfiguration;

    move-result-object v2

    .line 53
    .local v2, "_result":Landroid/net/IpConfiguration;
    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    .line 54
    if-eqz v2, :cond_27

    .line 55
    invoke-virtual {p3, v5}, Landroid/os/Parcel;->writeInt(I)V

    .line 56
    invoke-virtual {v2, p3, v5}, Landroid/net/IpConfiguration;->writeToParcel(Landroid/os/Parcel;I)V

    .line 61
    :goto_26
    return v5

    .line 59
    :cond_27
    invoke-virtual {p3, v4}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_26

    .line 65
    .end local v2    # "_result":Landroid/net/IpConfiguration;
    :sswitch_2b
    const-string/jumbo v4, "android.net.IEthernetManager"

    invoke-virtual {p2, v4}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 67
    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v4

    if-eqz v4, :cond_46

    .line 68
    sget-object v4, Landroid/net/IpConfiguration;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v4, p2}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/net/IpConfiguration;

    .line 73
    :goto_3f
    invoke-virtual {p0, v1}, Landroid/net/IEthernetManager$Stub;->setConfiguration(Landroid/net/IpConfiguration;)V

    .line 74
    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    .line 75
    return v5

    .line 71
    :cond_46
    const/4 v1, 0x0

    .local v1, "_arg0":Landroid/net/IpConfiguration;
    goto :goto_3f

    .line 79
    .end local v1    # "_arg0":Landroid/net/IpConfiguration;
    :sswitch_48
    const-string/jumbo v6, "android.net.IEthernetManager"

    invoke-virtual {p2, v6}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 80
    invoke-virtual {p0}, Landroid/net/IEthernetManager$Stub;->isAvailable()Z

    move-result v3

    .line 81
    .local v3, "_result":Z
    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    .line 82
    if-eqz v3, :cond_58

    move v4, v5

    :cond_58
    invoke-virtual {p3, v4}, Landroid/os/Parcel;->writeInt(I)V

    .line 83
    return v5

    .line 87
    .end local v3    # "_result":Z
    :sswitch_5c
    const-string/jumbo v4, "android.net.IEthernetManager"

    invoke-virtual {p2, v4}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 89
    invoke-virtual {p2}, Landroid/os/Parcel;->readStrongBinder()Landroid/os/IBinder;

    move-result-object v4

    invoke-static {v4}, Landroid/net/IEthernetServiceListener$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/IEthernetServiceListener;

    move-result-object v0

    .line 90
    .local v0, "_arg0":Landroid/net/IEthernetServiceListener;
    invoke-virtual {p0, v0}, Landroid/net/IEthernetManager$Stub;->addListener(Landroid/net/IEthernetServiceListener;)V

    .line 91
    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    .line 92
    return v5

    .line 96
    .end local v0    # "_arg0":Landroid/net/IEthernetServiceListener;
    :sswitch_71
    const-string/jumbo v4, "android.net.IEthernetManager"

    invoke-virtual {p2, v4}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    .line 98
    invoke-virtual {p2}, Landroid/os/Parcel;->readStrongBinder()Landroid/os/IBinder;

    move-result-object v4

    invoke-static {v4}, Landroid/net/IEthernetServiceListener$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/IEthernetServiceListener;

    move-result-object v0

    .line 99
    .restart local v0    # "_arg0":Landroid/net/IEthernetServiceListener;
    invoke-virtual {p0, v0}, Landroid/net/IEthernetManager$Stub;->removeListener(Landroid/net/IEthernetServiceListener;)V

    .line 100
    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    .line 101
    return v5

    .line 42
    :sswitch_data_86
    .sparse-switch
        0x1 -> :sswitch_11
        0x2 -> :sswitch_2b
        0x3 -> :sswitch_48
        0x4 -> :sswitch_5c
        0x5 -> :sswitch_71
        0x5f4e5446 -> :sswitch_a
    .end sparse-switch
.end method


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

goog.provide('goog.net.xpc.CrossPageChannelTest');
goog.setTestOnly('goog.net.xpc.CrossPageChannelTest');

goog.require('goog.Disposable');
goog.require('goog.Uri');
goog.require('goog.async.Deferred');
goog.require('goog.dom');
goog.require('goog.log');
goog.require('goog.log.Level');
goog.require('goog.net.xpc');
goog.require('goog.net.xpc.CfgFields');
goog.require('goog.net.xpc.CrossPageChannel');
goog.require('goog.net.xpc.CrossPageChannelRole');
goog.require('goog.net.xpc.TransportTypes');
goog.require('goog.object');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');

// Set this to false when working on this test.  It needs to be true for
// automated testing, as some browsers (eg IE8) choke on the large numbers of
// iframes this test would otherwise leave active.
var CLEAN_UP_IFRAMES = true;

var IFRAME_LOAD_WAIT_MS = 1000;
var stubs = new goog.testing.PropertyReplacer();
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(
    document.title);
var uniqueId = 0;
var driver;
var canAccessSameDomainIframe = true;
var accessCheckIframes = [];

function setUpPage() {
  // This test is insanely slow on IE8 for some reason.
  asyncTestCase.stepTimeout = 20 * 1000;

  // Show debug log
  var debugDiv = goog.dom.getElement('debugDiv');
  var logger = goog.log.getLogger('goog.net.xpc');
  logger.setLevel(goog.log.Level.ALL);
  goog.log.addHandler(logger, function(logRecord) {
    var msgElm = goog.dom.createDom('div');
    msgElm.innerHTML = logRecord.getMessage();
    goog.dom.appendChild(debugDiv, msgElm);
  });
  asyncTestCase.waitForAsync('Checking if we can access same domain iframes');
  checkSameDomainIframeAccess();
}

function setUp() {
  driver = new Driver();
}

function tearDown() {
  stubs.reset();
  driver.dispose();
}

function checkSameDomainIframeAccess() {
  accessCheckIframes.push(
      create1x1Iframe('nonexistant', 'testdata/i_am_non_existant.html'));
  window.setTimeout(function() {
    accessCheckIframes.push(
        create1x1Iframe('existant', 'testdata/access_checker.html'));
  }, 10);
}

function create1x1Iframe(iframeId, src) {
  var iframeAccessChecker = goog.dom.createElement('IFRAME');
  iframeAccessChecker.id = iframeAccessChecker.name = iframeId;
  iframeAccessChecker.style.width = iframeAccessChecker.style.height = '1px';
  iframeAccessChecker.src = src;
  document.body.insertBefore(iframeAccessChecker, document.body.firstChild);
  return iframeAccessChecker;
}

function sameDomainIframeAccessComplete(canAccess) {
  canAccessSameDomainIframe = canAccess;
  for (var i = 0; i < accessCheckIframes.length; i++) {
    document.body.removeChild(accessCheckIframes[i]);
  }
  asyncTestCase.continueTesting();
}

function testCreateIframeSpecifyId() {
  driver.createPeerIframe('new_iframe');

  asyncTestCase.waitForAsync('iframe load');
  window.setTimeout(function() {
    driver.checkPeerIframe();
    asyncTestCase.continueTesting();
  }, IFRAME_LOAD_WAIT_MS);
}

function testCreateIframeRandomId() {
  driver.createPeerIframe();

  asyncTestCase.waitForAsync('iframe load');
  window.setTimeout(function() {
    driver.checkPeerIframe();
    asyncTestCase.continueTesting();
  }, IFRAME_LOAD_WAIT_MS);
}

function testGetRole() {
  var cfg = {};
  cfg[goog.net.xpc.CfgFields.ROLE] = goog.net.xpc.CrossPageChannelRole.OUTER;
  var channel = new goog.net.xpc.CrossPageChannel(cfg);
  // If the configured role is ignored, this will cause the dynamicly
  // determined role to become INNER.
  channel.peerWindowObject_ = window.parent;
  assertEquals('Channel should use role from the config.',
      goog.net.xpc.CrossPageChannelRole.OUTER, channel.getRole());
  channel.dispose();
}

// The following batch of tests:
// * Establishes a peer iframe
// * Connects an XPC channel between the frames
// * From the connection callback in each frame, sends an 'echo' request, and
//   expects a 'response' response.
// * Reconnects the inner frame, sends an 'echo', expects a 'response'.
// * Optionally, reconnects the outer frame, sends an 'echo', expects a
//   'response'.
// * Optionally, reconnects the inner frame, but first reconfigures it to the
//   alternate protocol version, simulating an inner frame navigation that
//   picks up a new/old version.
//
// Every valid combination of protocol versions is tested, with both single and
// double ended handshakes.  Two timing scenarios are tested per combination,
// which is what the 'reverse' parameter distinguishes.
//
// Where single sided handshake is in use, reconnection by the outer frame is
// not supported, and therefore is not tested.
//
// The only known issue migrating to V2 is that once two V2 peers have
// connected, replacing either peer with a V1 peer will not work.  Upgrading V1
// peers to v2 is supported, as is replacing the only v2 peer in a connection
// with a v1.

function testLifeCycle_v1_v1() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v1_v1_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v1_v1_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v1_v1_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v1_v2() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v1_v2_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v1_v2_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v1_v2_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v2_v1() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v2_v1_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v2_v1_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v2_v1_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      true /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v2_v2() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v2_v2_rev() {
  checkLifeCycle(
      false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function testLifeCycle_v2_v2_onesided() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      false /* reverse */);
}

function testLifeCycle_v2_v2_onesided_rev() {
  checkLifeCycle(
      true /* oneSidedHandshake */,
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      true /* reverse */);
}

function checkLifeCycle(oneSidedHandshake, innerProtocolVersion,
    outerProtocolVersion, outerFrameReconnectSupported,
    innerFrameMigrationSupported, reverse) {
  driver.createPeerIframe('new_iframe', oneSidedHandshake,
      innerProtocolVersion, outerProtocolVersion);
  driver.connect(true /* fullLifeCycleTest */, outerFrameReconnectSupported,
      innerFrameMigrationSupported, reverse);
}

function testConnectMismatchedNames_v1_v1() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* reverse */);
}

function testConnectMismatchedNames_v1_v1_rev() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* reverse */);
}

function testConnectMismatchedNames_v1_v2() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* reverse */);
}

function testConnectMismatchedNames_v1_v2_rev() {
  checkConnectMismatchedNames(
      1 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* reverse */);
}

function testConnectMismatchedNames_v2_v1() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      false /* reverse */);
}

function testConnectMismatchedNames_v2_v1_rev() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      1 /* outerProtocolVersion */,
      true /* reverse */);
}

function testConnectMismatchedNames_v2_v2() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      false /* reverse */);
}

function testConnectMismatchedNames_v2_v2_rev() {
  checkConnectMismatchedNames(
      2 /* innerProtocolVersion */,
      2 /* outerProtocolVersion */,
      true /* reverse */);
}

function checkConnectMismatchedNames(innerProtocolVersion,
    outerProtocolVersion, reverse) {
  driver.createPeerIframe('new_iframe', false /* oneSidedHandshake */,
      innerProtocolVersion,
      outerProtocolVersion, true /* opt_randomChannelNames */);
  driver.connect(false /* fullLifeCycleTest */,
      false /* outerFrameReconnectSupported */,
      false /* innerFrameMigrationSupported */,
      reverse /* reverse */);
}

function testEscapeServiceName() {
  var escape = goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_;
  assertEquals('Shouldn\'t escape alphanumeric name',
               'fooBar123', escape('fooBar123'));
  assertEquals('Shouldn\'t escape most non-alphanumeric characters',
               '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
               escape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
  assertEquals('Should escape %, |, and :',
               'foo%3ABar%7C123%25', escape('foo:Bar|123%'));
  assertEquals('Should escape tp', '%25tp', escape('tp'));
  assertEquals('Should escape %tp', '%25%25tp', escape('%tp'));
  assertEquals('Should not escape stp', 'stp', escape('stp'));
  assertEquals('Should not escape s%tp', 's%25tp', escape('s%tp'));
}

function testSameDomainCheck_noMessageOrigin() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertTrue(channel.isMessageOriginAcceptable_(undefined));
}

function testSameDomainCheck_noPeerHostname() {
  var channel = new goog.net.xpc.CrossPageChannel({});
  assertTrue(channel.isMessageOriginAcceptable_('http://foo.com'));
}

function testSameDomainCheck_unconfigured() {
  var channel = new goog.net.xpc.CrossPageChannel({});
  assertTrue(channel.isMessageOriginAcceptable_(undefined));
}

function testSameDomainCheck_originsMatch() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertTrue(channel.isMessageOriginAcceptable_('http://foo.com'));
}

function testSameDomainCheck_originsMismatch() {
  var channel = new goog.net.xpc.CrossPageChannel(goog.object.create(
      goog.net.xpc.CfgFields.PEER_HOSTNAME, 'http://foo.com'));
  assertFalse(channel.isMessageOriginAcceptable_('http://nasty.com'));
}

function testUnescapeServiceName() {
  var unescape = goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_;
  assertEquals('Shouldn\'t modify alphanumeric name',
               'fooBar123', unescape('fooBar123'));
  assertEquals('Shouldn\'t modify most non-alphanumeric characters',
               '`~!@#$^&*()_-=+ []{}\'";,<.>/?\\',
               unescape('`~!@#$^&*()_-=+ []{}\'";,<.>/?\\'));
  assertEquals('Should unescape URL-escapes',
               'foo:Bar|123%', unescape('foo%3ABar%7C123%25'));
  assertEquals('Should unescape tp', 'tp', unescape('%25tp'));
  assertEquals('Should unescape %tp', '%tp', unescape('%25%25tp'));
  assertEquals('Should not escape stp', 'stp', unescape('stp'));
  assertEquals('Should not escape s%tp', 's%tp', unescape('s%25tp'));
}

/**
 * Tests the case where the channel is disposed before it is fully connected.
 */
function testDisposeBeforeConnect() {
  asyncTestCase.waitForAsync('Checking disposal before connection.');
  driver.createPeerIframe('new_iframe', false /* oneSidedHandshake */,
      2 /* innerProtocolVersion */, 2 /* outerProtocolVersion */,
      true /* opt_randomChannelNames */);
  driver.connectOuterAndDispose();
}

/**
 * Driver for the tests for CrossPageChannel.
 *
 * @constructor
 * @extends {goog.Disposable}
 */
Driver = function() {
  goog.Disposable.call(this);

  /**
   * The peer iframe.
   * @type {!Element}
   * @private
   */
  this.iframe_ = null;

  /**
   * The channel to use.
   * @type {goog.net.xpc.CrossPageChannel}
   * @private
   */
  this.channel_ = null;

  /**
   * Outer frame configuration object.
   * @type {Object}
   * @private
   */
  this.outerFrameCfg_ = null;

  /**
   * The initial name of the outer channel.
   * @type {?string}
   * @private
   */
  this.initialOuterChannelName_ = null;

  /**
   * Inner frame configuration object.
   * @type {Object}
   * @private
   */
  this.innerFrameCfg_ = null;

  /**
   * The contents of the payload of the 'echo' request sent by the inner frame.
   * @type {?string}
   * @private
   */
  this.innerFrameEchoPayload_ = null;

  /**
   * The contents of the payload of the 'echo' request sent by the outer frame.
   * @type {?string}
   * @private
   */
  this.outerFrameEchoPayload_ = null;

  /**
   * A deferred which fires when the inner frame receives its echo response.
   * @type {goog.async.Deferred}
   * @private
   */
  this.innerFrameResponseReceived_ = new goog.async.Deferred();

  /**
   * A deferred which fires when the outer frame receives its echo response.
   * @type {goog.async.Deferred}
   * @private
   */
  this.outerFrameResponseReceived_ = new goog.async.Deferred();

};
goog.inherits(Driver, goog.Disposable);

/** @override */
Driver.prototype.disposeInternal = function() {
  // Required to make this test perform acceptably (and pass) on slow browsers,
  // esp IE8.
  if (CLEAN_UP_IFRAMES) {
    goog.dom.removeNode(this.iframe_);
    delete this.iframe_;
  }
  goog.dispose(this.channel_);
  this.innerFrameResponseReceived_.cancel();
  this.innerFrameResponseReceived_ = null;
  this.outerFrameResponseReceived_.cancel();
  this.outerFrameResponseReceived_ = null;
  Driver.base(this, 'disposeInternal');
};

/**
 * Returns the child peer's window object.
 * @return {Window} Child peer's window.
 * @private
 */
Driver.prototype.getInnerPeer_ = function() {
  return this.iframe_.contentWindow;
};

/**
 * Sets up the configuration objects for the inner and outer frames.
 * @param {string=} opt_iframeId If present, the ID of the iframe to use,
 *     otherwise, tells the channel to generate an iframe ID.
 * @param {boolean=} opt_oneSidedHandshake Whether the one sided handshake
 *     config option should be set.
 * @param {string=} opt_channelName The name of the channel to use, or null
 *     to generate one.
 * @param {number=} opt_innerProtocolVersion The native transport protocol
 *     version used in the inner iframe.
 * @param {number=} opt_outerProtocolVersion The native transport protocol
 *     version used in the outer iframe.
 * @param {boolean=} opt_randomChannelNames Whether the different ends of the
 *     channel should be allowed to pick differing, random names.
 * @return {string} The name of the created channel.
 * @private
 */
Driver.prototype.setConfiguration_ = function(opt_iframeId,
    opt_oneSidedHandshake, opt_channelName, opt_innerProtocolVersion,
    opt_outerProtocolVersion, opt_randomChannelNames) {
  var cfg = {};
  if (opt_iframeId) {
    cfg[goog.net.xpc.CfgFields.IFRAME_ID] = opt_iframeId;
  }
  cfg[goog.net.xpc.CfgFields.PEER_URI] = 'testdata/inner_peer.html';
  if (!opt_randomChannelNames) {
    var channelName = opt_channelName || 'test_channel' + uniqueId++;
    cfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = channelName;
  }
  cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = 'does-not-exist.html';
  cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = 'does-not-exist.html';
  cfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] = !!opt_oneSidedHandshake;
  cfg[goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
      opt_outerProtocolVersion;
  function resolveUri(fieldName) {
    cfg[fieldName] =
        goog.Uri.resolve(window.location.href, cfg[fieldName]).toString();
  }
  resolveUri(goog.net.xpc.CfgFields.PEER_URI);
  resolveUri(goog.net.xpc.CfgFields.LOCAL_POLL_URI);
  resolveUri(goog.net.xpc.CfgFields.PEER_POLL_URI);
  this.outerFrameCfg_ = cfg;
  this.innerFrameCfg_ = goog.object.clone(cfg);
  this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
      opt_innerProtocolVersion;
};

/**
 * Creates an outer frame channel object.
 * @private
 */
Driver.prototype.createChannel_ = function() {
  if (this.channel_) {
    this.channel_.dispose();
  }
  this.channel_ = new goog.net.xpc.CrossPageChannel(this.outerFrameCfg_);
  this.channel_.registerService('echo',
      goog.bind(this.echoHandler_, this));
  this.channel_.registerService('response',
      goog.bind(this.responseHandler_, this));

  return this.channel_.name;
};

/**
 * Checks the names of the inner and outer frames meet expectations.
 * @private
 */
Driver.prototype.checkChannelNames_ = function() {
  var outerName = this.channel_.name;
  var innerName = this.getInnerPeer_().channel.name;
  var configName = this.innerFrameCfg_[goog.net.xpc.CfgFields.CHANNEL_NAME] ||
      null;

  // The outer channel never changes its name.
  assertEquals(this.initialOuterChannelName_, outerName);
  // The name should be as configured, if it was configured.
  if (configName) {
    assertEquals(configName, innerName);
  }
  // The names of both ends of the channel should match.
  assertEquals(innerName, outerName);
  G_testRunner.log('Channel name: ' + innerName);
};

/**
 * Returns the configuration of the xpc.
 * @return {?Object} The configuration of the xpc.
 */
Driver.prototype.getInnerFrameConfiguration = function() {
  return this.innerFrameCfg_;
};

/**
 * Creates the peer iframe.
 * @param {string=} opt_iframeId If present, the ID of the iframe to create,
 *     otherwise, generates an iframe ID.
 * @param {boolean=} opt_oneSidedHandshake Whether a one sided handshake is
 *     specified.
 * @param {number=} opt_innerProtocolVersion The native transport protocol
 *     version used in the inner iframe.
 * @param {number=} opt_outerProtocolVersion The native transport protocol
 *     version used in the outer iframe.
 * @param {boolean=} opt_randomChannelNames Whether the ends of the channel
 *     should be allowed to pick differing, random names.
 * @return {!Array<string>} The id of the created iframe and the name of the
 *     created channel.
 */
Driver.prototype.createPeerIframe = function(opt_iframeId,
    opt_oneSidedHandshake, opt_innerProtocolVersion, opt_outerProtocolVersion,
    opt_randomChannelNames) {
  var expectedIframeId;

  if (opt_iframeId) {
    expectedIframeId = opt_iframeId = opt_iframeId + uniqueId++;
  } else {
    // Have createPeerIframe() generate an ID
    stubs.set(goog.net.xpc, 'getRandomString', function(length) {
      return '' + length;
    });
    expectedIframeId = 'xpcpeer4';
  }
  assertNull('element[id=' + expectedIframeId + '] exists',
      goog.dom.getElement(expectedIframeId));

  this.setConfiguration_(opt_iframeId, opt_oneSidedHandshake,
      undefined /* opt_channelName */, opt_innerProtocolVersion,
      opt_outerProtocolVersion, opt_randomChannelNames);
  var channelName = this.createChannel_();
  this.initialOuterChannelName_ = channelName;
  this.iframe_ = this.channel_.createPeerIframe(document.body);

  assertEquals(expectedIframeId, this.iframe_.id);
};

/**
 * Checks if the peer iframe has been created.
 */
Driver.prototype.checkPeerIframe = function() {
  assertNotNull(this.iframe_);
  var peer = this.getInnerPeer_();
  assertNotNull(peer);
  assertNotNull(peer.document);
};

/**
 * Starts the connection. The connection happens asynchronously.
 */
Driver.prototype.connect = function(fullLifeCycleTest,
    outerFrameReconnectSupported, innerFrameMigrationSupported, reverse) {
  if (!this.isTransportTestable_()) {
    asyncTestCase.continueTesting();
    return;
  }

  asyncTestCase.waitForAsync('parent and child connect');

  // Set the criteria for the initial handshake portion of the test.
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.awaitDeferred(
      this.outerFrameResponseReceived_);
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));

  if (fullLifeCycleTest) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.testReconnects_, this,
            outerFrameReconnectSupported, innerFrameMigrationSupported));
  } else {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }

  this.continueConnect_(reverse);
};

Driver.prototype.continueConnect_ = function(reverse) {
  // Wait until the peer is fully established.  Establishment is sometimes very
  // slow indeed, especially on virtual machines, so a fixed timeout is not
  // suitable.  This wait is required because we want to take precise control
  // of the channel startup timing, and shouldn't be needed in production use,
  // where the inner frame's channel is typically not started by a DOM call as
  // it is here.
  if (!this.getInnerPeer_() || !this.getInnerPeer_().instantiateChannel) {
    window.setTimeout(goog.bind(this.continueConnect_, this, reverse), 100);
    return;
  }

  var connectFromOuterFrame = goog.bind(this.channel_.connect, this.channel_,
      goog.bind(this.outerFrameConnected_, this));
  var innerConfig = this.innerFrameCfg_;
  var connectFromInnerFrame = goog.bind(this.getInnerPeer_().instantiateChannel,
      this.getInnerPeer_(), innerConfig);

  // Take control of the timing and reverse of each frame's first SETUP call. If
  // these happen to fire right on top of each other, that tends to mask
  // problems that reliably occur when there is a short delay.
  window.setTimeout(connectFromOuterFrame, reverse ? 1 : 10);
  window.setTimeout(connectFromInnerFrame, reverse ? 10 : 1);
};

/**
 * Called by the outer frame connection callback.
 * @private
 */
Driver.prototype.outerFrameConnected_ = function() {
  var payload = this.outerFrameEchoPayload_ =
      goog.net.xpc.getRandomString(10);
  this.channel_.send('echo', payload);
};

/**
 * Called by the inner frame connection callback.
 */
Driver.prototype.innerFrameConnected = function() {
  var payload = this.innerFrameEchoPayload_ =
      goog.net.xpc.getRandomString(10);
  this.getInnerPeer_().sendEcho(payload);
};

/**
 * The handler function for incoming echo requests.
 * @param {string} payload The message payload.
 * @private
 */
Driver.prototype.echoHandler_ = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  this.channel_.send('response', payload);
};

/**
 * The handler function for incoming echo responses.
 * @param {string} payload The message payload.
 * @private
 */
Driver.prototype.responseHandler_ = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  assertEquals(this.outerFrameEchoPayload_, payload);
  this.outerFrameResponseReceived_.callback(true);
};

/**
 * The handler function for incoming echo replies.
 * @param {string} payload The message payload.
 */
Driver.prototype.innerFrameGotResponse = function(payload) {
  assertTrue('outer frame should be connected', this.channel_.isConnected());
  var peer = this.getInnerPeer_();
  assertTrue('child should be connected', peer.isConnected());
  assertEquals(this.innerFrameEchoPayload_, payload);
  this.innerFrameResponseReceived_.callback(true);
};

/**
 * The second phase of the standard test, where reconnections of both the inner
 * and outer frames are performed.
 * @param {boolean} outerFrameReconnectSupported Whether outer frame reconnects
 *     are supported, and should be tested.
 * @private
 */
Driver.prototype.testReconnects_ = function(outerFrameReconnectSupported,
    innerFrameMigrationSupported) {
  G_testRunner.log('Performing inner frame reconnect');
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));

  if (outerFrameReconnectSupported) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.performOuterFrameReconnect_, this,
            innerFrameMigrationSupported));
  } else if (innerFrameMigrationSupported) {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(this.migrateInnerFrame_, this));
  } else {
    this.innerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }

  this.performInnerFrameReconnect_();
};

/**
 * Initializes the deferreds and clears the echo payloads, ready for another
 * sub-test.
 * @private
 */
Driver.prototype.reinitializeDeferreds_ = function() {
  this.innerFrameEchoPayload_ = null;
  this.outerFrameEchoPayload_ = null;
  this.innerFrameResponseReceived_.cancel();
  this.innerFrameResponseReceived_ = new goog.async.Deferred();
  this.outerFrameResponseReceived_.cancel();
  this.outerFrameResponseReceived_ = new goog.async.Deferred();
};

/**
 * Get the inner frame to reconnect, and repeat the echo test.
 * @private
 */
Driver.prototype.performInnerFrameReconnect_ = function() {
  var peer = this.getInnerPeer_();
  peer.instantiateChannel(this.innerFrameCfg_);
};

/**
 * Get the outer frame to reconnect, and repeat the echo test.
 * @private
 */
Driver.prototype.performOuterFrameReconnect_ = function(
    innerFrameMigrationSupported) {
  G_testRunner.log('Closing channel');
  this.channel_.close();

  // If there is another channel still open, the native transport's global
  // postMessage listener will still be active.  This will mean that messages
  // being sent to the now-closed channel will still be received and delivered,
  // such as transport service traffic from its previous correspondent in the
  // other frame.  Ensure these messages don't cause exceptions.
  try {
    this.channel_.xpcDeliver(goog.net.xpc.TRANSPORT_SERVICE_, 'payload');
  } catch (e) {
    fail('Should not throw exception');
  }

  G_testRunner.log('Reconnecting outer frame');
  this.reinitializeDeferreds_();
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));
  if (innerFrameMigrationSupported) {
    this.outerFrameResponseReceived_.addCallback(
        goog.bind(this.migrateInnerFrame_, this));
  } else {
    this.outerFrameResponseReceived_.addCallback(
        goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  }
  this.channel_.connect(goog.bind(this.outerFrameConnected_, this));
};

/**
 * Migrate the inner frame to the alternate protocol version and reconnect it.
 * @private
 */
Driver.prototype.migrateInnerFrame_ = function() {
  G_testRunner.log('Migrating inner frame');
  this.reinitializeDeferreds_();
  var innerFrameProtoVersion = this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION];
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(this.checkChannelNames_, this));
  this.innerFrameResponseReceived_.addCallback(
      goog.bind(asyncTestCase.continueTesting, asyncTestCase));
  this.innerFrameCfg_[
      goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] =
      innerFrameProtoVersion == 1 ? 2 : 1;
  this.performInnerFrameReconnect_();
};

/**
 * Determines if the transport type for the channel is testable.
 * Some transports are misusing global state or making other
 * assumptions that cause connections to fail.
 * @return {boolean} Whether the transport is testable.
 * @private
 */
Driver.prototype.isTransportTestable_ = function() {
  var testable = false;

  var transportType = this.channel_.determineTransportType_();
  switch (transportType) {
    case goog.net.xpc.TransportTypes.IFRAME_RELAY:
    case goog.net.xpc.TransportTypes.IFRAME_POLLING:
      testable = canAccessSameDomainIframe;
      break;
    case goog.net.xpc.TransportTypes.NATIVE_MESSAGING:
    case goog.net.xpc.TransportTypes.FLASH:
    case goog.net.xpc.TransportTypes.DIRECT:
    case goog.net.xpc.TransportTypes.NIX:
      testable = true;
      break;
  }

  return testable;
};

/**
 * Connect the outer channel but not the inner one.  Wait a short time, then
 * dispose the outer channel and make sure it was torn down properly.
 */
Driver.prototype.connectOuterAndDispose = function() {
  this.channel_.connect();
  window.setTimeout(goog.bind(this.disposeAndCheck_, this), 2000);
};

/**
 * Dispose the cross-page channel. Check that the transport was also
 * disposed, and allow to run briefly to make sure no timers which will cause
 * failures are still running.
 * @private
 */
Driver.prototype.disposeAndCheck_ = function() {
  assertFalse(this.channel_.isConnected());
  var transport = this.channel_.transport_;
  this.channel_.dispose();
  assertNull(this.channel_.transport_);
  assertTrue(this.channel_.isDisposed());
  assertTrue(transport.isDisposed());

  // Let any errors caused by erroneous retries happen.
  window.setTimeout(goog.bind(asyncTestCase.continueTesting, asyncTestCase),
      2000);
};


text:
/**
 *
 */
package me.learn.personal.month5;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

/**
 * Title 1245 :
 *
 * Date : Dec 27, 2020
 *
 * @author bramanarayan
 *
 */
public class DiameterOfUnDirectedTree {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	// Find the diameter of undirected (bidirectional) Tree. Note that this is not a
	// binary tree.
	// This is the most famous problem in Google. Nodes are numbered from 0 to ..

	public int treeDiameter(int[][] edges) {

		int n = edges.length + 1;

		// Initialization of graph as adjacency list
		List<Set<Integer>> adjList = new ArrayList<Set<Integer>>();
		for (int i = 0; i < edges.length + 1; ++i) {
			adjList.add(new HashSet<Integer>());
		}

		// Edge (u ----> v)
		for (int[] edge : edges) {
			Integer u = edge[0], v = edge[1];
			adjList.get(u).add(v);
			adjList.get(v).add(u);
		}

		// 1). find one of the farthest nodes(LEAF) farthest_node, distance_1 = bfs(0)
		Node fathestNode = bfs(0, n, adjList);

		// 2). find the other farthest node (LEAF) and the distance between two farthest nodes
		// another_farthest_node, distance_2 = bfs(farthest_node)
		Node result = bfs(fathestNode.index, n, adjList);

		return result.dist;
	}

	/**
	 * return the farthest node from the 'start' node and the distance between them.
	 */
	private Node bfs(int start, int n, List<Set<Integer>> graph) {

		int[] distance = new int[n];
		Arrays.fill(distance, -1);

		Queue<Integer> q = new LinkedList<Integer>();

		q.add(start);
		distance[start] = 0;

		while (!q.isEmpty()) {
			int u = q.poll();

			Set<Integer> neighbours = graph.get(u); // get all the v's
			for (Integer v : neighbours) {
				if (distance[v] == -1) {
					// not visited yet
					q.add(v);
					distance[v] = distance[u] + 1;
				}
			}
		}

		// Find the maximum distance node
		int node = start;
		int max = -1;
		for (int i = 0; i < distance.length; i++) {
			if (max < distance[i]) {
				max = distance[i];
				node = i;
			}
		}

		return new Node(node, max);

	}

	class Node {
		public Node(int index, int dist) {
			this.index = index; // just an id for node
			this.dist = dist;
		}

		int index;
		int dist;
	}

}


text:
% sig.Spectrum class
%
% Copyright (C) 2014, Olivier Lartillot
%
% All rights reserved.
% License: New BSD License. See full text of the license in LICENSE.txt in
% the main folder of the MiningSuite distribution.

classdef Spectrum < sig.signal
    properties (Constant)
        spectrumsonify = @sonifier;
    end
    properties
        inputsampling
        power = 1;
        log = 0;
        inputlength
        phase
    end
    methods
        function s = Spectrum(varargin)
            i = 1;
            il = NaN;
            ph = [];
            is = [];
            while i < length(varargin)
                if strcmpi(varargin{i},'InputLength')
                    varargin(i) = [];
                    il = varargin{i};
                    varargin(i) = [];
                elseif strcmpi(varargin{i},'Phase')
                    varargin(i) = [];
                    ph = varargin{i};
                    varargin(i) = [];
                elseif strcmpi(varargin{i},'InputSampling')
                    varargin(i) = [];
                    is = varargin{i};
                    varargin(i) = [];
                else
                    i = i+1;
                end
            end
            s = s@sig.signal(varargin{:});
            if strcmp(s.yname,'Signal')
                s.yname = 'Spectrum';
            end
            s.xname = 'Frequency';
            s.xunit = 'Hz';
            s.inputlength = il;
            s.phase = ph;
            s.inputsampling = is;
        end
    end
end

function d = sonifier(d,varargin)
end


text:
package hudson.plugins.ec2;

import hudson.Extension;
import hudson.model.AsyncPeriodicWork;
import hudson.model.TaskListener;
import hudson.model.Node;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import hudson.plugins.ec2.util.MinimumInstanceChecker;
import jenkins.model.Jenkins;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.ec2.model.AmazonEC2Exception;

import static hudson.plugins.ec2.EC2Cloud.EC2_REQUEST_EXPIRED_ERROR_CODE;

/**
 * @author Bruno Meneguello
 */
@Extension
public class EC2SlaveMonitor extends AsyncPeriodicWork {
    private static final Logger LOGGER = Logger.getLogger(EC2SlaveMonitor.class.getName());

    private final Long recurrencePeriod;

    public EC2SlaveMonitor() {
        super("EC2 alive agents monitor");
        recurrencePeriod = Long.getLong("jenkins.ec2.checkAlivePeriod", TimeUnit.MINUTES.toMillis(10));
        LOGGER.log(Level.FINE, "EC2 check alive period is {0}ms", recurrencePeriod);
    }

    @Override
    public long getRecurrencePeriod() {
        return recurrencePeriod;
    }

    @Override
    protected void execute(TaskListener listener) throws IOException, InterruptedException {
        removeDeadNodes();
        MinimumInstanceChecker.checkForMinimumInstances();
    }

    private void removeDeadNodes() {
        for (Node node : Jenkins.get().getNodes()) {
            if (node instanceof EC2AbstractSlave) {
                final EC2AbstractSlave ec2Slave = (EC2AbstractSlave) node;
                try {
                    if (!ec2Slave.isAlive(true)) {
                        LOGGER.info("EC2 instance is dead: " + ec2Slave.getInstanceId());
                        ec2Slave.terminate();
                    }
                } catch (AmazonClientException e) {
                    if (e instanceof AmazonEC2Exception &&
                            EC2_REQUEST_EXPIRED_ERROR_CODE.equals(((AmazonEC2Exception) e).getErrorCode())) {
                        LOGGER.info("EC2 request expired, skipping consideration of " + ec2Slave.getInstanceId() + " due to unknown state.");
                    } else {
                        LOGGER.info("EC2 instance is dead and failed to terminate: " + ec2Slave.getInstanceId());
                        removeNode(ec2Slave);
                    }
                }
            }
        }
    }

    private void removeNode(EC2AbstractSlave ec2Slave) {
        try {
            Jenkins.get().removeNode(ec2Slave);
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to remove node: " + ec2Slave.getInstanceId());
        }
    }

}


text:
var _p = cc.inputManager;

/**
 * whether enable accelerometer event
 * @function
 * @param {Boolean} isEnable
 */
_p.setAccelerometerEnabled = function(isEnable){
    var _t = this;
    if(_t._accelEnabled === isEnable)
        return;

    _t._accelEnabled = isEnable;
    var scheduler = cc.director.getScheduler();
    if(_t._accelEnabled){
        _t._accelCurTime = 0;
        scheduler.scheduleUpdateForTarget(_t);
    } else {
        _t._accelCurTime = 0;
        scheduler.unscheduleUpdateForTarget(_t);
    }
};

/**
 * set accelerometer interval value
 * @function
 * @param {Number} interval
 */
_p.setAccelerometerInterval = function(interval){
    if (this._accelInterval !== interval) {
        this._accelInterval = interval;
    }
};

_p._registerKeyboardEvent = function(){
    cc._addEventListener(cc._canvas, "keydown", function (e) {
        cc.eventManager.dispatchEvent(new cc.EventKeyboard(e.keyCode, true));
        e.stopPropagation();
        e.preventDefault();
    }, false);
    cc._addEventListener(cc._canvas, "keyup", function (e) {
        cc.eventManager.dispatchEvent(new cc.EventKeyboard(e.keyCode, false));
        e.stopPropagation();
        e.preventDefault();
    }, false);
};

_p._registerAccelerometerEvent = function(){
    var w = window, _t = this;
    _t._acceleration = new cc.Acceleration();
    _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent;

    //TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below.
    if (cc.sys.browserType == cc.sys.BROWSER_TYPE_MOBILE_QQ)
        _t._accelDeviceEvent = window.DeviceOrientationEvent;

    var _deviceEventType = (_t._accelDeviceEvent == w.DeviceMotionEvent) ? "devicemotion" : "deviceorientation";
    var ua = navigator.userAgent;
    if (/Android/.test(ua) || (/Adr/.test(ua) && cc.sys.browserType == cc.BROWSER_TYPE_UC)) {
        _t._minus = -1;
    }

    cc._addEventListener(w, _deviceEventType, _t.didAccelerate.bind(_t), false);
};

_p.didAccelerate = function (eventData) {
    var _t = this, w = window;
    if (!_t._accelEnabled)
        return;

    var mAcceleration = _t._acceleration;

    var x, y, z;

    if (_t._accelDeviceEvent == window.DeviceMotionEvent) {
        var eventAcceleration = eventData["accelerationIncludingGravity"];
        x = _t._accelMinus * eventAcceleration.x * 0.1;
        y = _t._accelMinus * eventAcceleration.y * 0.1;
        z = eventAcceleration.z * 0.1;
    } else {
        x = (eventData["gamma"] / 90) * 0.981;
        y = -(eventData["beta"] / 90) * 0.981;
        z = (eventData["alpha"] / 90) * 0.981;
    }

    if(cc.sys.os === cc.sys.OS_ANDROID){
        mAcceleration.x = -x;
        mAcceleration.y = -y;
    }else{
        mAcceleration.x = x;
        mAcceleration.y = y;
    }
    mAcceleration.z = z;

    mAcceleration.timestamp = eventData.timeStamp || Date.now();

    var tmpX = mAcceleration.x;
    if(w.orientation === cc.UIInterfaceOrientationLandscapeRight){
        mAcceleration.x = -mAcceleration.y;
        mAcceleration.y = tmpX;
    }else if(w.orientation === cc.UIInterfaceOrientationLandscapeLeft){
        mAcceleration.x = mAcceleration.y;
        mAcceleration.y = -tmpX;
    }else if(w.orientation === cc.UIInterfaceOrientationPortraitUpsideDown){
        mAcceleration.x = -mAcceleration.x;
        mAcceleration.y = -mAcceleration.y;
    }
};

delete _p;


text:
FOUNDATION_EXPORT double SimonKitVersionNumber;

//! Project version string for SimonKit.
FOUNDATION_EXPORT const unsigned char SimonKitVersionString[];


text:
namespace CG.Contracts.Models
{
    using System;

    public interface IDeletableEntity
    {
        bool IsDeleted { get; set; }

        DateTime? DeletedOn { get; set; }
    }
}


text:
RSpec.describe Licensee::Matchers::DistZilla do
  subject { described_class.new(file) }

  let(:mit) { Licensee::License.find('mit') }
  let(:content) { 'license = MIT' }
  let(:file) { Licensee::ProjectFiles::LicenseFile.new(content, 'dist.ini') }

  it 'stores the file' do
    expect(subject.file).to eql(file)
  end

  it 'has confidence' do
    expect(subject.confidence).to be(90)
  end

  it 'matches' do
    expect(subject.match).to eql(mit)
  end

  {
    'spdx name'     => ['license = MIT', 'mit'],
    'non spdx name' => ['license = Mozilla_2_0', 'mpl-2.0'],
    'other license' => ['license = Foo', 'other']
  }.each do |description, license_declaration_and_key|
    context "with a #{description}" do
      let(:content) { license_declaration_and_key[0] }
      let(:license) { Licensee::License.find(license_declaration_and_key[1]) }

      it 'matches' do
        expect(subject.match).to eql(license)
      end
    end
  end

  context 'no license field' do
    let(:content) { 'foo = bar' }

    it 'returns nil' do
      expect(subject.match).to be_nil
    end
  end
end


text:
pub use rocksdb::{
    new_compaction_filter_raw, run_ldb_tool, run_sst_dump_tool, BlockBasedOptions, CFHandle, Cache,
    ColumnFamilyOptions, CompactOptions, CompactionFilter, CompactionFilterContext,
    CompactionFilterDecision, CompactionFilterFactory, CompactionFilterValueType,
    CompactionJobInfo, CompactionOptions, CompactionPriority, DBBottommostLevelCompaction,
    DBCompactionFilter, DBCompactionStyle, DBCompressionType, DBEntryType, DBInfoLogLevel,
    DBIterator, DBOptions, DBRateLimiterMode, DBRecoveryMode, DBStatisticsTickerType,
    DBTitanDBBlobRunMode, Env, EventListener, IngestExternalFileOptions, LRUCacheOptions,
    MemoryAllocator, PerfContext, Range, ReadOptions, SeekKey, SliceTransform, TableFilter,
    TablePropertiesCollector, TablePropertiesCollectorFactory, TitanBlobIndex, TitanDBOptions,
    Writable, WriteOptions, DB,
};


text:
<?php

namespace Concrete\Core\File;

use Concrete\Core\File\StorageLocation\StorageLocationFactory;

/**
 * A seervice class to manage data in the "incoming" folder.
 */
class Incoming
{
    /**
     * The StorageLocation factory.
     *
     * @var \Concrete\Core\File\StorageLocation\StorageLocationFactory
     */
    protected $storageLocationFactory;

    /**
     * Initialize the instance.
     *
     * @param \Concrete\Core\File\StorageLocation\StorageLocationFactory $storageLocationFactory
     */
    public function __construct(StorageLocationFactory $storageLocationFactory)
    {
        $this->storageLocationFactory = $storageLocationFactory;
    }

    /**
     * Get the path of the "incoming" directory (relative to the incoming filesystem).
     *
     * @return string
     */
    public function getIncomingPath()
    {
        return rtrim(REL_DIR_FILES_INCOMING, '/');
    }

    /**
     * Get the storage location for the "incoming" files.
     *
     * @return \Concrete\Core\Entity\File\StorageLocation\StorageLocation
     */
    public function getIncomingStorageLocation()
    {
        return $this->storageLocationFactory->fetchDefault();
    }

    /**
     * Get the filesystem object to be used to work with the incoming directory.
     *
     * @return \League\Flysystem\FilesystemInterface
     */
    public function getIncomingFilesystem()
    {
        return $this->getIncomingStorageLocation()->getFileSystemObject();
    }
}


text:
package pl.iterators.kebs.support

import pl.iterators.kebs.macros.CaseClass1Rep

trait PartialOrderingSupport {

  implicit def partialOrderingFromCaseClass1Rep[A, Rep](implicit cc1Rep: CaseClass1Rep[A, Rep],
                                                        partialOrderingRep: PartialOrdering[Rep]): PartialOrdering[A] =
    new PartialOrdering[A] {
      override def tryCompare(x: A, y: A): Option[Int] = partialOrderingRep.tryCompare(cc1Rep.unapply(x), cc1Rep.unapply(y))
      override def lteq(x: A, y: A): Boolean           = partialOrderingRep.lteq(cc1Rep.unapply(x), cc1Rep.unapply(y))
    }

}


text:
using System;
using UnityEngine;

public class NcDrawFpsText : MonoBehaviour
{
	public float updateInterval = 0.5f;

	private float accum;

	private int frames;

	private float timeleft;

	private void Start()
	{
		if (!base.guiText)
		{
			Debug.Log("UtilityFramesPerSecond needs a GUIText component!");
			base.enabled = false;
			return;
		}
		this.timeleft = this.updateInterval;
	}

	private void Update()
	{
		this.timeleft -= Time.deltaTime;
		this.accum += Time.timeScale / Time.deltaTime;
		this.frames++;
		if ((double)this.timeleft <= 0.0)
		{
			float num = this.accum / (float)this.frames;
			string text = string.Format("{0:F2} FPS", num);
			base.guiText.text = text;
			if (num < 30f)
			{
				base.guiText.material.color = Color.yellow;
			}
			else if (num < 10f)
			{
				base.guiText.material.color = Color.red;
			}
			else
			{
				base.guiText.material.color = Color.green;
			}
			this.timeleft = this.updateInterval;
			this.accum = 0f;
			this.frames = 0;
		}
	}
}


text:
package org.apereo.cas.shell.commands.jwt;

import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.util.EncodingUtils;
import org.apereo.cas.util.RandomUtils;
import org.apereo.cas.util.serialization.JacksonObjectMapperFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.PlainJWT;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.hjson.JsonValue;
import org.jose4j.jwk.JsonWebKeySet;
import org.jose4j.jwk.PublicJsonWebKey;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * This is {@link GenerateFullJwtCommand}.
 *
 * @author Misagh Moayyed
 * @since 6.6.0
 */
@ShellCommandGroup("JWT")
@ShellComponent
@Slf4j
public class GenerateFullJwtCommand {
    private static final ObjectMapper MAPPER = JacksonObjectMapperFactory.builder()
        .defaultTypingEnabled(false).build().toObjectMapper();

    /**
     * Generate key string.
     *
     * @param jwks   the jwks
     * @param iss    the iss
     * @param claims the claims
     * @param aud    the aud
     * @param exp    the exp
     * @param sub    the sub
     * @return the string
     * @throws Exception the exception
     */
    @ShellMethod(key = "generate-full-jwt", value = "Generate JWT and sign it using a given keystore")
    public String generateKey(
        @ShellOption(value = {"jwks", "--jwks"}, defaultValue = StringUtils.EMPTY, help = "Path to the JWKS file used to sign the token")
        final String jwks,
        @ShellOption(value = {"iss", "--iss"}, defaultValue = "https://localhost:8443/cas/oidc", help = "Issuer")
        final String iss,
        @ShellOption(value = {"claims", "--claims"}, defaultValue = "{}", help = "JWT claims as JSON")
        final String claims,
        @ShellOption(value = {"aud", "--aud"}, defaultValue = "CAS", help = "Audience")
        final String aud,
        @ShellOption(value = {"exp", "--exp"}, defaultValue = "300", help = "Expiration in seconds")
        final String exp,
        @ShellOption(value = {"sub", "--sub"}, help = "Subject")
        final String sub) throws Exception {

        val jwtClaims = new JwtClaims();
        jwtClaims.setJwtId(RandomUtils.randomAlphanumeric(8));
        jwtClaims.setIssuer(iss);
        jwtClaims.setAudience(aud);

        if (NumberUtils.isParsable(exp)) {
            val expireInSeconds = Long.parseLong(exp);
            if (expireInSeconds > 0) {
                val expirationDate = NumericDate.now();
                expirationDate.addSeconds(expireInSeconds);
                jwtClaims.setExpirationTime(expirationDate);
            }
        } else {
            val expirationDate = NumericDate.fromMilliseconds(Beans.newDuration(exp).toSeconds());
            jwtClaims.setExpirationTime(expirationDate);
        }
        jwtClaims.setIssuedAtToNow();
        jwtClaims.setNotBeforeMinutesInThePast(1);
        jwtClaims.setSubject(sub);

        val otherClaims = MAPPER.readValue(JsonValue.readHjson(claims).toString(), Map.class);
        otherClaims.forEach((key, value) -> jwtClaims.setClaim(key.toString(), value));

        if (StringUtils.isNotBlank(jwks)) {
            val keystore = new JsonWebKeySet(FileUtils.readFileToString(new File(jwks), StandardCharsets.UTF_8));
            val jsonWebKey = (PublicJsonWebKey) keystore.getJsonWebKeys()
                .stream()
                .filter(key -> StringUtils.equalsIgnoreCase(key.getUse(), "signing"))
                .findFirst()
                .orElseGet(() -> keystore.getJsonWebKeys().get(0));
            val jwt = EncodingUtils.signJwsRSASha512(jsonWebKey.getPrivateKey(),
                jwtClaims.toJson().getBytes(StandardCharsets.UTF_8), Map.of());
            val token = new String(jwt, StandardCharsets.UTF_8);
            //CHECKSTYLE:OFF
            LOGGER.info("Producing signed JWT:\n{}\n", token);
            //CHECKSTYLE:ON
            return token;
        }
        val jwt = new PlainJWT(JWTClaimsSet.parse(jwtClaims.getClaimsMap()));
        val token = jwt.serialize();
        //CHECKSTYLE:OFF
        LOGGER.info("Producing plain JWT:\n{}\n", token);
        //CHECKSTYLE:ON
        return token;
    }
}


text:
package cz.cuni.mff.xrg.odalic.api.rest.adapters;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import cz.cuni.mff.xrg.odalic.api.rest.values.FeedbackValue;
import cz.cuni.mff.xrg.odalic.api.rest.values.util.Annotations;
import cz.cuni.mff.xrg.odalic.feedbacks.Feedback;

public final class FeedbackAdapter extends XmlAdapter<FeedbackValue, Feedback> {

  @Override
  public FeedbackValue marshal(final Feedback bound) throws Exception {
    return new FeedbackValue(bound);
  }

  @Override
  public Feedback unmarshal(final FeedbackValue value) throws Exception {
    if (value == null) {
      return new Feedback();
    }

    return new Feedback(
        value.getSubjectColumnsPositions() == null ? ImmutableMap.of()
            : Annotations.toColumnPositionsDomain(value.getSubjectColumnsPositions()),
        value.getColumnIgnores() == null ? ImmutableSet.of() : value.getColumnIgnores(),
        value.getColumnCompulsory() == null ? ImmutableSet.of() : value.getColumnCompulsory(),
        value.getColumnAmbiguities() == null ? ImmutableSet.of() : value.getColumnAmbiguities(),
        value.getClassifications() == null ? ImmutableSet.of() : value.getClassifications(),
        value.getColumnRelations() == null ? ImmutableSet.of() : value.getColumnRelations(),
        value.getDisambiguations() == null ? ImmutableSet.of() : value.getDisambiguations(),
        value.getAmbiguities() == null ? ImmutableSet.of() : value.getAmbiguities(),
        value.getDataCubeComponents() == null ? ImmutableSet.of() : value.getDataCubeComponents());
  }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface org.neo4j.graphmatching.ValueMatcher (Neo4j Community 2.0.0 API)</title>
<meta name="date" content="2013-12-08">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Neo4j Community

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.neo4j.graphmatching.ValueMatcher

Packages that use ValueMatcher

Package
Description

org.neo4j.graphmatching

Facilities for finding occurrences of patterns in a Neo4j graph.

Uses of ValueMatcher in org.neo4j.graphmatching

Methods in org.neo4j.graphmatching that return ValueMatcher

Modifier and Type
Method and Description

static ValueMatcher
CommonValueMatchers.exact(Object valueToMatch)

Deprecated.

Checks for equality between a value and valueToMatch.

static ValueMatcher
CommonValueMatchers.exactAny(Object valueToMatch)

Deprecated.

Checks for equality between a value and valueToMatch.

static ValueMatcher
CommonValueMatchers.exactAnyOf(Object... anyOfTheseToMatch)

Deprecated.

Checks for equality between a value and any one of
 anyOfTheseToMatch.

static ValueMatcher
CommonValueMatchers.has()

Deprecated.

Checks that the property exists.

static ValueMatcher
CommonValueMatchers.regex(Pattern pattern)

Deprecated.

Checks that the String property matches the specified regular
 expression pattern.

Methods in org.neo4j.graphmatching that return types with arguments of type ValueMatcher

Modifier and Type
Method and Description

Iterable<Map.Entry<String,Collection<ValueMatcher>>>
AbstractPatternObject.getPropertyConstraints()

Deprecated.

Get all the constraints on the properties of this pattern object.

Methods in org.neo4j.graphmatching with parameters of type ValueMatcher

Modifier and Type
Method and Description

void
AbstractPatternObject.addPropertyConstraint(String propertyKey,
                     ValueMatcher matcher)

Deprecated.

Add a constraint to the property with the given key on this pattern
 object.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Neo4j Community

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002–2013 The Neo4j Graph Database Project. All rights reserved.


text:
<?php

namespace Ens\JobeetBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Ens\JobeetBundle\Entity\Job;
use Ens\JobeetBundle\Form\JobType;

/**
 * Job controller.
 *
 */
class JobController extends Controller
{
    /**
     * Lists all Job entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        //$entities = $em->getRepository('EnsJobeetBundle:Job')->findAll();

        /*$query = $em->createQuery(
            'SELECT j FROM EnsJobeetBundle:Job j WHERE j.expires_at > :date'
        )->setParameter('date', date('Y-m-d H:i:s', time()));
        $entities = $query->getResult();*/

        $entities = $em->getRepository('EnsJobeetBundle:Job')->getActiveJobs();

        $categories = $em->getRepository('EnsJobeetBundle:Category')->getWithJobs();

        foreach($categories as $category)
        {
          $category->setActiveJobs($em->getRepository('EnsJobeetBundle:Job')->getActiveJobs($category->getId(), $this->container->getParameter('max_jobs_on_homepage')));
          $category->setMoreJobs($em->getRepository('EnsJobeetBundle:Job')->countActiveJobs($category->getId()) - $this->container->getParameter('max_jobs_on_homepage'));
        }

        $format = $this->getRequest()->getRequestFormat();

        return $this->render('EnsJobeetBundle:Job:index.'.$format.'.twig', array(
            'categories' => $categories, //'entities' => $entities,
            'lastUpdated' => $em->getRepository('EnsJobeetBundle:Job')->getLatestPost()->getCreatedAt()->format(DATE_ATOM),
            'feedId' => sha1($this->get('router')->generate('ens_job', array('_format'=> 'atom'), true)),
        ));
    }

    /**
     * Finds and displays a Job entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        //$entity = $em->getRepository('EnsJobeetBundle:Job')->find($id);

        $entity = $em->getRepository('EnsJobeetBundle:Job')->getActiveJob($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Job entity.');
        }

        $session = $this->getRequest()->getSession();

        // fetch jobs already stored in the job history
        $jobs = $session->get('job_history', array());

        // store the job as an array so we can put it in the session and avoid entity serialize errors
        $job = array('id' => $entity->getId(), 'position' =>$entity->getPosition(), 'company' => $entity->getCompany(), 'companyslug' => $entity->getCompanySlug(), 'locationslug' => $entity->getLocationSlug(), 'positionslug' => $entity->getPositionSlug());

        if (!in_array($job, $jobs)) {
          // add the current job at the beginning of the array
          array_unshift($jobs, $job);

          // store the new job history back into the session
          $session->set('job_history', array_slice($jobs, 0, 3));
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EnsJobeetBundle:Job:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    public function previewAction($token)
    {
      $em = $this->getDoctrine()->getEntityManager();

      $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

      if (!$entity) {
        throw $this->createNotFoundException('Unable to find Job entity.');
      }

      $deleteForm = $this->createDeleteForm($entity->getId());
      $publishForm = $this->createPublishForm($entity->getToken());
      $extendForm = $this->createExtendForm($entity->getToken());

      return $this->render('EnsJobeetBundle:Job:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
        'publish_form' => $publishForm->createView(),
        'extend_form' => $extendForm->createView(),
      ));
    }

    public function publishAction($token)
    {
      $form = $this->createPublishForm($token);
      $request = $this->getRequest();

      $form->bindRequest($request);

      if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

        if (!$entity) {
          throw $this->createNotFoundException('Unable to find Job entity.');
        }

        $entity->publish();
        $em->persist($entity);
        $em->flush();

        $this->get('session')->setFlash('notice', 'Your job is now online for 30 days.');
      }

      return $this->redirect($this->generateUrl('ens_job_preview', array(
          'company' => $entity->getCompanySlug(),
          'location' => $entity->getLocationSlug(),
          'token' => $entity->getToken(),
          'position' => $entity->getPositionSlug()
      )));
    }

    private function createPublishForm($token)
    {
      return $this->createFormBuilder(array('token' => $token))
      ->add('token', 'hidden')
      ->getForm()
      ;
    }

    /**
     * Displays a form to create a new Job entity.
     *
     */
    public function newAction()
    {
        $entity = new Job();
        $entity->setType('full-time');
        $form   = $this->createForm(new JobType(), $entity);

        return $this->render('EnsJobeetBundle:Job:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a new Job entity.
     *
     */
    public function createAction(Request $request)
    {
      $entity  = new Job();
      $form = $this->createForm(new JobType(), $entity);
      $form->bind($request);

      if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ens_job_preview', array(
          'company' => $entity->getCompanySlug(),
          'location' => $entity->getLocationSlug(),
          'token' => $entity->getToken(),
          'position' => $entity->getPositionSlug()
        )));
      }

      return $this->render('EnsJobeetBundle:Job:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
      ));
    }

    /**
     * Displays a form to edit an existing Job entity.
     *
     */
    public function editAction($token)
    {
      $em = $this->getDoctrine()->getManager();

      $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

      if (!$entity) {
        throw $this->createNotFoundException('Unable to find Job entity.');
      }

      if ($entity->getIsActivated()) {
        throw $this->createNotFoundException('Job is activated and cannot be edited.');
      }

      $editForm = $this->createForm(new JobType(), $entity);
      $deleteForm = $this->createDeleteForm($token);

      return $this->render('EnsJobeetBundle:Job:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
      ));
    }

    /**
     * Edits an existing Job entity.
     *
     */
    public function updateAction(Request $request, $token)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

        if (!$entity) {
          throw $this->createNotFoundException('Unable to find Job entity.');
        }

        $deleteForm = $this->createDeleteForm($token);
        $editForm = $this->createForm(new JobType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
          $em->persist($entity);
          $em->flush();

          return $this->redirect($this->generateUrl('ens_job_preview', array(
            'company' => $entity->getCompanySlug(),
            'location' => $entity->getLocationSlug(),
            'token' => $entity->getToken(),
            'position' => $entity->getPositionSlug()
          )));
        }

        return $this->render('EnsJobeetBundle:Job:edit.html.twig', array(
          'entity'      => $entity,
          'edit_form'   => $editForm->createView(),
          'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Job entity.
     *
     */
    public function deleteAction(Request $request, $token)
    {
      $form = $this->createDeleteForm($token);
      $form->bind($request);

      if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

        if (!$entity) {
          throw $this->createNotFoundException('Unable to find Job entity.');
        }

        $em->remove($entity);
        $em->flush();
      }

      return $this->redirect($this->generateUrl('ens_job'));
    }

    private function createDeleteForm($token)
    {
      return $this->createFormBuilder(array('token' => $token))
        ->add('token', 'hidden')
        ->getForm()
      ;
    }

    public function extendAction($token)
    {
      $form = $this->createExtendForm($token);
      $request = $this->getRequest();

      $form->bindRequest($request);

      if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('EnsJobeetBundle:Job')->findOneByToken($token);

        if (!$entity) {
          throw $this->createNotFoundException('Unable to find Job entity.');
        }

        if (!$entity->extend()) {
          throw $this->createNotFoundException('Unable to find extend the Job.');
        }

        $em->persist($entity);
        $em->flush();

        $this->get('session')->setFlash('notice', sprintf('Your job validity has been extended until %s.', $entity->getExpiresAt()->format('m/d/Y')));
      }

      return $this->redirect($this->generateUrl('ens_job_preview', array(
          'company' => $entity->getCompanySlug(),
          'location' => $entity->getLocationSlug(),
          'token' => $entity->getToken(),
          'position' => $entity->getPositionSlug()
      )));
    }

    private function createExtendForm($token)
    {
      return $this->createFormBuilder(array('token' => $token))
      ->add('token', 'hidden')
      ->getForm()
      ;
    }
}