text:
package com.alibaba.ttl.integration.vertx3;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.agent.TtlAgent;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.DeliveryOptions;
import org.junit.Test;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * @author tk (soulmate.tangk at gmail dot com)
 */
public class VertxTransformletTest {
    @Test
    public void testTransmitThreadLocal_InEventbus() throws Exception {
        final TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();
        final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

        final String transmittedData = "transmitted_data";
        final String inheritedData = "inherited_data_ttl";
        final String message = "message_42";

        final Vertx vertx = Vertx.vertx();
        final String address = "consumer";

        vertx.eventBus().consumer(address, msg -> {
            // be executed in netty event loop thread
            System.out.println("========================================");
            assertEquals(message, msg.body());

            if (TtlAgent.isTtlAgentLoaded()) {
                System.out.println("Test **WITH** TTL Agent");
                assertEquals(transmittedData, transmittableThreadLocal.get());
            } else {
                System.out.println("Test WITHOUT TTL Agent");
                assertNull(transmittableThreadLocal.get());
            }

            // InheritableThreadLocal is always null
            assertNull(inheritableThreadLocal.get());

            System.out.println("========================================");

            msg.reply(message);
        });

        transmittableThreadLocal.set(transmittedData);
        inheritableThreadLocal.set(inheritedData);

        // delivery message
        final DeliveryOptions deliveryOptions = new DeliveryOptions();
        deliveryOptions.setSendTimeout(1000);
        vertx.eventBus().send(address, message, deliveryOptions, event -> {
            System.out.println("receive reply message:" + event.result().body());
        });
    }

    @Test
    public void testCallbackInHttpClient() throws Exception {
        final TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();
        final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
        final String transmittedData = "transmitted_data_ttl";
        final String inheritedData = "inherited_data_ttl";

        final Vertx vertx = Vertx.vertx();

        //set value after eventLoop thread was created
        transmittableThreadLocal.set(transmittedData);
        inheritableThreadLocal.set(inheritedData);

        vertx.createHttpClient().get(80, "bing.com", "/", event -> {
            System.out.println("receive msg:" + event.statusCode());
            System.out.println("===================callback=====================");
            event.bodyHandler(body -> {
                System.out.println("receive response body: " + body.toString(UTF_8));
            });

            if (TtlAgent.isTtlAgentLoaded()) {
                System.out.println("Test **WITH** TTL Agent");
                assertEquals(transmittedData, transmittableThreadLocal.get());
                assertNull(inheritableThreadLocal.get());
            } else {
                System.out.println("Test WITHOUT TTL Agent");
                assertNull(transmittableThreadLocal.get());
                assertNull(inheritableThreadLocal.get());
            }

            System.out.println("===================callback=====================");
        }).end();

        //wait for callback
        Thread.sleep(2000);
    }

    @Test
    public void testCallbackInVertxImpl() throws Exception {
        final TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();
        final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
        final String transmittedData = "transmitted_data_ttl";
        final String inheritedData = "inherited_data_ttl";
        final String messageReplyInBlockingCode = "messageReplyInBlockingCode___";

        final Vertx vertx = Vertx.vertx();

        //set value after eventLoop thread was created
        transmittableThreadLocal.set(transmittedData);
        inheritableThreadLocal.set(inheritedData);

        vertx.executeBlocking(a -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a.complete(messageReplyInBlockingCode);
        }, event -> {
            System.out.println("receive msg from blocking code:" + event.result());
            System.out.println("===================callback=====================");

            if (TtlAgent.isTtlAgentLoaded()) {
                System.out.println("Test **WITH** TTL Agent");
                assertEquals(transmittedData, transmittableThreadLocal.get());
            } else {
                System.out.println("Test WITHOUT TTL Agent");
                assertNull(transmittableThreadLocal.get());
            }
            assertNull(inheritableThreadLocal.get());

            System.out.println("===================callback=====================");
        });

        //wait for callback
        Thread.sleep(2000);
    }
}


text:
namespace chrome_cleaner {

// Singleton interface to interact with the sandboxed engine.
class EngineClient : public base::RefCountedThreadSafe<EngineClient> {
 public:
  // An engine call. Values from this enum are used for histograms through the
  // registry logger. Do not re-use existing values.
  enum class Operation {
    UNKNOWN = 0,
    Initialize = 1,
    DEPRECATED_RegisterTargetProcess = 2,
    DEPRECATED_TargetProcessStarted = 3,
    DEPRECATED_Shutdown = 4,
    DEPRECATED_InitializeSandboxTarget = 5,
    DEPRECATED_StartSandboxTarget = 6,
    DEPRECATED_GetVersion = 7,
    DEPRECATED_GetSupportedUwS = 8,
    StartScan = 9,
    ScanDoneCallback = 10,
    StartCleanup = 11,
    CleanupDoneCallback = 12,
    DEPRECATED_CancelScan = 13,
    Finalize = 14,
    DEPRECATED_RebootAndRerun = 15,
    DEPRECATED_StartPostRebootCleanup = 16,
    DEPRECATED_PostRebootCleanupDoneCallback = 17,
    DEPRECATED_EndPostRebootCleanup = 18,
    // Values for EngineOperations go here.
    // Keep in sync with EngineOperationStatus.Operation enum in proto.

    // The SoftwareReporter.EngineErrorCode histogram logic requires that the
    // EngineOperation occupies at most 16 bits.
    MAX_OPERATION = 2 ^ 16 - 1,
  };

  typedef base::RepeatingCallback<void(int)> ResultCodeLoggingCallback;

  // Creates an EngineClient which will call the given |logging_callback| to
  // log result codes after every operation. IPC tasks will be posted with
  // |mojo_task_runner|, which must not be null. If
  // |interface_metadata_observer| is not nullptr its ObserveCall method will
  // be called with information about all engine calls.
  static scoped_refptr<EngineClient> CreateEngineClient(
      const Engine::Name engine,
      const ResultCodeLoggingCallback& logging_callback,
      const SandboxConnectionErrorCallback& connection_error_callback,
      scoped_refptr<MojoTaskRunner> mojo_task_runner,
      std::unique_ptr<InterfaceMetadataObserver> interface_metadata_observer =
          nullptr);

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

  // Return the watchdog timeout that should be used for scanning using this
  // client.
  uint32_t ScanningWatchdogTimeoutInSeconds() const;

  mojo::Remote<mojom::EngineCommands>* engine_commands_remote() const {
    return engine_commands_.get();
  }

  // Posts a task to the mojo thread to bind an EngineCommands remote to |pipe|.
  // |error_handler| will be called for errors on this connection.
  //
  // TODO(joenotcharles): When the EngineClient interface is updated to be
  // asynchronous, rename Initialize, StartScan, StartCleanup, and Finalize to
  // match this naming scheme.
  //
  // CAREFUL: some methods (eg. StartScan), have callback parameters and the
  // caller (eg. ScannerImpl::Start) binds tasks to the callback using
  // base::Unretained. This is safe right now because StartScan is synchronous
  // so the callbacks are called while it is still executing, so ScannerImpl
  // definitely still exists. But if StartScan is made asynchronous, we need to
  // make sure that all callbacks are still valid before calling them. (This
  // could happen during shutdown when ScannerImpl has been deleted but
  // EngineClient is still being kept alive because a StartScanAsync task
  // that's still queued has a reference to it.)
  virtual void PostBindEngineCommandsRemote(mojo::ScopedMessagePipeHandle pipe);

  using FoundUwSCallback = EngineScanResultsImpl::FoundUwSCallback;
  using DoneCallback = EngineScanResultsImpl::DoneCallback;

  // Return the list of UwS enabled for this engine.
  virtual std::vector<UwSId> GetEnabledUwS() const;

  virtual uint32_t Initialize();

  // Note that |DoneCallback| should call MaybeLogResultCode().
  virtual uint32_t StartScan(
      const std::vector<UwSId>& enabled_uws,
      const std::vector<UwS::TraceLocation>& enabled_locations,
      bool include_details,
      FoundUwSCallback found_callback,
      DoneCallback done_callback);

  // Note that |DoneCallback| should call MaybeLogResultCode().
  virtual uint32_t StartCleanup(const std::vector<UwSId>& enabled_uws,
                                DoneCallback done_callback);

  virtual uint32_t Finalize();

  // Logs operation and result_code to the registry so Chrome later uploads them
  // as one UMA histogram. Successive calls to this method will clobber the
  // registry value until |result_code| is not SUCCESS.
  //
  // TODO(joenotcharles): Make this method private. StartScan(), StartCleanup()
  // and StartPostRebootCleanup() can wrap |DoneCallback| around another
  // callback which calls this method.
  virtual void MaybeLogResultCode(Operation operation, uint32_t result_code);

  virtual bool needs_reboot() const;

 protected:
  friend class base::RefCountedThreadSafe<EngineClient>;

  EngineClient(
      Engine::Name engine,
      const ResultCodeLoggingCallback& logging_callback,
      const SandboxConnectionErrorCallback& connection_error_callback,
      scoped_refptr<MojoTaskRunner> mojo_task_runner,
      std::unique_ptr<InterfaceMetadataObserver> metadata_observer = nullptr);

  virtual ~EngineClient();

 private:
  friend class ExtensionCleanupTest;
  using InitializeCallback = mojom::EngineCommands::InitializeCallback;
  using StartScanCallback = mojom::EngineCommands::StartScanCallback;
  using StartCleanupCallback = mojom::EngineCommands::StartCleanupCallback;
  using FinalizeCallback = mojom::EngineCommands::FinalizeCallback;

  void BindEngineCommandsRemote(mojo::ScopedMessagePipeHandle pipe,
                                base::OnceClosure error_handler);

  void InitializeReadOnlyCallbacks();
  bool InitializeCleaningCallbacks();
  bool InitializeQuarantine(std::unique_ptr<ZipArchiver>* archiver);

