text:
package controllers.admin

import java.util.UUID

import akka.pattern.ask
import akka.util.Timeout
import controllers.BaseController
import models._
import play.api.i18n.MessagesApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.supervisor.ActorSupervisor
import services.user.AuthenticationEnvironment

import scala.concurrent.duration._

@javax.inject.Singleton
class TraceController @javax.inject.Inject() (override val messagesApi: MessagesApi, override val env: AuthenticationEnvironment) extends BaseController {
  implicit val timeout = Timeout(10.seconds)

  def traceConnection(connectionId: UUID) = withAdminSession("connection") { implicit request =>
    (ActorSupervisor.instance ask ConnectionTrace(connectionId)).map {
      case tr: TraceResponse => Ok(views.html.admin.trace("Connection", tr))
      case se: ServerError => Ok(s"${se.reason}: ${se.content}")
    }
  }

  def traceClient(connectionId: UUID) = withAdminSession("client") { implicit request =>
    (ActorSupervisor.instance ask ClientTrace(connectionId)).map {
      case tr: TraceResponse => Ok(views.html.admin.trace("Client", tr))
      case se: ServerError => Ok(s"${se.reason}: ${se.content}")
    }
  }
}


text:
package com.thinkaurelius.titan.graphdb.query;

import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.core.TitanRelation;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.SliceQuery;
import com.thinkaurelius.titan.graphdb.internal.InternalVertex;
import com.thinkaurelius.titan.graphdb.query.condition.Condition;
import com.thinkaurelius.titan.graphdb.relations.RelationComparator;
import com.tinkerpop.blueprints.Direction;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;

/**
 * @author Matthias Broecheler (me@matthiasb.com)
 */

public class VertexCentricQuery extends BaseVertexCentricQuery implements ElementQuery<TitanRelation, SliceQuery> {

    private final InternalVertex vertex;

    public VertexCentricQuery(InternalVertex vertex, Condition<TitanRelation> condition,
                              Direction direction,
                              List<BackendQueryHolder<SliceQuery>> queries,
                              int limit) {
        super(condition, direction, queries, limit);
        Preconditions.checkNotNull(vertex);
        this.vertex = vertex;
    }

    public VertexCentricQuery(InternalVertex vertex, BaseVertexCentricQuery base) {
        super(base);
        Preconditions.checkNotNull(vertex);
        this.vertex = vertex;
    }

    protected VertexCentricQuery(InternalVertex vertex) {
        super();
        Preconditions.checkNotNull(vertex);
        this.vertex = vertex;
    }

    public static VertexCentricQuery emptyQuery(InternalVertex vertex) {
        return new VertexCentricQuery(vertex);
    }

    public InternalVertex getVertex() {
        return vertex;
    }

    @Override
    public boolean isSorted() {
        return true;
    }

    @Override
    public Comparator getSortOrder() {
        return new RelationComparator(vertex);
    }

    @Override
    public boolean hasDuplicateResults() {
        return false; //We wanna count self-loops twice
    }

