text:
# Federated Queues

## Overview

This guide covers federated queues, a subset of functionality offered by the [Federation plugin](federation.html).

Some covered topics include:

* An overview of queue federation
* Common [use cases](#use-cases)
* [Usage and configuration](#usage)
* [Limitations](#limitations) and [pitfalls](#pitfalls) of queue federation
* [Implementation details](#details)

A separate [Federation plugin reference](./federation-reference.html) guide is available.

In addition to [federated exchanges](federated-exchanges.html), RabbitMQ supports federated queues.
This feature provides a way of balancing the load of a single logical queue
across nodes or clusters. It does so by moving messages to other federation
peers (nodes or clusters) when the local queue has no consumers.

While federated exchanges replicate their stream of messages from the upstream
to one or more downstreams, federated queues move data where the consumers are,
always preferring local consumers to remote ones. Federated queues are considered
to be equal peers, there is no "leader/follower" relationship between them like with federated exchanges.

A federated queue links to other of its federated peers (called _upstream_ queues).
It will retrieve messages from upstream queues in order to satisfy demand for
messages from local consumers. The upstream queues do not
need to be reconfigured. They are assumed to be located on a separate node or in a separate
cluster.

An upstream definition is a URI with certain recognised query parameters that
control link connection parameters. Upstreams can be managed using [CLI tools](cli.html)
or the HTTP API with [an additional plugin](https://github.com/rabbitmq/rabbitmq-federation-management).

The following diagram demonstrates several federated and unfederated
queues in two RabbitMQ nodes connected using queue federation:

When queue federation is used, usually only a subset of queues in a cluster is federated.
Some queues can be inherently local to the "site" (cluster) and its uses.

## Use Cases

The typical use would be to have the same "logical" queue
distributed over many brokers. Each broker would declare a federated
queue with all the other federated queues upstream. The links
would form a complete bi-directional graph on the federated peers (nodes or clusters).

Such a logical distributed queue is capable of having rather
higher capacity than a single queue. It will perform best when
there is some degree of locality; i.e. as many messages as
possible are consumed from the same queue as they were published
to, and the federation mechanism only needs to move messages
around in order to perform load balancing.

## Limitations

Federated queues include a number of limitations or differences compared to their non-federated peers
as well as federated exchanges.

Queue federation will not propagate [bindings](./tutorials/amqp-concepts.html) from the downstream to the upstreams.

Applications that use basic.get (consume via polling, a highly discouraged practice)
cannot retrieve messages over federation if there aren't any in a local queue (on the node the client is connected to).
Since basic.get is a synchronous method, the node serving a request would have to
block while contacting all the other nodes to retrieve more
messages. This wouldn't sit well with federation's availability and partition tolerance-oriented
design and use cases.

Brokers running different versions of RabbitMQ can be connected
using federation. However, since queue federation requires
consumer priorities, it is not possible to federate a queue with a
broker running a RabbitMQ version prior to 3.2.0.

## Usage and Configuration

Federated queues are declared just like any other queue, by applications.
In order for RabbitMQ to recognize that a queue needs to be federated,
and what other nodes messages should be consumed from, _downstream_
(consuming) nodes need to be configured.

Federation configuration uses [runtime parameters and policies](parameters.html), which means it can be configured
and reconfigured on the fly as system topology changes. There are two key pieces of configuration involved:

* Upstreams: these are remote endpoints in a federated system
* Federation policies: these control what queues are federated and what upstreams (peers) they will connect to

Both of those are configured on the upstream nodes or clusters.

To add an upstream, use the `rabbitmqctl set_parameter` command. It accepts three parameters:

  * Parameter type, `federation-upstream`
  * An upstream name that federation policies will refer to
  * An upstream definition JSON document with at least one mandatory key, `uri`

The following example configures an upstream named "source" which can be contacted at `remote-host.local:5672`:

# Adds a federation upstream named "origin"
rabbitmqctl set_parameter federation-upstream origin '{"uri":"amqp://localhost:5673"}'

On Windows, use rabbitmqctl.bat and suitable PowerShell quoting:

# Adds a federation upstream named "origin"
rabbitmqctl.bat set_parameter federation-upstream origin "{""uri"":""amqp://localhost:5673""}"

Once an upstream has been specified, a policy that controls federation can be added.
It is added just like any other [policy](parameters.html#policies), using `rabbitmqctl set_policy`:

# Adds a policy named "queue-federation"
rabbitmqctl set_policy queue-federation "^federated\." '{"federation-upstream-set":"all"}' \
    --priority 10 \
    --apply-to queues

Here's a Windows version of the above example:

# Adds a policy named "queue-federation"
rabbitmqctl.bat set_policy queue-federation "^federated\." "{""federation-upstream-set"":""all""}" ^
    --priority 10 ^
    --apply-to queues

In the example above, the policy will match queues whose name begins with a `federated.` prefix
in the default virtual host. Those queues will set up federation links for all declared upstreams.
The name of the policy is `queue-federation`. As with any policy, if multiple policies match a queue,
the one with the highest priority will be used. Multiple policy definitions will not be combined, even if their
priorities are equal.

Once configured, a federation link (connection) will be opened for every matching queue and upstream pair.
By "matching queue" here we mean a queue that is matched by the [federation policy pattern](parameters.html#policies).
If no queues matched, no links will be started.

To deactivate federation for the matching queues, delete the policy using its name:

rabbitmqctl clear_policy queue-federation

## Complex Topologies and Loop Handling

A federated queue can be "upstream"
from another federated queue. One can even form "loops", for
example, queue A declares queue B to be upstream from it, and
queue B declares queue A to be upstream from it. More complex
multiple-connected arrangements are allowed. Such complex topologies
will be increasingly difficult to reason about and troubleshoot, however.

Unlike federated exchanges, queue federation does not replicate data and
does not handle loops explicitly. There is no limit to how
many times a message can be forwarded between federated queues.

In a set of mutually-federated queues, messages will move to where
the spare consuming capacity is so if the spare consuming
capacity keeps moving around then so will the messages. Since messages are moved to remote nodes
only when there are no local consumers, it is rare for a message to be moved
across all nodes and "wrap around".

## Implementation

The federated queue will connect to all its upstream queues
using AMQP 0-9-1 (optionally [secured with TLS](ssl.html)).

The federated queue will only retrieve messages when it has run
out of messages locally, it has consumers that need messages, and
the upstream queue has "spare" messages that are not being
consumed. The intent is to ensure that messages are only
transferred between federated queues when needed. This is
implemented using [consumer priorities](consumer-priority.html).

If messages are forwarded from one queue to another then message
ordering is only preserved for messages which have made exactly
the same journey between nodes. In some cases messages which were
adjacent when published may take different routes to the same node
to be consumed; therefore messages can be reordered in the
presence of queue federation.

Each individual queue applies its arguments separately;
for example if you set `x-max-length` on a federated
queue then that queue will have its length limited (possibly
discarding messages when it gets full) but other queues that are
federated with it will not be affected. Note in particular that
when [per-queue or per-message TTL](ttl.html) is in
use, a message will have its timer reset when it is transferred to
another queue.

## Pitfalls

Federated queues cannot currently cause messages to
traverse multiple hops between brokers based solely on need for
messages in one place. For example, if you federate queues on
nodes A, B and C, with A and B connected and B and C connected,
but not A and C, then if messages are available at A and consumers
waiting at C then messages will not be transferred from A to C via
B unless there is also a consumer at B.

It is possible to bind a federated queue to a federated
exchange. However, the results may be unexpected to some.
Since a federated exchange will retrieve messages from its
upstream that match its bindings, any message published to a
federated exchange will be copied to any nodes that matching
bindings. A federated queue will then move these messages
around between nodes, and it is therefore possible to end up
with multiple copies of the same message on the same node.


text:
This is all examples based code to help people understand more about angular form validation & submissions. Start with ex1 and work your way up to ex4 . by then end you will have a form being validated and posted to your mock backend.

## Example One - Build the basics of the form

```html
    <form name="formExample" role="form" novalidate>
        <div class="form-group" >
            <label>Username</label>
            <input name="username" type="text" maxLength=10 class="form-control" data-ng-model="formData.username" id="username" placeholder="Username" required>
        </div>
    </form>
```

## Example Two - Add Validation to the form

```html
    <div class="form-group" ng-class="{ 'has-error' : submitted && formExample.username.$invalid }">
        <label>Username</label>
        <input name="username" type="text"  ng-minlength="3" ng-maxlength="8" class="form-control" data-ng-model="formData.username" id="username" placeholder="Username" required>
        <div ng-show="submitted && formExample.username.$invalid" class="help-block">
            <p ng-show="formExample.username.$error.required">Username is required</p>
            <p ng-show="formExample.username.$error.minlength" class="help-block">Username is too short.</p>
            <p ng-show="formExample.username.$error.maxlength" class="help-block">Username is too long.</p>
        </div>
    </div>
    {{formExample}}
```

## Example Three - Add $http to post to a mock backand

```javascript
    $http.post('/form',$scope.formData).
      then(function(response) {
      	//success response
        $scope.submittedData.push(response.data)
        $scope.formData = {};
        $scope.submitted = false;
        alert("The form was posted to the httpBackend")
      }, function(response) {
        //error response
      });
```

## Example Four - Add $resource to post to a mock backand

```javascript
    var Forms = $resource('/form');
	Forms.save($scope.formData, function(data){
	  	$scope.submittedData.push(data)
        $scope.formData = {};
        $scope.submitted = false;
        alert("The form was posted to the httpBackend")
	});
```

## MISC - Build Mock Backend
```javascript
        var formApp = angular.module('formApp', ['ngMockE2E','ngResource']);
        formApp.controller('formController', function ($scope,$resource,$httpBackend) {
            $httpBackend.whenPOST('/form').respond(function(method, url, data, headers){
                console.log('Received these data:', method, url, data, headers);
                return [200, data, {}];
            });

            //more logic here
        });

```

## MISC - END JS SOLUTION
```javascript
	var formApp = angular.module('formApp', ['ngMockE2E','ngResource']);
    // create angular controller
    formApp.controller('formController', function ($scope,$resource,$httpBackend) {
        //create variables needed  - form data object, submitted forms array
        $scope.formData = {};
        $scope.submittedData=[];
            // create function to submit the form after all validation has occurred
        $scope.submitForm = function (isValid) {
            // check to make sure the form is completely valid if so - push the form being submitted - then clear that form
            // if not make scope.submitted true
            if (!isValid) {
            	//https://docs.angularjs.org/api/ngResource/service/$resource
            	var Forms = $resource('/form');
				Forms.save($scope.formData, function(data){
				  	$scope.submittedData.push(data)
                    $scope.formData = {};
                    $scope.submitted = false;
                    alert("The form was posted to the httpBackend")
				});
            } else {
                $scope.submitted = true;
            }
        };
        //set up an angular mock backend to handle the form submission
        $httpBackend.whenPOST('/form').respond(function(method, url, data, headers){
            console.log('Received these data:', method, url, data, headers);
            return [200, data, {}];
        });
    });
```

## MISC - END HTML SOLUTION - SHORTEN
```html
	<form name="formExample" role="form" data-ng-submit="submitForm(formExample.$valid)" novalidate>
        <div class="form-group" ng-class="{ 'has-error' : submitted && formExample.name.$invalid }">
            <label>Name</label>
            <input name="name" type="text" class="form-control" data-ng-model="formData.name" id="name" placeholder="Name" required>
            <div ng-show="submitted && formExample.name.$invalid" class="help-block">
                <p ng-show="formExample.name.$error.required">Name is required</p>
            </div>
        </div>
        <!-- More inputs go here  -->
        <div class="form-group">
            <button type="submit" class="btn btn-success btn-lg btn-block">
                <span class="glyphicon glyphicon-ok"></span> Submit!
            </button>
        </div>
    </form>
```

#### This is [on GitHub](https://github.com/GreenPioneer/angular-forms)
#### Find us [on GitHub](https://github.com/GreenPioneer)
#### Find us [on Twitter](https://twitter.com/greenpioneerdev)
#### Find us [on Facebook](https://www.facebook.com/Green-Pioneer-Solutions-1023752974341910)
#### Find us [on The Web](http://greenpioneersolutions.com/)

redpajama_set_name: RedPajamaGithub


text:
namespace net {

QuicPriority ConvertRequestPriorityToQuicPriority(
    const RequestPriority priority) {
  DCHECK_GE(priority, MINIMUM_PRIORITY);
  DCHECK_LT(priority, NUM_PRIORITIES);
  return static_cast<QuicPriority>(HIGHEST - priority);
}

NET_EXPORT_PRIVATE RequestPriority ConvertQuicPriorityToRequestPriority(
    QuicPriority priority) {
  // Handle invalid values gracefully.
  return (priority >= 5) ?
      IDLE : static_cast<RequestPriority>(HIGHEST - priority);
}

}  // namespace net


text:
package nl.nn.adapterframework.util;

import java.sql.JDBCType;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;

import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.jdbc.dbms.IDbmsSupport;
import nl.nn.adapterframework.stream.MessageOutputStream;
import nl.nn.adapterframework.stream.StreamingException;
import nl.nn.adapterframework.stream.document.ArrayBuilder;
import nl.nn.adapterframework.stream.document.DocumentBuilderFactory;
import nl.nn.adapterframework.stream.document.DocumentFormat;
import nl.nn.adapterframework.stream.document.INodeBuilder;
import nl.nn.adapterframework.stream.document.ObjectBuilder;

public class DB2DocumentWriter {
	protected static Logger log = LogUtil.getLogger(DB2DocumentWriter.class);

	private String docname = "result";
	private String recordname = "rowset";
	private String nullValue = "";
	private boolean trimSpaces=true;
	private boolean decompressBlobs=false;
	private boolean getBlobSmart=false;
	private String blobCharset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
	private static boolean convertFieldnamesToUppercase = AppConstants.getInstance().getBoolean("jdbc.convertFieldnamesToUppercase", false);

	public static String getFieldType (int type) {
		return JDBCType.valueOf(type).getName();
	}

	/**
	 * Retrieve the Resultset as a well-formed XML string
	 */
	public String getXML(IDbmsSupport dbmsSupport, ResultSet rs) {
		return getXML(dbmsSupport, rs, Integer.MAX_VALUE);
	}

	/**
	 * Retrieve the Resultset as a well-formed XML string
	 */
	public String getXML(IDbmsSupport dbmsSupport, ResultSet rs, int maxlength) {
		return getXML(dbmsSupport, rs, maxlength, true);
	}

	public String getXML(IDbmsSupport dbmsSupport, ResultSet rs, int maxlength, boolean includeFieldDefinition) {
		try {
			ObjectBuilder documentBuilder = DocumentBuilderFactory.startObjectDocument(DocumentFormat.XML, docname);
			try {
				writeDocument(dbmsSupport, rs, maxlength, includeFieldDefinition, documentBuilder);
			} finally {
				documentBuilder.close();
			}
			return documentBuilder.toString();
		} catch (SAXException e) {
			log.warn("cannot convert ResultSet to XML", e);
			return "<error>"+XmlUtils.encodeCharsAndReplaceNonValidXmlCharacters(e.getMessage())+"</error>";
		}
	}

	public void writeDocument(DocumentFormat format, IDbmsSupport dbmsSupport, ResultSet rs, int maxlength, boolean includeFieldDefinition, MessageOutputStream target, boolean prettyPrint) throws StreamingException, SAXException {
		try (ObjectBuilder documentBuilder = DocumentBuilderFactory.startObjectDocument(format, docname, target, prettyPrint)) {
			writeDocument(dbmsSupport, rs, maxlength, includeFieldDefinition, documentBuilder);
		}
	}

	public void writeDocument(IDbmsSupport dbmsSupport, ResultSet rs, int maxlength, boolean includeFieldDefinition, ObjectBuilder documentBuilder) throws SAXException {

		if (null == rs) {
			return;
		}
		if (maxlength < 0) {
			maxlength = Integer.MAX_VALUE;
		}
		Statement stmt=null;
		try {
			stmt = rs.getStatement();
			if (stmt!=null) {
				JdbcUtil.warningsToDocument(stmt.getWarnings(), documentBuilder);
			}
		} catch (SQLException e1) {
			log.warn("exception obtaining statement warnings", e1);
		}
		int rowCounter=0;
		try {
			ResultSetMetaData rsmeta = rs.getMetaData();
			if (includeFieldDefinition) {
				addFieldDefinitions(documentBuilder, rsmeta);
			}

			//----------------------------------------
			// Process result rows
			//----------------------------------------

			try (ArrayBuilder rows = documentBuilder.addArrayField(recordname,"row")) {
				while (rs.next() && rowCounter < maxlength) {
					writeRow(rows, dbmsSupport, rs,rsmeta,getBlobCharset(),decompressBlobs,nullValue,trimSpaces,getBlobSmart);
					rowCounter++;
				}
			}
		} catch (Exception e) {
			log.error("Error occured at row [" + rowCounter+"]", e);
		}
	}

//	public static String getFieldDefinitions(ResultSet rs) throws SAXException, SQLException {
//		XmlWriter writer = new XmlWriter();
//		addFieldDefinitions(rs, writer);
//		return writer.toString();
//	}
//	public static void addFieldDefinitions(ResultSet rs, ContentHandler handler) throws SAXException, SQLException {
//		ResultSetMetaData rsmeta = rs.getMetaData();
//		try (SaxElementBuilder fields = new SaxElementBuilder("fielddefinition", handler)) {
//			addFieldDefinitionsToContainer(fields, rsmeta);
//		}
//	}
	public static void addFieldDefinitions(ObjectBuilder documentBuilder, ResultSetMetaData rsmeta) throws SAXException, SQLException {
		try (ArrayBuilder fields = documentBuilder.addArrayField("fielddefinition","field")) {
			addFieldDefinitionsToContainer(fields, rsmeta);
		}
	}

	private static void addFieldDefinitionsToContainer(ArrayBuilder fields, ResultSetMetaData rsmeta) throws SAXException, SQLException {
		int nfields = rsmeta.getColumnCount();

		for (int j = 1; j <= nfields; j++) {
			try (INodeBuilder nodeBuilder=fields.addElement()) {
				try (ObjectBuilder field=nodeBuilder.startObject()) {

					String columnName = rsmeta.getColumnName(j);
					if(convertFieldnamesToUppercase) {
						columnName = columnName.toUpperCase();
					}
					field.addAttribute("name", columnName);

					//Not every JDBC implementation implements these attributes!
					try {
						field.addAttribute("type", getFieldType(rsmeta.getColumnType(j)));
					} catch (SQLException e) {
						log.debug("Could not determine columnType",e);
					}
					try {
						field.addAttribute("columnDisplaySize", rsmeta.getColumnDisplaySize(j));
					} catch (SQLException e) {
						log.debug("Could not determine columnDisplaySize",e);
					}
					try {
						field.addAttribute("precision", rsmeta.getPrecision(j));
					} catch (SQLException e) {
						log.warn("Could not determine precision",e);
					} catch (NumberFormatException e2) {
						if (log.isDebugEnabled()) log.debug("Could not determine precision: "+e2.getMessage());
					}
					try {
						field.addAttribute("scale", rsmeta.getScale(j));
					} catch (SQLException e) {
						log.debug("Could not determine scale",e);
					}
					try {
						field.addAttribute("isCurrency", rsmeta.isCurrency(j));
					} catch (SQLException e) {
						log.debug("Could not determine isCurrency",e);
					}
					try {
						String columnTypeName = rsmeta.getColumnTypeName(j);
						if(convertFieldnamesToUppercase)
							columnTypeName = columnTypeName.toUpperCase();
						field.addAttribute("columnTypeName", columnTypeName);
					} catch (SQLException e) {
						log.debug("Could not determine columnTypeName",e);
					}
					try {
						field.addAttribute("columnClassName", rsmeta.getColumnClassName(j));
					} catch (SQLException e) {
						log.debug("Could not determine columnClassName",e);
					}
				}
			}
		}
	}

//	public static String getRowXml(IDbmsSupport dbmsSupport, ResultSet rs, int rowNumber, ResultSetMetaData rsmeta, String blobCharset, boolean decompressBlobs, String nullValue, boolean trimSpaces, boolean getBlobSmart) throws SenderException, SQLException, SAXException {
//		SaxElementBuilder parent = new SaxElementBuilder();
//		getRowXml(parent, dbmsSupport, rs, rowNumber, rsmeta, blobCharset, decompressBlobs, nullValue, trimSpaces, getBlobSmart);
//		return parent.toString();
//	}

	public static void writeRow(ArrayBuilder rows, IDbmsSupport dbmsSupport, ResultSet rs, ResultSetMetaData rsmeta, String blobCharset, boolean decompressBlobs, String nullValue, boolean trimSpaces, boolean getBlobSmart) throws SenderException, SQLException, SAXException {
		try (INodeBuilder nodeBuilder = rows.addElement()) {
			try (ObjectBuilder row=nodeBuilder.startObject()) {
				for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
					String columnName = "" + rsmeta.getColumnName(i);
					if(convertFieldnamesToUppercase) {
						columnName = columnName.toUpperCase();
					}
					try {
						String value = JdbcUtil.getValue(dbmsSupport, rs, i, rsmeta, blobCharset, decompressBlobs, nullValue, trimSpaces, getBlobSmart, false);
						if (rs.wasNull()) {
							row.add(columnName, null);
						} else {
							if (JdbcUtil.isNumeric(rsmeta.getColumnType(i))) {
								row.addNumber(columnName, value);
							} else {
								row.add(columnName, value);
							}
						}
					} catch (Exception e) {
						throw new SenderException("error getting fieldvalue column ["+i+"] fieldType ["+getFieldType(rsmeta.getColumnType(i))+ "]", e);
					}
				}
				//JdbcUtil.warningsToXml(rs.getWarnings(), row);
			}
		}
	}

	public void setDocumentName(String s) {
		docname = s;
	}

	public void setRecordName(String s) {
		recordname = s;
	}

	/**
	 * Set the presentation of a Null value
	 */
	public void setNullValue(String s) {
		nullValue = s;
	}

	/**
	 * Get the presentation of a Null value
	 */
	public String getNullValue() {
		return nullValue;
	}

	public void setTrimSpaces(boolean b) {
		trimSpaces = b;
	}
	public boolean isTrimSpaces() {
		return trimSpaces;
	}

	public void setDecompressBlobs(boolean b) {
		decompressBlobs = b;
	}
	public boolean isDecompressBlobs() {
		return decompressBlobs;
	}

	public void setGetBlobSmart(boolean b) {
		getBlobSmart = b;
	}
	public boolean isGetBlobSmart() {
		return getBlobSmart;
	}

	public String getBlobCharset() {
		return blobCharset;
	}

	public void setBlobCharset(String string) {
		blobCharset = string;
	}

}


text:
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

{-| Unittests for ganeti-htools.

-}

{-

Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Test.Ganeti.Ssconf (testSsconf) where

import Test.QuickCheck

import Data.List

import Test.Ganeti.TestHelper

import qualified Ganeti.Ssconf as Ssconf

-- * Ssconf tests

$(genArbitrary ''Ssconf.SSKey)

prop_filename :: Ssconf.SSKey -> Property
prop_filename key =
  printTestCase "Key doesn't start with correct prefix" $
    Ssconf.sSFilePrefix `isPrefixOf` Ssconf.keyToFilename "" key

testSuite "Ssconf"
  [ 'prop_filename
  ]


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
     <translate
          android:fromYDelta="0"
          android:toYDelta="-100%p"
          android:duration="@android:integer/config_shortAnimTime"
          />
     <alpha
          android:fromAlpha="1.0"
          android:toAlpha="0.0"
          android:duration="@android:integer/config_shortAnimTime"
          />
</set>
<!-- From: file:/Users/sww/Code/npm/Publish/react-native-swRefresh/RefreshDemo/android/app/build/intermediates/exploded-aar/com.facebook.react/react-native/0.35.0/res/anim/catalyst_push_up_out.xml -->


text:
<?php

namespace Symfony\Component\Security\Http\Tests\Authenticator;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\FormLoginAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Tests\Authenticator\Fixtures\PasswordUpgraderProvider;

class FormLoginAuthenticatorTest extends TestCase
{
    private $userProvider;
    private $successHandler;
    private $failureHandler;
    /** @var FormLoginAuthenticator */
    private $authenticator;

    protected function setUp(): void
    {
        $this->userProvider = new InMemoryUserProvider(['test' => ['password' => 's$cr$t']]);
        $this->successHandler = $this->createMock(AuthenticationSuccessHandlerInterface::class);
        $this->failureHandler = $this->createMock(AuthenticationFailureHandlerInterface::class);
    }

    /**
     * @dataProvider provideUsernamesForLength
     */
    public function testHandleWhenUsernameLength($username, $ok)
    {
        if ($ok) {
            $this->expectNotToPerformAssertions();
        } else {
            $this->expectException(BadCredentialsException::class);
            $this->expectExceptionMessage('Username too long.');
        }

        $request = Request::create('/login_check', 'POST', ['_username' => $username, '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator();
        $this->authenticator->authenticate($request);
    }

    public function provideUsernamesForLength()
    {
        yield [str_repeat('x', UserBadge::MAX_USERNAME_LENGTH + 1), false];
        yield [str_repeat('x', UserBadge::MAX_USERNAME_LENGTH - 1), true];
    }

    /**
     * @dataProvider postOnlyDataProvider
     */
    public function testHandleNonStringUsernameWithArray($postOnly)
    {
        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('The key "_username" must be a string, "array" given.');

        $request = Request::create('/login_check', 'POST', ['_username' => []]);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['post_only' => $postOnly]);
        $this->authenticator->authenticate($request);
    }

    /**
     * @dataProvider postOnlyDataProvider
     */
    public function testHandleNonStringUsernameWithInt($postOnly)
    {
        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('The key "_username" must be a string, "integer" given.');

        $request = Request::create('/login_check', 'POST', ['_username' => 42]);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['post_only' => $postOnly]);
        $this->authenticator->authenticate($request);
    }

    /**
     * @dataProvider postOnlyDataProvider
     */
    public function testHandleNonStringUsernameWithObject($postOnly)
    {
        $this->expectException(BadRequestHttpException::class);
        $this->expectExceptionMessage('The key "_username" must be a string, "object" given.');

        $request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['post_only' => $postOnly]);
        $this->authenticator->authenticate($request);
    }

    /**
     * @dataProvider postOnlyDataProvider
     */
    public function testHandleNonStringUsernameWithToString($postOnly)
    {
        $usernameObject = $this->createMock(DummyUserClass::class);
        $usernameObject->expects($this->once())->method('__toString')->willReturn('someUsername');

        $request = Request::create('/login_check', 'POST', ['_username' => $usernameObject, '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['post_only' => $postOnly]);
        $this->authenticator->authenticate($request);
    }

    public function postOnlyDataProvider()
    {
        yield [true];
        yield [false];
    }

    public function testCsrfProtection()
    {
        $request = Request::create('/login_check', 'POST', ['_username' => 'wouter', '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['enable_csrf' => true]);
        $passport = $this->authenticator->authenticate($request);
        $this->assertTrue($passport->hasBadge(CsrfTokenBadge::class));
    }

    public function testUpgradePassword()
    {
        $request = Request::create('/login_check', 'POST', ['_username' => 'wouter', '_password' => 's$cr$t']);
        $request->setSession($this->createSession());

        $this->userProvider = new PasswordUpgraderProvider(['test' => ['password' => 's$cr$t']]);

        $this->setUpAuthenticator();
        $passport = $this->authenticator->authenticate($request);
        $this->assertTrue($passport->hasBadge(PasswordUpgradeBadge::class));
        $badge = $passport->getBadge(PasswordUpgradeBadge::class);
        $this->assertEquals('s$cr$t', $badge->getAndErasePlaintextPassword());
    }

    /**
     * @dataProvider provideContentTypes()
     */
    public function testSupportsFormOnly(string $contentType, bool $shouldSupport)
    {
        $request = new Request();
        $request->headers->set('CONTENT_TYPE', $contentType);
        $request->server->set('REQUEST_URI', '/login_check');
        $request->setMethod('POST');

        $this->setUpAuthenticator(['form_only' => true]);

        $this->assertSame($shouldSupport, $this->authenticator->supports($request));
    }

    public function provideContentTypes()
    {
        yield ['application/json', false];
        yield ['application/x-www-form-urlencoded', true];
    }

    private function setUpAuthenticator(array $options = [])
    {
        $this->authenticator = new FormLoginAuthenticator(new HttpUtils(), $this->userProvider, $this->successHandler, $this->failureHandler, $options);
    }

    private function createSession()
    {
        return $this->createMock(SessionInterface::class);
    }
}

class DummyUserClass
{
    public function __toString(): string
    {
        return '';
    }
}


text:
/**
 * Constructor to make a HTTP request on the server
 *
 * @param {string} method - GET or POST
 * @param {string} url - URL to make the request to
 * @param {object} [params] - Key paired values of parameters to sent in the request
 * @param {Function} [responseHandler] - Key paired values of parameters to sent in the request
 *
 * @memberOf module:Server~Ape
 * @constructor Request
 */
Ape.Request = function(method, url, params, responseHandler){

	// Parses the URL
	var result  = url.match(/^.*?:\/\/(.*?)(:([0-9]+))?((\/.*)|)$/);

	this.url = url;
	this.host   = result[1];
	this.port   = result[3] || 80;
	this.query  = result[4] || '/';
	this.method = method || 'GET';

	this.headers = {};
	this.body = [];
	this.responseHeaders = null;

	/**
	 * Get the response of the request
	 *
	 * @param {Function} callback - Three parameter are passed to the callback
	 *                              responseBody, responseStatusCode, responseHeaders
	 *
	 * @memberOf module:Server~Ape.Request
	 * @method getResponse
	 */
	this.getResponse = function(callback)
	{
		this.connect();
		this.read(callback);
	}

	/**
	 * Set a request header
	 *
	 * @param {string} key - The header name
	 * @param {string|Number} value - The header value
	 *
	 * @memberOf module:Server~Ape.Request
	 * @method setHeader
	 */
	this.setHeader = function(key, value)
	{
		this.headers[key] = value;
	}

	/**
	 * Set all request headers
	 * Note: this method overwrite any existing headers
	 *
	 * @param {Object} object - Key pair of headers
	 *
	 * @memberOf module:Server~Ape.Request
	 * @method setHeaders
	 */
	this.setHeaders = function(object)
	{
		this.headers = object;
	}

	/**
	 * Assign parameter to send with the request
	 *
	 * @param {Object|String} dataORkey - A key pair object of parameters
	 * @param {*} [value] - The value of the parameter
	 *
	 * @memberOf module:Server~Ape.Request
	 * @method addParam
	 */
	this.addParam = function(dataORkey, value)
	{
		var tmp = {}
		if ( this.method == 'POST')
		{
			if (typeof dataORkey == "object")
			{
				this.write(this.serialize(dataORkey));
			}
			else
			{
				tmp[dataORkey] = value;
				this.write(this.serialize(tmp));
			}
		}
		else
		{
			if (typeof dataORkey == "object")
			{
				this.query += '&' + this.serialize(dataORkey);
			}
			else
			{
				tmp[dataORkey] = value;
				this.query += '&' + this.serialize(tmp);
			}
		}
	}

	/**
	 * Serializes a JS object
	 *
	 * @param {Object} obj - Object to serialize
	 * @param {String} [prefix]
	 *
	 * @memberOf module:Server~Ape.Request
	 * @method serialize
	 * @private
	 */
	this.serialize = function(obj, prefix) {
		var str = [];
		for(var p in obj) {
			if (obj.hasOwnProperty(p))
			{
				var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
				str.push(typeof v == "object" ?
					this.serialize(v, k) :
					encodeURIComponent(k) + "=" + encodeURIComponent(v));
			}
		}
		return str.join("&");
	}

	this.write = function(data)
	{
		this.body.push(data);
	}

	this.connect = function()
	{
		if (this.method.toUpperCase() == 'POST')
		{
			this.setHeader('Content-length', this.body.join('&').length);
			this.setHeader('Content-Type', 'application/x-www-form-urlencoded');
		}

		this.setHeader('User-Agent', 'APE Server');
		this.setHeader('Accept', '*/*');

		this.socket = new Ape.sockClient(this.port, this.host, { flushlf: false });

		this.sockConnect();
		this.sockRead();
	}

	this.sockConnect = function()
	{
		this.socket.onConnect = function() {
			var toWrite = this.method + " " + this.query + " HTTP/1.0\r\nHost: " + this.host + "\r\n";

			for (var i in this.headers) {
				if (this.headers.hasOwnProperty(i)) {
					toWrite += i + ': ' + this.headers[i] + "\r\n";
				}
			}

			this.socket.write(toWrite + "\r\n");
			this.socket.write(this.body.join('&'));
		}.bind(this);
	}

	this.sockRead = function()
	{
		this.response = '';
		this.socket.onRead = function(data) {
			/*
			 * Check if headers need to be read
			 */
			if (data.indexOf("\r\n\r\n") != -1 && ! this.responseHeaders)
			{
				var tmp = data.split("\r\n\r\n");

				var headers = tmp[0];
				var body = tmp.slice(1).join();

				headers = headers.split("\r\n");

				this.responseHeaders = {};

				/*
				 * Get the response code
				 */
				this.responseCode = headers.shift().split(" ");
				this.responseCode = parseInt(this.responseCode[1]);

				/*
				 * Get all headers into a object
				 */
				for (var i = 0; i < headers.length; i++)
				{
					var tmpHeaders = headers[i].split(": ");
					this.responseHeaders[tmpHeaders[0]] = tmpHeaders[1];
				}

				/*
				 * Add the body
				 */
				this.response = body;

				if ( !! this.responseHeaders['Content-Length'] && body.length >= this.responseHeaders['Content-Length'])
				{
					this.socket.close();
				}
				if ( !! this.responseHeaders['Location'] )
				{
					this.socket.close();
				}
			}
			else
			{
				/*
				 * Incrementally keep adding the request body
				 */
				this.response += data;
			}
		}.bind(this);
	}

	this.read = function(callback)
	{
		this.socket.onDisconnect = function(callback) {
			if ( !! this.responseHeaders )
			{
				if ( !! this.responseHeaders['Location'] )
				{
					var newRequest = new Request(this.responseHeaders['Location']);
					newRequest.setHeaders(this.headers);
					newRequest.set('method', this.method);
					newRequest.write(this.body.join('&'));
					newRequest.getResponse(callback);
				}
				else
				{
					callback.apply(this, [this.response, this.responseCode, this.responseHeaders]);
				}
			}
			else
			{
				Ape.log('Request Failed: ' + this.url);
			}
		}.bind(this, callback);
	}

	/*
	 * Adds parameter from the constructor or/and the handler
	 */
	switch (typeof params)
	{
		case "function":
			this.getResponse(params);
			break;
		case "object":
			this.addParam(params);
			if ( typeof responseHandler == 'function' )
			{
				this.getResponse(responseHandler);
			}
			break;
	}
}

/**
 * Constructor to make a GET HTTP request on the server
 * @param {string} url - The request url
 * @param {object} params - Key paired values of parameters to sent in the request
 * @param {Function} [responseHandler] - Key paired values of parameters to sent in the request
 *
 * @memberOf module:Server~Ape
 * @class GetRequest
 * @extends module:Server~Ape.Request
 */
Ape.GetRequest = Ape.Request.bind(Ape.Request,'GET');

/**
 * Constructor to make a POST HTTP request on the server
 * @param {string} url - The request url
 * @param {object} params - Key paired values of parameters to sent in the request
 * @param {Function} [responseHandler] - Key paired values of parameters to sent in the request
 *
 * @memberOf module:Server~Ape
 * @class PostRequest
 * @extends module:Server~Ape.Request
 */
Ape.PostRequest = Ape.Request.bind(Ape.Request,'POST');

/*
 * Add backward comparability to the original global objects
 */
var Request = Ape.Request;
var GetRequest = Ape.GetRequest;
var PostRequest = Ape.PostRequest;


text:
package parser;

// for each cell
// Dont go above Z column
public class EntryDO {

	 int char_low= 65;
	int char_upper = 90;

	private int row=0;
	private int col=0;
	private String content="";

	/**
	 * @return the col
	 */
	public int getCol() {
		return col;
	}

	/**
	 * @param col the col to set
	 */
	public void setCol(int col) {
		this.col = col;
	}

	/**
	 * @return the content
	 */
	public String getContent() {
		return content;
	}

	/**
	 * @param content the content to set
	 */
	public void setContent(String content) {
		this.content = content;
	}

	public void setValue(String RC, String content){
		if(content==null)
			return;
		this.setContent(content);
		if(RC==null)
			return;
		RC = RC.toUpperCase();
		if(RC.length()==2){
			char C = RC.charAt(0);

			col = ((int) C)-65;
			setRow(Integer.parseInt(RC.substring(1))-1);
		}else{
			char C = RC.charAt(0);

			col = ((int) C)-65;
			setRow(Integer.parseInt(RC.substring(1))-1);
		}

	}

	/**
	 * @return the row
	 */
	public int getRow() {
		return row;
	}

	/**
	 * @param row the row to set
	 */
	public void setRow(int row) {
		this.row = row;
	}

}


text:
<?php

namespace Vinala\Kernel\Filesystem\Exception;

/**
 * File not fount exception.
 */
class FileNotFoundException extends \Exception
{
    protected $message;   // exception message

    public function __construct($path)
    {
        $this->message = "File does not existe in ($path)";
    }
}


text:
dart_library.library('sunflower/circle', null, /* Imports */[
  "dart_runtime/dart",
  'dart/core'
], /* Lazy imports */[
], function(exports, dart, core) {
  'use strict';
  let dartx = dart.dartx;
  class Circle extends core.Object {
    Circle(x, y, radius) {
      this.x = x;
      this.y = y;
      this.radius = radius;
    }
  }
  dart.setSignature(Circle, {
    constructors: () => ({Circle: [Circle, [core.num, core.num, core.num]]})
  });
  // Exports:
  exports.Circle = Circle;
});


text:
/* global describe, it */

var assert = require('assert')
var bitcoin = require('../../')
var blockchain = require('./_blockchain')

describe('bitcoinjs-lib (advanced)', function () {
  it('can sign a Bitcoin message', function () {
    var keyPair = bitcoin.ECPair.fromWIF('5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss')
    var message = 'This is an example of a signed message.'

    var signature = bitcoin.message.sign(keyPair, message)
    assert.strictEqual(signature.toString('base64'), 'G9L5yLFjti0QTHhPyFrZCT1V/MMnBtXKmoiKDZ78NDBjERki6ZTQZdSMCtkgoNmp17By9ItJr8o7ChX0XxY91nk=')
  })

  it('can verify a Bitcoin message', function () {
    var address = '1HZwkjkeaoZfTSaJxDw6aKkxp45agDiEzN'
    var signature = 'HJLQlDWLyb1Ef8bQKEISzFbDAKctIlaqOpGbrk3YVtRsjmC61lpE5ErkPRUFtDKtx98vHFGUWlFhsh3DiW6N0rE'
    var message = 'This is an example of a signed message.'

    assert(bitcoin.message.verify(address, signature, message))
  })

  it('can create an OP_RETURN transaction', function (done) {
    this.timeout(20000)

    var network = bitcoin.networks.testnet
    var keyPair = bitcoin.ECPair.makeRandom({ network: network })
    var address = keyPair.getAddress()

    blockchain.t.faucet(address, 2e4, function (err) {
      if (err) return done(err)

      blockchain.t.addresses.unspents(address, function (err, unspents) {
        if (err) return done(err)

        var tx = new bitcoin.TransactionBuilder(network)
        var data = new Buffer('bitcoinjs-lib')
        var dataScript = bitcoin.script.nullDataOutput(data)

        var unspent = unspents.pop()

        tx.addInput(unspent.txId, unspent.vout)
        tx.addOutput(dataScript, 1000)
        tx.sign(0, keyPair)

        var txBuilt = tx.build()

        blockchain.t.transactions.propagate(txBuilt.toHex(), function (err) {
          if (err) return done(err)

          // check that the message was propagated
          blockchain.t.transactions.get(txBuilt.getId(), function (err, transaction) {
            if (err) return done(err)

            var actual = bitcoin.Transaction.fromHex(transaction.txHex)
            var dataScript2 = actual.outs[0].script
            var data2 = bitcoin.script.decompile(dataScript2)[1]

            assert.deepEqual(dataScript, dataScript2)
            assert.deepEqual(data, data2)

            done()
          })
        })
      })
    })
  })
})


text:
package il.co.codeguru.corewars8086.gui;

import il.co.codeguru.corewars8086.war.*;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;

/**
 * @author BS
 */
public class CompetitionWindow extends JFrame
    implements ScoreEventListener, ActionListener, CompetitionEventListener {
	private static final long serialVersionUID = 1L;

	private Competition competition;
    private ColumnGraph columnGraph;

    // widgets
    private JButton runWarButton;
    private JLabel warCounterDisplay;
    private JCheckBox showBattleCheckBox;
    private JTextField battlesPerGroupField;
    private JTextField warriorsPerGroupField;
    private WarFrame battleFrame;

    private int warCounter;
    private int totalWars;
    private Thread warThread;
	private boolean competitionRunning;

    private static final String SEED_PREFIX = "SEED!@#=";
    private JTextField seed;

	private JCheckBox startPausedCheckBox;

    public CompetitionWindow() throws IOException {
        super("CodeGuru Extreme - Competition Viewer");
        getContentPane().setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        competition = new Competition();
        competition.addCompetitionEventListener(this);
        WarriorRepository warriorRepository = competition
                        .getWarriorRepository();
        warriorRepository.addScoreEventListener(this);
        columnGraph = new ColumnGraph(warriorRepository.getGroupNames());
        getContentPane().add(columnGraph, BorderLayout.CENTER);
        // -------------
        JPanel controlArea = new JPanel();
        controlArea.setLayout(new BoxLayout(controlArea, BoxLayout.Y_AXIS));
        // -------------- Button Panel
        JPanel buttonPanel = new JPanel();
        runWarButton = new JButton("Start!");
        runWarButton.addActionListener(this);
        buttonPanel.add(runWarButton);
        warCounterDisplay = new JLabel("");
        buttonPanel.add(warCounterDisplay);
        buttonPanel.add(Box.createHorizontalStrut(30));
        showBattleCheckBox = new JCheckBox("Show war on start");
        buttonPanel.add(showBattleCheckBox);

        startPausedCheckBox = new JCheckBox("Start Paused");
		startPausedCheckBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(startPausedCheckBox.isSelected())
					showBattleCheckBox.setSelected(true);
			}
		});
		buttonPanel.add(startPausedCheckBox);

        controlArea.add(buttonPanel);
        // -------------
        controlArea.add(new JSeparator(JSeparator.HORIZONTAL));
        // ------------ Control panel
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(new JLabel("Survivor groups per war:"));

        // If total number of teams is less then four, make it the defauld number
		int numberOfGropus = Math.min(4,
            competition.getWarriorRepository().getNumberOfGroups());

		warriorsPerGroupField = new JTextField(String.format("%d", numberOfGropus), 3);
		controlPanel.add(warriorsPerGroupField);
		controlPanel.add(new JLabel("Wars per groups combination:"));
		battlesPerGroupField = new JTextField("100", 4);
		controlPanel.add(battlesPerGroupField);
		seed = new JTextField(15);
		seed.setText("guru");
		controlPanel.add(new JLabel("seed:"));
		controlPanel.add(seed);

		controlArea.add(controlPanel);

        // ------------
        getContentPane().add(controlArea, BorderLayout.SOUTH);

        addWindowListener(new WindowListener() {
            public void windowOpened(WindowEvent e) {}
            public void windowClosing(WindowEvent e) {
                if (warThread!= null) {
                    competition.setAbort(true);
                }
            }

            public void windowClosed(WindowEvent e) {}
            public void windowIconified(WindowEvent e) {}
            public void windowDeiconified(WindowEvent e) {}
            public void windowActivated(WindowEvent e) {}
            public void windowDeactivated(WindowEvent e) {}
        });
    }

    /**
     * Starts a new war.
     * @return whether or not a new war was started.
     */
    public boolean runWar() {
        try {
            long seedValue;
            if (seed.getText().startsWith(SEED_PREFIX)){
                seedValue = Long.parseLong(seed.getText().substring(SEED_PREFIX.length()));
            }
            else {
                seedValue = seed.getText().hashCode();
            }
            competition.setSeed(seedValue);
            final int battlesPerGroup = Integer.parseInt(
                battlesPerGroupField.getText().trim());
            final int warriorsPerGroup = Integer.parseInt(
                warriorsPerGroupField.getText().trim());
            if (competition.getWarriorRepository().getNumberOfGroups() < warriorsPerGroup) {
                JOptionPane.showMessageDialog(this,
                    "Not enough survivors (got " +
                    competition.getWarriorRepository().getNumberOfGroups() +
                    " but " + warriorsPerGroup + " are needed)");
                return false;
            }
            warThread = new Thread("CompetitionThread") {
                @Override
                public void run() {
                    try {
                        competition.runCompetition(battlesPerGroup, warriorsPerGroup, startPausedCheckBox.isSelected());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
            };
            if (!competitionRunning) {
            	warThread.start();
            	return true;
            }
        } catch (NumberFormatException e2) {
            JOptionPane.showMessageDialog(this, "Error in configuration");
        }
        return false;
    }

    public void scoreChanged(String name, float addedValue, int groupIndex, int subIndex) {
        columnGraph.addToValue(groupIndex, subIndex, addedValue);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == runWarButton) {
        	showBattleFrameIfNeeded();
        	switch (runWarButton.getText().trim()){
                case "Start!":
                    if (runWar()) {
                        competitionRunning = true;
                    }
                    break;
                case ("Stop!"):
                    competition.setAbort(true);
                    competitionRunning = false;
                    break;
                default:
                    break;
            }
        }
    }

    public void onWarStart() {
    	showBattleFrameIfNeeded();
    }

    private void showBattleFrameIfNeeded() {
    	if (showBattleCheckBox.isSelected() && battleFrame == null ) {
    		showBattleRoom();
    		showBattleCheckBox.setSelected(false);
    	}
    }

    private void showBattleRoom() {
        competition.setSpeed(5);
        battleFrame = new WarFrame(competition);
        battleFrame.addWindowListener(new WindowListener() {
            public void windowOpened(WindowEvent e) {
            }

            public void windowClosing(WindowEvent e) {
            }

            public void windowClosed(WindowEvent e) {
                //System.out.println("BattleFrame=null");
                battleFrame = null;
                competition.setSpeed(Competition.MAXIMUM_SPEED);
            }

            public void windowIconified(WindowEvent e) {
            }

            public void windowDeiconified(WindowEvent e) {
            }

            public void windowActivated(WindowEvent e) {
            }

            public void windowDeactivated(WindowEvent e) {
            }
        });

        competition.addMemoryEventLister(battleFrame);
        competition.addCompetitionEventListener(battleFrame);
        Rectangle battleFrameRect = new Rectangle(0, getY(), 750, 700);
        Rectangle screen = getGraphicsConfiguration().getBounds(); //for multiple monitors

        if (getX() + getWidth() <= screen.getX() + screen.getWidth()
        		- battleFrameRect.width)
        {
        	battleFrameRect.x = getX() + getWidth();
        }
        else if (screen.getX() + screen.getWidth() - battleFrameRect.width
        	- getWidth() >= screen.getX())
        {
        	setLocation((int) (screen.getX() + screen.getWidth() - battleFrameRect.width
        			- getWidth()), getY());
        	battleFrameRect.x = getX() + getWidth();
        }
        else
        {
        	setLocation((int)screen.getX(), getY());
        	battleFrameRect.x = getWidth();
        }

        battleFrame.setBounds(battleFrameRect);
        battleFrame.setVisible(true);
    }

    public void onWarEnd(int reason, String winners) {
        warCounter++;
        seed.setText(SEED_PREFIX + competition.getSeed());
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                warCounterDisplay.setText("Wars so far:" + warCounter +
                    " (out of " + totalWars + ")");
            };
        });
    }

    public void onRound(int round) {
    }

    public void onWarriorBirth(String warriorName) {
    }

    public void onWarriorDeath(String warriorName, String reason) {
    }

    public void onCompetitionStart() {
        warCounter = 0;
        totalWars = competition.getTotalNumberOfWars();
        competition.setAbort(false);
        runWarButton.setText("Stop!");
    }

    public void onCompetitionEnd() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                warCounterDisplay.setText("The competition is over. " +
                    warCounter + " wars were run.");
            };
        });
        warThread = null;
        runWarButton.setText("Start!");
		competitionRunning = false;
    }

	@Override
	public void onEndRound() {
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SCPSA Independientes / IZEA Independente</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/landing-page3.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Navegación

                </button>
                SCPSA Independientes / IZEA Independente

                        Presentación

                        Foro

                        Contacto

Detrás solo hay personas

Acceso a nuestro foro:

En el foro puedes hacerte oir.

Contacta con nosotras/os:

                             scpsaindependientes@gmail.com

                            Presentación

⋅

                            Foro

⋅

                            Contacto

Copyright © SCPSA Independientes / IZEA Independente. All Rights Reserved


text:
/*
 * duplication of sbpcd.c for multiple interfaces
 */
#define SBPCD_ISSUE 3
#include "sbpcd.c"


text:
'use strict';

import mongoose from 'mongoose';

module.exports = function (done){
  const debug = $.createDebug('init:mongodb');
  debug('connecting to mongoDB...');

  const conn = mongoose.createConnection($.config.get('db.mongodb'));
  $.mongodb = conn;
  $.model = {};

  const ObjectId = mongoose.Types.ObjectId;
  $.utils.ObjectId = ObjectId;

  done();
}


text:
package com.ea.orbit.actors.extensions;

import com.ea.orbit.actors.runtime.Message;
import com.ea.orbit.actors.runtime.Runtime;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * Extension interface to define how actor messages are serialized.
 */
public interface MessageSerializer extends ActorExtension
{
    Message deserializeMessage(final com.ea.orbit.actors.runtime.Runtime runtime, final InputStream inputStream) throws Exception;

    void serializeMessage(final Runtime runtime, OutputStream out, Message message) throws Exception;
}


text:
package com.hubspot.jinjava.lib.exptest;

import com.hubspot.jinjava.doc.annotations.JinjavaDoc;
import com.hubspot.jinjava.doc.annotations.JinjavaParam;
import com.hubspot.jinjava.doc.annotations.JinjavaSnippet;
import com.hubspot.jinjava.el.TruthyTypeConverter;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.interpret.TemplateSyntaxException;
import de.odysseus.el.misc.BooleanOperations;
import de.odysseus.el.misc.TypeConverter;

@JinjavaDoc(
  value = "Returns true if an object has the different value from another object",
  input = @JinjavaParam(value = "first", type = "object", required = true),
  params = {
    @JinjavaParam(
      value = "other",
      type = "object",
      desc = "Another object to check inequality against",
      required = true
    )
  },
  snippets = {
    @JinjavaSnippet(
      code = "{% if foo.expression is ne 42 %}\n" +
      "    the foo attribute evaluates to the constant 43 \n" +
      "{% endif %}\n"
    ),
    @JinjavaSnippet(
      desc = "Usage with the selectattr filter",
      code = "{{ users|selectattr(\"email\", \"ne\", \"foo@bar.invalid\") }}"
    )
  }
)
public class IsNeExpTest implements ExpTest {
  private static final TypeConverter TYPE_CONVERTER = new TruthyTypeConverter();

  @Override
  public String getName() {
    return "ne";
  }

  @Override
  public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) {
    if (args.length == 0) {
      throw new TemplateSyntaxException(
        interpreter,
        getName(),
        "requires 1 argument (other object to check inequality against)"
      );
    }

    return BooleanOperations.ne(TYPE_CONVERTER, var, args[0]);
  }
}


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_REDUCTION_FUNCTIONS_MAXIMUM_HPP_INCLUDED
#define BOOST_SIMD_REDUCTION_FUNCTIONS_MAXIMUM_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
#include <boost/simd/include/constants/maxinit.hpp>

namespace boost { namespace simd
{
  namespace tag
  {
   /*!
     @brief maximum generic tag

     Represents the maximum function in generic contexts.

     @par Models:
        Hierarchy
   **/
    struct max_;
    struct Maxinit;

    struct maximum_ : ext::reduction_<maximum_, tag::max_, tag::Maxinit>
    {
      /// @brief Parent hierarchy
      typedef ext::reduction_<maximum_, tag::max_, tag::Maxinit> parent;
    };
  }
  /*!
    Returns the greatest element of the SIMD vector

    @par Semantic:

    For every parameter of type T0

    @code
    scalar_of<T0> r = maximum(a0);
    @endcode

    is similar to:

    @code
      scalar_of<T0> r = Minf;
      for(std::size_t i=0;i<cardinal_of<T0>;++i)
        r =  r < a0[i] ? a0[i] : r;
    @endcode

    @param a0

    @return a value of the scalar type associated to the parameter
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::maximum_, maximum, 1)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::maximum_, maximum, 2)
} }
#endif


text:
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import DateTime
from sqlalchemy.types import Binary
from sqlalchemy.types import Text
from sqlalchemy.orm import relationship
from sqlalchemy import UniqueConstraint
from sqlalchemy.ext.hybrid import hybrid_property
from . import Base

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    post_id = Column(Integer, nullable=False)
    owner_id = Column(Integer, nullable=False)
    from_id = Column(Integer)
    date = Column(DateTime, nullable=False)
    likes_count = Column('likes_count', Integer, default=0)
    reposts_count = Column('reposts_count', Integer, default=0)
    _text = Column('text', Binary, nullable=True)
    attachments = Column(Text)
    photos = relationship("Photo", back_populates='post')
    UniqueConstraint('post_id', 'owner_id', name='uidx_PostId_OwnerId')

    @hybrid_property
    def text(self):
        return self._text

    @text.setter
    def text(self, value):
        self._text = value.encode('utf8')

    @text.expression
    def text(cls):
        return cls._text


text:
package org.h2.jaqu;

/**
 * This class represents "SET column = (column + x)" in an UPDATE statement.
 *
 * @param <T> the query type
 * @param <A> the new value data type
 */
public class UpdateColumnIncrement<T, A> implements UpdateColumn {

    private final Query<T> query;
    private final A x;
    private A y;

    UpdateColumnIncrement(Query<T> query, A x) {
        this.query = query;
        this.x = x;
    }

    public Query<T> by(A y) {
        query.addUpdateColumnDeclaration(this);
        this.y = y;
        return query;
    }

    @Override
    public void appendSQL(SQLStatement stat) {
        query.appendSQL(stat, x);
        stat.appendSQL("=(");
        query.appendSQL(stat, x);
        stat.appendSQL("+");
        query.appendSQL(stat, y);
        stat.appendSQL(")");
    }

}


text:
using namespace GameServer::Common;

namespace GameServer
{
namespace Epoch
{

ActivateEpochOperatorAutPtr ActivateEpochOperatorFactory::createActivateEpochOperator(
    IPersistenceFacadeAbstractFactoryShrPtr a_persistence_facade_abstract_factory
)
{
    return ActivateEpochOperatorAutPtr(
               new ActivateEpochOperator(a_persistence_facade_abstract_factory->createEpochPersistenceFacade(),
                                         a_persistence_facade_abstract_factory->createWorldPersistenceFacade())
           );
}

} // namespace Epoch
} // namespace GameServer


text:
#include <QApplication>
#include <QTimer>

#include <QOpenGLContext>

#include <GuiBase/TimerData/FrameTimerData.hpp>
#include <GuiBase/Viewer/Viewer.hpp>

#include <Engine/Managers/EntityManager/EntityManager.hpp>
#include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp>

#include <minimalradium.hpp>
/* This file contains a minimal radium/qt application which shows the
classic "Spinning Cube" demo. */
#include <minimalapp.hpp>

int main( int argc, char* argv[] ) {

    // Create default format for Qt.
    QSurfaceFormat format;
    format.setVersion( 4, 4 );
    format.setProfile( QSurfaceFormat::CoreProfile );
    format.setDepthBufferSize( 24 );
    format.setStencilBufferSize( 8 );
    // format.setSamples( 16 );
    format.setSwapBehavior( QSurfaceFormat::DoubleBuffer );
    format.setSwapInterval( 0 );
    QSurfaceFormat::setDefaultFormat( format );

    // Create app and show viewer window
    MinimalApp app( argc, argv );
    app.m_viewer->show();
    CORE_ASSERT( app.m_viewer->getContext()->isValid(), "OpenGL was not initialized" );
    // process all events so that everithing is initialized
    QApplication::processEvents();

    // Create one system
    MinimalSystem* sys = new MinimalSystem;
    app.m_engine->registerSystem( "Minimal system", sys );

    // Create and initialize entity and component
    Ra::Engine::Entity* e = app.m_engine->getEntityManager()->createEntity( "Cube" );
    MinimalComponent* c   = new MinimalComponent( e );
    sys->addComponent( e, c );
    c->initialize();

    // Start the app.
    app.m_frame_timer->start();
    app.m_close_timer->start();
    return app.exec();
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>n45y2_n67x2</title>
  <meta name="author" content="Reid Netterville III" />
  <link rel="stylesheet" href="/styles/adpe.css" type="text/css" />

Copyright © 2013-2018 Reid Netterville III


text:
/*
 * Created on Mar 30, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package edu.gatech.csc.visualfirewall.datasource;

import edu.gatech.csc.visualfirewall.data.*;
import edu.gatech.csc.visualfirewall.data.listener.IPTableResultListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.*;

import javax.swing.event.EventListenerList;

/**
 * @author chris
 * Mar 30, 2005
 * IPTablesLog
 */
public class IPTablesLog extends FirewallLog {
	EventListenerList iptableResultListeners = new EventListenerList();
	static boolean DEBUG = false;

	static final Pattern protopattern = Pattern.compile( "PROTO=(\\w+)" );
	static final Pattern udppattern = Pattern.compile( "(\\w+\\s+\\d+\\s+[\\d\\d:]+)\\s+.*?(DROP|ACCEPT)\\s+.*?SRC=([\\d\\.]+)\\s+DST=([\\d\\.]+)\\s+"
			+"LEN=(\\d+).*?SPT=(\\d+)\\s+DPT=(\\d+)\\s+LEN=(\\d+)" );
	static final Pattern tcppattern = Pattern.compile( "(\\w+\\s+\\d+\\s+[\\d\\d:]+)\\s+.*?(DROP|ACCEPT)\\s+.*?SRC=([\\d\\.]+)\\s+DST=([\\d\\.]+)\\s+"
			+"LEN=(\\d+).*?SPT=(\\d+)\\s+DPT=(\\d+)" );
	static final Pattern icmppattern = Pattern.compile( "(\\w+\\s+\\d+\\s+[\\d\\d:]+)\\s+.*?(DROP|ACCEPT)\\s+.*?SRC=([\\d\\.]+)\\s+DST=([\\d\\.]+)\\s+"
			+"LEN=(\\d+).*?TYPE=(\\d+)\\s+CODE=(\\d+)" );
	SimpleDateFormat sdf = new SimpleDateFormat("MMM d H:mm:ss");
	int year = new Date().getYear();

	public IPTablesLog ( File input ) {
		this.input = input;
		produces = IPTableResult.class;
	}

	IPTableResult parseData( byte[] data ) {
		String mystr = new String( data );
		Matcher matcher = protopattern.matcher( mystr );
		if ( ! matcher.find() )
			return null;
		String proto = matcher.group(1);
		try {
			int i = 1;
			if ( proto.equals("UDP") ) {
				matcher = udppattern.matcher( mystr );
				if ( ! matcher.find() )
					return null;
				Date timestamp = sdf.parse( matcher.group(i++) );
				timestamp.setYear(year);
				boolean accepted = ( matcher.group(i++) ).startsWith("ACCEPT");
				InetAddress src = java.net.InetAddress.getByName( matcher.group(i++) );
				InetAddress dst = java.net.InetAddress.getByName( matcher.group(i++) );
				short len = Short.parseShort( matcher.group(i++) );
				int spt = Integer.parseInt( matcher.group(i++) );
				int dpt = Integer.parseInt( matcher.group(i++) );
				short udplen = Short.parseShort( matcher.group(i++) );
				return( new IPTableResult( timestamp, accepted, new IPPacket( src, dst, new UDPPacket( spt, dpt, udplen ), len ) ) );
			} else if ( proto.equals("TCP") ) {
				matcher = tcppattern.matcher( mystr );
				if ( ! matcher.find() )
					return null;
				Date timestamp = sdf.parse( matcher.group(i++) );
				timestamp.setYear(year);
				boolean accepted = ( matcher.group(i++) ).startsWith("ACCEPT");
				InetAddress src = java.net.InetAddress.getByName( matcher.group(i++) );
				InetAddress dst = java.net.InetAddress.getByName( matcher.group(i++) );
				short len = Short.parseShort( matcher.group(i++) );
				int spt = Integer.parseInt( matcher.group(i++) );
				int dpt = Integer.parseInt( matcher.group(i++) );
				return( new IPTableResult( timestamp, accepted, new IPPacket( src, dst, new TCPPacket( spt, dpt, 0, len ), len ) ) );
			} else if ( proto.equals("ICMP") ) {
				matcher = icmppattern.matcher( mystr );
				if ( ! matcher.find() )
					return null;
				Date timestamp = sdf.parse( matcher.group(i++) );
				timestamp.setYear(year);
				boolean accepted = ( matcher.group(i++) ).startsWith("ACCEPT");
				InetAddress src = java.net.InetAddress.getByName( matcher.group(i++) );
				InetAddress dst = java.net.InetAddress.getByName( matcher.group(i++) );
				short len = Short.parseShort( matcher.group(i++) );
				short type = Short.parseShort( matcher.group(i++) );
				short code = Short.parseShort( matcher.group(i++) );
				return( new IPTableResult( timestamp, accepted, new IPPacket( src, dst, new ICMPPacket( type, code, len ), len ) ) );
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void addIPTableResultListener( IPTableResultListener listener ) {
		iptableResultListeners.add( IPTableResultListener.class, listener );
	}

	public void removeIPTableResultListener( IPTableResultListener listener ) {
		iptableResultListeners.remove( IPTableResultListener.class, listener );
	}

	protected void fireIPTableResult( IPTableResult iptr ) {
		Object[] listeners = iptableResultListeners.getListenerList();
		int numListeners = listeners.length;
		if (DEBUG) System.out.println( iptr );
		for ( int i = 0; i < numListeners; i += 2 ) {
			if ( listeners[i] == IPTableResultListener.class )
				((IPTableResultListener)listeners[i+1]).dispatchResult( iptr );
		}
	}

	public void run () {
		try {
			FileReader fr = new FileReader(input);
			BufferedReader br = new BufferedReader(fr);
			String line;
			while ( ( line = br.readLine() ) != null ) {
				if (DEBUG) System.out.println( "Received line." );
				IPTableResult itr = parseData( line.getBytes() );
				if ( itr != null )
				{
					if (DEBUG) System.out.println( itr );
					fireIPTableResult( itr );
				}

				Thread.sleep( (int)(Math.random()*100 ) );
			}
		} catch ( Exception e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public static void main ( String[] args ) {
		DEBUG = true;
		IPTablesLog ipl = new IPTablesLog( new File( "logs/iptables.txt" ) );
		ipl.run();
	}

}


text:
module LinkListsHelper
  def navigation(link_list, options = {})
    seperator = options.delete(:seperator) || ' '
    content_tag 'nav', navigation_links(link_list).join(seperator).html_safe, { :class => link_list.handle }.merge(options)
  end

  def navigation_links(link_list)
    escaped_path = CGI.unescape(request.fullpath).mb_chars
    link_list.links.map do |link|
      if !!escaped_path.starts_with?(CGI.unescape(link.url).mb_chars)
        link_to(link.title, link.url, :class => 'current')
      else
        link_to(link.title, link.url)
      end
    end
  end
end


text:
"""
A package that implements offline messages for Django
Web Framework.

(C) 2011-2014 oDesk www.oDesk.com w/revisions by Zapier.com
"""

from setuptools import setup

setup(
    name='django-offline-messages',
    version='0.3.7',
    description='A package that implements offline messages for Django plus more',
    long_description='A package that implements offline messages for Django Web Framework',
    license='BSD',
    keywords='django offline messages',
    url='https://github.com/dym/django-offline-messages',
    author='oDesk, www.odesk.com',
    author_email='developers@odesk.com',
    maintainer='Dmitriy Budashny',
    maintainer_email='dmitriy.budashny@gmail.com',
    packages=['offline_messages', 'offline_messages.migrations', 'offline_messages.south_migrations'],
    classifiers=['Development Status :: 3 - Alpha',
                 'Environment :: Web Environment',
                 'Framework :: Django',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: BSD License',
                 'Operating System :: OS Independent',
                 'Programming Language :: Python',
                 'Topic :: Software Development :: Libraries :: Python Modules',
                 ],
    test_suite='tests.runtests.runtests',
    install_requires=['django-jsonfield'],
    zip_safe=False
)


text:
{-# LANGUAGE BangPatterns #-}
module Search where
import Text.Regex.Posix
import Data.Char
import System.Posix.Files.ByteString
import System.Directory
import Data.ByteString.Char8 (pack)
import System.FilePath.Windows
import qualified Data.ByteString as B
import System.IO.Unsafe
import Control.Exception
import Data.String.Utils

type FileMatches = (FilePath ,[String])

recurseThroughDirTree :: FilePath -> (FilePath -> IO a) -> IO [a]
recurseThroughDirTree dir fun = recWithPred dir (\_ -> return True) fun

recWithPred :: FilePath -> (FilePath -> IO Bool) -> (FilePath -> IO a) -> IO [a]
recWithPred dir pred fun = do
  abs <- makeAbsolute dir
  dirContents <- listDirectory dir
  let files = map (fixFP abs) dirContents
  res <- unsafeInterleaveMapIO (r abs) files
  return $ foldl (++) [] res
    where
      fixFP dir fp = dir ++ "/" ++ fp
      r dir fp = do
        status <- getFileStatus $ pack fp
        if isDirectory status
          then recWithPred fp pred fun
          else do
          b <- pred fp
          if b
            then do
            res <- fun fp
            return [res]
            else return []

unsafeInterleaveMapIO f (x:xs) = unsafeInterleaveIO $ do
  y <- f x
  ys <- unsafeInterleaveMapIO f xs
  return (y : ys)
unsafeInterleaveMapIO _ [] = return []

getDirContentsByPred :: FilePath -> (FilePath -> IO Bool) -> IO [(FilePath, B.ByteString)]
getDirContentsByPred dir pred = do
  abs <- makeAbsolute dir
  dirContents <- listDirectory dir
  let files = map (fixFP abs) dirContents
  res <- unsafeInterleaveMapIO (r abs) files
  return $ foldl (++) [] res
        where
          fixFP dir fp = dir ++ "/" ++ fp
          r dir fp = do
            status <- getFileStatus $ pack fp
            if isDirectory status
              then getDirContentsByPred fp pred
              else do
              b <- pred fp
              if b
                then do
                contents <- B.readFile fp
                return [(fp,contents)]
                else return []

getFileNamesByPred :: FilePath -> (FilePath -> IO Bool) -> IO [FilePath]
getFileNamesByPred dir pred =
  if endswith "dist" dir
  then return []
  else do
    abs <- makeAbsolute dir
    dirContents <- listDirectory dir
    let files = map (fixFP abs) dirContents
    res <- mapM (r abs) files
    return $ foldl (++) [] res
      where
        fixFP dir fp = dir ++ "/" ++ fp
        r dir fp = do
          status <- getFileStatus $ pack fp
          if isDirectory status
            then  getFileNamesByPred fp pred
            else do
            b <- pred fp
            if b
              then return [fp]
              else return []

listDirectory :: FilePath -> IO [FilePath]
listDirectory fp = do
  contents <- getDirectoryContents fp
  return $ filter (\fp -> not (fp == ".." || fp == ".")) contents


text:
package org.codehaus.mojo.appassembler;

/**
 * The class which is used to contain the JVM settings.
 *
 * @author Karl Heinz Marbaise
 */
public class JvmSettings
{
    private String initialMemorySize;

    private String maxMemorySize;

    private String maxStackSize;

    private String[] systemProperties;

    private String[] extraArguments;

    /**
     * The initial memory size.
     *
     * @return value as string.
     */
    public String getInitialMemorySize()
    {
        return initialMemorySize;
    }

    /**
     * The maximum memory size.
     *
     * @return The max memory size.
     */
    public String getMaxMemorySize()
    {
        return maxMemorySize;
    }

    /**
     * Max Stack Size.
     *
     * @return The max stack size.
     */
    public String getMaxStackSize()
    {
        return maxStackSize;
    }

    /**
     * The system properties.
     *
     * @return The array with with the system properties.
     */
    public String[] getSystemProperties()
    {
        return systemProperties;
    }

    /**
     * Extra arguments.
     *
     * @return The array with the extra arguments.
     */
    public String[] getExtraArguments()
    {
        return extraArguments;
    }
}


text:
package com.facebook.buck.apple.toolchain;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;

import com.dd.plist.NSArray;
import com.dd.plist.NSObject;
import com.dd.plist.NSString;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.HashCode;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Optional;
import org.junit.Test;

public class ProvisioningProfileStoreTest {
  private static ProvisioningProfileMetadata makeTestMetadata(
      String appID, Date expirationDate, String uuid) throws Exception {
    return makeTestMetadata(appID, expirationDate, uuid, ImmutableMap.of());
  }

  private static ProvisioningProfileMetadata makeTestMetadata(
      String appID, Date expirationDate, String uuid, ImmutableMap<String, NSObject> entitlements)
      throws Exception {
    return makeTestMetadata(appID, expirationDate, uuid, entitlements, ImmutableSet.of());
  }

  private static ProvisioningProfileMetadata makeTestMetadata(
      String appID,
      Date expirationDate,
      String uuid,
      ImmutableMap<String, NSObject> entitlements,
      ImmutableSet<HashCode> fingerprints) {
    return ProvisioningProfileMetadata.builder()
        .setAppID(ProvisioningProfileMetadata.splitAppID(appID))
        .setExpirationDate(expirationDate)
        .setUUID(uuid)
        .setProfilePath(Paths.get("dummy.mobileprovision"))
        .setEntitlements(entitlements)
        .setDeveloperCertificateFingerprints(fingerprints)
        .build();
  }

  private static ProvisioningProfileStore createStorefromProvisioningProfiles(
      Iterable<ProvisioningProfileMetadata> profiles) {
    return ProvisioningProfileStore.of(Suppliers.ofInstance(ImmutableList.copyOf(profiles)));
  }

  @Test
  public void testExpiredProfilesAreIgnored() throws Exception {
    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                makeTestMetadata(
                    "AAAAAAAAAA.*", new Date(0), "00000000-0000-0000-0000-000000000000")));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            ProvisioningProfileStore.MATCH_ANY_ENTITLEMENT,
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual, is(equalTo(Optional.empty())));
  }

  @Test
  public void testPrefixOverride() throws Exception {
    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "AAAAAAAAAA.*", new Date(Long.MAX_VALUE), "00000000-0000-0000-0000-000000000000");

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                expected,
                makeTestMetadata(
                    "BBBBBBBBBB.com.facebook.test",
                    new Date(Long.MAX_VALUE),
                    "00000000-0000-0000-0000-000000000000")));

    NSString[] fakeKeychainAccessGroups = {new NSString("AAAAAAAAAA.*")};
    ImmutableMap<String, NSObject> fakeEntitlements =
        ImmutableMap.of("keychain-access-groups", new NSArray(fakeKeychainAccessGroups));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            Optional.of(fakeEntitlements),
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual.get(), is(equalTo(expected)));
  }

  @Test
  public void testEntitlementKeysAreMatched() throws Exception {
    NSString[] fakeKeychainAccessGroups = {new NSString("AAAAAAAAAA.*")};
    NSArray fakeKeychainAccessGroupsArray = new NSArray(fakeKeychainAccessGroups);

    ImmutableMap<String, NSObject> fakeDevelopmentEntitlements =
        ImmutableMap.of(
            "keychain-access-groups",
            fakeKeychainAccessGroupsArray,
            "aps-environment",
            new NSString("development"),
            "com.apple.security.application-groups",
            new NSArray(new NSString("foo"), new NSString("bar")));

    ImmutableMap<String, NSObject> fakeProductionEntitlements =
        ImmutableMap.of(
            "keychain-access-groups",
            fakeKeychainAccessGroupsArray,
            "aps-environment",
            new NSString("production"),
            "com.apple.security.application-groups",
            new NSArray(new NSString("foo"), new NSString("bar"), new NSString("baz")));

    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "AAAAAAAAAA.com.facebook.test",
            new Date(Long.MAX_VALUE),
            "11111111-1111-1111-1111-111111111111",
            fakeProductionEntitlements);

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                makeTestMetadata(
                    "AAAAAAAAAA.com.facebook.test",
                    new Date(Long.MAX_VALUE),
                    "00000000-0000-0000-0000-000000000000",
                    fakeDevelopmentEntitlements),
                expected));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            Optional.of(
                ImmutableMap.of(
                    "keychain-access-groups",
                    fakeKeychainAccessGroupsArray,
                    "aps-environment",
                    new NSString("production"),
                    "com.apple.security.application-groups",
                    new NSArray(new NSString("foo"), new NSString("bar")))),
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual.get(), is(equalTo(expected)));

    actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            Optional.of(
                ImmutableMap.of(
                    "keychain-access-groups",
                    fakeKeychainAccessGroupsArray,
                    "aps-environment",
                    new NSString("production"),
                    "com.apple.security.application-groups",
                    new NSArray(new NSString("foo"), new NSString("xxx")))),
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);
    assertFalse(actual.isPresent());

    // Test without keychain access groups.
    actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            Optional.of(
                ImmutableMap.of(
                    "aps-environment",
                    new NSString("production"),
                    "com.apple.security.application-groups",
                    new NSArray(new NSString("foo"), new NSString("bar")))),
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual.get(), is(equalTo(expected)));

    actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            Optional.of(
                ImmutableMap.of(
                    "aps-environment",
                    new NSString("production"),
                    "com.apple.security.application-groups",
                    new NSArray(new NSString("foo"), new NSString("xxx")))),
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);
    assertFalse(actual.isPresent());
  }

  @Test
  public void testOnlyProfilesContainingValidFingerprintsAreMatched() throws Exception {
    CodeSignIdentity validIdentity =
        CodeSignIdentity.builder()
            .setFingerprint(
                CodeSignIdentity.toFingerprint("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"))
            .setSubjectCommonName("iPhone Developer: Foo Bar (54321EDCBA)")
            .build();

    CodeSignIdentity otherIdentity =
        CodeSignIdentity.builder()
            .setFingerprint(
                CodeSignIdentity.toFingerprint("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))
            .setSubjectCommonName("iPhone Developer: Foo Bar (ABCDE12345)")
            .build();

    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "AAAAAAAAAA.com.facebook.test",
            new Date(Long.MAX_VALUE),
            "11111111-1111-1111-1111-111111111111",
            ImmutableMap.of(),
            ImmutableSet.of(
                validIdentity.getFingerprint().get(), otherIdentity.getFingerprint().get()));

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                makeTestMetadata(
                    "AAAAAAAAAA.com.facebook.test",
                    new Date(Long.MAX_VALUE),
                    "00000000-0000-0000-0000-000000000000",
                    ImmutableMap.of(),
                    ImmutableSet.of(otherIdentity.getFingerprint().get())),
                expected));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            ProvisioningProfileStore.MATCH_ANY_ENTITLEMENT,
            Optional.of(ImmutableList.of(validIdentity)));

    assertThat(actual.get(), is(equalTo(expected)));
  }

  @Test
  public void testGetByUUID() throws Exception {
    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "BBBBBBBBBB.*", new Date(Long.MAX_VALUE), "11111111-1111-1111-1111-111111111111");

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                expected,
                makeTestMetadata(
                    "BBBBBBBBBB.com.facebook.test",
                    new Date(Long.MAX_VALUE),
                    "00000000-0000-0000-0000-000000000000")));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getProvisioningProfileByUUID("11111111-1111-1111-1111-111111111111");

    assertThat(actual.get(), is(equalTo(expected)));
  }

  @Test
  public void testMatchesSpecificApp() throws Exception {
    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "BBBBBBBBBB.com.facebook.test",
            new Date(Long.MAX_VALUE),
            "00000000-0000-0000-0000-000000000000");

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(
            ImmutableList.of(
                expected,
                makeTestMetadata(
                    "BBBBBBBBBB.com.facebook.*",
                    new Date(Long.MAX_VALUE),
                    "11111111-1111-1111-1111-111111111111")));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            ProvisioningProfileStore.MATCH_ANY_ENTITLEMENT,
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual.get(), is(equalTo(expected)));
  }

  @Test
  public void testMatchesWildcard() throws Exception {
    ProvisioningProfileMetadata expected =
        makeTestMetadata(
            "BBBBBBBBBB.*", new Date(Long.MAX_VALUE), "00000000-0000-0000-0000-000000000000");

    ProvisioningProfileStore profiles =
        createStorefromProvisioningProfiles(ImmutableList.of(expected));

    Optional<ProvisioningProfileMetadata> actual =
        profiles.getBestProvisioningProfile(
            "com.facebook.test",
            ApplePlatform.IPHONEOS,
            ProvisioningProfileStore.MATCH_ANY_ENTITLEMENT,
            ProvisioningProfileStore.MATCH_ANY_IDENTITY);

    assertThat(actual.get(), is(equalTo(expected)));
  }
}