  // TODO(joenotcharles): When the synchronous Initialize method is removed,
  // rename this to Initialize and name the public accessor PostInitialize.
  // Same for StartScan and similar methods.
  void InitializeAsync(InitializeCallback result_callback);

  void StartScanAsync(const std::vector<UwSId>& enabled_uws,
                      const std::vector<UwS::TraceLocation>& enabled_locations,
                      bool include_details,
                      FoundUwSCallback found_callback,
                      DoneCallback done_callback,
                      StartScanCallback result_callback);

  void StartCleanupAsync(const std::vector<UwSId>& enabled_uws,
                         DoneCallback done_callback,
                         StartCleanupCallback result_callback);

  void FinalizeAsync(FinalizeCallback result_callback);

  void SetRebootRequired();

  void ResetCreatedInstanceCheckForTesting();

  Engine::Name engine_;

  // Keeps track of whether an operation was started (with a call to a Start*
  // method) but not ended (with a matching call to the End* method). Ensures
  // that we never shutdown while an operation is in progress. Also serves for
  // some debug checks.
  bool operation_in_progress_ = false;

  // Keeps track of the last result code stored in the registry.
  uint32_t cached_result_code_ = EngineResultCode::kSuccess;

  // The callback to call to report the experimental engine result code.
  ResultCodeLoggingCallback registry_logging_callback_;

  // The callback to call to report the sandbox connection error.
  SandboxConnectionErrorCallback connection_error_callback_;

  // Task runner used to send IPC commands to the sandbox target process.
  scoped_refptr<MojoTaskRunner> mojo_task_runner_;

  // Proxy object that implements the EngineCommands interface by sending the
  // commands over IPC to the sandbox target process.
  std::unique_ptr<mojo::Remote<mojom::EngineCommands>> engine_commands_;

  // Handler for scan results returned over the Mojo pipe.
  std::unique_ptr<EngineScanResultsImpl> scan_results_impl_;

  // Handler for cleanup results returned over the Mojo pipe.
  std::unique_ptr<EngineCleanupResultsImpl> cleanup_results_impl_;

  // Handler for file reading requests from the sandbox that have to run
  // outside the sandbox.
  std::unique_ptr<EngineFileRequestsImpl> sandbox_file_requests_;

  // Handler for requests from the sandbox that have to run outside the sandbox.
  std::unique_ptr<EngineRequestsImpl> sandbox_requests_;

  // Handler for cleaning requests from the sandbox that have to run outside the
  // sandbox.
  std::unique_ptr<CleanerEngineRequestsImpl> sandbox_cleaner_requests_;

  // Allow tests overwrite the archiver used.
  std::unique_ptr<ZipArchiver> archiver_for_testing_;

  // Keep track of if this cleaning requires a reboot to be fully completed.
  bool needs_reboot_ = false;

  // Keeps track of the calls of both EngineRequestsImpl and
  // CleanerEngineRequestsImpl.
  std::unique_ptr<InterfaceMetadataObserver> interface_metadata_observer_;
};

}  // namespace chrome_cleaner

#endif  // CHROME_CHROME_CLEANER_ENGINES_BROKER_ENGINE_CLIENT_H_

redpajama_set_name: RedPajamaGithub


text:
@extends('layouts.admin')
{{-- Content --}}
@section('content')

 Creat News Category

@if (isset($newscategory))
{!! Form::model($newscategory, array('route' => array('newscategory.update', $newscategory->id), 'method' => 'PATCH')) !!}
@else
{!! Form::open(array('url' => 'admin/newscategory')) !!}
@endif

				  {!! Form::label('name', 'Title') !!}

				    {!! Form::text('name', null, ['class' => 'form-control']) !!}

				  {!! Form::label('alias', 'Alias') !!}

				    {!! Form::text('alias', null, ['class' => 'form-control']) !!}

				<button type="reset" class="btn btn-sm btn-warning close_popup">
					 Cancel
				</button>
				<button type="reset" class="btn btn-sm btn-default">
					 Reset
				</button>
				<button type="submit" class="btn btn-sm btn-success">

					@if (isset($newscategory))
						{{ 'Edit' }}
					@else
						{{ 'Create' }}
				    	@endif
				</button>

{!! Form::close() !!}
@endsection


text:
from default import *

NOSE_ARGS = [
    '--with-coverage',
    '--cover-package=rapidsms',
]


text:
package com.googlecode.vfsjfilechooser2.accessories.bookmarks;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.apache.commons.vfs2.FileObject;

import com.googlecode.vfsjfilechooser2.VFSJFileChooser;
import com.googlecode.vfsjfilechooser2.utils.VFSResources;
import com.googlecode.vfsjfilechooser2.utils.VFSUtils;

/**
 * Bookmarks manager panel
 * @author Yves Zoundi <yveszoundi at users dot sf dot net>
 * @author Jojada Tirtowidjojo <jojada at users.sourceforge.net>
 * @version 0.0.1
 */
@SuppressWarnings("serial")
public class BookmarksManagerPanel extends JPanel
{
    public static final int NO_BOOKMARK_SELECTION_INDEX = -1;
    private JScrollPane scrollPane;
    private JTable table;
    private JButton bOpen;
    private JButton bCancel;
    private JButton bEdit;
    private JButton bAdd;
    private JButton bDelete;
    private JButton bMoveUp;
    private JButton bMoveDown;
    private Bookmarks model;
    private VFSJFileChooser chooser;
    private final Dimension tableSize = new Dimension(350, 200);
    private BookmarksDialog parentDialog;