    @Override
    public String toString() {
        return vertex+super.toString();
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<testng-results skipped="0" failed="0" total="5" passed="5">
  <reporter-output>
  </reporter-output>
  <suite name="Default suite" duration-ms="10788" started-at="2015-08-21T21:27:36Z" finished-at="2015-08-21T21:27:47Z">
    <groups>
    </groups>
    <test name="Default test" duration-ms="10788" started-at="2015-08-21T21:27:36Z" finished-at="2015-08-21T21:27:47Z">
      <class name="com.example.tests.ContactCreationTests">
        <test-method status="PASS" signature="testContactCreation()[pri:0, instance:com.example.tests.ContactCreationTests@224aed64]" name="testContactCreation" duration-ms="2167" started-at="2015-08-22T00:27:41Z" finished-at="2015-08-22T00:27:43Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testContactCreation -->
      </class> <!-- com.example.tests.ContactCreationTests -->
      <class name="com.example.tests.AlsoGroupCreationTests">
        <test-method status="PASS" signature="testEmptyGroupCreation()[pri:0, instance:com.example.tests.AlsoGroupCreationTests@c39f790]" name="testEmptyGroupCreation" duration-ms="664" started-at="2015-08-22T00:27:45Z" finished-at="2015-08-22T00:27:46Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testEmptyGroupCreation -->
        <test-method status="PASS" signature="testNonEmptyGroupCreation()[pri:0, instance:com.example.tests.AlsoGroupCreationTests@c39f790]" name="testNonEmptyGroupCreation" duration-ms="728" started-at="2015-08-22T00:27:46Z" finished-at="2015-08-22T00:27:46Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testNonEmptyGroupCreation -->
      </class> <!-- com.example.tests.AlsoGroupCreationTests -->
      <class name="com.example.tests.GroupCreationTests">
        <test-method status="PASS" signature="setUp()[pri:0, instance:com.example.tests.GroupCreationTests@6979e8cb]" name="setUp" is-config="true" duration-ms="5197" started-at="2015-08-22T00:27:36Z" finished-at="2015-08-22T00:27:41Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- setUp -->
        <test-method status="PASS" signature="testEmptyGroupCreation()[pri:0, instance:com.example.tests.GroupCreationTests@6979e8cb]" name="testEmptyGroupCreation" duration-ms="751" started-at="2015-08-22T00:27:43Z" finished-at="2015-08-22T00:27:44Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testEmptyGroupCreation -->
        <test-method status="PASS" signature="testNonEmptyGroupCreation()[pri:0, instance:com.example.tests.GroupCreationTests@6979e8cb]" name="testNonEmptyGroupCreation" duration-ms="869" started-at="2015-08-22T00:27:44Z" finished-at="2015-08-22T00:27:45Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testNonEmptyGroupCreation -->
        <test-method status="PASS" signature="tearDown()[pri:0, instance:com.example.tests.GroupCreationTests@6979e8cb]" name="tearDown" is-config="true" duration-ms="404" started-at="2015-08-22T00:27:46Z" finished-at="2015-08-22T00:27:47Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- tearDown -->
      </class> <!-- com.example.tests.GroupCreationTests -->
    </test> <!-- Default test -->
  </suite> <!-- Default suite -->
</testng-results>


text:
<!DOCTYPE html><meta charset="utf-8"/><title>StrapDown.js on lbesson.bitbucket.org/md</title><xmp theme="cyborg">
# StrapDown.js
**StrapDown.js** is an awesome **on-the-fly** [Markdown](https://en.wikipedia.org/wiki/Markdown)
to [HTML](https://en.wikipedia.org/wiki/HTML) [text processor](https://en.wikipedia.org/wiki/Compiler).

## Features
- *Directly write your documents in Markdown*, and let the browser do the boring *compilation* steps,
- no need for CSS, theming or painless styling : *StrapDown.js* is already *friggin' beautiful*, and *responsive*,
- *quick* and *secure*, thanks to *bitbucket* and its SSL (even if the certificate is not valid for [lbesson.bitbucket.org](https://lbesson.bitbucket.org), it is still secure),
- an almost perfect support for text-only browsers : pure Markdown is simpler to read than complicated HTML full of javascript,
- no external dependencies other than itself,
- no spying, no logging, no leaking of your pages (only [Google Analytics](http://besson.qc.to/beacon.html) with the default template, and [rum.js from bitbucket hosting server](https://confluence.atlassian.com/display/BITBUCKET/Publishing+a+Website+on+Bitbucket#PublishingaWebsiteonBitbucket-TechnicalFeaturesandLimitationsofthisFeature)).

- And, the last but not the least, *experimental* embedding of the even awesomer [SquirtFR](https://lbesson.bitbucket.org/squirt) bookmarklet to read *as quickly as Lucky Luke*.

## Defaults ?
 - It might get slow for *long* pages (3000 lines seem to be too much),
 - a reduced support for browsers *without javascript* or *with javascript disabled* (the pages are still readable, but really ugly),
 - hosted on bitbucket, which is wonderful but might not be always available (~ 3 hours of maintenance every 6 months).

Concretly, bitbucket is always *up*, *secured* and *quick* (ooh, and bitbucket is also awesome, completely free, and awesome too). Yeah, *bitbucket is so awesome* that I had to say it twice, you read it correctly.

But if you prefer, feel free to download [StrapDown.js.zip](https://bitbucket.org/lbesson/lbesson.bitbucket.org/downloads/StrapDown.js.zip) and embed it on your own server.

> ## A quick "thank you" to the initial project
> My version of StrapDown.js is a fork of [strapdownjs.com](http://strapdownjs.com), a cool project that kinda seems dead by now.

----

## How to start using StrapDown.js ?
**Just follow this short tutorial** :

### [Default template to use](example0.html) *(you can click this to see it)*
Create an empty file, save it to *mytext.html*
(yes, *.html* as HTML, but you will write in Markdown in no time),
and then copy and paste the following 5 lines :

```markdown
<!DOCTYPE html><html><head><title>A StrapDown.js template</title></head><body><textarea theme="cyborg">
### Write here in Markdown rather than in HTML
> This document is empty right now. Fill it out with awesome content !

</textarea><script type="text/javascript" src="//lbesson.bitbucket.org/md/strapdown.js?src=example0"></script></body></html>
```

### [A first example](example1.html) *(you can click this to see it)*
There we use some markup.

```markdown
<!DOCTYPE html><html><head><meta charset="utf-8"/><title>« My first test with StrapDown.js »</title></head><body><textarea theme="cyborg">
# This is a Markdown document
You can now write your web page in Markdown.

You opened a `textarea` tag, but a `xmp` tag works as well.

And, yes, it is **as simple** as **one** HTML line at the beginning and **one** HTML line at the end of this document.
</textarea><script type="text/javascript" src="//lbesson.bitbucket.org/md/strapdown.js?src=example1"></script></body></html>
```

### [A second example](example2.html) *(you can click this to see it)*
There we embed two images, and describe a little more how cool is StrapDown.js !
We also use another theme (*united*).

```markdown
<!DOCTYPE html><html><head><title>Awesome second example with StrapDown.js</title></head><body><textarea theme="united">
# This is a Markdown document
You can now write your web page in Markdown.
You opened a `textarea` tag, but a `xmp` tag works as well.
And, yes, it is **as simple** as **one** HTML line at the beginning and **one** HTML line at the end of this document.

## What to say more
Feel free to use it, redistribute it etc, *under the condition of the GPLv3 License*.

## Only for textual, simple documents
StrapDown.js is *awesome* to quickly build nice-looking web page,
but it might not be efficient for anything more complicated, as it is really not designed for it.

## Add a picture ?
With Markdown syntax, it's easy : ![GA|Analytics](https://ga-beacon.appspot.com/UA-38514290-14/example2.html "Thanks to ga-beacon").

### An other one ?
Alright, here comes the mighty Cthulhu ![Logo Squirt](../squirt/images/logo.png "Logo Cthulhu")

### A last one, because it's dangerous to go alone :

![Logo Take this from dotcore](../squirt/images/takethis.jpg "Logo «Take this» from dotcore")

## Add anything you want, it *might* work
For instance, you can add use Google Analytics to monitor the page's activity,
with including a piece of Javascript code, before *or* after closing the *textarea* tag.

<script type="text/javascript">
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create','UA-38514290-14','lbesson.bitbucket.org'); ga('send','pageview');
</script>
<noscript>
  The previous parapraph was supposed to include Google Analytics web monitoring tool,
  but hey, you are browsing without JavaScript enabled, what can I do for it ? <br/>
  Maybe you are using a text-only browser (w3m, links, elinks ? I love elinks !),
  or a 19th-century IE, or maybe you disabled JavaScript globally (which is kinda stupid) or site-by-site (with NoScript, as I do, which is brilliant, and safer).
</noscript>

## That's it
This was a brief overview, to show the basic use of [StrapDown.js](index.html).
</textarea><script type="text/javascript" src="//lbesson.bitbucket.org/md/strapdown.js?src=example2"></script></body></html>
```

### Themes
Only two themes from [strapdownjs.com]() are pretty enough to be included :

 - [cyborg](http://bootswatch.com/cyborg) for a demo,
 - [united](http://bootswatch.com/united) for a demo.

More will soon be availables !

### Printing to a nice looking PDF
Rather than use the built-in "Print to a PDF" function
of your browser, you should consider using [StrapDown2PDF](strapdown2pdf.html).

----

# Cloning
As of now, StrapDown.js does **not** have it own git repository.
And I don't want to, because it is cleaner to let it live on http://lbesson.bitbucket.org/md.

But, there, you can download this not up-to-date version of the *md* subdir of my [lbesson.bitbucket.org](https://bitbucket.org/lbesson/lbesson.bitbucket.org/src/master/md/) repository :
[StrapDown.js.zip](https://bitbucket.org/lbesson/lbesson.bitbucket.org/downloads/StrapDown.js.zip)
(and [its PGP signature](https://bitbucket.org/lbesson/lbesson.bitbucket.org/downloads/StrapDown.js.zip.asc).)

----

# Future features
- Maybe host it on a *CDN*,
- More themes,
- Hack something to force using local cached version of the script and stylesheets rather than download them every time ?

----

# About
### Hacked by [Lilian Besson](https://bitbucket.org/lbesson)

### Languages
 - JavaScript;
 - CSS 3.

### License
This project is released under the **GPLv3 license**, for more details,
take a look at the [LICENSE](http://besson.qc.to/LICENSE.html) file in the source.

*Basically, that allow you to use all or part of the project for you own business.*
</xmp>


text:
<?php

namespace ShopBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * GoodRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GoodRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('category' => 'ASC'));
    }
}


text:
package certgen.controller.action;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import certgen.util.ImageUtil;
import certgen.util.security.KeyStoreUtil;
import certgen.view.dialog.NewPasswordDialog;
import certgen.view.frame.MainFrame;

/**
 * Extended AbstractAction class which performs necessary things for new saving key store to file.
 *
 * @author Dražen Đanić
 *
 */
public class SaveAsKeyStoreAction extends AbstractAction {

	private static final long serialVersionUID = -7049295203087653165L;

	public SaveAsKeyStoreAction() {
		putValue(NAME, "Save As Keystore");
		putValue(SHORT_DESCRIPTION, "Save key store to new file");
		putValue(SMALL_ICON, ImageUtil.loadImageIcon(getClass().getResource("/certgen/resource/img/save_as-icon.png"), 20, 20));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		MainFrame mf = MainFrame.getInstance();

		if (mf.getCurrentKS() != null) {
			JFileChooser fchKeyStore = new JFileChooser();
			fchKeyStore.setDialogTitle("Save Keystore");
			fchKeyStore.setAcceptAllFileFilterUsed(false);
			fchKeyStore.setFileFilter(new FileNameExtensionFilter("Java KeyStore file (*.jks)", "jks"));
			int retVal = fchKeyStore.showSaveDialog(null);

			if (retVal == JFileChooser.APPROVE_OPTION) {
				File selectedKSFile = fchKeyStore.getSelectedFile();
				String selectedKSPath = selectedKSFile.getAbsolutePath();

				if (!selectedKSPath.endsWith(".jks")) {
					selectedKSPath += ".jks";
				}

				NewPasswordDialog npd = new NewPasswordDialog();
				npd.setVisible(true);

				char[] newPassword = npd.getNewPassword();
				npd.dispose();

				if (newPassword != null) {
					boolean successSave = KeyStoreUtil.saveKeyStore(mf.getCurrentKS(), selectedKSPath, newPassword);

					if (successSave) {
						// Successfully saved
						mf.setCurrentKSFilePath(selectedKSPath);
						mf.setChangedKS(false);
						mf.refreshStatusBar();
					} else {
						JOptionPane.showMessageDialog(null, "An error has occurred while saving keystore!", "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		} else {
			JOptionPane.showMessageDialog(null, "You must create or open a keystore first!", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

}


text:
using safe_browsing::ClientDownloadResponse;
using safe_browsing::ClientSafeBrowsingReportRequest;

namespace {

const char kDownloadDangerPromptPrefix[] = "Download.DownloadDangerPrompt";

// Converts DownloadDangerType into their corresponding string.
const char* GetDangerTypeString(
    const download::DownloadDangerType& danger_type) {
  switch (danger_type) {
    case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE:
      return "DangerousFile";
    case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
      return "DangerousURL";
    case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
      return "DangerousContent";
    case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
      return "DangerousHost";
    case download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
      return "UncommonContent";
    case download::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
      return "PotentiallyUnwanted";
    case download::DOWNLOAD_DANGER_TYPE_ASYNC_SCANNING:
      return "AsyncScanning";
    case download::DOWNLOAD_DANGER_TYPE_BLOCKED_PASSWORD_PROTECTED:
      return "BlockedPasswordProtected";
    case download::DOWNLOAD_DANGER_TYPE_BLOCKED_TOO_LARGE:
      return "BlockedTooLarge";
    case download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING:
      return "SensitiveContentWarning";
    case download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK:
      return "SensitiveContentBlock";
    case download::DOWNLOAD_DANGER_TYPE_DEEP_SCANNED_SAFE:
      return "DeepScannedSafe";
    case download::DOWNLOAD_DANGER_TYPE_DEEP_SCANNED_OPENED_DANGEROUS:
      return "DeepScannedOpenedDangerous";
    case download::DOWNLOAD_DANGER_TYPE_PROMPT_FOR_SCANNING:
      return "PromptForScanning";
    case download::DOWNLOAD_DANGER_TYPE_BLOCKED_UNSUPPORTED_FILETYPE:
      return "BlockedUnsupportedFiletype";
    case download::DOWNLOAD_DANGER_TYPE_DANGEROUS_ACCOUNT_COMPROMISE:
      return "DangerousAccountCompromise";
    case download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
    case download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
    case download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
    case download::DOWNLOAD_DANGER_TYPE_ALLOWLISTED_BY_POLICY:
    case download::DOWNLOAD_DANGER_TYPE_MAX:
      break;
  }
  NOTREACHED();
  return nullptr;
}

}  // namespace

void DownloadDangerPrompt::SendSafeBrowsingDownloadReport(
    ClientSafeBrowsingReportRequest::ReportType report_type,
    bool did_proceed,
    const download::DownloadItem& download) {
  safe_browsing::SafeBrowsingService* sb_service =
      g_browser_process->safe_browsing_service();
  Profile* profile = Profile::FromBrowserContext(
      content::DownloadItemUtils::GetBrowserContext(&download));
  auto report = std::make_unique<ClientSafeBrowsingReportRequest>();
  report->set_type(report_type);
  ClientDownloadResponse::Verdict download_verdict =
      safe_browsing::DownloadDangerTypeToDownloadResponseVerdict(
          download.GetDangerType());
  if (download_verdict == ClientDownloadResponse::SAFE) {
    // Don't send report if the verdict is SAFE.
    return;
  }
  report->set_download_verdict(download_verdict);
  report->set_url(download.GetURL().spec());
  report->set_did_proceed(did_proceed);
  *report->mutable_population() =
      safe_browsing::GetUserPopulationForProfile(profile);
  std::string token =
      safe_browsing::DownloadProtectionService::GetDownloadPingToken(&download);
  if (!token.empty())
    report->set_token(token);
  std::string serialized_report;
  if (report->SerializeToString(&serialized_report)) {
    sb_service->SendSerializedDownloadReport(profile, serialized_report);

    // The following is to log this ClientSafeBrowsingReportRequest on any open
    // chrome://safe-browsing pages.
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(
            &safe_browsing::WebUIInfoSingleton::AddToCSBRRsSent,
            base::Unretained(safe_browsing::WebUIInfoSingleton::GetInstance()),
            std::move(report)));
  } else {
    DLOG(ERROR) << "Unable to serialize the threat report.";
  }
}

void DownloadDangerPrompt::RecordDownloadDangerPrompt(
    bool did_proceed,
    const download::DownloadItem& download) {
  int64_t file_type_uma_value =
      safe_browsing::FileTypePolicies::GetInstance()->UmaValueForFile(
          download.GetTargetFilePath());
  download::DownloadDangerType danger_type = download.GetDangerType();

  base::UmaHistogramSparse(
      base::StringPrintf("%s.%s.Shown", kDownloadDangerPromptPrefix,
                         GetDangerTypeString(danger_type)),
      file_type_uma_value);
  if (did_proceed) {
    base::UmaHistogramSparse(
        base::StringPrintf("%s.%s.Proceed", kDownloadDangerPromptPrefix,
                           GetDangerTypeString(danger_type)),
        file_type_uma_value);
  }
}


text:
package stellar;

import com.itextpdf.text.DocumentException;

import stellar.data.Astrogation;
import stellar.io.AstrogationFileReader;
import stellar.io.Resources;
import stellar.swing.AstrogationChangeEvent;
import stellar.data.GroupRecord;
import stellar.data.HexID;
import stellar.dialog.EditGroups;
import stellar.dialog.EditLink;
import stellar.dialog.EditOptions;
import stellar.dialog.EditSystem;
import stellar.dialog.EditViewOptions;
import stellar.dialog.Map_AboutBoxPanel1;
import stellar.dialog.ViewTableData;
import stellar.io.AccessXMLFile;
import stellar.io.filter.CXMLFileFilter;
import stellar.io.GalDATReader;
import stellar.io.GalSARReader;
import stellar.io.filter.JPEGFileFilter;
import stellar.io.filter.PDFFileFilter;
import stellar.io.PDFFileWriter;
import stellar.io.filter.SARFileFilter;
import stellar.io.filter.SECFileFilter;
import stellar.io.SECFileReader;
import stellar.io.SECFileStateMachineException;
import stellar.io.filter.WBSFileFilter;
import stellar.io.WBSReader;
import stellar.io.filter.XMLFileFilter;
import stellar.map.MapIcon;
import stellar.swing.AstrogationChangeListener;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionEvent;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;

import org.jibx.runtime.JiBXException;

/**
 * MapCommands implements the handlers for the menu and toolbar commands in one
 * place. MapMenu and MapToolbar use this class
 * indirectly through the Action interface and .properties files to
 * construct the menu items and toolbar buttons.
 *
 * @see MapMenu
 * @see MapToolbar
 * @see com.softstart.stellar.io.AppDefaults
 * @see com.softstart.stellar.swing.Command
 * @version $Id$
 */
public class MapCommands
{
    EventListenerList listenerList = new EventListenerList ();
    PropertyChangeEvent propertyChange;
    PropertyChangeEvent refreshMap =
        new PropertyChangeEvent (this, MapMenu.VIEW_REFRESH, null, null);
    Component display;
    MapIcon map;

    public MapCommands (Component display, MapIcon map)
    {
        this.display = display;
        this.map = map;
    }

    public void setMapIcon (MapIcon map)
    {
        this.map = map;
    }

    public void addChangeListener (ChangeListener l)
    {
        listenerList.add (ChangeListener.class, l);
    }

    public void removeChangeListener (ChangeListener l)
    {
        listenerList.remove (ChangeListener.class, l);
    }

    /**
     * Adds an AstrogationChangeListener to the command handler.
     * @param l the AstrogationChangeListener to be added.
     */
    public void addAstrogationChangeListener (AstrogationChangeListener l)
    {
        listenerList.add (AstrogationChangeListener.class, l);
    }

    /**
     * Removes an AstrogationChangeListener from the command handler.
     * @param l the AstrogationChangeListener to be removed.
     */
    public void removeAstrogationChangeListener (AstrogationChangeListener l)
    {
        listenerList.remove (AstrogationChangeListener.class, l);
    }

    /**
     * Adds a PropertyChangeListener to the command handler.
     * @param l the PropertyChangeListener to be added.
     */
    public void addPropertyChangeListener (PropertyChangeListener l)
    {
        listenerList.add (PropertyChangeListener.class, l);
    }

    /**
     * Removed a PropertyChangeListener from the command handler.
     * @param l the PropertyChangeListener to be removed.
     */
    public void removePropertyChangeListener (PropertyChangeListener l)
    {
        listenerList.remove (PropertyChangeListener.class, l);
    }

    protected void fireAstrogationChanged (Astrogation data)
    {
        AstrogationChangeEvent change = null;
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList ();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        {
            if (listeners[i] == AstrogationChangeListener.class)
            {
                // Lazily create the event:
                if (change == null)
                    change = new AstrogationChangeEvent (data);
                ((AstrogationChangeListener)listeners[i +
                 1]).stateChanged (change);
            }
        }
    }

    protected void fireStateChanged ()
    {
        ChangeEvent change = null;
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList ();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        {
            if (listeners[i] == ChangeListener.class)
            {
                // Lazily create the event:
                if (change == null)
                    change = new ChangeEvent (this);
                ((ChangeListener)listeners[i + 1]).stateChanged (change);
            }
        }
    }

    protected void firePropertyChanged ()
    {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList ();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        {
            if (listeners[i] == PropertyChangeListener.class)
            {
                // Lazily create the event:
                ((PropertyChangeListener)listeners[i +
                 1]).propertyChange (propertyChange);
            }
        }
    }

    public void fileNew (ActionEvent e)
    {
        Astrogation starData = new Astrogation ();
        setAstrogrationData (starData);
        fireAstrogationChanged (starData);
        viewRefresh (e);
    }

    public void fileOpen (ActionEvent e)
    {
        AstrogationFileReader data = null;
        Astrogation starData = null;
        JFileChooser chooser = new JFileChooser ();
        chooser.setDialogTitle (Resources.getString ("map.openTitle"));
        chooser.setCurrentDirectory (new File (MapPreferences.getInstance().getWorkingDir()));
        chooser.addChoosableFileFilter (new SARFileFilter ());
        chooser.addChoosableFileFilter (new SECFileFilter ());
        chooser.addChoosableFileFilter (new WBSFileFilter ());
        chooser.addChoosableFileFilter (new CXMLFileFilter ());
        chooser.addChoosableFileFilter (new XMLFileFilter ());
        int option = chooser.showOpenDialog (display);
        if (option == JFileChooser.APPROVE_OPTION)
        {
            display.setCursor (Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR));
            File file = chooser.getSelectedFile ();
            if (file.canRead () && file.getName ().endsWith ("xml"))
            {
                data = new AccessXMLFile (file);
                if (file.getName ().endsWith ("cxml"))
                {
                    ((AccessXMLFile)data).setUseCompressedFile (true);
                }
            } else if (file.canRead () &&
                       file.getName ().toLowerCase ().endsWith ("sec"))
            {
                data = new SECFileReader (file);
            } else if (file.canRead () &&
                       file.getName ().toLowerCase ().endsWith ("dat"))
            {
                data = new GalDATReader (file);
            } else if (file.canRead () &&
                       file.getName ().toLowerCase ().endsWith ("sar"))
            {
                data = new GalSARReader (file);
            } else if (file.canRead () &&
                       file.getName ().toLowerCase ().endsWith ("wbs"))
            {
                data = new WBSReader (file);
            }
            if (data == null)
            {
                display.setCursor (Cursor.getDefaultCursor ());
                JOptionPane.showMessageDialog (display,
                                               "Unrecognized data file. No data loaded", Resources.getString ("map.NoFileTitle"),
                                               JOptionPane.ERROR_MESSAGE);
                return;
            }
            try
            {
                data.read ();
            } catch (FileNotFoundException ex)
            {
                JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.NoFileTitle"),
                                               JOptionPane.ERROR_MESSAGE);
            } catch (IOException ex)
            {
                JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.IOExceptionTitle"),
                                               JOptionPane.ERROR_MESSAGE);
            } catch (SECFileStateMachineException ex)
            {
                JOptionPane.showMessageDialog (display, ex.getMessage (),
                                               "Error: Sector File Read State Machine Error",
                                               JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace ();
            } catch (JiBXException ex)
            {
                JOptionPane.showMessageDialog (display, ex.getMessage (),
                                               "Error: Global Reference Read Failure",
                                               JOptionPane.ERROR_MESSAGE);
            }
            starData = data.getAstrogation ();
            display.setCursor (Cursor.getDefaultCursor ());
            //statusBar.setText("Rendering Map...");
            MapPreferences.getInstance ().setCurrentFile(file.getAbsolutePath());
            MapPreferences.getInstance ().setWorkingDir(file.getParent ());
            if (starData != null)
            {
                setAstrogrationData (starData);
            }
            fireAstrogationChanged (starData);
            viewRefresh (e);
            //mapGraphic.invalidate();
        } // if approved to open the file
    }

    public void fileSave (ActionEvent e)
    {
        String outputFile = MapPreferences.getInstance ().getCurrentFile ();
        if (outputFile == null)
        {
            fileSaveAs (e);
            return;
        }
        if (!outputFile.endsWith ("xml"))
        {
            /* replace the file name with an xml file name */
            outputFile =
                    outputFile.substring (0, outputFile.length () - 4) + ".xml";
            MapPreferences.getInstance ().setCurrentFile (outputFile);
        }
        AccessXMLFile data = new AccessXMLFile (outputFile);
        data.setAstrogation (map.getMapData ());
        if (outputFile.endsWith ("cxml"))
        {
            data.setUseCompressedFile (true);
        }
        try
        {
            data.write ();
        } catch (IOException ex)
        {
            JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.IOExceptionTitle"),
                                           JOptionPane.ERROR_MESSAGE);
        } catch (JiBXException ex)
        {
            JOptionPane.showMessageDialog (display, ex.getMessage (),
                                           "Error: JiBX XML Writer Exception",
                                           JOptionPane.ERROR_MESSAGE);
        }
    }

    public void fileSaveAs (ActionEvent e)
    {
        JFileChooser chooser = new JFileChooser ();
        chooser.setDialogTitle (Resources.getString ("map.saveTitle"));
        chooser.setCurrentDirectory (new File (MapPreferences.getInstance ().getWorkingDir ()));
        chooser.addChoosableFileFilter (new JPEGFileFilter ());
        chooser.addChoosableFileFilter (new PDFFileFilter ());
        chooser.addChoosableFileFilter (new CXMLFileFilter ());
        chooser.addChoosableFileFilter (new XMLFileFilter ());
        int option = chooser.showSaveDialog (display);

        if (option == JFileChooser.APPROVE_OPTION)
        {
            File file = chooser.getSelectedFile ();
            MapPreferences.getInstance ().setWorkingDir(file.getParent ());
            MapPreferences.getInstance ().setCurrentFile (file.getAbsolutePath ());

            if (chooser.getFileFilter () instanceof JPEGFileFilter)
            {
                if (!file.getName ().endsWith (".jpeg"))
                {
                    file = new File (file.getAbsoluteFile () + ".jpeg");
                }
                try
                {
                    map.write (file);
                } catch (IOException ex)
                {
                    JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.IOExceptionTitle"),
                                                   JOptionPane.ERROR_MESSAGE);
                }
            } else if (chooser.getFileFilter () instanceof PDFFileFilter)
            {
                if (!file.getName ().endsWith (".pdf"))
                {
                    file = new File (file.getAbsoluteFile () + ".pdf");
                }
                try
                {
                    PDFFileWriter data = new PDFFileWriter (file);
                    data.setMapData (map.getMapData ());
                    data.setScale (map.getScale ());
                    data.setScope (map.getScope ());
                    if (map.getGroupData () != null)
                        data.setGroup (map.getGroupData ());
                    data.write ();
                } catch (IOException ex)
                {
                    JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.IOExceptionTitle"),
                                                   JOptionPane.ERROR_MESSAGE);
                } catch (DocumentException ex)
                {
                    JOptionPane.showMessageDialog (display, ex.getMessage (),
                                                   "Error: Document Exception",
                                                   JOptionPane.ERROR_MESSAGE);
                }
            } else
            {
                fileSave (e);
            }
        }
    }

    public void fileExit (ActionEvent e)
    {
        MapPreferences.getInstance ().savePreferences ();
        System.exit (0);
    }

    public void editSystem (ActionEvent e)
    {
        Astrogation data;
        EditSystem dialog = EditSystem.getInstance ();
        dialog.setLocationRelativeTo (display);
        dialog.newSystem ();
        dialog.setVisible (true);
        if (dialog.getSystem () == null)
            return;
        if (map.getMapData () == null)
        {
            data = new Astrogation ();
            data.addSystem (dialog.getSystem ());
        } else
        {
            data = map.getMapData ();
            data.addSystem (dialog.getSystem ());
        }
        fireAstrogationChanged (data);

    }

    public void editGroups (ActionEvent e)
    {
        EditGroups dialog = new EditGroups (map.getMapData ());
        dialog.setLocationRelativeTo (display);
        dialog.setVisible (true);
    }

    public void editLinks (ActionEvent e)
    {
        EditLink dialog = new EditLink (map.getMapData ());
        dialog.setLocationRelativeTo (display);
        dialog.setVisible (true);
    }

    public void editTable (ActionEvent e)
    {
        //ViewTableData.getInstance ().setVisible (true);
        ViewTableData instance = new ViewTableData();
        instance.setData(map.getMapData());
        instance.setVisible(true);
    }

    public void editPreferences (ActionEvent e)
    {
        EditOptions.getInstance ().setVisible (true);
        viewRefresh (e);
    }

    public void viewMap (ActionEvent e)
    {
        propertyChange =
                new PropertyChangeEvent (this, MapMenu.VIEW_MAP, null, null);
        firePropertyChanged ();
        //        if (viewMode != VIEW_MODE_MAP)
        //        {
        //            viewMode = VIEW_MODE_MAP;
        //            mapScrollPanel.getViewport().remove(mapTable);
        //            mapScrollPanel.getViewport().add(mapGraphic);
        //        }
    }

    public void viewTable (ActionEvent e)
    {
        propertyChange =
                new PropertyChangeEvent (this, MapMenu.VIEW_TABLE, null, null);
        firePropertyChanged ();
        /*
        if (viewMode != VIEW_MODE_TABLE)
        {
            viewMode = VIEW_MODE_TABLE;
            mapScrollPanel.getViewport().remove(mapGraphic);
            mapScrollPanel.getViewport().add(mapTable);
        }\\

*/
    }

    public void viewLegend (ActionEvent e)
    {
        JOptionPane.showMessageDialog (display, "View Legend Dialog placeholder dialog",
                                       "View Legend",
                                       JOptionPane.INFORMATION_MESSAGE);
    }

    public void viewShiftZoomIn (ActionEvent e)
    {
        map.zoomIn ();
        Color backColor = map.getLayout().getOptions().getBackgroundColor();
        EditViewOptions.getInstance ().setScale (map.getScale ());
        propertyChange = refreshMap;
        firePropertyChanged ();
    }

    public void viewShiftZoomOut (ActionEvent e)
    {
        map.zoomOut ();
        Color backColor = map.getLayout().getOptions().getBackgroundColor();
        EditViewOptions.getInstance ().setScale (map.getScale ());

        propertyChange = refreshMap;
        firePropertyChanged ();
    }

    public void viewRefresh (ActionEvent e)
    {
        propertyChange = refreshMap;
        firePropertyChanged ();
    }

    public void viewShiftRight (ActionEvent e)
    {
        GroupRecord g = map.getGroupData ();
        Astrogation data = map.getMapData ();
        HexID h = new HexID (g.getLocation ().toString ());
        //h.convertHextoID();
        h.x += 1;
        g = data.getGroup (h, g.getType ());
        if (g != null)
            map.setGroup (g);
        propertyChange = refreshMap;
        firePropertyChanged ();
    }

    public void viewShiftLeft (ActionEvent e)
    {
        GroupRecord g = map.getGroupData ();
        Astrogation data = map.getMapData ();
        if (g != null && data != null)
        {
            HexID h = new HexID (g.getLocation ().toString ());
            //h.convertHextoID();
            h.x -= 1;
            g = data.getGroup (h, g.getType ());
            if (g != null)
                map.setGroup (g);
            propertyChange = refreshMap;
            firePropertyChanged ();
        }
    }

    public void viewShiftUp (ActionEvent e)
    {
        GroupRecord g = map.getGroupData ();
        Astrogation data = map.getMapData ();
        HexID h = new HexID (g.getLocation ().toString ());
        //h.convertHextoID();
        h.y -= 1;
        g = data.getGroup (h, g.getType ());
        if (g != null)
            map.setGroup (g);
        propertyChange = refreshMap;
        firePropertyChanged ();

    }

    public void viewShiftDown (ActionEvent e)
    {
        GroupRecord g = map.getGroupData ();
        Astrogation data = map.getMapData ();
        HexID h = new HexID (g.getLocation ().toString ());
        //h.convertHextoID();
        h.y += 1;
        g = data.getGroup (h, g.getType ());
        if (g != null)
            map.setGroup (g);
        propertyChange = refreshMap;
        firePropertyChanged ();

    }

    public void viewDisplay (ActionEvent e)
    {
        EditViewOptions dialogEditViewOptions = EditViewOptions.getInstance ();
        dialogEditViewOptions.setLocationRelativeTo (display);
        dialogEditViewOptions.setVisible (true);
        if (!dialogEditViewOptions.isUpdated ())
        {
            dialogEditViewOptions.setLevel (map.getLevel ());
            dialogEditViewOptions.setScale (map.getScale ());
            dialogEditViewOptions.setScope (map.getScope ());
        } else
        {
            propertyChange =
                    new PropertyChangeEvent (this, MapMenu.VIEW_DISPLAY, null,
                                             null);
            firePropertyChanged ();
            propertyChange = null;
        }
    }

    public void helpAbout (ActionEvent e)
    {
        JOptionPane.showMessageDialog (display, new Map_AboutBoxPanel1 (),
                                       "About", JOptionPane.PLAIN_MESSAGE);
    }

    private void setAstrogrationData (Astrogation starData)
    {
        try
        {
            starData.loadGlobalReferences (MapPreferences.getInstance ().getExternalRefsFileName ());
        } catch (IOException ex)
        {
            JOptionPane.showMessageDialog (display, ex.getMessage (), Resources.getString ("map.IOExceptionTitle"),
                                           0);
        } catch (JiBXException ex)
        {
            JOptionPane.showMessageDialog (display, ex.getMessage (),
                                           "Error: Load Global JiBX XML Reader Exception",
                                           0);
        }
    }

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of linea
 *
 * @author Diego
 */
class linea extends CI_Controller{
    var $base;
    var $css;
    var $jquery;

    public function __construct() {
        parent::__construct();
        $this->base = $this->config->item('base_url');
        $this->load->library(array('session'));
        $this->load->model('linea_model');
    }

    function index () {

        $data['datos'] = $this->linea_model->query();
        $data['base'] = $this->base;
        $data['title'] = 'Lineas';
        $this->load->view('/templates/header',$data);
        $this->load->view('linea/listLinea.php', $data);
        $this->load->view('templates/copyright',$data);
    }

    function delete($idLinea){
        if (isset($idLinea)){
            $this->linea_model->delete($idLinea);
        }
        $this->index();
    }

    function insert() {
        $linea= new LineaPojo();
        $linea->setLinea($this->input->post('linea', TRUE));
        if (empty($linea->getLinea())){
            $this->load->view('/templates/header');
            $data['title_page'] = 'Agrega Linea';
            $this->load->view('linea/addLinea.php',$data);
            $this->load->view('templates/copyright',$data);

            return;
        }
        $this->linea_model->insert($linea); // Invocamos nuestro metodo de insertar
        $this->index(); // Invocalos la opción listar
    }

    function update($idLinea){
        $data['base'] = $this->base;
        $data['jquery'] = $this->jquery;
        $data = $this->linea_model->query($idLinea);
        $linea = new LineaPojo();
        foreach ($data as $dat){
            $data['title_page'] = 'Actualizar Linea';
            $data['idLinea'] = $dat->getIdLinea();
            $data['linea'] = $dat->getLinea();
            $linea->setIdLinea($dat->getIdLinea());
        }
        $linea->setLinea($this->input->post('linea', TRUE));
        if (empty($linea->getLinea())){
           $this->load->view('/templates/header');
           $data['title_page'] = 'Actualiza Linea';
            $this->load->view('linea/editLinea.php',$data);
            $this->load->view('templates/copyright.php', $data);

            return;
        }
        $this->linea_model->update($linea); // Invocamos nuestro metodo de insertar
        $this->index(); // Invocalos la opción listar
    }
}


text:
@interface MWGridCell () {

    UIImageView *_imageView;
    UIImageView *_loadingError;
	DACircularProgressView *_loadingIndicator;
    UIButton *_selectedButton;

}

@end

@implementation MWGridCell

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {

        // Grey background
        self.backgroundColor = [UIColor colorWithWhite:0.12 alpha:1];

        // Image
        _imageView = [UIImageView new];
        _imageView.frame = self.bounds;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        _imageView.autoresizesSubviews = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self addSubview:_imageView];

        // Selection button
        _selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectedButton.contentMode = UIViewContentModeTopRight;
        _selectedButton.adjustsImageWhenHighlighted = NO;
        [_selectedButton setImage:nil forState:UIControlStateNormal];
        [_selectedButton setImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/ImageSelectedSmallOff.png"] forState:UIControlStateNormal];
        [_selectedButton setImage:[UIImage imageNamed:@"MWPhotoBrowser.bundle/images/ImageSelectedSmallOn.png"] forState:UIControlStateSelected];
        [_selectedButton addTarget:self action:@selector(selectionButtonPressed) forControlEvents:UIControlEventTouchDown];
        _selectedButton.hidden = YES;
        _selectedButton.frame = CGRectMake(0, 0, 44, 44);
        [self addSubview:_selectedButton];

		// Loading indicator
		_loadingIndicator = [[DACircularProgressView alloc] initWithFrame:CGRectMake(0, 0, 40.0f, 40.0f)];
        _loadingIndicator.userInteractionEnabled = NO;
        _loadingIndicator.thicknessRatio = 0.1;
        _loadingIndicator.roundedCorners = NO;
		[self addSubview:_loadingIndicator];

        // Listen for photo loading notifications
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(setProgressFromNotification:)
                                                     name:MWPHOTO_PROGRESS_NOTIFICATION
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleMWPhotoLoadingDidEndNotification:)
                                                     name:MWPHOTO_LOADING_DID_END_NOTIFICATION
                                                   object:nil];

    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - View

- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = self.bounds;
    _loadingIndicator.frame = CGRectMake(floorf((self.bounds.size.width - _loadingIndicator.frame.size.width) / 2.),
                                         floorf((self.bounds.size.height - _loadingIndicator.frame.size.height) / 2),
                                         _loadingIndicator.frame.size.width,
                                         _loadingIndicator.frame.size.height);
    _selectedButton.frame = CGRectMake(self.bounds.size.width - _selectedButton.frame.size.width - 0,
                                       0, _selectedButton.frame.size.width, _selectedButton.frame.size.height);
}

#pragma mark - Cell

- (void)prepareForReuse {
    _photo = nil;
    _gridController = nil;
    _imageView.image = nil;
    _loadingIndicator.progress = 0;
    _selectedButton.hidden = YES;
    [self hideImageFailure];
    [super prepareForReuse];
}

#pragma mark - Image Handling

- (void)setPhoto:(id <MWPhoto>)photo {
    _photo = photo;
    if (_photo) {
        if (![_photo underlyingImage]) {
            [self showLoadingIndicator];
        } else {
            [self hideLoadingIndicator];
        }
    } else {
        [self showImageFailure];
    }
}

- (void)displayImage {
    _imageView.image = [_photo underlyingImage];
    _selectedButton.hidden = !_selectionMode;
    [self hideImageFailure];
}

#pragma mark - Selection

- (void)setSelectionMode:(BOOL)selectionMode {
    _selectionMode = selectionMode;
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    _selectedButton.selected = isSelected;
}

- (void)selectionButtonPressed {
    _selectedButton.selected = !_selectedButton.selected;
    [_gridController.browser setPhotoSelected:_selectedButton.selected atIndex:_index];
}

#pragma mark - Touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    _imageView.alpha = 0.6;
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    _imageView.alpha = 1;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    _imageView.alpha = 1;
    [super touchesCancelled:touches withEvent:event];
}

#pragma mark Indicators

- (void)hideLoadingIndicator {
    _loadingIndicator.hidden = YES;
}

- (void)showLoadingIndicator {
    _loadingIndicator.progress = 0;
    _loadingIndicator.hidden = NO;
    [self hideImageFailure];
}

- (void)showImageFailure {
    if (!_loadingError) {
        _loadingError = [UIImageView new];
        _loadingError.image = [UIImage imageNamed:@"MWPhotoBrowser.bundle/images/ImageError.png"];
        _loadingError.userInteractionEnabled = NO;
        [_loadingError sizeToFit];
        [self addSubview:_loadingError];
    }
    [self hideLoadingIndicator];
    _imageView.image = nil;
    _loadingError.frame = CGRectMake(floorf((self.bounds.size.width - _loadingError.frame.size.width) / 2.),
                                     floorf((self.bounds.size.height - _loadingError.frame.size.height) / 2),
                                     _loadingError.frame.size.width,
                                     _loadingError.frame.size.height);
}

- (void)hideImageFailure {
    if (_loadingError) {
        [_loadingError removeFromSuperview];
        _loadingError = nil;
    }
}

#pragma mark - Notifications

- (void)setProgressFromNotification:(NSNotification *)notification {
    NSDictionary *dict = [notification object];
    id <MWPhoto> photoWithProgress = [dict objectForKey:@"photo"];
    if (photoWithProgress == _photo) {
        //        NSLog(@"%f", [[dict valueForKey:@"progress"] floatValue]);
        float progress = [[dict valueForKey:@"progress"] floatValue];
        _loadingIndicator.progress = MAX(MIN(1, progress), 0);
    }
}

- (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification {
    id <MWPhoto> photo = [notification object];
    if (photo == _photo) {
        if ([photo underlyingImage]) {
            // Successful load
            [self displayImage];
        } else {
            // Failed to load
            [self showImageFailure];
        }
        [self hideLoadingIndicator];
    }
}

@end


text:
import React, {Component} from 'react'
import { whoami } from '../reducers/auth'
import { connect } from "react-redux";
import { Redirect } from 'react-router'

class TestButton extends Component{
  constructor(props) {
    super(props);
    this.state ={
    }
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.login(this.state.email, this.state.password)
  }

  render(){
    return(

            Start Rescue

    )
  }
}

const mapStateToProps = state => ({
  user: state.auth
})

const mapDispatchToProps = dispatch => ({
  getUser: () => {
    dispatch(whoami())
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(TestButton)


text:
package org.odata4j.core;

/** Entity-set title and href. */
public interface EntitySetInfo extends Titled {

  String getHref();

}


text:
<?php

return array(
    'ezcWorkflowSignalSlotPlugin'        => 'WorkflowSignalSlotTiein/plugin.php',
    'ezcWorkflowSignalSlotPluginOptions' => 'WorkflowSignalSlotTiein/options/plugin.php',
    'ezcWorkflowSignalSlotReturnValue'   => 'WorkflowSignalSlotTiein/structs/return_value.php',
);
?>


text:
<?xml version="1.0" encoding="us-ascii" ?>
<!--

    Licensed to the Austrian Association for Software Tool Integration (AASTI)
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. The AASTI licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file except in compliance
    with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">

  <service>
    <interfaces>
      <value>org.openengsb.core.api.ConnectorInstanceFactory</value>
    </interfaces>
    <service-properties>
      <entry key="domain" value="contact" />
      <entry key="connector" value="gcontacts" />
    </service-properties>
    <bean class="org.openengsb.connector.gcontacts.internal.GcontactsServiceInstanceFactory">
      <property name="persistInterface" ref="persistInterface" />
    </bean>
  </service>

  <service>
    <interfaces>
      <value>org.openengsb.core.api.ConnectorProvider</value>
    </interfaces>
    <service-properties>
      <entry key="domain" value="contact" />
      <entry key="connector" value="gcontacts" />
    </service-properties>
    <bean class="org.openengsb.connector.gcontacts.internal.GcontactsConnectorProvider">
      <property name="id" value="gcontacts" />
      <property name="bundleContext" ref="blueprintBundleContext" />
    </bean>
  </service>

  <reference id="persistInterface" interface="org.openengsb.core.api.ekb.PersistInterface" />

</blueprint>


text:
class Line(object):
    def __init__(self, start, end, width, layer):
        self.start = start
        self.end = end
        self.width = width
        self.layer = layer

class Rectangle(object):
    def __init__(self, topleft, bottomright, layer):
        self.topleft = topleft
        self.bottomright = bottomright
        self.layer = layer

class Polygon(object):
    def __init__(self, vertices, width, layer):
        self.vertices = vertices
        self.width = width
        self.layer = layer

class Circle(object):
    def __init__(self, position, radius, width, layer):
        self.position = position
        self.radius = radius
        self.width = width
        self.layer = layer

class Text(object):
    def __init__(self, s, position, size, ratio, layer):
        self.s = s
        self.position = position
        self.size = size
        self.ratio = ratio
        self.layer = layer


text:
@class JavaIoObjectInputStream;
@class JavaNetInetAddress;

#include "J2ObjC_header.h"
#include "java/net/SocketAddress.h"

#define JavaNetInetSocketAddress_serialVersionUID 5076001401234631237LL

@interface JavaNetInetSocketAddress : JavaNetSocketAddress {
}

- (instancetype)init;

- (instancetype)initWithInt:(jint)port;

- (instancetype)initWithJavaNetInetAddress:(JavaNetInetAddress *)address
                                   withInt:(jint)port;

- (instancetype)initWithNSString:(NSString *)host
                         withInt:(jint)port;

- (instancetype)initWithNSString:(NSString *)hostname
                         withInt:(jint)port
                     withBoolean:(jboolean)needResolved;

+ (JavaNetInetSocketAddress *)createUnresolvedWithNSString:(NSString *)host
                                                   withInt:(jint)port;

- (jint)getPort;

- (JavaNetInetAddress *)getAddress;

- (NSString *)getHostName;

- (NSString *)getHostString;

- (jboolean)isUnresolved;

- (NSString *)description;

- (jboolean)isEqual:(id)socketAddr;

- (NSUInteger)hash;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaNetInetSocketAddress)

CF_EXTERN_C_BEGIN

FOUNDATION_EXPORT JavaNetInetSocketAddress *JavaNetInetSocketAddress_createUnresolvedWithNSString_withInt_(NSString *host, jint port);

J2OBJC_STATIC_FIELD_GETTER(JavaNetInetSocketAddress, serialVersionUID, jlong)
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(JavaNetInetSocketAddress)

#endif // _JavaNetInetSocketAddress_H_


text:
If you are looking for the face to face guided training repository for CTS-IT Gitflow training then you are in the right spot. In this repository you will find instructions that will help you work with an instructor to learn the sequence of events for a successful gitflow workflow. This workflow is a simplified version of the process that happens on a bi-weekly basis at CTS-IT.

1) Install gitflow which is a one-time operation
- With the laptop on click, go>utilities>terminal
- Type `brew install git-flow`

2) Browse to github.com and login
- Navigate to [github.com/ctsit](http://github.com/ctsit "CTS-IT Github Page").
- Locate the repository named [J.O.B.-Jump-On-Board](https://github.com/ctsit/J.O.B.-Jump-On-Board "CTS-IT Job Training")
- Click the fork button
- Select personal github account
- Click 'clone or download' button
- Copy URL into clipboard

3) Clone forked repository to local laptop
- Return to terminal window
- Type `git clone` and paste repository url in terminal and press enter

4) Initialize repository with gitflow
- Type `git flow init`
- Follow prompts and accept defaults by hitting enter

5) Set the develop branch to the upstream develop branch on GitHub
- Type `git branch --set-upstream-to=origin/develop develop`
- Review screen output

6) Create feature branch
- Type `git flow feature start helloworld`
- Review screen output

7) Make helloworld Python file
- Type `touch helloworld.py`
- Type `nano helloworld.py`
- In the nano editor on line 1 type `#This is my hello world program` on line 2 type `print 'Hello World'`
- Press ctrl O
- Name the file helloworld.py and save

8) Run the helloworld.py program to verify it works
- Type `python helloworld.py`
- Review screen output

9) Add the helloworld.py program to the repository
- Type `git add helloworld.py`
- Review screen output

10) Type the commit message for the file remembering to use "with this commit, I will" to start the message
- Type `git commit -m "add strings to return hello world as output`
- Review screen output

11) Push the file to the repository
- Type `git push`
- Review screen output

12) Close feature branch
- Type `git flow feature finish`

13) Go to github.com to create pull request from your forked repository branch to the develop branch of J.O.B-Training-Repo-1
- Browse to github.com personal account
- Locate [J.O.B-Training-Repo-1](https://github.com/ctsit/J.O.B-Training-Repo-1) repository
- Click pull requests tab
- Click new pull request
- Click create pull request and use the personal fork to the develop branch of [J.O.B-Training-Repo-1]https://github.com/ctsit/J.O.B-Training-Repo-1
- Click create pull request again

14) Review pull request with instructor
- Review changes made with pull request using Github.com interface
- Click merge pull request
- Click confirm merge

15) Create release using gitflow
- Type `git checkout master && git pull && git checkout develop && git pull && git fetch --tags && git tag`
- Type `git tag`
- Type `git flow release start 0.0.1`
- Type `git chlog 0.0.1..HEAD`
- Type `git add CHANGELOG`
- Type `git commit –m "update CHANGELOG for release 0.0.1"`
- Type `git flow release finish 0.0.1`
- Type `git push && git checkout master && git push && git push --tags && git checkout develop`


text:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from .forms import ProjectForm

def home(request):
    return HttpResponseRedirect(reverse('project_list'))

def view_project_list(request):
    return render(request, 'project_list.html')

def add_project(request):
    form = ProjectForm()
    return render(request, 'project_new.html')

def edit_project(request):
    form = ProjectForm()
    return render(request, 'project_new.html')


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pagina-tematica >
    <conteudo>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Chegando ao meu usuário com o

Portal de Serviços

Bem Vindo, editor!

Você agora faz parte de um esforço, feito por toda a Administração Pública Federal, com o objetivo de aproximar os serviços públicos do usuário, para que ele seja capaz de entender, utilizar, satisfazer suas necessidades e oferecer dados e sugestões para melhoria destes mesmos serviços.

 E este empenho começa aqui, no Portal de Serviços. É aqui que o primeiro ponto de encontro com o usuário será feito e é aqui que, brevemente, ele irá dar início à utilização da maioria dos serviços públicos federais. Assim, seu trabalho, de cadastrar e atualizar as informações dos serviços do seu órgão, são de valor essencial para a melhoria da relação administração-sociedade.

 Este guia visa te ajudar a entender como funciona o Portal de Serviços e o seu Editor, assim como fornecer ferramentas  e conhecimentos que aprimorem sua comunicação com os usuários.

 As seções apresentadas a seguir tratam dos tipos de atividades cadastradas no Portal, de como esse cadastro funciona na interface do Editor de Serviços e de como se pode, com pequenas mudanças, transformar completamente a comunicação com o seu usuário.

 Volte sempre aqui, estaremos sempre acrescentando e complementando o conteúdo para torná-lo cada vez mais útil para você.

<button class="button">O que colocar no Portal?</button>

<button class="button">Como colocar no Portal?</button>

<button class="button">Falando a língua do Usuário</button>

</conteudo>
    <dbId>109</dbId>
    <nome>Guia Rápido do Portal de Serviços</nome>
    <orgaos>
        <orgao id="2981" dbId="37545">
            <nomeOrgao>Ministério do Planejamento, Desenvolvimento e Gestão (MP)</nomeOrgao>
        </orgao>
    </orgaos>
</pagina-tematica>


text:
order: 2
title: 典型表单
---

示例展示了如何通过使用 `Form.create` 来获取和更新表单提交的数值。

````jsx
import { Form, Input, Button, Checkbox, Radio, Tooltip, Icon } from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

let Demo = React.createClass({
  handleSubmit(e) {
    e.preventDefault();
    console.log('收到表单值:', this.props.form.getFieldsValue());
  },

  render() {
    const { getFieldProps } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    return (
      <Form horizontal onSubmit={this.handleSubmit}>
        <FormItem
          {...formItemLayout}
          label="用户名:">
          <p className="ant-form-text" id="userName" name="userName">大眼萌 minion</p>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="密码:">
          <Input type="password" {...getFieldProps('pass')} placeholder="请输入密码" />
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="您的性别:">
          <RadioGroup {...getFieldProps('gender', { initialValue: 'female' })}>
            <Radio value="male">男的</Radio>
            <Radio value="female">女的</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="备注:"
          help="随便写点什么">
          <Input type="textarea" placeholder="随便写" {...getFieldProps('remark')} />
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={<span>卖身华府 <Tooltip title="我为秋香"><Icon type="question-circle-o" /></Tooltip> :</span>}>
          <Checkbox {...getFieldProps('agreement')}>同意</Checkbox>
        </FormItem>
        <FormItem wrapperCol={{ span: 16, offset: 6 }} style={{ marginTop: 24 }}>
          <Button type="primary" htmlType="submit">确定</Button>
        </FormItem>
      </Form>
    );
  },
});

Demo = Form.create()(Demo);

ReactDOM.render(<Demo />, mountNode);
````


text:
package org.cloudfoundry.client.v2.applications;

import org.junit.Test;

public final class DownloadApplicationDropletRequestTest {

    @Test(expected = IllegalStateException.class)
    public void noApplicationId() {
        DownloadApplicationDropletRequest.builder()
            .build();
    }

    @Test
    public void valid() {
        DownloadApplicationDropletRequest.builder()
            .applicationId("test-application-id")
            .build();
    }

}


text:
@interface ViewController : UIViewController<OTOplugDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *connectStatusIcon;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *portStatusImageViews;
@property (weak, nonatomic) IBOutlet UILabel *connectStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *idTextLabel;
@end


text:
package net.ME1312.SubServers.Client.Sponge.Graphic;

import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.inventory.ItemStack;

/**
 * Plugin GUI Renderer Layout Class
 */
public interface PluginRenderer<T> {

    /**
     * Open the GUI
     *
     * @param player Player Opening
     * @param object Object passed
     */
    void open(Player player, T object);

    /**
     * Get Renderer Icon
     *
     * @return Icon
     */
    ItemStack getIcon();

    /**
     * Check if this Renderer is enabled for this Object
     *
     * @param object Object passed
     * @return Enabled Status
     */
    boolean isEnabled(T object);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  A dummy POM to make GitHub recognize the groupId and artifactId and to show the number of dependents.
  See: https://help.github.com/en/articles/listing-the-projects-that-depend-on-a-repository
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.linecorp.armeria</groupId>
  <artifactId>armeria</artifactId>
  <packaging>jar</packaging>
  <version>0</version>
</project>


text:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Model::unguard();

		$this->call(UserTableSeeder::class);
		$this->call(TemplateTableSeeder::class);
		$this->call(TemplateDetailTableSeeder::class);
        $this->call(SeoTableSeeder::class);
		$this->call(PageTableSeeder::class);
        $this->call(PageDetailTableSeeder::class);
	}

}


text:
    position: relative;
    border: 2px dashed #ccc;
    width: 90%;
    height: 250px;
    overflow: auto;
}

#screenshot-inner {
    position: absolute;
    left: 0;
    bottom: 48%;
    width: 100%;
    text-align: center;
}

#screenshot-zone.screenshot-pasted {
    border: 2px solid #333;
}


text:
package main

import (
	"testing"
)

func Test_ContainerLogPath(t *testing.T) {
	DockerRoot = "./test-fixtures/"
	paths := ContainerLogFilePaths("a")

	if len(paths) <= 0 {
		t.Error("path is empty")
	}
}


text:
using Moq;
using NBi.Core;
using NBi.Core.Configuration;
using NBi.Core.Configuration.FailureReport;
using NBi.Framework;
using NBi.Framework.FailureMessage;
using NBi.Framework.FailureMessage.Markdown;
using NBi.Framework.Sampling;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Testing.Framework.FailureMessage.Markdown
{
    public class ItemsMessageMardownTest
    {
        #region Helpers
        private IEnumerable<string> GetDataRows(int count)
        {
            var list = new List<string>();
            for (int i = 0; i < count; i++)
                list.Add(String.Format("Item {0:00}", i));

            return list;
        }
        #endregion

        [Test]
        public void RenderExpected_MoreThanMaxRowsCount_ReturnCorrectNumberOfRowsOnTop()
        {
            var list = new List<string>();
            for (int i = 0; i < 20; i++)
                list.Add(String.Format("Item {0:00}", i));

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');
            var firstLine = lines[0];

            Assert.That(firstLine, Is.EqualTo("Set of 20 items"));
        }

        public void RenderExpected_OneRow_ReturnCorrectNumberOfRowsOnTopWithoutPlurial()
        {
            var list = new List<string>() { "Item 01" };

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');
            var firstLine = lines[0];

            Assert.That(firstLine, Is.EqualTo("Set of 1 item"));
        }

        public void RenderExpected_MoreThanMaxRowsCount_ReturnSampleRowsCountAndHeaderAndSeparation()
        {
            var list = new List<string>();
            for (int i = 0; i < 20; i++)
                list.Add(String.Format("Item {0:00}", i));

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');

            Assert.That(lines.Count(l => l.Contains("*")), Is.EqualTo(10));
        }

        [Test]
        public void RenderExpected_MoreThanSampleRowsCountButLessThanMaxRowsCount_ReturnEachRowAndHeaderAndSeparation()
        {
            var rowCount = 12;

            var list = new List<string>();
            for (int i = 0; i < rowCount; i++)
                list.Add(String.Format("Item {0:00}", i));

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');

            Assert.That(lines.Count(l => l.Contains("*")), Is.EqualTo(rowCount));
        }

        [Test]
        public void RenderExpected_MoreThanSampleRowsAndMaxRowsCountWithSpecificFailureReportProfile_ReturnEachRowAndHeaderAndSeparation()
        {
            var rowCount = 120;
            var threshold = rowCount - 20;
            var max=threshold/2;

            var list = new List<string>();
            for (int i = 0; i < rowCount; i++)
                list.Add(String.Format("Item {0:00}", i));

            var profile = Mock.Of<IFailureReportProfile>(p =>
                p.MaxSampleItem == max
                && p.ThresholdSampleItem == threshold
                && p.ExpectedSet == FailureReportSetType.Sample
            );

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(profile);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');

            Assert.That(lines.Count(l => l.Contains("*")), Is.EqualTo(max));
        }

        [Test]
        public void RenderExpected_MoreThanMaxRowsCount_ReturnCorrectCountOfSkippedRow()
        {
            var list = new List<string>();
            for (int i = 0; i < 22; i++)
                list.Add(String.Format("Item {0:00}", i));

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();
            var lines = value.Replace("\n", string.Empty).Split('\r');
            //Not exactly the last line but the previous due to paragraph rendering.
            var lastLine = lines.Reverse().ElementAt(1);

            Assert.That(lastLine, Is.EqualTo("... and 12 others not displayed."));
        }

        [Test]
        [TestCase(5)]
        [TestCase(12)]
        public void RenderExpected_LessThanMaxRowsCount_DoesntDisplaySkippedRow(int rowCount)
        {
            var list = new List<string>();
            for (int i = 0; i < rowCount; i++)
                list.Add(String.Format("Item {0:00}", i));

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(list, null, null);
            var value = msg.RenderExpected();

            Assert.That(value, Does.Not.Contain(" others not displayed."));
        }

        [Test]
        [TestCase(0, 5, "Missing items:")]
        [TestCase(5, 0, "Unexpected items:")]
        public void RenderCompared_NoSpecialRows_DoesntDisplayTextForThisKindOfRows(
            int missingRowCount
            , int unexpectedRowCount
            , string unexpectedText)
        {
            var compared = new ListComparer.Result(
                    GetDataRows(missingRowCount)
                    , GetDataRows(unexpectedRowCount)
                );

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(null, null, compared);
            var value = msg.RenderAnalysis();

            Assert.That(value, Does.Not.Contain(unexpectedText));
        }

        [Test]
        [TestCase(3, 0, "Missing items:")]
        [TestCase(0, 3, "Unexpected items:")]
        public void RenderCompared_WithSpecialRows_DisplayTextForThisKindOfRows(
            int missingRowCount
            , int unexpectedRowCount
            , string expectedText)
        {
            var compared = new ListComparer.Result(
                    GetDataRows(missingRowCount)
                    , GetDataRows(unexpectedRowCount)
                );

            var factory = new SamplersFactory<string>();
            var samplers = factory.Instantiate(FailureReportProfile.Default);

            var msg = new ItemsMessageMarkdown(samplers);
            msg.Build(null, null, compared);
            var value = msg.RenderAnalysis();

            Assert.That(value, Does.Contain(expectedText));
        }

    }
}


text:
package com.google.common.util.concurrent;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ForwardingQueue;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckForNull;

/**
 * A {@link BlockingQueue} which forwards all its method calls to another {@link BlockingQueue}.
 * Subclasses should override one or more methods to modify the behavior of the backing collection
 * as desired per the decorator
 * pattern.
 *
 *
{@code default} method warning: This class does not forward calls to {@code
 * default} methods. Instead, it inherits their default implementations. When those implementations
 * invoke methods, they invoke methods on the {@code ForwardingBlockingQueue}.
 *
 * @author Raimundo Mirisola
 * @param <E> the type of elements held in this collection
 * @since 4.0
 */
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
    implements BlockingQueue<E> {

  /** Constructor for use by subclasses. */
  protected ForwardingBlockingQueue() {}

  @Override
  protected abstract BlockingQueue<E> delegate();

  @CanIgnoreReturnValue
  @Override
  public int drainTo(Collection<? super E> c, int maxElements) {
    return delegate().drainTo(c, maxElements);
  }

  @CanIgnoreReturnValue
  @Override
  public int drainTo(Collection<? super E> c) {
    return delegate().drainTo(c);
  }

  @CanIgnoreReturnValue // TODO(kak): consider removing this
  @Override
  public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
    return delegate().offer(e, timeout, unit);
  }