text:
var userAccess = (function(){
	var getUserAccess = $('input[data-id="user_access"]').val();

	var hideNodes = function(){
		switch(getUserAccess){
				case '3' :
						$('#app_users').remove();
						$('#app_reports').remove();
						break;
				case '4' :
						$('#app_messsages').remove();
						$('#app_reports').remove();
						$('#app_users').remove();
						break;
				default :
						break;
		}
	}

	return {
		Build : function(){
			hideNodes();
		}
	}
})();

$(document).ready(function(){
	userAccess.Build();
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 | Version 10.2
 | Copyright 2012 Esri
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |    http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
-->
<configuration>
	<facilities>
	<!-- Specify the facility Layer to find closest facility,label :specify
		the name of layer,url: specify the feature layer url -->
	</facilities>

<!--<layerLabel> tag Specifies Configurable Labels for Drop Down Lists.-->
<!--<fieldLabeltag Specifies Configurable Labels for Drop Down Lists.-->
	<layerLabel label="Select Facility Layers"/>
	<fieldLabel label="Select  Facility Type"/>
	<incidents>
<!-- These are incidents to route to nearest facilities: a map or feature
	service. The user can draw new ones, so leave blank if desired -->
	</incidents>
	<!-- <fieldtype> specifies the type of you want to select -->
	<fieldtype>FCODE</fieldtype>

<!-- <fieldAliastype> : specifies Layer label to be displayed in the Select Facility Layer dropdown -->
<!-- NOTE:  Layer label (from Main Config) and fieldAliastype must be same.  Like: 'Hospital'. -->

	<fieldAliastype>Resource</fieldAliastype>

<!-- <configureField> : Specifies Configured Field Type From Map Service -->

	<configureField>CATEGORY</configureField>

<!-- <closestFacilitySvc>Specifies the service for Closest Facility.-->
	<closestFacilitySvc>
		<url>http://route.arcgis.com/arcgis/rest/services/World/ClosestFacility/NAServer/ClosestFacility_World/solveClosestFacility
		</url>
	</closestFacilitySvc>

<!--	fieldTypes :specifies the configurable columns to show in the result view-->
<!--	fieldAlias: specifies the configurable column header text in the result view-->
	<outFields fieldTypes="routeName,routeName,Resource Type,routeId,totalTime,totalLength" fieldAlias="From,To,Resource Type,Rank,Total Time,Distance"/>
	<ColumnWidth>100,100,200,50,100,100</ColumnWidth>
<!--<configureField> :specifies Configured Field Type From Map Service-->

<!--<configureFieldType> :specifies Header of Configured Label in Grid View .-->
	<configureFieldType>Resource Type</configureFieldType>

<!-- <barrier>:Specifies the barrier layer for Closest Facility.-->
<!-- label: Specifies the name of barrier layer.-->

	<barrierLayers>
		<barrier label="Road Blocks CF">
			http://arcgis-localgov-61933129.us-west-1.elb.amazonaws.com/arcgis/rest/services/PublicSafetyCOP/IncidentCommand/FeatureServer/3
		</barrier>
	</barrierLayers>
	<!-- Accumulated attributes as defined by the network analyst service.
		Leave the <routeRequestAccumulatedAttributes> tag empty to indicate no accumulation.
		Typically time or distance of some sort. For example, the attribute "Length"
		under "Network Attributes" here: http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Closest%20Facility
		The accumulation for this attribute usually gets returned in an attribute
		called "Total_" plus the attribute name (e.g. "Total_Length") -->
	<routeRequestAccumulatedAttributes>
		<attrName>Length</attrName>
	</routeRequestAccumulatedAttributes>

<!--	<formatString>Specifies labels used to format the columns in the data grid in Search Results Table. -->
	<formatString>
	<source label="To"/>
	<Destination label="From"/>
	<time label="totalTime"/>
	<length label="totalLength"/>
	<Name label="routeName"/>
	<FieldType label="FieldType"/>
	</formatString>

<!-- Set the Buffer radius in Statute Miles -->
	<bufferParameter>250</bufferParameter>
	<symbology>
<!-- What attribute will be used to specify the z-order of result route polylines? -->
		<routeZOrderAttrName>FacilityRank</routeZOrderAttrName>
<!-- What attribute will be used to symbolize the result route polylines? -->
		<routeRendererAttrName>FacilityRank</routeRendererAttrName>
		<barrier style="dashdot" color="0xAA0000" width="3" />
		<event size="15" style="circle" outlineColor="0x000000"
			outlineWidth="2" markerColor="0x00CC00" />
	</symbology>

<!--<TITELEBARTOOLTIP>:CONTAINS DIFFERENT TOOL TIPS USED IN CLOSEST FACILITY.-->
<!--<SHOWROUTETOOLTIP>:SPECIFIES TOOL TIP FOR FIRST TITLE BAR TAB IN THE CLOSEST FACILITY.-->
<!--<SHOWDIRECTIONSTOOLTIP>: SPECIFIES THE TOOL TIP FOR SECOND TITLE BAR TAB IN THE CLOSEST FACILITY.-->
<!--<PRINTTOOLTIP>:SPECIFIES THE TOOL TIP FOR THIRD TITLE BAR TAB IN THE CLOSEST FACILITY.-->

	<titleBarToolTip>
		<showRouteToolTip>Search</showRouteToolTip>
		<showDirectionsToolTip>Show Direction</showDirectionsToolTip>
		<printTooltip>Print</printTooltip>
		<showResultsTooltip>Show Results</showResultsTooltip>
	</titleBarToolTip>

<!--<showdirectionarrows>: Specifies to show direction in the exported PDF File.-->

	<showdirectionarrows>true</showdirectionarrows>

<!--<exportpdfbtnlabel>: Specifies to the label used on button for export to PDF file.-->

	<exportpdfbtnlabel>Save to PDF</exportpdfbtnlabel>

<!--<includemaplabel>: Specifies to the label used for check box to include map.-->
	<includemaplabel>Include Map</includemaplabel>

<!--<printmapbtnlabel>: Specifies to the label used on button for pint.-->

	<printmapbtnlabel>Print</printmapbtnlabel>

<!--<pdfgenerationwarning>: Specifies the message generated for user before opening save dialog box.-->

	<pdfgenerationwarning>If you choose to save a PDF then please be
		patient.<br />A save dialog will open once the PDF has been
		generated.</pdfgenerationwarning>

<!--<genpdf>: Specifies to the message shown while system prepare PDF file.-->

	<genpdf>Generating PDF...</genpdf>

	<!-- Get Direction Label -->
	<getDirLabel>Get Directions</getDirLabel>

	<!-- Reverse Direction Label -->
	<revDirLabel>Reverse Route Directions</revDirLabel>

	<!--<alerts>: Alert messages.-->
	<alerts>
		<noResultFound alertheader="Alert"
			alertmessage="No Result Found"/>
		<noClosestFacilityFound alertheader="Alert"
			alertmessage="Cannot find closest facility."/>
		<selectfacilityType alertheader="Alert"
			alertmessage="Please select a facility Type."/>
		<drowPtError alertheader="Location missing"
			alertmessage="Please define a location on the map first."/>
		<selectfacilityLayer alertheader="Alert"
			alertmessage="Please select a facility layer."/>
		<noDirectionSelection alertheader="Alert"
			alertmessage="No Direction Are Selected."/>
	</alerts>

	<!-- <titlebarimagepath>: Title bar image path -->
	<titlebarimagepath>
		<routeimagepath>widgets/ClosestFacility/assets/images/i_route.png</routeimagepath>
		<resultimagepath>widgets/ClosestFacility/assets/images/i_table.png</resultimagepath>
		<directionimagepath>widgets/ClosestFacility/assets/images/critical-infrastructure.png</directionimagepath>
	</titlebarimagepath>
</configuration>


text:
using UnityEngine;

public abstract class AIState : MonoBehaviour {

	public enum StateType {

		IDLE,
		NORMAL,
		AGGRESSIVE

	}

	[SerializeField]
	protected StateType stateType;

	protected bool isInUse;

	public StateType State { get { return stateType; } }
	public bool IsInUse { get { return isInUse; } }

	public AIState() {

		isInUse = false;

	}

	public void Activate() {

		isInUse = true;

	}

	public void Deactivate() {

		isInUse = false;

	}

	public abstract void Behave();
}


text:
Binary Trees Exercise #70
------------------


text:
set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/vadim/CLionProjects/VJDetector")
set(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/vadim/CLionProjects/VJDetector/cmake-build-release")

# Force unix paths in dependencies.
set(CMAKE_FORCE_UNIX_PATHS 1)

# The C and CXX include file regular expressions for this directory.
set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})


text:
$(document).ready(function()
{
    $('.setExpense').click(function()
    {
        var href = $(this).prop('href');
        var app  = 'cash';
        $.openEntry(app, href);
        return false;
    });
});


text:
layout: post-livere
category: paintings
name: my-dad
original: 2021/my-dad-original.jpg
thumbnail: 2021/my-dad-thumbnail.jpg
date: Sun Jan 24 22:17:22 2021
title: 我的爸爸
---

![{{page.title}}](/gallery/{{page.category}}/{{page.original}})
故事内容


text:
namespace HaveIBeenPwned
{
    public class ProgressHelper
    {
        public ProgressHelper(int totalBreaches)
        {
            TotalBreaches = totalBreaches;
            CurrentBreach = 0;
        }

        public int TotalBreaches { get; private set; }

        public int CurrentBreach { get; set; }
    }
}