    public BookmarksManagerPanel(BookmarksDialog parentDialog,
        VFSJFileChooser chooser)
    {
        this.parentDialog = parentDialog;
        this.chooser = chooser;

        model = new Bookmarks();

        table = new JTable(model);
        scrollPane = new JScrollPane(table);

        table.setPreferredScrollableViewportSize(tableSize);
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        bCancel = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.closeButtonText"));

        bOpen = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.openButtonText"));
        bOpen.setIcon(new ImageIcon(getClass()
                                        .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/document-open.png")));
        bOpen.setHorizontalAlignment(SwingConstants.LEFT);

        bAdd = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.addButtonText"));
        bAdd.setIcon(new ImageIcon(getClass()
                                       .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/list-add.png")));
        bAdd.setHorizontalAlignment(SwingConstants.LEFT);

        bEdit = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.editButtonText"));
        bEdit.setIcon(new ImageIcon(getClass()
                                        .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/book_edit.png")));
        bEdit.setHorizontalAlignment(SwingConstants.LEFT);

        bDelete = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.deleteButtonText"));
        bDelete.setIcon(new ImageIcon(getClass()
                                          .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/list-remove.png")));
        bDelete.setHorizontalAlignment(SwingConstants.LEFT);

        bMoveUp = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.moveUpButtonText"));
        bMoveUp.setIcon(new ImageIcon(getClass()
                                          .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/go-up.png")));
        bMoveUp.setHorizontalAlignment(SwingConstants.LEFT);

        bMoveDown = new JButton(VFSResources.getMessage(
                    "VFSJFileChooser.moveDownButtonText"));
        bMoveDown.setIcon(new ImageIcon(getClass()
                                            .getResource("/com/googlecode/vfsjfilechooser2/plaf/icons/go-down.png")));
        bMoveDown.setHorizontalAlignment(SwingConstants.LEFT);

        final ActionHandler ah = new ActionHandler();

        bOpen.addActionListener(ah);
        bCancel.addActionListener(ah);
        bEdit.addActionListener(ah);
        bAdd.addActionListener(ah);
        bDelete.addActionListener(ah);
        bMoveUp.addActionListener(ah);
        bMoveDown.addActionListener(ah);

        final Box south = Box.createHorizontalBox();
        south.add(Box.createHorizontalGlue());
        south.add(bCancel);
        south.add(Box.createHorizontalGlue());

        final JPanel buttons = new JPanel(new GridLayout(0, 1, 5, 5));

        buttons.add(bAdd);
        buttons.add(bEdit);
        buttons.add(bDelete);
        buttons.add(bOpen);
        buttons.add(Box.createVerticalStrut(10));
        buttons.add(bMoveUp);
        buttons.add(bMoveDown);

        JPanel east = new JPanel();
        east.add(buttons, BorderLayout.NORTH);
        east.add(new JPanel(), BorderLayout.CENTER); // don't ask

        setLayout(new BorderLayout(10, 10));

        add(scrollPane, BorderLayout.CENTER);
        add(south, BorderLayout.SOUTH);
        add(east, BorderLayout.EAST);

        setBorder(BorderFactory.createMatteBorder(10, 10, 10, 10,
                UIManager.getColor("Panel.background")));
    }

    public Bookmarks getModel()
    {
        return model;
    }

    public void cancel()
    {
        parentDialog.setVisible(false);
    }

    private class ActionHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent actionEvent)
        {
            JButton button = (JButton) actionEvent.getSource();

            final int row = table.getSelectedRow();

            if (button.equals(bAdd))
            {
                parentDialog.showEditorView(NO_BOOKMARK_SELECTION_INDEX);
            }
            else if (button.equals(bEdit))
            {
                if (row != NO_BOOKMARK_SELECTION_INDEX)
                {
                    parentDialog.showEditorView(row);
                }
                else
                {
                    JOptionPane.showMessageDialog(getParent(),
                        VFSResources.getMessage(
                            "VFSJFileChooser.noselectionLabel"),
                        VFSResources.getMessage(
                            "VFSJFileChooser.errorLabel"),
                        JOptionPane.ERROR_MESSAGE);
                }
            }
            else if (button.equals(bOpen))
            {
                if (row != NO_BOOKMARK_SELECTION_INDEX)
                {
                    Thread worker = new Thread()
                        {
                            @Override
                            public void run()
                            {
                                setCursor(Cursor.getPredefinedCursor(
                                        Cursor.WAIT_CURSOR));

                                TitledURLEntry aTitledURLEntry = model.getEntry(row);

                                FileObject fo = null;

                                try
                                {
                                    fo = VFSUtils.resolveFileObject(aTitledURLEntry.getURL());

                                    if ((fo != null) && !fo.exists())
                                    {
                                        fo = null;
                                    }
                                }
                                catch (Exception exc)
                                {
                                    fo = null;
                                }

                                setCursor(Cursor.getDefaultCursor());

                                if (fo == null)
                                {
                                    StringBuilder msg = new StringBuilder();
                                    msg.append("Failed to connect to ");
                                    msg.append(aTitledURLEntry.getURL());
                                    msg.append("\n");
                                    msg.append(
                                        "Please check URL entry and try again.");
                                    JOptionPane.showMessageDialog(null, msg,
                                        "Error", JOptionPane.ERROR_MESSAGE);
                                }
                                else
                                {
                                    chooser.setCurrentDirectoryObject(fo);
                                    parentDialog.setVisible(false);
                                }
                            }
                        };

                    worker.setPriority(Thread.MIN_PRIORITY);
                    SwingUtilities.invokeLater(worker);
                }
                else
                {
                    JOptionPane.showMessageDialog(getParent(),
                        VFSResources.getMessage(
                            "VFSJFileChooser.noselectionLabel"),
                        VFSResources.getMessage(
                            "VFSJFileChooser.errorLabel"),
                        JOptionPane.ERROR_MESSAGE);
                }
            }
            else if (button.equals(bDelete))
            {
                int[] rows = table.getSelectedRows();

                if (rows.length == 0)
                {
                    JOptionPane.showMessageDialog(getParent(),
                        VFSResources.getMessage(
                            "VFSJFileChooser.noselectionLabel"),
                        VFSResources.getMessage(
                            "VFSJFileChooser.errorLabel"),
                        JOptionPane.ERROR_MESSAGE);

                    return;
                }
                else
                {
                    for (int i = rows.length - 1; i >= 0; i--)
                    {
                        model.delete(rows[i]);
                    }
                }
            }
            else if (button.equals(bMoveUp))
            {
                int[] rows = table.getSelectedRows();

                if (rows.length == 0)
                {
                    JOptionPane.showMessageDialog(getParent(),
                        VFSResources.getMessage(
                            "VFSJFileChooser.noselectionLabel"),
                        VFSResources.getMessage(
                            "VFSJFileChooser.errorLabel"),
                        JOptionPane.ERROR_MESSAGE);

                    return;
                }
                else if (rows.length > 1)
                {
                    return;
                }
                else if (rows[0] > 0)
                {
                    model.moveup(rows[0]);
                    table.setRowSelectionInterval(rows[0] - 1, rows[0] - 1);
                }
            }
            else if (button.equals(bMoveDown))
            {
                int[] rows = table.getSelectedRows();

                if (rows.length == 0)
                {
                    JOptionPane.showMessageDialog(getParent(),
                        VFSResources.getMessage(
                            "VFSJFileChooser.noselectionLabel"),
                        VFSResources.getMessage(
                            "VFSJFileChooser.errorLabel"),
                        JOptionPane.ERROR_MESSAGE);

                    return;
                }
                else if (rows.length > 1)
                {
                    return;
                }
                else if (rows[0] < (model.getRowCount() - 1))
                {
                    model.movedown(rows[0]);
                    table.setRowSelectionInterval(rows[0] + 1, rows[0] + 1);
                }
            }
            else if (button.equals(bCancel))
            {
                cancel();
            }
        }
    } // inner class ActionHandler
}


text:
const uuidRegex = new RegExp('' +
  /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b/.source +
  /-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.source);
var templateUuid;

// Basic browser tests for the wmDesksPrivate API.
chrome.test.runTests([
  async function testGetDeskTemplateJson() {
    await chrome.test.assertPromiseRejects(
      chrome.wmDesksPrivate.getDeskTemplateJson(
      // Get desk template JSON with an invalid UUID.
        'invalid-uuid'), 'Error: Invalid template UUID.');
    chrome.test.succeed();
  },

  // Tests setting window to show up on all desks.
  async function testSetToAllDeskWindowWithValidID() {
    // Create a new window.
    const window = await chrome.windows.create();

    await chrome.wmDesksPrivate.setWindowProperties(window.tabs[0].windowId,
      { allDesks: true });

    chrome.test.succeed();
  },

  // Tests reverting setting window to show up on all desks.
  async function testUnsetToAllDeskWindowWithValidID() {
    // Create a new window.
    const window = await chrome.windows.create();
    await chrome.wmDesksPrivate.setWindowProperties(window.tabs[0].windowId,
      { allDesks: false });
    chrome.test.succeed();
  },

  // Tests SetToAllDeskWindow with invalid `window_id`.
  async function testSetToAllDeskWindowWithInvalidID() {
    // Launch invalid template Uuid.
    await chrome.test.assertPromiseRejects(
      chrome.wmDesksPrivate.setWindowProperties(1234, { allDesks: true }),
      "Error: The window cannot be found.");
    chrome.test.succeed();

  },

  // Tests UnsetAllDeskWindow with invalid `window_id`.
  async function testUnsetAllDeskWindowWithInvalidID() {
    // Launch invalid template Uuid.
    await chrome.test.assertPromiseRejects(
      chrome.wmDesksPrivate.setWindowProperties(1234, { allDesks: false }),
      "Error: The window cannot be found.");
    chrome.test.succeed();
  },

  // Tests save an active desk to library.
  async function testSaveActiveDesk() {
    const savedDesk = await chrome.wmDesksPrivate.saveActiveDesk();
    chrome.test.assertTrue(uuidRegex.test(savedDesk.deskUuid));
    chrome.test.assertTrue(savedDesk.hasOwnProperty('deskName'));
    chrome.test.succeed();
  },

  // Tests delete a saved desk from library.
  async function testDeleteSavedDesk() {
    const savedDesk = await chrome.wmDesksPrivate.saveActiveDesk();
    await chrome.wmDesksPrivate.deleteSavedDesk(savedDesk.deskUuid);
    chrome.test.succeed();
  },

  // Tests recall a saved desk from library.
  async function testRecallSavedDesk() {
    const savedDesk = await chrome.wmDesksPrivate.saveActiveDesk();
    const newDeskUuid = await chrome.wmDesksPrivate.recallSavedDesk(
      savedDesk.deskUuid);
    chrome.test.assertTrue(uuidRegex.test(newDeskUuid));
    chrome.test.succeed();
  },
]);


text:
FROM ubuntu:14.04
MAINTAINER Philippe ALEXANDRE <alexandre.philippe+github@gmail.com>
ENV DEBIAN_FRONTEND noninteractive
ENV ENV INITRD No
ENV DEBIAN_PRIORITY critical
ENV DEBCONF_NOWARNINGS yes

ENV PHANTOMJS_VERSION 1.9.7

RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y git-core libfreetype6 libfontconfig python
WORKDIR /srv
ADD https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-${PHANTOMJS_VERSION}-linux-x86_64.tar.bz2 /srv/phantomjs-${PHANTOMJS_VERSION}-linux-x86_64.tar.bz2
RUN tar jxvf /srv/phantomjs-${PHANTOMJS_VERSION}-linux-x86_64.tar.bz2 -C /usr/local/
RUN ln -sf /usr/local/phantomjs-${PHANTOMJS_VERSION}-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
RUN git clone https://github.com/n1k0/casperjs.git /usr/local/casperjs
RUN ln -sf /usr/local/casperjs/bin/casperjs /usr/local/bin/casperjs


text:
var http = require('http');

var bunyan = require('../lib/bunyan');
var verror = require('verror');

// node-tap API
if (require.cache[__dirname + '/tap4nodeunit.js'])
        delete require.cache[__dirname + '/tap4nodeunit.js'];
var tap4nodeunit = require('./tap4nodeunit.js');
var after = tap4nodeunit.after;
var before = tap4nodeunit.before;
var test = tap4nodeunit.test;

function CapturingStream(recs) {
    this.recs = recs;
}
CapturingStream.prototype.write = function (rec) {
    this.recs.push(rec);
}

test('req serializer', function (t) {
    var records = [];
    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [
            {
                stream: new CapturingStream(records),
                type: 'raw'
            }
        ],
        serializers: {
            req: bunyan.stdSerializers.req
        }
    });

    // None of these should blow up.
    var bogusReqs = [
        undefined,
        null,
        {},
        1,
        'string',
        [1, 2, 3],
        {'foo':'bar'}
    ];
    for (var i = 0; i < bogusReqs.length; i++) {
        log.info({req: bogusReqs[i]}, 'hi');
        t.equal(records[i].req, bogusReqs[i]);
    }

    // Get http request and response objects to play with and test.
    var theReq, theRes;
    var server = http.createServer(function (req, res) {
        theReq = req;
        theRes = res;
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    })
    server.listen(8765, function () {
        http.get({host: '127.0.0.1', port: 8765, path: '/'}, function (res) {
            res.resume();
            log.info({req: theReq}, 'the request');
            var lastRecord = records[records.length-1];
            t.equal(lastRecord.req.method, 'GET');
            t.equal(lastRecord.req.url, theReq.url);
            t.equal(lastRecord.req.remoteAddress,
                theReq.connection.remoteAddress);
            t.equal(lastRecord.req.remotePort, theReq.connection.remotePort);
            server.close();
            t.end();
        }).on('error', function (err) {
            t.ok(false, 'error requesting to our test server: ' + err);
            server.close();
            t.end();
        });
    });
});

test('res serializer', function (t) {
    var records = [];
    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [
            {
                stream: new CapturingStream(records),
                type: 'raw'
            }
        ],
        serializers: {
            res: bunyan.stdSerializers.res
        }
    });

    // None of these should blow up.
    var bogusRess = [
        undefined,
        null,
        {},
        1,
        'string',
        [1, 2, 3],
        {'foo':'bar'}
    ];
    for (var i = 0; i < bogusRess.length; i++) {
        log.info({res: bogusRess[i]}, 'hi');
        t.equal(records[i].res, bogusRess[i]);
    }

    // Get http request and response objects to play with and test.
    var theReq, theRes;
    var server = http.createServer(function (req, res) {
        theReq = req;
        theRes = res;
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    })
    server.listen(8765, function () {
        http.get({host: '127.0.0.1', port: 8765, path: '/'}, function (res) {
            res.resume();
            log.info({res: theRes}, 'the response');
            var lastRecord = records[records.length-1];
            t.equal(lastRecord.res.statusCode, theRes.statusCode);
            t.equal(lastRecord.res.header, theRes._header);
            server.close();
            t.end();
        }).on('error', function (err) {
            t.ok(false, 'error requesting to our test server: ' + err);
            server.close();
            t.end();
        });
    });
});

test('err serializer', function (t) {
    var records = [];
    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [
            {
                stream: new CapturingStream(records),
                type: 'raw'
            }
        ],
        serializers: {
            err: bunyan.stdSerializers.err
        }
    });

    // None of these should blow up.
    var bogusErrs = [
        undefined,
        null,
        {},
        1,
        'string',
        [1, 2, 3],
        {'foo':'bar'}
    ];
    for (var i = 0; i < bogusErrs.length; i++) {
        log.info({err: bogusErrs[i]}, 'hi');
        t.equal(records[i].err, bogusErrs[i]);
    }

    var theErr = new TypeError('blah');

    log.info(theErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, theErr.message);
    t.equal(lastRecord.err.name, theErr.name);
    t.equal(lastRecord.err.stack, theErr.stack);
    t.end();
});

test('err serializer: custom serializer', function (t) {
    var records = [];

    function customSerializer(err) {
        return {
            message: err.message,
            name: err.name,
            stack: err.stack,
            beep: err.beep
        };
    }

    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [
            {
                stream: new CapturingStream(records),
                type: 'raw'
            }
        ],
        serializers: {
            err: customSerializer
        }
    });

    var e1 = new Error('message1');
    e1.beep = 'bop';
    var e2 = new Error('message2');
    var errs = [e1, e2];

    for (var i = 0; i < errs.length; i++) {
        log.info(errs[i]);
        t.equal(records[i].err.message, errs[i].message);
        t.equal(records[i].err.beep, errs[i].beep);
    }
    t.end();
});