  @CanIgnoreReturnValue // TODO(kak): consider removing this
  @Override
  @CheckForNull
  public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    return delegate().poll(timeout, unit);
  }

  @Override
  public void put(E e) throws InterruptedException {
    delegate().put(e);
  }

  @Override
  public int remainingCapacity() {
    return delegate().remainingCapacity();
  }

  @CanIgnoreReturnValue // TODO(kak): consider removing this
  @Override
  public E take() throws InterruptedException {
    return delegate().take();
  }
}


text:
var program = require('commander')
  , commands = require('./commands');

// Define the program commands.
program.version(require('../package.json').version);

program
  .command('authentication')
  .alias('set-auth')
  .description('Set the access-key pin for client authentication.')
  .action(commands.authentication);

program
  .command('test-authentication')
  .alias('test-auth')
  .description('Test if access-key is up and running.')
  .action(commands.test_authentication);

// Parse the application arguments.
program.parse(process.argv);

// Check if there are no arguments.
if (!process.argv.slice(2).length) {
  // Check if app has oauth
  commands.validate_authentication(function(response) {
    if(response == '200') {
      require("./ui/main");
    } else {
      console.log('AUTHENTICATION FAILED');
    }
  })
}

// Check if there is a token on the arguments.
if (program.token) {
  commands.setToken(program.token);
}


text:
package com.caffeinedrivendesign.examples.spring;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("query")
public class QueryProperties {

  private boolean enabled;

  private String url;

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

}


text:
<phpunit colors="true" bootstrap="../unittest/bootstrap.php">
	<testsuites>
		<testsuite name="Jelly Tests">
			<file>../unittest/tests.php</file>
		</testsuite>
	</testsuites>
	<groups>
	  <include>
		<group>jelly</group>
	  </include>
	</groups>
</phpunit>


text:
FROM python:3.6 as builder

# Set the GOOGLE_APPLICATION_CREDENTIALS environment variable.
# At run time, /data must be binded to a volume containing a valid Service
# Account credentials file named sisense2dc-datacatalog-credentials.json.
ENV GOOGLE_APPLICATION_CREDENTIALS=/data/sisense2dc-datacatalog-credentials.json

WORKDIR /app

# Copy project files (see .dockerignore).
COPY . .

# QUALITY ASSURANCE
FROM builder as qa

# Run static code checks.
RUN pip install flake8 yapf
RUN yapf --diff --recursive src tests
RUN flake8 src tests

# Run the unit tests.
RUN python setup.py test
# END OF QUALITY ASSURANCE STEPS

# RESUME THE IMAGE BUILD PROCESS
FROM builder as run