test('err serializer: long stack', function (t) {
    var records = [];
    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [ {
                stream: new CapturingStream(records),
                type: 'raw'
        } ],
        serializers: {
            err: bunyan.stdSerializers.err
        }
    });

    var topErr, midErr, bottomErr;

    // Just a VError.
    topErr = new verror.VError('top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message, 'Just a VError');
    t.equal(lastRecord.err.name, topErr.name, 'Just a VError');
    t.equal(lastRecord.err.stack, topErr.stack, 'Just a VError');

    // Just a WError.
    topErr = new verror.WError('top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message, 'Just a WError');
    t.equal(lastRecord.err.name, topErr.name, 'Just a WError');
    t.equal(lastRecord.err.stack, topErr.stack, 'Just a WError');

    // WError <- TypeError
    bottomErr = new TypeError('bottom err');
    topErr = new verror.WError(bottomErr, 'top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message, 'WError <- TypeError');
    t.equal(lastRecord.err.name, topErr.name, 'WError <- TypeError');
    var expectedStack = topErr.stack + '\nCaused by: ' + bottomErr.stack;
    t.equal(lastRecord.err.stack, expectedStack, 'WError <- TypeError');

    // WError <- WError
    bottomErr = new verror.WError('bottom err');
    topErr = new verror.WError(bottomErr, 'top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message, 'WError <- WError');
    t.equal(lastRecord.err.name, topErr.name, 'WError <- WError');
    var expectedStack = topErr.stack + '\nCaused by: ' + bottomErr.stack;
    t.equal(lastRecord.err.stack, expectedStack, 'WError <- WError');

    // WError <- WError <- TypeError
    bottomErr = new TypeError('bottom err');
    midErr = new verror.WError(bottomErr, 'mid err');
    topErr = new verror.WError(midErr, 'top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message,
        'WError <- WError <- TypeError');
    t.equal(lastRecord.err.name, topErr.name, 'WError <- WError <- TypeError');
    var expectedStack = (topErr.stack
        + '\nCaused by: ' + midErr.stack
        + '\nCaused by: ' + bottomErr.stack);
    t.equal(lastRecord.err.stack, expectedStack,
            'WError <- WError <- TypeError');

    // WError <- WError <- WError
    bottomErr = new verror.WError('bottom err');
    midErr = new verror.WError(bottomErr, 'mid err');
    topErr = new verror.WError(midErr, 'top err');
    log.info(topErr, 'the error');
    var lastRecord = records[records.length-1];
    t.equal(lastRecord.err.message, topErr.message,
        'WError <- WError <- WError');
    t.equal(lastRecord.err.name, topErr.name, 'WError <- WError <- WError');
    var expectedStack = (topErr.stack
        + '\nCaused by: ' + midErr.stack
        + '\nCaused by: ' + bottomErr.stack);
    t.equal(lastRecord.err.stack, expectedStack, 'WError <- WError <- WError');

    t.end();
});

// Bunyan 0.18.3 introduced a bug where *all* serializers are applied
// even if the log record doesn't have the associated key. That means
// serializers that don't handle an `undefined` value will blow up.
test('do not apply serializers if no record key', function (t) {
    var records = [];
    var log = bunyan.createLogger({
        name: 'serializer-test',
        streams: [ {
                stream: new CapturingStream(records),
                type: 'raw'
        } ],
        serializers: {
            err: bunyan.stdSerializers.err,
            boom: function (value) {
                throw new Error('boom');
            }
        }
    });

    log.info({foo: 'bar'}, 'record one');
    log.info({err: new Error('record two err')}, 'record two');

    t.equal(records[0].boom, undefined);
    t.equal(records[0].foo, 'bar');
    t.equal(records[1].boom, undefined);
    t.equal(records[1].err.message, 'record two err');

    t.end();
});


text:
package com.ctrip.zeus.domain;

public enum RouteRuleType {

    UNKNOWN(""),
    HEADER("header");

    private String value;

    RouteRuleType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public static RouteRuleType getType(String type) {
        if (RouteRuleType.HEADER.value.equalsIgnoreCase(type)) {
            return RouteRuleType.HEADER;
        }
        return UNKNOWN;
    }

    @Override
    public String toString() {
        return value;
    }
}


text:
#include "core/fetch/ResourceFetcher.h"

#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/FetchInitiatorTypeNames.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/MockFetchContext.h"
#include "core/fetch/MockResource.h"
#include "core/fetch/MockResourceClient.h"
#include "core/fetch/RawResource.h"
#include "core/fetch/ResourceLoader.h"
#include "platform/WebTaskRunner.h"
#include "platform/exported/WrappedResourceResponse.h"
#include "platform/heap/Handle.h"
#include "platform/heap/HeapAllocator.h"
#include "platform/heap/Member.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceTimingInfo.h"
#include "platform/scheduler/test/fake_web_task_runner.h"
#include "platform/testing/URLTestHelpers.h"
#include "platform/testing/weburl_loader_mock.h"
#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
#include "public/platform/WebURLLoaderMockFactory.h"
#include "public/platform/WebURLResponse.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "wtf/Allocator.h"
#include "wtf/PtrUtil.h"
#include "wtf/Vector.h"
#include <memory>

namespace blink {

namespace {
constexpr char kTestResourceFilename[] = "white-1x1.png";
constexpr char kTestResourceMimeType[] = "image/png";
constexpr int kTestResourceSize = 103;  // size of web/tests/data/white-1x1.png
}

class ResourceFetcherTest : public ::testing::Test {};

TEST_F(ResourceFetcherTest, StartLoadAfterFrameDetach) {
  KURL secureURL(ParsedURLString, "https://secureorigin.test/image.png");
  // Try to request a url. The request should fail, and a resource in an error
  // state should be returned, and no resource should be present in the cache.
  ResourceFetcher* fetcher = ResourceFetcher::create(nullptr);
  ResourceRequest resourceRequest(secureURL);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->errorOccurred());
  EXPECT_TRUE(resource->resourceError().isAccessCheck());
  EXPECT_FALSE(memoryCache()->resourceForURL(secureURL));

  // Start by calling startLoad() directly, rather than via requestResource().
  // This shouldn't crash.
  fetcher->startLoad(RawResource::create(secureURL, Resource::Raw));
}

TEST_F(ResourceFetcherTest, UseExistingResource) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, kTestResourceFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = MockResource::fetch(fetchRequest, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(resource->isLoaded());
  EXPECT_TRUE(memoryCache()->contains(resource));

  Resource* newResource = MockResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);
  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, Vary) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  resource->responseReceived(response, nullptr);
  resource->finish();
  ASSERT_TRUE(resource->hasVaryHeader());

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Platform::current()->getURLLoaderMockFactory()->registerURL(
      url, WebURLResponse(), "");
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_NE(resource, newResource);
  newResource->loader()->cancel();
  memoryCache()->remove(newResource);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);

  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, NavigationTimingInfo) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setFrameType(WebURLRequest::FrameTypeNested);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextForm);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Platform::current()->getURLLoaderMockFactory()->registerURL(
      url, WebURLResponse(), "");
  Resource* resource =
      RawResource::fetchMainResource(fetchRequest, fetcher, SubstituteData());
  resource->responseReceived(response, nullptr);
  EXPECT_EQ(resource->getType(), Resource::MainResource);

  ResourceTimingInfo* navigationTimingInfo = fetcher->getNavigationTimingInfo();
  ASSERT_TRUE(navigationTimingInfo);
  long long encodedDataLength = 123;
  resource->loader()->didFinishLoading(0.0, encodedDataLength, 0);
  EXPECT_EQ(navigationTimingInfo->transferSize(), encodedDataLength);

  // When there are redirects.
  KURL redirectURL(ParsedURLString, "http://127.0.0.1:8000/redirect.html");
  ResourceResponse redirectResponse;
  redirectResponse.setURL(redirectURL);
  redirectResponse.setHTTPStatusCode(200);
  long long redirectEncodedDataLength = 123;
  redirectResponse.setEncodedDataLength(redirectEncodedDataLength);
  ResourceRequest redirectResourceRequest(url);
  fetcher->recordResourceTimingOnRedirect(resource, redirectResponse, false);
  EXPECT_EQ(navigationTimingInfo->transferSize(),
            encodedDataLength + redirectEncodedDataLength);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