# Install the connector from source files.
RUN pip install .

ENTRYPOINT ["google-datacatalog-sisense-connector"]


text:
require 'spec_helper'

describe SendgridMailer do

  let(:header) { subject.header.to_s.gsub(/\r|\n/, "") }

  describe "when sendgrid default category is set" do
    subject(:message) { described_class.default_category }

    it 'header should have category' do
      expect(header).to include('"category": ["system"]')
    end
  end

  describe "when sendgrid category is set" do
    subject(:message) { described_class.new_category }

    it 'header should have new category' do
      expect(header).to include('"category": ["new_category"]')
    end
  end

  describe "when sendgrid recipients present" do
    subject(:message) { described_class.dummy_recipient }

    before(:each) { sendgrid_config_setup }

    it 'header should have dummy recipient' do
      expect(header).to include('To: noreply@brightbytes.net')
    end
  end

  describe "when sendgrid recipients are set" do
    subject(:message) { described_class.with_recipients }

    it 'header should have recipients' do
      expect(header).to include('"to": ["email1@email.com","email2@email.com"]')
    end
  end

  describe "when unsubscribe not required" do
    subject(:message) { described_class.unsubscribe_not_required }

    before(:each) { sendgrid_config_setup }

    it 'unsubscribe html version should be empty' do
      expect(header).to include('"{{unsubscribe_html}}": ["",""]')
    end

    it 'unsubscribe text version should be empty' do
      expect(header).to include('"{{unsubscribe_text}}": ["",""]')
    end

    it 'unsubscribe url should be empty' do
      expect(header).to include('"{{unsubscribe_url}}": ["",""]')
    end
  end

  describe "when unsubscribe required" do
    subject(:message) { described_class.unsubscribe_required }

    before(:each) { sendgrid_config_setup }

    it 'unsubscribe html section should be set' do
      expect(header).to include('"{{unsubscribe_html_section}}": "If you would like to unsubscribe and stop receiving these emails click here."')
    end

    it 'unsubscribe text section should be set' do
      expect(header).to include('"{{unsubscribe_text_section}}": "If you would like to unsubscribe and stop receiving these emails click here: {{unsubscribe_url}}"')
    end

    it 'unsubscribe html version should be set' do
      expect(header).to include('"{{unsubscribe_html}}": ["{{unsubscribe_html_section}}","{{unsubscribe_html_section}}"]')
    end

    it 'unsubscribe text version should be set' do
      expect(header).to include('"{{unsubscribe_text}}": ["{{unsubscribe_text_section}}","{{unsubscribe_text_section}}"]')
    end

    it 'unsubscribe url should be set' do
      expect(header).to include('"{{unsubscribe_url}}": ["http://example.com/u?email=email1%40email.com&category=unsubscribe","http://example.com/u?email=email2%40email.com&category=unsubscribe"]')
    end
  end

end


text:
package org.coursera.naptime.actions

import com.linkedin.data.DataList
import com.linkedin.data.DataMap
import com.linkedin.data.Null
import com.linkedin.data.schema.DataSchema
import com.linkedin.data.template.RecordTemplate
import org.coursera.naptime.courier.CourierFormats
import play.api.libs.json.JsArray
import play.api.libs.json.JsBoolean
import play.api.libs.json.JsNull
import play.api.libs.json.JsNumber
import play.api.libs.json.JsObject
import play.api.libs.json.JsString
import play.api.libs.json.OFormat

/**
 * Abstracts over the Play-JSON API and the Courier underlying record template support for
 * serialization, allowing us to convert Play-JSON into Pegasus DataMaps.
 */
trait NaptimeSerializer[T] {
  def serialize(t: T): DataMap

  def schema(t: T): Option[DataSchema]
}

object NaptimeSerializer {

  /**
   * Retrieves the underlying DataMap from a RecordTemplate from a [Courier generated] object.
   *
   * @tparam T The type of the model.
   */
  implicit def courierModels[T <: RecordTemplate]: NaptimeSerializer[T] = {
    new NaptimeSerializer[T] {
      override def serialize(t: T): DataMap = t.data()

      override def schema(t: T): Option[DataSchema] = Some(t.schema())
    }
  }