TEST_F(ResourceFetcherTest, VaryOnBack) {
  MockFetchContext* context =
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
  context->setCachePolicy(CachePolicyHistoryBuffer);
  ResourceFetcher* fetcher = ResourceFetcher::create(context);

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  resource->responseReceived(response, nullptr);
  resource->finish();
  ASSERT_TRUE(resource->hasVaryHeader());

  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);

  memoryCache()->remove(newResource);
}

TEST_F(ResourceFetcherTest, VaryResource) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, kTestResourceFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = MockResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  ASSERT_TRUE(resource->hasVaryHeader());

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = MockResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);

  memoryCache()->remove(newResource);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

class RequestSameResourceOnComplete
    : public GarbageCollectedFinalized<RequestSameResourceOnComplete>,
      public RawResourceClient {
  USING_GARBAGE_COLLECTED_MIXIN(RequestSameResourceOnComplete);

 public:
  explicit RequestSameResourceOnComplete(Resource* resource)
      : m_resource(resource), m_notifyFinishedCalled(false) {}

  void notifyFinished(Resource* resource) override {
    EXPECT_EQ(m_resource, resource);
    MockFetchContext* context =
        MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
    context->setCachePolicy(CachePolicyRevalidate);
    ResourceFetcher* fetcher2 = ResourceFetcher::create(context);
    FetchRequest fetchRequest2(m_resource->url(), FetchInitiatorInfo());
    Resource* resource2 = MockResource::fetch(fetchRequest2, fetcher2);
    EXPECT_EQ(m_resource, resource2);
    m_notifyFinishedCalled = true;
  }
  bool notifyFinishedCalled() const { return m_notifyFinishedCalled; }

  DEFINE_INLINE_TRACE() {
    visitor->trace(m_resource);
    RawResourceClient::trace(visitor);
  }

  String debugName() const override { return "RequestSameResourceOnComplete"; }

 private:
  Member<Resource> m_resource;
  bool m_notifyFinishedCalled;
};

TEST_F(ResourceFetcherTest, RevalidateWhileFinishingLoading) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::ETag, "1234567890");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, kTestResourceFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));
  ResourceFetcher* fetcher1 = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest request1(url);
  request1.setHTTPHeaderField(HTTPNames::Cache_Control, "no-cache");
  FetchRequest fetchRequest1 = FetchRequest(request1, FetchInitiatorInfo());
  Resource* resource1 = MockResource::fetch(fetchRequest1, fetcher1);
  Persistent<RequestSameResourceOnComplete> client =
      new RequestSameResourceOnComplete(resource1);
  resource1->addClient(client);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(client->notifyFinishedCalled());
  resource1->removeClient(client);
  memoryCache()->remove(resource1);
}

TEST_F(ResourceFetcherTest, DontReuseMediaDataUrl) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest request(KURL(ParsedURLString, "data:text/html,foo"));
  request.setRequestContext(WebURLRequest::RequestContextVideo);
  ResourceLoaderOptions options;
  options.dataBufferingPolicy = DoNotBufferData;
  FetchRequest fetchRequest =
      FetchRequest(request, FetchInitiatorTypeNames::internal, options);
  Resource* resource1 = RawResource::fetchMedia(fetchRequest, fetcher);
  Resource* resource2 = RawResource::fetchMedia(fetchRequest, fetcher);
  EXPECT_NE(resource1, resource2);
  memoryCache()->remove(resource2);
}

class ServeRequestsOnCompleteClient final
    : public GarbageCollectedFinalized<ServeRequestsOnCompleteClient>,
      public RawResourceClient {
  USING_GARBAGE_COLLECTED_MIXIN(ServeRequestsOnCompleteClient);

 public:
  void notifyFinished(Resource*) override {
    Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  }

  // No callbacks should be received except for the notifyFinished() triggered
  // by ResourceLoader::cancel().
  void dataSent(Resource*, unsigned long long, unsigned long long) override {
    ASSERT_TRUE(false);
  }
  void responseReceived(Resource*,
                        const ResourceResponse&,
                        std::unique_ptr<WebDataConsumerHandle>) override {
    ASSERT_TRUE(false);
  }
  void setSerializedCachedMetadata(Resource*, const char*, size_t) override {
    ASSERT_TRUE(false);
  }
  void dataReceived(Resource*, const char*, size_t) override {
    ASSERT_TRUE(false);
  }
  bool redirectReceived(Resource*,
                        const ResourceRequest&,
                        const ResourceResponse&) override {
    ADD_FAILURE();
    return true;
  }
  void dataDownloaded(Resource*, int) override { ASSERT_TRUE(false); }
  void didReceiveResourceTiming(Resource*, const ResourceTimingInfo&) override {
    ASSERT_TRUE(false);
  }

  DEFINE_INLINE_TRACE() { RawResourceClient::trace(visitor); }

  String debugName() const override { return "ServeRequestsOnCompleteClient"; }
};

// Regression test for http://crbug.com/594072.
// This emulates a modal dialog triggering a nested run loop inside
// ResourceLoader::cancel(). If the ResourceLoader doesn't promptly cancel its
// WebURLLoader before notifying its clients, a nested run loop  may send a
// network response, leading to an invalid state transition in ResourceLoader.
TEST_F(ResourceFetcherTest, ResponseOnCancel) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  Persistent<ServeRequestsOnCompleteClient> client =
      new ServeRequestsOnCompleteClient();
  resource->addClient(client);
  resource->loader()->cancel();
  resource->removeClient(client);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

class ScopedMockRedirectRequester {
  STACK_ALLOCATED();
  WTF_MAKE_NONCOPYABLE(ScopedMockRedirectRequester);

 public:
  ScopedMockRedirectRequester() : m_context(nullptr) {}

  ~ScopedMockRedirectRequester() { cleanUp(); }

  void registerRedirect(const WebString& fromURL, const WebString& toURL) {
    KURL redirectURL(ParsedURLString, fromURL);
    WebURLResponse redirectResponse;
    redirectResponse.setURL(redirectURL);
    redirectResponse.setHTTPStatusCode(301);
    redirectResponse.setHTTPHeaderField(HTTPNames::Location, toURL);
    redirectResponse.setEncodedDataLength(kRedirectResponseOverheadBytes);
    Platform::current()->getURLLoaderMockFactory()->registerURL(
        redirectURL, redirectResponse, "");
  }

  void registerFinalResource(const WebString& url) {
    KURL finalURL(ParsedURLString, url);
    URLTestHelpers::registerMockedURLLoad(finalURL, kTestResourceFilename);
  }

  void request(const WebString& url) {
    DCHECK(!m_context);
    m_context =
        MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
    ResourceFetcher* fetcher = ResourceFetcher::create(m_context);
    ResourceRequest resourceRequest(url);
    resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
    FetchRequest fetchRequest =
        FetchRequest(resourceRequest, FetchInitiatorInfo());
    RawResource::fetch(fetchRequest, fetcher);
    Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  }

  void cleanUp() {
    Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs();
    memoryCache()->evictResources();
  }

  MockFetchContext* context() const { return m_context; }

 private:
  Member<MockFetchContext> m_context;
};