  /**
   * Converts Play-JSON's JsObject to a DataMap.
   */
  implicit object PlayJson extends NaptimeSerializer[JsObject] {
    override def serialize(t: JsObject): DataMap = {

      /**
       * Structured in this manner to avoid the DataMap's cycle checker from wasting a bunch of time
       */
      def serializeMap(obj: JsObject, map: DataMap): Unit = {
        for {
          (name, value) <- obj.value
        } {
          try {
            value match {
              case s: JsString =>
                map.put(name, s.value)
              case i: JsNumber =>
                map.put(name, CourierFormats.bigDecimalToNumber(i.value))
              case b: JsBoolean =>
                map.put(name, Boolean.box(b.value))
              case JsNull =>
                map.put(name, Null.getInstance())
              case a: JsArray =>
                val list = new DataList() // Don't include initial size because Scala Lists are slow!
                map.put(name, list)
                serializeList(a, list)
              case o: JsObject =>
                val childMap = new DataMap(o.value.size) // TODO: verify Map.size is fast.
                map.put(name, childMap)
                serializeMap(o, childMap)
            }
          } catch {
            case e: NullPointerException =>
              throw new RuntimeException(
                s"Null encountered when serializing field $name -> $value in object $obj",
                e)
          }
        }
      }

      def serializeList(jsArray: JsArray, list: DataList): Unit = {
        for (i <- jsArray.value) {
          i match {
            case s: JsString =>
              list.add(s.value)
            case i: JsNumber =>
              list.add(CourierFormats.bigDecimalToNumber(i.value))
            case b: JsBoolean =>
              list.add(Boolean.box(b.value))
            case JsNull =>
              list.add(Null.getInstance())
            case a: JsArray =>
              val childList = new DataList() // Don't include initial size b/c Scala Lists are slow!
              list.add(childList)
              serializeList(a, childList)
            case o: JsObject =>
              val childMap = new DataMap(o.value.size)
              list.add(childMap)
              serializeMap(o, childMap)
          }
        }
      }

      val map = new DataMap(t.value.size)
      serializeMap(t, map)
      map
    }

    /**
     * Convenience function to invert serialization.
     *
     * @param dataMap The input dataMap to convert back.
     * @return The DataMap converted to a JsObject
     */
    def deserialize(dataMap: DataMap): JsObject = {
      CourierFormats.dataMapToObj(dataMap)
    }

    override def schema(t: JsObject): Option[DataSchema] = None
  }

  /**
   * Serializes a [case] class that has an implicit [[OFormat]] in scope.
   *
   * @param playJsonFormat Serializes the [case] class to Play-JSON.
   */
  implicit def playJsonFormats[T](implicit playJsonFormat: OFormat[T]): NaptimeSerializer[T] = {
    new NaptimeSerializer[T] {
      override def serialize(t: T): DataMap = {
        val json = playJsonFormat.writes(t)
        PlayJson.serialize(json)
      }

      override def schema(t: T): Option[DataSchema] = None
    }
  }

  /**
   * Useful for mocking tests / etc.
   */
  object AnyWrites {
    implicit val anyWrites: NaptimeSerializer[Any] = new NaptimeSerializer[Any] {
      override def serialize(t: Any): DataMap = {
        val m = new DataMap()
        m.put("id", t.toString)
        m
      }

      override def schema(t: Any): Option[DataSchema] = {
        None
      }
    }
  }
}


text:
package foam.lib.query;

import foam.lib.parse.PStream;
import foam.lib.parse.Parser;
import foam.lib.parse.ParserContext;

public class ValueParser
  implements Parser {
  @Override
  public PStream parse(PStream ps, ParserContext x) {
    StringBuilder s = new StringBuilder();

    while ( ps.valid() ) {
      char c = ps.head();
      if ( c == ' ' ) break;
      ps = ps.tail();
      s.append(c);
    }

    return ps.setValue(new foam.mlang.Constant(s.toString()));
  }
}


text:
package org.gradle.api.internal.cache;

import org.gradle.cache.CacheRepository;
import org.gradle.cache.PersistentCache;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.cache.PersistentIndexedCacheParameters;
import org.gradle.cache.internal.FileLockManager;
import org.gradle.internal.serialize.Serializer;

import static org.apache.commons.lang.WordUtils.uncapitalize;
import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;
import static org.gradle.internal.serialize.BaseSerializerFactory.LONG_SERIALIZER;
import static org.gradle.util.GUtil.toCamelCase;

public class SingleOperationPersistentStore<V> {

    //The cache only keeps single value, so we're always use the same index.
    //We probably should improve our cross-process caching infrastructure so that we support Stores (e.g. not-indexed caches).
    private final static long CACHE_KEY = 0;

    private final CacheRepository cacheRepository;

    private final Object scope;
    private final String cacheName;
    private final Serializer<V> valueSerializer;

    private PersistentIndexedCache<Long, V> cache;
    private PersistentCache cacheAccess;

    public SingleOperationPersistentStore(CacheRepository cacheRepository, Object scope, String cacheName, Serializer<V> valueSerializer) {
        this.cacheRepository = cacheRepository;
        this.scope = scope;
        this.cacheName = cacheName;
        this.valueSerializer = valueSerializer;
    }

    //Opens and closes the cache for operation
    public void putAndClose(final V value) {
        initCaches("write");
        try {
            cache.put(CACHE_KEY, value);
        } finally {
            closeCaches();
        }
    }

    //Opens and closes the cache for operation
    public V getAndClose() {
        initCaches("read");
        try {
            return cache.get(CACHE_KEY);
        } finally {
            cacheAccess.close();
        }
    }

    private void initCaches(String operation) {
        String identifier = uncapitalize(toCamelCase(cacheName));
        cacheAccess = cacheRepository.store(scope, identifier)
                .withDisplayName(cacheName + " " + operation + " cache")
                .withLockOptions(mode(FileLockManager.LockMode.Exclusive))
                .open();

        cache = cacheAccess.createCache(new PersistentIndexedCacheParameters<Long, V>(identifier, LONG_SERIALIZER, valueSerializer));
    }

    private void closeCaches() {
        cacheAccess.close();
        cache = null;
        cacheAccess = null;
    }
}


text:
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <linux/netlink.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/mman.h>

#include "rt_data.h"

#include <android/log.h>
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "Ballsort-JNI", __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "Ballsort-JNI", __VA_ARGS__)

int fd = 0;
volatile rt_control_data* data;

extern "C" jboolean JNICALL Java_rtandroid_ballsort_hardware_Sorter_openMemory(JNIEnv* env, jobject obj)
{
    LOGI("Opening shared memory");

    // looks like we are already initialized
    if (fd != 0)
    {
        LOGE("The file descriptor is already initialized");
        return JNI_FALSE;
    }

    // map kernel memory to userspace
    fd = open("/proc/rtdma", O_RDWR);
    if (fd < 0)
    {
        LOGE("Failed to open rtdma debug filesystem. errno: %d", errno);
        return JNI_FALSE;
    }

    // try to get access to that memory
    data = (rt_control_data*) mmap(NULL, RT_PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (data == NULL || data == MAP_FAILED)
    {
        LOGE("Failed to mmap the control data. errno: %d", errno);
        return JNI_FALSE;
    }

    // init delays
    data->base_delay = 0;
    data->next_delay = 0;
    data->ball_count = 0;

    // we are good to go
    LOGI("Memory was opened");
    return JNI_TRUE;
}

extern "C" void JNICALL Java_rtandroid_ballsort_hardware_Sorter_setDelays(JNIEnv* env, jobject obj, jint baseDelay, jint nextDelay)
{
    data->base_delay = baseDelay;
    data->next_delay = nextDelay;
}

extern "C" jint JNICALL Java_rtandroid_ballsort_hardware_Sorter_getBallCount(JNIEnv* env, jobject obj)
{
    return data->ball_count;
}

extern "C" void JNICALL Java_rtandroid_ballsort_hardware_Sorter_resetBallCount(JNIEnv* env, jobject obj)
{
    data->ball_count = 0;
}

extern "C" jboolean JNICALL Java_rtandroid_ballsort_hardware_Sorter_closeMemory(JNIEnv* env, jobject obj)
{
    LOGI("Closing shared memory");

    // looks like we are already initialized
    if (fd == 0)
    {
        LOGE("Operation failed: the file descriptor wasn't initialized");
        return JNI_FALSE;
    }

    // close the memory region
    close(fd);
    fd = 0;

    LOGI("Memory was closed");
}


text:
package com.intellij.ide.hierarchy.newAPI.actions;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.hierarchy.LanguageCallHierarchy;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import org.jetbrains.annotations.NotNull;

public final class BrowseCallHierarchyAction extends BrowseHierarchyActionBase {
  public BrowseCallHierarchyAction() {
    super(LanguageCallHierarchy.INSTANCE);
  }

  @Override
  public final void update(@NotNull final AnActionEvent event){
    final Presentation presentation = event.getPresentation();
    if (!ActionPlaces.isMainMenuOrActionSearch(event.getPlace())) {
      presentation.setText(IdeBundle.lazyMessage("action.browse.call.hierarchy"));
    }

    super.update(event);
  }
}


text:
Debian
====================
This directory contains files used to package doriancoind/doriancoin-qt
for Debian-based Linux systems. If you compile doriancoind/doriancoin-qt yourself, there are some useful files here.

## doriancoin: URI support ##

doriancoin-qt.desktop  (Gnome / Open Desktop)
To install:

	sudo desktop-file-install doriancoin-qt.desktop
	sudo update-desktop-database

If you build yourself, you will either need to modify the paths in
the .desktop file or copy or symlink your doriancoin-qt binary to `/usr/bin`
and the `../../share/pixmaps/doriancoin128.png` to `/usr/share/pixmaps`

doriancoin-qt.protocol (KDE)


text:
<!--
	This is an example of making the browser "keep" the user
	on the page when you want him to.

	Why is this so ugly?
	- firefox before 4 could show what ever string you returned from the function
	bound to the 'onbeforeunload' event. Firefox 4 and onward refuses this.
	- that what this hack is for.
	- I haven't tested this on other (chrome, chromium, IE, opera) browsers...

	Resources:
	http://stackoverflow.com/questions/5398772/firefox-4-onbeforeunload-custom-message

	Mark Veltzer <mark.veltzer@gmail.com>
-->
<html>
	<head>
		<script>
			window.onbeforeunload=function() {
				if(/Firefox[\/\s](\d+)/.test(window.navigator.userAgent) && new Number(RegExp.$1) >= 4) {
					if(window.confirm("Are you Sure do you want to leave this wonderful demo?")) {
						window.history.go();
					} else {
						window.setTimeout(function() {
							window.stop();
						}, 1);
					}
					return null;
				} else {
					return "Are you Sure do you want to leave this wonderful demo?";
				}
			};
			/*
			window.onbeforeunload = function() {
				console.log("what?!?")
				return true
				return confirm("You're leaving the site.");
			};
			*/
		</script>
	</head>
</html>