TEST_F(ResourceFetcherTest, SameOriginRedirect) {
  const char redirectURL[] = "http://127.0.0.1:8000/redirect.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL);

  EXPECT_EQ(kRedirectResponseOverheadBytes + kTestResourceSize,
            requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, CrossOriginRedirect) {
  const char redirectURL[] = "http://otherorigin.test/redirect.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL);

  EXPECT_EQ(kTestResourceSize, requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, ComplexCrossOriginRedirect) {
  const char redirectURL1[] = "http://127.0.0.1:8000/redirect1.html";
  const char redirectURL2[] = "http://otherorigin.test/redirect2.html";
  const char redirectURL3[] = "http://127.0.0.1:8000/redirect3.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL1, redirectURL2);
  requester.registerRedirect(redirectURL2, redirectURL3);
  requester.registerRedirect(redirectURL3, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL1);

  EXPECT_EQ(kTestResourceSize, requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, SynchronousRequest) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest(resourceRequest, FetchInitiatorInfo());
  fetchRequest.makeSynchronous();
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_TRUE(resource->isLoaded());
  EXPECT_EQ(ResourceLoadPriorityHighest,
            resource->resourceRequest().priority());

  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, PreloadResourceTwice) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = MockResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = MockResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);
  fetcher->preloadStarted(resource);

  fetcher->clearPreloads(ResourceFetcher::ClearAllPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_FALSE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, LinkPreloadResourceAndUse) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  // Link preload preload scanner
  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestOriginal.setLinkPreload(true);
  Resource* resource = MockResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  // Resource created by preload scanner
  FetchRequest fetchRequestPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* preloadScannerResource =
      MockResource::fetch(fetchRequestPreloadScanner, fetcher);
  EXPECT_EQ(resource, preloadScannerResource);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Resource created by parser
  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = MockResource::fetch(fetchRequest, fetcher);
  Persistent<MockResourceClient> client = new MockResourceClient(newResource);
  EXPECT_EQ(resource, newResource);
  EXPECT_FALSE(resource->isLinkPreload());

  // DCL reached
  fetcher->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, LinkPreloadResourceMultipleFetchersAndUse) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceFetcher* fetcher2 = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestOriginal.setLinkPreload(true);
  Resource* resource = MockResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  FetchRequest fetchRequestSecond = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestSecond.setLinkPreload(true);
  Resource* secondResource = MockResource::fetch(fetchRequestSecond, fetcher2);
  ASSERT_TRUE(secondResource);
  EXPECT_TRUE(secondResource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher2->preloadStarted(secondResource);

  // Link rel preload scanner
  FetchRequest fetchRequestLinkPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  fetchRequestLinkPreloadScanner.setLinkPreload(true);
  Resource* linkPreloadScannerResource =
      MockResource::fetch(fetchRequestLinkPreloadScanner, fetcher);
  EXPECT_EQ(resource, linkPreloadScannerResource);
  EXPECT_TRUE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Resource created by preload scanner
  FetchRequest fetchRequestPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* preloadScannerResource =
      MockResource::fetch(fetchRequestPreloadScanner, fetcher);
  EXPECT_EQ(resource, preloadScannerResource);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Resource created by preload scanner on the second fetcher
  FetchRequest fetchRequestPreloadScanner2 =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* preloadScannerResource2 =
      MockResource::fetch(fetchRequestPreloadScanner2, fetcher2);
  EXPECT_EQ(resource, preloadScannerResource2);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher2->preloadStarted(resource);

  // Resource created by parser
  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = MockResource::fetch(fetchRequest, fetcher);
  Persistent<MockResourceClient> client = new MockResourceClient(newResource);
  EXPECT_EQ(resource, newResource);
  EXPECT_FALSE(resource->isLinkPreload());

  // Resource created by parser on the second fetcher
  FetchRequest fetchRequest2 = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource2 = MockResource::fetch(fetchRequest, fetcher2);
  Persistent<MockResourceClient> client2 = new MockResourceClient(newResource2);
  EXPECT_EQ(resource, newResource2);
  EXPECT_FALSE(resource->isLinkPreload());

  // DCL reached on first fetcher
  EXPECT_TRUE(resource->isPreloaded());
  fetcher->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_TRUE(resource->isPreloaded());

  // DCL reached on second fetcher
  fetcher2->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, Revalidate304) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(304);
  response.setHTTPHeaderField("etag", "1234567890");
  resource->responseReceived(response, nullptr);
  resource->finish();

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Platform::current()->getURLLoaderMockFactory()->registerURL(
      url, WebURLResponse(), "");
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  fetcher->stopFetching();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);

  EXPECT_NE(resource, newResource);
}

TEST_F(ResourceFetcherTest, LinkPreloadResourceMultipleFetchersAndMove) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceFetcher* fetcher2 = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, kTestResourceFilename,
                                        kTestResourceMimeType);

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestOriginal.setLinkPreload(true);
  Resource* resource = MockResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Resource created by parser on the second fetcher
  FetchRequest fetchRequest2 = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource2 = MockResource::fetch(fetchRequest2, fetcher2);
  Persistent<MockResourceClient> client2 = new MockResourceClient(newResource2);
  EXPECT_EQ(resource, newResource2);
  EXPECT_FALSE(fetcher2->isFetching());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

}  // namespace blink


text:
class VotesController < ApplicationController

  def index
    @votes = current_user.votes.includes(:poll, :option).paginate(page: params[:page], per_page: 5)
  end

end


text:
<?php
namespace FileConverter\Console;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use FileConverter\FileConverter;

class InfoCommand extends \Symfony\Component\Console\Command\Command {
  protected function configure() {
    $this->setName('info');
    $this->setDescription('List supported converters and extensions');
    $this->setDefinition(array(
      new InputArgument('info_type', InputArgument::OPTIONAL, 'Type of info request (converters|convert-paths|defaults|extension-table)'),
    ));
  }

  protected function execute(InputInterface $input, OutputInterface $output, $mode = NULL) {
    $items = array();

    switch ($input->getArgument('info_type', 'converters')) {
      case 'converters':
        $fc = FileConverter::factory();
        foreach ($fc->getEngineConfigurations() as $configurations) {
          foreach ($configurations->getAllConverters() as $convert_path => $converters) {
            foreach ($converters as $id => $converter) {
              $item = array(
                '#title' => $id,
              );
              $item['Engine'] = preg_replace('@^.*\\\\@', '', $converter['#engine']);
              if (isset($converter['chain']) && $converter['chain']) {
                $item['Engine'] .= ' ' . $converter['chain'];
              }

              $items[$id] = $item;
            }
          }
        }
        break;

      case 'convert-paths':
        $fc = FileConverter::factory();
        foreach ($fc->getEngineConfigurations() as $configurations) {
          foreach ($configurations->getAllConverters() as $convert_path => $converters) {
            $items[$convert_path]['#title'] = $convert_path;
            foreach ($converters as $id => $converter) {
              $engine = preg_replace('@^.*\\\\@', '', $converter['#engine']);
              if ($converter['chain']) {
                $engine .= ' ' . $converter['chain'];
              }
              $item = sprintf('%- 28s %s', $id, $engine);
              $items[$convert_path][] = $item;
            }
          }
        }
        break;

      case 'defaults':
        $output->writeln("File Converter Default Settings:");
        $fc = FileConverter::factory();
        foreach ($fc->getSettings() as $k => $v) {
          $items[] = sprintf('% -25s: %s', $k, $v);
        }
        break;

      case 'extension-table':
        $rows = array();
        $fc = FileConverter::factory();
        $all_tos = array();
        foreach ($fc->getEngineConfigurations() as $configurations) {
          foreach ($configurations->getAllConverters() as $convert_path => $converters) {
            if (preg_match('@^(.*)->(.*)$@', $convert_path, $arr)) {
              $froms = explode('|', trim($arr[1], '()'));
              $tos = explode('|', trim($arr[2], '()'));
            }
            elseif (preg_match('@^(.*)~optimize$@', $convert_path, $arr)) {
              $froms = $tos = array(
                $arr[1],
              );
            }
            else {
              continue;
            }
            foreach ($froms as $from) {
              if (!isset($rows[$from])) {
                $rows[$from] = array();
              }
              foreach ($tos as $to) {
                $all_tos[] = $to;
                if (!isset($rows[$to])) {
                  $rows[$to] = array();
                }
                $rows[$from][$to] += sizeof($converters);
              }
            }
          }
        }

        // Build the table.
        $all_tos = array_unique($all_tos);
        sort($all_tos);
        ksort($rows);
        $exts = array_keys($rows);
        echo "source | " . join(" | ", $all_tos) . "\n";
        echo str_repeat("--- | ", sizeof($all_tos)) . "---\n";
        foreach ($rows as $from => $row) {
          if (empty($row)) {
            continue;
          }
          echo $from;
          foreach ($all_tos as $to) {
            if (isset($row[$to]) && $row[$to]) {
              echo " | " . $row[$to];
            }
            else {
              echo " | ";
            }
          }
          echo "\n";
        }
        break;

      default:
        $output->writeln("Usage: fileconverter info [converters|convert-paths|extension-table]");
        return;
    }

    // Sort and display the items.
    ksort($items);
    foreach ($items as $id => $item) {
      $output->writeln($item['#title']);
      foreach ($item as $k => $v) {
        if ($k{0} !== '#') {
          if (is_array($v)) {
            $output->writeln('   ' . $v['#title']);
            foreach ($v as $k1 => $v1) {
              if ($k1{0} !== '#') {
                $output->writeln('      ' . $v1);
              }
            }
          }
          else {
            $output->writeln('   ' . $v);
          }
        }
      }
    }
  }

}


text:
//
//  ListViewItem.h
//  CustomControl
//
//  Created by liww on 2014/12/2.
//  Copyright (c) 2014年 liww. All rights reserved.
//

#import <Foundation/Foundation.h>

@class ZZListView;

typedef enum {
    State_None,
    State_Prepare,
    State_Start,
    State_Success,
    State_Fail,
    State_Abort,
}State;

/**
 ListViewItem: ListView中使用的数据对象
 */
@interface ZZListViewItem : NSObject{
    CGFloat             _itemHeight;
    NSString            *_text;
    NSString            *_description;
    NSString            *_percent;
    NSAttributedString  *_attributedText;
    NSImage             *_stateImage;
    State               _state;
    CGFloat             _alphaValue;
}
@property (atomic, assign) CGFloat itemHeight;
@property (atomic, copy) NSString *text;
@property (nonatomic, copy) NSString *description;
@property (nonatomic, copy) NSString *percent;
@property (atomic, copy) NSAttributedString *attributedText;
@property (atomic, retain) NSImage *stateImage;
@property (atomic, assign) State state;
@property (nonatomic)CGFloat alphaValue;

@end

/**
 ListViewItemMgr: 管理ListView中使用的数据对象
 */
@interface ZZListViewItemMgr : NSObject{
    NSMutableArray      *_items;
    ZZListView          *_listView;
}

- (id)initWithListView:(ZZListView *)listView;

- (NSArray *)items;
- (NSInteger)itemCount;

- (ZZListViewItem *)itemAtIndex:(NSInteger)index;
- (NSInteger)indexOfItem:(ZZListViewItem *)item;
- (CGFloat)heightAtIndex:(NSInteger)index;

- (void)setText:(NSString *)text
    description:(NSString *)description
          state:(State)state
        atIndex:(NSInteger)index
       isReload:(BOOL)isReload;

- (void)setText:(NSString *)text
    description:(NSString *)description
          state:(State)state
           item:(ZZListViewItem *)item
       isReload:(BOOL)isReload;

- (void)setState:(State)state atIndex:(NSInteger)index isReload:(BOOL)isReload;
- (void)setText:(NSString *)text atIndex:(NSInteger)index isReload:(BOOL)isReload;
- (void)resetItemState;

- (void)addItem:(ZZListViewItem *)item;
- (void)insertItem:(ZZListViewItem *)item atIndex:(NSInteger)index;

- (void)removeItem:(ZZListViewItem *)item;
@end


text:
<?php
header("Suborigin: foobar");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><meta http-equiv=Set-Cookie> should not work in suborigin</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<meta http-equiv="Set-Cookie" content="TestCookieMetaSetCookieDisabledInSuborigin=a_value"></meta>
</head>
<body>
<script>
window.onmessage = function(e) {
  assert_equals(e.data.cookie_val, '');
  done();
};
</script>
<iframe src="resources/post-document-cookie.php"></iframe>
</body>
</html>


text:
define([
	'translates/locale_pt-br',
	'translates/locale_en',

	'square/app',

	'services/services',
	'services/resources',

	'controllers/controllers',
	'controllers/home-ctrl',
	'controllers/todo-ctrl'

], function (localePtBR, localeEn) {

	'use strict';

	var app = angular.module('app', ['square', '$strap.directives', 'app.services', 'app.controllers']);

	app.config(function ($translateProvider) {
		$translateProvider.translations('pt-BR', localePtBR);
		$translateProvider.translations('en', localeEn);
	});

	app.run(function ($window, $security, $bootstrap, $q, $error, $rootScope, $timeout, $translate) {
		$translate.use('pt-BR');

		$rootScope.$on('squareReady', function () {
			$window.document.title = I18n.t('titulo');

			$rootScope.header = {title: I18n.t('titulo'), infos: [], links: []};
			$rootScope.subheader = {};

			$rootScope.menu = [];
			$rootScope.menu.push({'text': I18n.t('menu.inicio'), href: '#/', 'submenu': []});
			$rootScope.menu.push({'text': I18n.t('menu.todo'), href: '#/todo', 'submenu': []});
		});

		$bootstrap.setProgress(0);

		var promise1 = function () {
			var defer = $q.defer();
			$timeout(function () {
				$bootstrap.setProgress($bootstrap.getProgress() + 20);
				defer.resolve();
			}, 500);
			return defer.promise;
		};

		$q.all([promise1(), promise1(), promise1(), promise1(), promise1()]).always(function () {
			$bootstrap.ready();
		});
	});

	return app;

});


text:
package org.meteogroup.jbrotli.servlet;

import io.dropwizard.Configuration;

public class HelloBrotliConfiguration extends Configuration {

}


text:
/* eslint-env serviceworker */
/* eslint-disable no-console */
/// <reference lib="webworker" />
export type {};

const CACHE_VERSION = 'v1';
const appShellFiles = ['./index.html'];
const worker: ServiceWorkerGlobalScope = self as unknown as ServiceWorkerGlobalScope;

async function fetchFromCache(request: Request) {
	const res = await caches.match(request);

	if (res) {
		return res;
	}

	return null;
}

async function fetchFromNetwork(request: Request) {
	try {
		const netRes = await fetch(request);

		const STORAGE_TRESHOLD = 0.7;
		const { quota, usage } = await navigator.storage.estimate();
		const isReachingQuota = (usage ?? 0) / (quota ?? 1) >= STORAGE_TRESHOLD;

		if (!isReachingQuota) {
			const cacheRes = netRes.clone();
			const cache = await caches.open(CACHE_VERSION);

			await cache.put(request, cacheRes);
		}

		return netRes;
	} catch (err) {
		console.error('[⚙] Network fetch failed!');
		console.error(err);
	}

	return new Response('Service Unavailable', {
		// eslint-disable-next-line @typescript-eslint/naming-convention
		headers: new Headers({ 'Content-Type': 'text/plain' }),
		status: 503,
		statusText: 'Service Unavailable'
	});
}

worker.addEventListener('install', async () => {
	try {
		const cache = await caches.open(CACHE_VERSION);

		await cache.addAll(appShellFiles);

		await worker.skipWaiting();
		console.log(`[⚙] Service worker installed for version ${CACHE_VERSION}`);
	} catch (err) {
		console.error('[⚙] Error installing worker:');
		console.error(err);
	}
});

worker.addEventListener('activate', async () => {
	const clientList = await worker.clients.matchAll({ includeUncontrolled: true });

	clientList.forEach((client) => {
		console.log(`[⚙] Matching client: ${client.url}`);
	});

	const cacheNames = await caches.keys();

	for await (const cacheName of cacheNames) {
		if (cacheName !== CACHE_VERSION) {
			console.log(`[⚙] Deleting old cache "${cacheName}"`);

			await caches.delete(cacheName);
		}

		console.log(`[⚙] Claming clients for version: ${CACHE_VERSION}`);

		await worker.clients.claim();
	}
});

worker.addEventListener('fetch', async (evt) => {
	let response = await fetchFromCache(evt.request);

	if (!response) {
		response = await fetchFromNetwork(evt.request);
	}

	return response;
});


text:
Describe provides a simple method for testing asynchronous and synchronous
code within JavaScript projects.

## API Documentation

### describe

describe( *groupName*, *tests*[, *options*] );

#### Arguments

- *groupName* (string): A human-readable description of the test group.
- *tests* (object): An object made up of human-readable test descriptions as
keys and functions to run as tests.  Tests functions will be given access to
`this.expect`.
- *options*: Configuration options.  Possible values:
	- timeout (int): The max amount of time in milliseconds to wait for a test
to run before timing out.
	- callbackMode (string): if set to 'node', this.expect will treat the first
argument to the callback as an error and the second argument as the result.

### describe.config

describe.config( *key*, *value* )

Sets the global configuration for tests.

### Synchronous Assertions

this.expect( *subject*, *expected* )

#### Arguments

- *subject* (mixed): the actual result.
- *expected* (mixed): the expected result.

#### Example

```javascript
describe("assertions", {
	'basic synchronous expectation': function() {
		this.expect(42, 42);
	}
});
```

### Asynchronous Assertions

By passing this.expect as the callback parameter to an asynchronous function,
describe will know to wait for the result of the operation before checking to
see if the result matches what was expected.

this.expect( *expected* )

#### Basic Callbacks

```javascript
function addNumbersAsync(a, b, callback) {
	callback(a+b);
}

describe("assertions", {
	'basic asynchronous expectation': function() {
		addNumbersAsync(2, 2, this.expect(4));
	}
});
```

#### Node.js-style (e, data) Callbacks

```javascript
function addNumbersAsync(a, b, callback) {
	callback(null, a+b);
}

describe("assertions", {
	'basic asynchronous expectation': function() {
		addNumbersAsync(2, 2, this.expect(4));
	}
}, { callbackMode: 'node' });
```

#### Promises-style Callbacks

```javascript
function addThingsPromise() {
	var n = 0;
	for (var i in arguments) n+=arguments[i];
	return {
		then: function(success, failure) {
			success(n);
		}
	};
}

describe("promise callback style", {
	'promises-style addition': function() {
		this.expect(addThingsPromise(2, 2), 4);
	}
}, {
	callbackMode: 'promises'
});
```

### describe.getResults

An asynchronous method.  Calls back with the results of all tests described up
to that point.  You should probably wait until you're done defining tests to
call this.

#### Example Results

```javascript
{
	passed: 1,
	total: 2,
	results: {
		"sample test group": {
			passed: 1,
			total: 2,
			results: {
				"this test passed because its error is null": null,
				"this test failed because there's an error": "Error or message"
			}
		}
	}
}
```

### describe.logResults

Gets the results and outputs them either to the DOM or the console.

### describe.new

Create a new independant instance of `describe`.

### Test Hooks

Each test group supports beforeEach, afterEach, beforeAll, and afterAll as
test hooks.

#### Example

```javascript
(function() {

	var arr = [], bowties;

	describe('array stuff', {
		beforeAll: function() {
			bowties = 'cool';
		},
		beforeEach: function() {
			arr = arr.concat(1,2,3);
		},
		afterEach: function() {
			arr = [];
		},
		afterAll: function() {
			tests = null;
		},
		'bowties are cool': function() {
			this.expect(bowties, 'cool');
		},
		'arrays have three things': function() {
			this.expect(arr.length, 3);
			arr.push(5);
		},
		'arrays still have three things': function() {
			this.expect(arr.length, 3);
		}
	});

}());
```


text:
package com.book1.idongri_log_analysis;

import java.util.*;

import org.json.simple.JSONValue;

import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;

public class SplitFunction extends BaseFunction {
	@Override
	public void execute(TridentTuple tuple, TridentCollector collector) {
		String string = tuple.getString(0);
//		System.out.println("str:" + string);
		String[] ss = string.split(" ");
		Values values = new Values();
//		for (int i = 0; i < ss.length; i++) {
//			System.out.println(ss[i]);
////			values.add(ss[i]);
//		}
		String method = ss[6];
		String time = ss[7].replaceAll("ms", "");
		int len1 = method.indexOf(")")+1;
		values.add(method.substring(0,len1));
		values.add(time);
//		System.out.println(values);
		collector.emit(values);
	}

}


text:
#pragma once

#if ENABLE(B3_JIT)

namespace JSC { namespace B3 { namespace Air {

class Code;

// Converts code that seems to have one entrypoint and emulates multiple entrypoints with
// EntrySwitch into code that really has multiple entrypoints. This is accomplished by duplicating
// the backwards transitive closure from all EntrySwitches.
void lowerEntrySwitch(Code&);

} } } // namespace JSC::B3::Air

#endif // ENABLE(B3_JIT)


text:
<?php

/* $Id: slirconfigdefaults.class.php 126 2010-12-22 18:43:22Z joe.lencioni $ */

/**
 * SLIR Config Class
 *
 * @since 2.0
 * @author Joe Lencioni <joe@shiftingpixel.com>
 * $Date: 2010-12-22 12:43:22 -0600 (Wed, 22 Dec 2010) $
 * @version $Revision: 126 $
 * @package SLIR
 */
class SLIRConfigDefaults
{
	/**
	 * How long (in seconds) the web browser should use its cached copy of the image
	 * before checking with the server for a new version
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $browserCacheTTL	= 604800; // 7 * 24 * 60 * 60

	/**
	 * Whether we should use the faster, symlink-based request cache as a first
	 * line cache
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $useRequestCache	= TRUE;

	/**
	 * Whether EXIF information should be copied from the source image
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $copyEXIF	= FALSE;

	/**
	 * How much memory (in megabytes) SLIR is allowed to allocate for memory-intensive processes such as rendering
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $maxMemoryToAllocate	= 100;

	/**
	 * Default quality setting to use if quality is not specified in the request.
	 * Ranges from 0 (worst quality, smaller file) to 100 (best quality, largest
	 * filesize).
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $defaultQuality	= 80;

	/**
	 * Default crop mode setting to use if crop mode is not specified in the request.
	 *
	 * Possible values are:
	 * SLIR::CROP_CLASS_CENTERED
	 * SLIR::CROP_CLASS_TOP_CENTERED
	 * SLIR::CROP_CLASS_SMART
	 * SLIR::CROP_CLASS_FACE (not finished)
	 *
	 * @since 2.0
	 * @var string
	 */
	public static $defaultCropper	= SLIR::CROP_CLASS_CENTERED;

	/**
	 * Default setting for whether JPEGs should be progressive JPEGs (interlaced)
	 * or not.
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $defaultProgressiveJPEG	= TRUE;

	/**
	 * Whether SLIR should log errors
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $logErrors	= TRUE;

	/**
	 * Whether SLIR should generate and output images from error messages
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $errorImages	= TRUE;

	/**
	 * Absolute path to the web root (location of files when visiting
	 * http://domainname.com/) (no trailing slash)
	 *
	 * @since 2.0
	 * @var string
	 */
	public static $documentRoot	= NULL;

	/**
	 * Path to SLIR (no trailing slash)
	 *
	 * @since 2.0
	 * @var string
	 */
	public static $SLIRDir	= NULL;

	/**
	 * Name of directory to store cached files in (no trailing slash)
	 *
	 * @since 2.0
	 * @var string
	 */
	public static $cacheDirName	= '/cache';

	/**
	 * Absolute path to cache directory. This directory must be world-readable,
	 * writable by the web server, and must end with SLIR_CACHE_DIR_NAME (no
	 * trailing slash). Ideally, this should be located outside of the web tree.
	 *
	 * @var string
	 */
	public static $cacheDir	= NULL;

	/**
	 * Path to the error log file. Needs to be writable by the web server. Ideally,
	 * this should be located outside of the web tree.
	 *
	 * @since 2.0
	 * @var string
	 */
	public static $errorLogPath	= NULL;

	/**
	 * If TRUE, forces SLIR to always use the query string for parameters instead
	 * of mod_rewrite.
	 *
	 * @since 2.0
	 * @var boolean
	 */
	public static $forceQueryString	= FALSE;

	/**
	 * In conjunction with $garbageCollectDivisor is used to manage probability that the garbage collection routine is started.
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $garbageCollectProbability	= 1;

	/**
	 * Coupled with $garbageCollectProbability defines the probability that the garbage collection process is started on every request.
	 *
	 * The probability is calculated by using $garbageCollectProbability/$garbageCollectDivisor, e.g. 1/100 means there is a 1% chance that the garbage collection process starts on each request.
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $garbageCollectDivisor	= 200;

	/**
	 * Specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up (deleted from the cache).
	 *
	 * @since 2.0
	 * @var integer
	 */
	public static $garbageCollectFileCacheMaxLifetime	= 86400; // 1 day = 1 * 24 * 60 * 60

	/**
	 * Initialize variables that require some dynamic processing.
	 *
	 * @since 2.0
	 * @return void
	 */
	public static function init()
	{
		if (self::$documentRoot === NULL)
		{
			self::$documentRoot	= preg_replace('/\/$/', '', $_SERVER['DOCUMENT_ROOT']);
		}

		if (self::$SLIRDir === NULL)
		{
			self::$SLIRDir		= dirname($_SERVER['SCRIPT_NAME']);
		}

		if (self::$cacheDir === NULL)
		{
			self::$cacheDir = self::$documentRoot . self::$SLIRDir . self::$cacheDirName;
		}

		if (self::$errorLogPath === NULL)
		{
			self::$documentRoot . self::$SLIRDir . '/slir-error-log';
		}
	}
}


text:
/**
 * DO NOT MODIFY, GENERATED BY TOOLS
 */
package com.titanium.zldt.mapper.base;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.titanium.component.query.Condition;

import com.titanium.zldt.models.DailyRepair;
import com.titanium.zldt.mapper.DailyRepairSearchTerms;

public interface DailyRepairMapperBase  {
   public int createDailyRepair(DailyRepair dailyRepair);

    public int updateDailyRepair(DailyRepair dailyRepair);

    public int deleteDailyRepair (int id);

	public int deleteDailyRepairByTerms(DailyRepairSearchTerms dailyRepairSearchTerms);

 	public DailyRepair getDailyRepair (int id);

    public List<DailyRepair> listDailyRepair(DailyRepairSearchTerms dailyRepairSearchTerms);

  public List<DailyRepair> listDailyRepairByIds(List<Integer> ids);

 	 public long countDailyRepair(DailyRepairSearchTerms dailyRepairSearchTerms);

}


text:
  * Mac OS X, Windows, or Linux
  * [Node.js](https://nodejs.org/) v8 or newer

### Directory Layout

Before you start, take a moment to see how the project structure looks like:

```
.
├── /build/                     # The folder for compiled output
├── /docs/                      # Documentation files for the project
├── /extra/                     # Extra resources like nginx config file and so on
├── /node_modules/              # 3rd-party libraries and utilities
├── /src/                       # The source code of the application
│   ├── /client/                # All JS files will be here
│   ├── /html/                  # All templates used by the Node server ([Marko](http://markojs.com/))
│   ├── /server/                # Node.js server files and config
│   ├── /ssl/                   # SSL local certificates to use on your machine. (The certificate is for localhost domain name)
│   ├── /static/                # All static files will be here. Images, robots.txt, favicon, etc.
│   ├── /styles/                # Styles folder, using Sass
├── /test/                      # Unit and end-to-end tests
├── /tools/                     # Build automation scripts and utilities
│   ├── /lib/                   # Utilities used for various tasks like fs, logging etc.
│   ├── /tasks/                 # Task files to clean compile and build
│   	├── /browserSync.js     # Browsersync task
│   	├── /clean.js           # Cleans up the output (build) folder
│   	├── /compiler.js        # Compiles js code using webpack
│   	├── /copy.js            # Copies static files and various extra to output (build) folder
│   	├── /gulpfile.js        # Main gulp entry file where all tasks are defined
│   	├── /css-minify.js      # Task to minify the CSS output using CleanCSS
│   	├── /postcss.config.js  # Configuration for transforming styles with PostCSS plugins
│   	├── /run-server.js      # Launches (or restarts) Node.js server
│   ├── /config.js              # Config file used by all tasks
│  	├── /postcss.config.js      # Configuration for transforming styles with PostCSS plugins
│   └── /webpack.config.js      # Configurations for client-side bundles
├── Dockerfile                  # TODO: Commands for building a Docker image for production
└── package.json                # The list of 3rd party libraries and utilities
```

### Quick Start

#### 1. Get the latest version

You can start by cloning the latest version on your local machine by running:

```shell
$ git clone -o webapp-boilerplate -b master --single-branch \
      https://github.com/radum/webapp-boilerplate.git MyApp
$ cd MyApp
```

Alternatively, you can start a new project by using Yeoman generator (TODO).

#### 2. Run `npm install`

This will install both run-time project dependencies and developer tools listed
in [package.json](../package.json) file.

#### 3. Run `npm run dev`

This command will build the app from the source files (`/src`) into the output
`/build` folder. As soon as the initial build completes, it will start the
Node.js server and [Browsersync](https://browsersync.io/).

> [http://localhost:3000/](http://localhost:3000/) — Node.js server with Browsersync and HMR enabled<br>
> [http://localhost:3001/](http://localhost:3002/) — Browsersync control panel (UI)

*NOTE: Port number are subject to change based on the .env / .env.[mode].local files in the root folder*

Now you can open your web app in a browser, on mobile devices and start
hacking. Whenever you modify any of the source files inside the `/src` folder,
the module bundler ([Webpack](http://webpack.github.io/)) will recompile the
app on the fly and refresh all the connected browsers.

Note that the `npm run dev` command launches the app in `development` mode,
the compiled output files are not optimized and minimized in this case.

### How to Build, Test, Deploy

If you need just to build the app (without running a dev server), simply run:

```shell
$ npm run build
```

After running this command, the `/build` folder will contain the compiled
version of the app. For example, you can launch Node.js server normally by
running `node build/server/server.js`.

TODO: To check the source code for syntax errors and potential issues run:

```shell
$ npm run lint
```

TODO: To launch unit tests:

```shell
$ npm run test          # Run unit tests with Mocha
$ npm run test:watch    # Launch unit test runner and start watching for changes
```

TODO: To deploy the app, run:

```shell
$ npm run deploy
```

### How to Update

If you need to keep your project up to date with the recent changes made to RSK,
you can always fetch and merge them from [this repo](https://github.com/radum/webapp-boilerplate)
back into your own project by running:

```shell
$ git checkout master
$ git fetch webapp-boilerplate
$ git merge webapp-boilerplate/master
$ npm install
```