text:
 * zooming (mouse wheel)
 * moving (by dragging the picture)
 * interactive buttons (for zooming)
 * annotations (colored areas over the picture)
 * quiz mode
   * define a solution polygon
   * start in editAnswer-mode to let user set a answer point on the image
   * start in showSolution-mode to show the user if she or he guessed correctly

## Demo

See [here](http://pfirpfel.github.io/image-viewer)!

## Usage

Add a canvas element to your HTML with an id:

```html
<canvas id="viewerCanvas" width="500" height="300"></canvas>
```

Then initialize the viewer in javascript:

```javascript
// start a simple image viewer mit zooming and dragging features
var myImageViewer = new ImageViewer('viewerCanvas', 'myImage.jpg');
```

That's it!

### Creating the viewer

```javascript
function ImageViewer(canvasId, imageUrl, options)
```

Parameters:

- **canvasId**: id of the canvas element in the HTML DOM
- **imageUrl**: URL of the image to load (can be relative or absolute)
- **options**: object with settings
  - mode: string (other than default viewer-only mode)
    - 'editAnswer'   : displays answer and answer related buttons
    - 'editSolution' : displays solution and solution related buttons
    - 'showSolution' : displays answer and solution
  - answer: position-object (like ```{ x: 0; y: 0; }```); position of answer inside the image
  - solution: array of positions (like ```[{ x: 0; y: 0; }, { x: 1; y: 1; }]```); the positions represent vertices which make up the solution polygon

Example:
```javascript
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', { answer: { x: 0; y: 0; } });
```

### Useful initializations

#### Define a new solution
These settings the tools to create a new solution.

```javascript
var options = {
  mode: 'editSolution'
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

#### Change an existing solution
These settings display the solution and the tools to change it.

```javascript
var options = {
  mode: 'editSolution',
  solution: [{ x: 0; y: 0; }, { x: 100; y: 100; }, { x: 100; y: 200; }, { x: 0; y: 0; }]
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

#### Quiz mode
Here the tools to create an answer point are made available to the user.
These settings don't include a solution, to prevent cheating.

```javascript
var options = {
  mode: 'editAnswer'
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

#### Show a solution
These settings display the solution and the answer without giving the user the possibility to change either.

```javascript
var options = {
  mode: 'showSolution',
  solution: [{ x: 0; y: 0; }, { x: 100; y: 100; }, { x: 100; y: 200; }, { x: 0; y: 0; }],
  answer: { x: 55; y: 55; }
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

#### Define annotations
These settings display the annotations and the tools to change them. The *annotations* option is optional.

```javascript
var options = {
  mode: 'editAnnotations'
  annotations: [
                {
                 polygon: [{ x: 0; y: 0; }, { x: 1; y: 1; }, { x: 2; y: 2; }, { x: 0; y: 0; }],
                 color: '#00FF00'
                }
               ]
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

#### Show annotations
These settings display the annotations without giving the user the possibility to change them.

```javascript
var options = {
  mode: 'showAnnotations'
  annotations: [
                {
                 polygon: [{ x: 0; y: 0; }, { x: 1; y: 1; }, { x: 2; y: 2; }, { x: 0; y: 0; }],
                 color: '#00FF00'
                }
               ]
};
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', options);
```

### Changing the image

Change the image.src-property of your image viewer object:
```javascript
myImageViewer.image.src = 'assets/otherImage.png';
```

### Solution
#### Export solution
```javascript
var solution = myImageViewer.exportSolution();
```
The solution is an array of point objects with x/y-coordinates.

#### Import solution
Two possibilities:

1. During runtime
```javascript
myImageViewer.importSolution([{ x: 0, y: 0 }, { x: 1, y: 1 }]);
```

2. On initialization
```javascript
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', { solution: [{ x: 0, y: 0 }, { x: 1, y: 1 }] });
```
The solution is an array of point objects with x/y-coordinates.

#### On Change Event
On every change on the solution (while in editSolution mode), the onSolutionChange event gets called.
The solution object given to the event is the output of exportSolution().

```javascript
myImageViewer.onSolutionChange = function(solution){
 // do something with solution
}
```

### Answer
#### Accessing answer position
```javascript
var position = myImageViewer.answer;
```
answer is an object like:

```javascript
{ x: 0, y: 0 }
```

#### Setting answer position
Two possibilities:

1. During runtime
```javascript
myImageViewer.answer = { x: 0, y: 0 };
myImageViewer.refresh();
```

2. On initialization
```javascript
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', { answer: { x: 0, y: 0 } });
```

#### On Change Event
On every change on the solution (while in editSolution mode), the onSolutionChange event gets called.
The solution object given to the event is the output of exportSolution().

```javascript
myImageViewer.onSolutionChange = function(solution){
 // do something with solution
}
```

### Annotations
#### Export annotations
```javascript
var annotations = myImageViewer.exportAnnotations();
```
Annotations are an array of annotation objects. Example:
```javascript
[
  {
   polygon: [{ x: 0; y: 0; }, { x: 1; y: 1; }, { x: 2; y: 2; }, { x: 0; y: 0; }],
   color: '#00FF00'
  }
]
```

#### Import annotations
Two possibilities:

1. During runtime
```javascript
var annotations = [
                    {
                     polygon: [{ x: 0; y: 0; }, { x: 1; y: 1; }, { x: 2; y: 2; }, { x: 0; y: 0; }],
                     color: '#00FF00'
                    }
                  ];
myImageViewer.importAnnotations(annotations);
```

2. On initialization
```javascript
var myImageViewer = new ImageViewer('viewerCanvas', 'image.png', { annotations: annotations });
```
Annotations are an array of annotation objects, see 'Export annotations'.

#### On Change Event
On every change on any annotation, the onAnnotationChange event gets called.
The parameter given to the event is the output of exportAnnotations().

```javascript
myImageViewer.onAnnotationChange = function(annotations){
 // do something with these annotations
}
```


text:
<?php

/* @var $this yii\web\View */
$this->title = 'PASH UBB';
?>

Texto

Informacion de Autentificacion

<button class="btn btn-default glyphicon glyphicon glyphicon-arrow-up control"> Ocultar</button>

        <?php
            if(!Yii::$app -> user -> isGuest){
                echo '
Autentificado como rol de: ';
                if(Yii::$app -> user -> identity -> ID_ROL == 1){
                    echo "Administrador";
                }else{
                    echo "Docente";
                }
                echo "
";
            }else {
                echo '
Plataforma PASH UBB
';
            }
        ?>

<?php echo date('j \d\e F \d\e Y\, g:ia') ?>

Estimad@s Usuari@s:

Les damos la más cordial bienvenida a la Plataforma de Administracion de Salas y Horarios PASH UBB. Favor, ante cualquier consulta, inconveniente o requerimiento asociado a claves de acceso, y otras situaciones relativas a la plataforma, les invitamos a contactarnos al correo plataformapash@ubiobio.cl.

Les saluda,

Administrador Plataforma PASH UBB

PASH es una Plataforma de Administracion que tiene por finalidad prestar servicios de apoyo a la docencia de Pregrado y Postgrado de la Universidad del Bío-Bío, optimizando las asignaciones de salas y horarios.

El diseño de PASH permite que el Administrador y los Academicos la utilicen fácilmente, dado que sus funcionalidades han sido configuradas en función de sus necesidades.

PASH es una plataforma en constante desarrollo, diseñada y construida en la Universidad del Bío-Bío, por lo cual invitamos a sus usuarios a enviar comentarios y sugerencias, a objeto de continuar ofreciéndoles un servicio de calidad.

redpajama_set_name: RedPajamaGithub


text:
typedef struct bio_st BIO;
// <openssl/ssl.h>
typedef struct ssl_st SSL;
typedef struct x509_store_ctx_st X509_STORE_CTX;

namespace net {

class SSLInfo;

class SSLServerContextOpenSSL : public SSLServerContext {
 public:
  SSLServerContextOpenSSL(X509Certificate* certificate,
                          const crypto::RSAPrivateKey& key,
                          const SSLServerConfig& ssl_server_config);
  ~SSLServerContextOpenSSL() override;

  scoped_ptr<SSLServerSocket> CreateSSLServerSocket(
      scoped_ptr<StreamSocket> socket) override;

 private:
  ScopedSSL_CTX ssl_ctx_;

  // Options for the SSL socket.
  SSLServerConfig ssl_server_config_;

  // Certificate for the server.
  scoped_refptr<X509Certificate> cert_;

  // Private key used by the server.
  scoped_ptr<crypto::RSAPrivateKey> key_;
};

}  // namespace net

#endif  // NET_SOCKET_SSL_SERVER_SOCKET_OPENSSL_H_


text:
def cross(A, B):
    "Cross product of elements in A and elements in B."
    return [a+b for a in A for b in B]

digits   = '123456789'
rows     = 'ABCDEFGHI'
cols     = digits
squares  = cross(rows, cols)
unitlist = ([cross(rows, c) for c in cols] +
            [cross(r, cols) for r in rows] +
            [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
units = dict((s, [u for u in unitlist if s in u])
             for s in squares)
peers = dict((s, set(sum(units[s],[]))-set([s]))
             for s in squares)

def test():
    "A set of unit tests."
    assert(len(squares) == 81)
    assert(len(unitlist) == 27)
    assert(all(len(units[s]) == 3 for s in squares))
    assert(all(len(peers[s]) == 20 for s in squares))
    assert(units['C2'] == [['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'],
                           ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'],
                           ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']])
    assert(peers['C2'] == set(['A2', 'B2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2',
                               'C1', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9',
                               'A1', 'A3', 'B1', 'B3']))
    print('All tests pass.')

test()

def grid_values(grid):
    "Convert grid into a dict of {square: char} with '0' or '.' for empties."
    chars = [c for c in grid if c in digits or c in '0.']
    assert(len(chars) == 81)
    return dict(zip(squares, chars))

def parse_grid(grid):
    """Convert grid to a dict of possible values, {square: digits}, or
    return False if a contradiction is detected."""
    ## To start, every square can be any digit; then assign values from the grid.
    values = dict((s, digits) for s in squares)
    for s,d in grid_values(grid).items():
        if d in digits and not assign(values, s, d):
            return False ## (Fail if we can't assign d to square s.)
    return values

def assign(values, s, d):
    """Eliminate all the other values (except d) from values[s] and propagate.
    Return values, except return False if a contradiction is detected."""
    other_values = values[s].replace(d, '')
    if all(eliminate(values, s, d2) for d2 in other_values):
        return values
    else:
        return False

def eliminate(values, s, d):
    """Eliminate d from values[s]; propagate when values or places <= 2.
    Return values, except return False if a contradiction is detected."""
    if d not in values[s]:
        return values ## Already eliminated
    values[s] = values[s].replace(d,'')
    ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.
    if len(values[s]) == 0:
	    return False ## Contradiction: removed last value
    elif len(values[s]) == 1:
        d2 = values[s]
        if not all(eliminate(values, s2, d2) for s2 in peers[s]):
            return False
    ## (2) If a unit u is reduced to only one place for a value d, then put it there.
    for u in units[s]:
	    dplaces = [s for s in u if d in values[s]]
	    if len(dplaces) == 0:
	        return False ## Contradiction: no place for this value
	    elif len(dplaces) == 1:
	        # d can only be in one place in unit; assign it there
                if not assign(values, dplaces[0], d):
                    return False
    return values

def solve(grid): return search(parse_grid(grid))

def search(values):
    "Using depth-first search and propagation, try all possible values."
    if values is False:
        return False ## Failed earlier
    if all(len(values[s]) == 1 for s in squares):
        return values ## Solved!
    ## Chose the unfilled square s with the fewest possibilities
    n,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
    return some(search(assign(values.copy(), s, d))
		for d in values[s])

def some(seq):
    "Return some element of seq that is true."
    for e in seq:
        if e: return e
    return False

puzzles = []
current = ''
with open('p096_sudoku.txt') as f:
    for row in f.readlines():
        if len(row) == 10:
            current += row
        elif len(row) == 9:
            current += row + '\n'
            puzzles.append(solve(current))
        elif len(row) == 8:
            if current:
                puzzles.append(solve(current))
            current = ''

print(sum(map(lambda x: int(x['A1'] + x['A2'] + x['A3']), puzzles)))


text:
<?php

namespace Tkotosz\CatalogRouter\Model\Service;

use Magento\Catalog\Model\AbstractModel;
use Magento\Store\Model\StoreManagerInterface;

class StoreIdResolver
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(StoreManagerInterface $storeManager)
    {
        $this->storeManager = $storeManager;
    }

    /**
     * Replicate the original magento behaviour for store is handling from the url model
     *
     * @param AbstractModel $entity
     * @param array         $params
     *
     * @return int
     */
    public function resolve(AbstractModel $entity, array $params = []) : int
    {
        $storeId = $entity->getStoreId();

        if (isset($params['_scope'])) {
            $storeId = $this->storeManager->getStore($params['_scope'])->getId();
        }

        if (!$storeId) {
            $storeId = $this->storeManager->getStore()->getId();
        }

        return $storeId;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<records>

	<record>
		<newName>Theologie und Religionswissenschaft</newName>
	</record>

	<record />

	<record>
		<newName>Philosophie</newName>
	</record>

	<record>
		<newName>Psychologie</newName>
	</record>

	<record>
		<newName>Psychologie</newName>
	</record>

	<record />

	<record>
		<newName>Allgemeines</newName>
	</record>


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import EmberObject from '@ember/object';

module('Integration | Component | rental-listing', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    this.rental = EmberObject.create({
      image: 'fake.png',
      title: 'test-title',
      owner: 'test-owner',
      type: 'test-type',
      city: 'test-city',
      bedrooms: 3
    });
  });

  test('should display rental details', async function(assert) {
    await render(hbs`{{rental-listing rental=rental}}`);
    assert.equal(this.$('.listing h3').text(), 'test-title', 'Title: test-title');
    assert.equal(this.$('.listing .owner').text().trim(), 'Owner: test-owner', 'Owner: test-owner')
  });

  test('should toggle wide class on click', async function(assert) {
    await render(hbs`{{rental-listing rental=rental}}`);
  });
});


text:
using System;
using NControlDemo.FormsApp;
using System.Linq;

using Foundation;
using UIKit;

namespace NControlDemo.iOS
{
	public class Application
	{
		// This is the main entry point of the application.
		static void Main (string[] args)
		{
			// if you want to use a different Application Delegate class from "AppDelegate"
			// you can specify it here.
			UIApplication.Main (args, null, "AppDelegate");
		}
	}
}


text:
package com.ctrip.xpipe.testutils.stateful.config;

import com.ctrip.xpipe.testutils.stateful.StateHolder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Slight
 * <p>
 * Sep 17, 2021 10:45 PM
 */
@Configuration
public class StatefulConfig {

    @Bean
    public StateHolder stateHolder() {
        return new StateHolder(System.getProperty("server.state"));
    }
}


text:
const server = require('server');
const run = require('server/test/run');
const { get } = require('server/router');
const send = require('server/reply/send');

describe('static plugin', () => {
  it('can handle sessions', async () => {
    return run({ public: 'test' }, [
      get('/a', ctx => {
        ctx.session.page = 'pageA';
        return send('');
      }),
      get('/b', ctx => send(ctx.session.page))
    ]).alive(async api => {
      expect((await api.get('/a')).body).toEqual('');
      expect((await api.get('/b')).body).toEqual('pageA');
    });
  });

  it('persists the session', async () => {
    const mid = ctx => {
      ctx.session.counter = (ctx.session.counter || 0) + 1;
      return 'n' + ctx.session.counter;
    };
    return run(mid).alive(async api => {
      for (let i = 0; i < 3; i++) {
        const res = await api.get('/');
        expect(res.body).toBe('n' + (i + 1));
      }
    });
  });

  it('has the session for creating stores', () => {
    expect(server.session).toHaveProperty('Store', jasmine.any(Function));
  });
});


text:
package com.github.sps.metrics;

import com.codahale.metrics.*;
import com.codahale.metrics.Timer;
import com.github.sps.metrics.opentsdb.OpenTsdb;
import com.github.sps.metrics.opentsdb.OpenTsdbMetric;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * A reporter which publishes metric values to a OpenTSDB server.
 *
 * @author Sean Scanlon <sean.scanlon@gmail.com>
 * @author Randy Buck <buck@adobe.com>
 * @author alugowski (modified for Turn)
 */
public class OpenTsdbReporter extends ScheduledReporter {

    private final OpenTsdb opentsdb;
    private final Clock clock;
    private final String prefix;
    private final Map<String, String> tags;
    private final Timer timeToBuildReport;
    private final Timer timeToSendReport;

    private boolean decorateCounters = true;
    private boolean decorateGauges = true;

    /**
     * Returns a new {@link Builder} for {@link OpenTsdbReporter}.
     *
     * @param registry the registry to report
     * @return a {@link Builder} instance for a {@link OpenTsdbReporter}
     */
    public static Builder forRegistry(MetricRegistry registry) {
        return new Builder(registry);
    }

    /**
     * A builder for {@link OpenTsdbReporter} instances. Defaults to not using a prefix, using the
     * default clock, converting rates to events/second, converting durations to milliseconds, and
     * not filtering metrics.
     */
    public static class Builder {
        private final MetricRegistry registry;
        private Clock clock;
        private String prefix;
        private TimeUnit rateUnit;
        private TimeUnit durationUnit;
        private MetricFilter filter;
        private Map<String, String> tags;
        private int batchSize;
        private boolean decorateCounters;
        private boolean decorateGauges;

        private Builder(MetricRegistry registry) {
            this.registry = registry;
            this.clock = Clock.defaultClock();
            this.prefix = "";
            this.rateUnit = TimeUnit.SECONDS;
            this.durationUnit = TimeUnit.MILLISECONDS;
            this.filter = MetricFilter.ALL;
            this.batchSize = OpenTsdb.DEFAULT_BATCH_SIZE_LIMIT;
            this.decorateCounters = true;
            this.decorateGauges = true;
        }

        /**
         * Use the given {@link Clock} instance for the time.
         *
         * @param clock a {@link Clock} instance
         * @return {@code this}
         */
        public Builder withClock(Clock clock) {
            this.clock = clock;
            return this;
        }

        /**
         * Prefix all metric names with the given string.
         *
         * @param prefix the prefix for all metric names
         * @return {@code this}
         */
        public Builder prefixedWith(String prefix) {
            this.prefix = prefix;
            return this;
        }

        /**
         * Convert rates to the given time unit.
         *
         * @param rateUnit a unit of time
         * @return {@code this}
         */
        public Builder convertRatesTo(TimeUnit rateUnit) {
            this.rateUnit = rateUnit;
            return this;
        }

        /**
         * Convert durations to the given time unit.
         *
         * @param durationUnit a unit of time
         * @return {@code this}
         */
        public Builder convertDurationsTo(TimeUnit durationUnit) {
            this.durationUnit = durationUnit;
            return this;
        }

        /**
         * Only report metrics which match the given filter.
         *
         * @param filter a {@link MetricFilter}
         * @return {@code this}
         */
        public Builder filter(MetricFilter filter) {
            this.filter = filter;
            return this;
        }

        /**
         * Append tags to all reported metrics
         *
         * @param tags
         * @return {@code this}
         */
        public Builder withTags(Map<String, String> tags) {
            this.tags = tags;
            return this;
        }

        /**
         * Enable decorating Counter metric names with {@code .count} and Gauge metric names with
         * {@code .value}.
         *
         * @param withCounterGaugeDecorations
         * @return {@code this}
         */
        public Builder withCounterGaugeDecorations(boolean withCounterGaugeDecorations) {
            this.decorateCounters = withCounterGaugeDecorations;
            this.decorateGauges = withCounterGaugeDecorations;
            return this;
        }

        /**
         * specify number of metrics send in each request
         *
         * @param batchSize
         * @return {@code this}
         */
        public Builder withBatchSize(int batchSize) {
            this.batchSize = batchSize;
            return this;
        }

        /**
         * Builds a {@link OpenTsdbReporter} with the given properties, sending metrics using the
         * given {@link com.github.sps.metrics.opentsdb.OpenTsdb} client.
         *
         * @param opentsdb a {@link OpenTsdb} client
         * @return a {@link OpenTsdbReporter}
         */
        public OpenTsdbReporter build(OpenTsdb opentsdb) {
            opentsdb.setBatchSizeLimit(batchSize);
            return new OpenTsdbReporter(registry,
                    opentsdb,
                    clock,
                    prefix,
                    rateUnit,
                    durationUnit,
                    filter, tags, decorateCounters, decorateGauges);
        }
    }

    private static class MetricsCollector {
        private final String prefix;
        private final Map<String, String> tags;
        private final long timestamp;
        private final Set<OpenTsdbMetric> metrics = new HashSet<OpenTsdbMetric>();

        private MetricsCollector(String prefix, Map<String, String> tags, long timestamp) {
            this.prefix = prefix;
            this.tags = tags;
            this.timestamp = timestamp;
        }

        public static MetricsCollector createNew(String prefix, Map<String, String> tags, long timestamp) {
            return new MetricsCollector(prefix, tags, timestamp);
        }

        public MetricsCollector addMetric(String metricName, Object value) {
            this.metrics.add(OpenTsdbMetric.named(MetricRegistry.name(prefix, metricName))
                    .withTimestamp(timestamp)
                    .withValue(value)
                    .withTags(tags).build());
            return this;
        }

        public Set<OpenTsdbMetric> build() {
            return metrics;
        }
    }

    private OpenTsdbReporter(MetricRegistry registry, OpenTsdb opentsdb, Clock clock, String prefix, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter, Map<String, String> tags, boolean decorateCounters, boolean decorateGauges) {
        super(registry, "opentsdb-reporter", filter, rateUnit, durationUnit);
        this.opentsdb = opentsdb;
        this.clock = clock;
        this.prefix = prefix;
        this.tags = tags;
        this.timeToSendReport = registry.timer("open-tsdb-reporter-time-to-send-report");
        this.timeToBuildReport = registry.timer("open-tsdb-reporter-time-to-build-report");
        this.decorateCounters = decorateCounters;
        this.decorateGauges = decorateGauges;
    }

    @Override
    public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
    	final Timer.Context context = timeToBuildReport.time();
        final long timestamp = clock.getTime() / 1000;

        final Set<OpenTsdbMetric> metrics = new HashSet<OpenTsdbMetric>();

        for (Map.Entry<String, Gauge> g : gauges.entrySet()) {
            if(g.getValue().getValue() instanceof Collection && ((Collection)g.getValue().getValue()).isEmpty()) {
                continue;
            }

            Map<String, String> tagsToUse = new HashMap<String, String>(tags);
            String key = g.getKey();
        	if(g.getValue() instanceof TaggedMetric ) {
        		key = TaggedMetricRegistry.getBaseName(key);
        		Map<String, String> objectTags = ((TaggedMetric) g.getValue()).getTags();
        		if(objectTags != null) {
        			tagsToUse.putAll(objectTags);
        		}
        	}
            metrics.add(buildGauge(key, g.getValue(), timestamp, tagsToUse));
        }

        for (Map.Entry<String, Counter> entry : counters.entrySet()) {
        	Map<String, String> tagsToUse = new HashMap<String, String>(tags);
        	String key = entry.getKey();
        	if(entry.getValue() instanceof TaggedCounter) {
        		key = TaggedMetricRegistry.getBaseName(key);
        		Map<String, String> objectTags = ((TaggedCounter) entry.getValue()).getTags();
        		if(objectTags != null) {
        			tagsToUse.putAll(objectTags);
        		}
        	}
            metrics.add(buildCounter(key, entry.getValue(), timestamp, tagsToUse));
        }

        for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
        	Map<String, String> tagsToUse = new HashMap<String, String>(tags);
        	String key = entry.getKey();
        	if(entry.getValue() instanceof TaggedHistogram) {
        		key = TaggedMetricRegistry.getBaseName(key);
        		Map<String, String> objectTags = ((TaggedHistogram) entry.getValue()).getTags();
        		if(objectTags != null) {
        			tagsToUse.putAll(objectTags);
        		}
        	}
            metrics.addAll(buildHistograms(key, entry.getValue(), timestamp, tagsToUse));
        }

        for (Map.Entry<String, Meter> entry : meters.entrySet()) {
        	Map<String, String> tagsToUse = new HashMap<String, String>(tags);
        	String key = entry.getKey();
        	if(entry.getValue() instanceof TaggedMeter) {
        		key = TaggedMetricRegistry.getBaseName(key);
        		Map<String, String> objectTags = ((TaggedMeter) entry.getValue()).getTags();
        		if(objectTags != null) {
        			tagsToUse.putAll(objectTags);
        		}
        	}
            metrics.addAll(buildMeters(key, entry.getValue(), timestamp, tagsToUse));
        }

        for (Map.Entry<String, Timer> entry : timers.entrySet()) {
        	Map<String, String> tagsToUse = new HashMap<String, String>(tags);
        	String key = entry.getKey();
        	if(entry.getValue() instanceof TaggedTimer) {
        		key = TaggedMetricRegistry.getBaseName(key);
        		Map<String, String> objectTags = ((TaggedTimer) entry.getValue()).getTags();
        		if(objectTags != null) {
        			tagsToUse.putAll(objectTags);
        		}
        	}
            metrics.addAll(buildTimers(key, entry.getValue(), timestamp, tagsToUse));
        }
        context.stop();

        final Timer.Context context2 = timeToSendReport.time();
        opentsdb.send(metrics);
        context2.stop();

    }

    private Set<OpenTsdbMetric> buildTimers(String name, Timer timer, long timestamp, Map<String, String> tags) {
        final MetricsCollector collector = MetricsCollector.createNew(prefix(name), tags, timestamp);
        final Snapshot snapshot = timer.getSnapshot();

        return collector.addMetric("count", timer.getCount())
                //convert rate
                .addMetric("m15", convertRate(timer.getFifteenMinuteRate()))
                .addMetric("m5", convertRate(timer.getFiveMinuteRate()))
                .addMetric("m1", convertRate(timer.getOneMinuteRate()))
                .addMetric("mean_rate", convertRate(timer.getMeanRate()))
                // convert duration
                .addMetric("max", convertDuration(snapshot.getMax()))
                .addMetric("min", convertDuration(snapshot.getMin()))
                .addMetric("mean", convertDuration(snapshot.getMean()))
                .addMetric("stddev", convertDuration(snapshot.getStdDev()))
                .addMetric("median", convertDuration(snapshot.getMedian()))
                .addMetric("p75", convertDuration(snapshot.get75thPercentile()))
                .addMetric("p95", convertDuration(snapshot.get95thPercentile()))
                .addMetric("p98", convertDuration(snapshot.get98thPercentile()))
                .addMetric("p99", convertDuration(snapshot.get99thPercentile()))
                .addMetric("p999", convertDuration(snapshot.get999thPercentile()))
                .build();
    }

    private Set<OpenTsdbMetric> buildHistograms(String name, Histogram histogram, long timestamp, Map<String, String> tags) {

        final MetricsCollector collector = MetricsCollector.createNew(prefix(name), tags, timestamp);
        final Snapshot snapshot = histogram.getSnapshot();

        return collector.addMetric("count", histogram.getCount())
                .addMetric("max", snapshot.getMax())
                .addMetric("min", snapshot.getMin())
                .addMetric("mean", snapshot.getMean())
                .addMetric("stddev", snapshot.getStdDev())
                .addMetric("median", snapshot.getMedian())
                .addMetric("p75", snapshot.get75thPercentile())
                .addMetric("p95", snapshot.get95thPercentile())
                .addMetric("p98", snapshot.get98thPercentile())
                .addMetric("p99", snapshot.get99thPercentile())
                .addMetric("p999", snapshot.get999thPercentile())
                .build();
    }

    private Set<OpenTsdbMetric> buildMeters(String name, Meter meter, long timestamp, Map<String, String> tags) {

        final MetricsCollector collector = MetricsCollector.createNew(prefix(name), tags, timestamp);

        return collector.addMetric("count", meter.getCount())
                // convert rate
                .addMetric("mean_rate", convertRate(meter.getMeanRate()))
                .addMetric("m1", convertRate(meter.getOneMinuteRate()))
                .addMetric("m5", convertRate(meter.getFiveMinuteRate()))
                .addMetric("m15", convertRate(meter.getFifteenMinuteRate()))
                .build();
    }

    private OpenTsdbMetric buildCounter(String name, Counter counter, long timestamp, Map<String, String> tags) {
        return OpenTsdbMetric.named(decorateCounters ? prefix(name, "count") : prefix(name))
                .withTimestamp(timestamp)
                .withValue(counter.getCount())
                .withTags(tags)
                .build();
    }

    private OpenTsdbMetric buildGauge(String name, Gauge gauge, long timestamp, Map<String, String> tags) {
        return OpenTsdbMetric.named(decorateGauges ? prefix(name, "value") : prefix(name))
                .withValue(gauge.getValue())
                .withTimestamp(timestamp)
                .withTags(tags)
                .build();
    }

    private String prefix(String... components) {
        if (prefix.length() == 0)
            return MetricRegistry.name(prefix, components);
        else
            return OpenTsdbMetric.fixEncodedTagsInNameAfterPrefix(MetricRegistry.name(prefix, components));
    }

}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Ninject.Extensions.Azure.Clients;
using Proactima.AzureWorkers;

namespace ExampleWorker
{
    public class SimpleServicebusTopicWorker : BaseServiceBusTopicWorker
    {
        private readonly List<string> _failedMessages = new List<string>();

        public SimpleServicebusTopicWorker(ICreateClientsAsync clientFactory)
            : base(clientFactory)
        {
            MessageRepostMaxCount = 4;
        }
        protected override string TopicName
        {
            get { return "SimpleTopic"; }
        }
        public override bool Enabled
        {
            get { return false; }
        }
        protected override async Task Do(string message)
        {
            var client = new HttpClient();
            await client.GetAsync("http://blog.uxrisk.com").ConfigureAwait(false);
        }

        protected override async Task HandleFailedMessageAsync(string messageBody)
        {
            await Task.Factory.StartNew(() => _failedMessages.Add(messageBody));
        }

        protected override void DebugLogging(string message, string messageId = "", double timerValue = 0)
        {
            Debug.WriteLine("msg: {0}, timer: {1}", message, timerValue);
        }

        protected override void InfoLogging(string message, string messageId = "")
        {
            Debug.WriteLine("msg: {0}", message);
        }
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Rasmus Mikkelsen
// Copyright (c) 2015-2016 eBay Software Foundation
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Snapshots;

namespace EventFlow.TestHelpers.Aggregates.Snapshots.Upgraders
{
    public class ThingySnapshotV2ToV3Upgrader : ISnapshotUpgrader<ThingySnapshotV2, ThingySnapshot>
    {
        public Task<ThingySnapshot> UpgradeAsync(ThingySnapshotV2 fromVersionedType, CancellationToken cancellationToken)
        {
            var thingySnapshot = new ThingySnapshot(
                fromVersionedType.PingsReceived,
                new [] {ThingySnapshotVersion.Version2, }.Concat(fromVersionedType.PreviousVersions));

            return Task.FromResult(thingySnapshot);
        }
    }
}


text:
<?php
/**
 * 用户道具背包数据访问层
 *
 * the last known user to change this file in the repository  <$LastChangedBy: leiwei $>
 * @author Su qian <suqian@pipi.cn>
 * @version $Id: UserPropsUseModel.php 10953 2013-05-27 07:47:51Z leiwei $
 * @package model
 * @subpackage props
 */
class UserPropsUseModel extends PipiActiveRecord {
	public function tableName(){
		return '{{user_props_use}}';
	}

	/**
	 * @param string $className
	 * @return UserPropsAttributeModel
	 */
	public static function model($className = __CLASS__){
		return parent::model($className);
	}

	public function getDbConnection(){
		return Yii::app()->db_consume;
	}

	/**
	 * 获取用户使用的道具
	 *
	 * @param int $uid 用户ID
	 * @param int $propId 道具ID
	 * @param int $validTime 道具有效时间, 传递Unix时间缀
	 * @return array
	 */
	public function getUserValidPropsOfUseByPropId($uid,$propId = 0,$validTime = null){
		if($uid <= 0){
			return array();
		}

		$option['condition'] = 'uid = :uid';
		$option['params'][':uid'] = $uid;

		if($propId){
			$option['condition'] .= ' AND prop_id = :prop_id';
			$option['params'][':prop_id'] = $propId;
		}
		if($validTime){
			$option['condition'] .= ' AND (valid_time = 0 OR valid_time >= :vtime)';
			$option['params'][':vtime'] = $validTime ? $validTime : time();
		}
		$option['order'] = 'valid_time DESC';
		return $this->findAll($option);
	}

	/**
	 * 获取用户使用的道具
	 *
	 * @param int $uid 用户ID
	 * @param int $catId 道具ID
	 * @param int $validTime 道具有效时间, 传递Unix时间缀
	 * @return array
	 */
	public function getUserValidPropsOfUseByCatId($uid,$catId = 0,$validTime = null){
		if($uid <= 0){
			return array();
		}

		$option['condition'] = 'uid = :uid';
		$option['params'][':uid'] = $uid;

		if($catId){
			$option['condition'] .= ' AND cat_id = :cat_id';
			$option['params'][':cat_id'] = $catId;
		}
		if($validTime){
			$option['condition'] .= ' AND (valid_time = 0 OR valid_time >= :vtime)';
			$option['params'][':vtime'] = $validTime ? $validTime : time();
		}
		$option['order'] = 'valid_time DESC';
		return $this->findAll($option);
	}

	/**
	 * 取得某分类道具下最后一次被使用情况
	 *
	 * @param int $uid
	 * @param int $catId
	 * @return PipiActiveRecord
	 */
	public function getUserLatestPropsOfUsedByCatId($uid,$catId){
		if($uid <= 0 || $catId <= 0){
			return array();
		}
		$option['select'] = 'use_id,uid,to_uid,prop_id,cat_id,valid_time,create_time';
		$option['condition'] = 'to_uid = :uid AND cat_id = :cat_id ';
		$option['params'] = array(':uid'=>$uid,':cat_id'=>$catId);
		$option['order'] = 'create_time DESC';
		$option['limit'] = 1;
		return $this->find($option);
	}

	public function getUserPropsUseCount($uid, $propId, $condition)
	{
		$criteria = $this->getDbCriteria();
		$criteria->select = ' uid,sum(`num`) as nums ';
		$criteria->condition = 'uid = :uid AND prop_id = :prop_id ';
		if(isset($condition['start_time']) && $condition['start_time']>0){
			$criteria->condition .= ' and create_time>= :stime';
		}
		if(isset($condition['end_time']) && $condition['end_time']>0){
			$criteria->condition .= ' and create_time<= :etime';
		}
		$criteria->params = array(':uid'=>$uid,':prop_id'=>$propId,':stime'=>$condition['start_time'],':etime'=>$condition['end_time']);

		$data = $this->getCommandBuilder()->createFindCommand($this->tableName(),$criteria)->queryRow();
		return $data['num'];
	}

	/**
	 * 根据道具Id获取道具的使用数量
	 * @author leiwei
	 * @param int $uid  用户uid
	 * @param int $catId 道具分类ID
	 * @param array $condition 检索条件
	 * @return int
	 */
	public function getUserPropsUserCountByCatId($uid, $catId, $condition){
		$criteria = $this->getDbCriteria();
		$criteria->select = 'uid,sum(num) as num';
		$criteria->condition='uid = :uid AND cat_id = :cat_id';
		$criteria->params[':uid']=$uid;
		$criteria->params[':cat_id']=$catId;
		if(isset($condition['use_type'])){
			$criteria->condition.=' AND use_type=:use_type';
			$criteria->params[':use_type']=$condition['use_type'];
		}
		if(isset($condition['start_time'])){
			$criteria->condition.=' AND create_time>=:start_time ';
			$criteria->params[':start_time']=strtotime($condition['start_time']);
		}
		if(isset($condition['end_time'])){
			$criteria->condition.=' AND create_time<=:end_time ';
			$criteria->params[':end_time']=strtotime($condition['end_time']);
		}
		$data = $this->getCommandBuilder()->createFindCommand($this->tableName(),$criteria)->queryRow();
		return $data['num'];
	}

}

?>


text:
package com.github.obsessive.simplifyreader.ui.activity.qrcode.decode;

import com.google.zxing.BarcodeFormat;

import java.util.Collection;
import java.util.EnumSet;
import java.util.Set;

public class DecodeFormatManager {

    private static final Set<BarcodeFormat> PRODUCT_FORMATS;
    private static final Set<BarcodeFormat> INDUSTRIAL_FORMATS;
    private static final Set<BarcodeFormat> ONE_D_FORMATS;

    private static final Set<BarcodeFormat> QR_CODE_FORMATS;

    static {
        PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A, BarcodeFormat.UPC_E, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8, BarcodeFormat.RSS_14, BarcodeFormat.RSS_EXPANDED);
        INDUSTRIAL_FORMATS = EnumSet.of(BarcodeFormat.CODE_39, BarcodeFormat.CODE_93, BarcodeFormat.CODE_128, BarcodeFormat.ITF, BarcodeFormat.CODABAR);
        ONE_D_FORMATS = EnumSet.copyOf(PRODUCT_FORMATS);
        ONE_D_FORMATS.addAll(INDUSTRIAL_FORMATS);

        QR_CODE_FORMATS = EnumSet.of(BarcodeFormat.QR_CODE, BarcodeFormat.PDF_417);
    }

    public static Collection<BarcodeFormat> getQrCodeFormats() {
        return QR_CODE_FORMATS;
    }

    public static Collection<BarcodeFormat> getBarCodeFormats() {
        return ONE_D_FORMATS;
    }
}


text:
.file-uploader {
	display: inline-block;
}

.file-uploader-items {
	list-style-type: none;
	display: flex;
	flex-wrap: wrap;
}
.file-uploader-button {
	line-height: 44px;
}
.file-uploader-button label {
	background-color: var(--normal-background);
	border-radius: 4px;
	color: var(--white-text);
	display: inline-block;
	text-decoration: none;
	line-height: 22px;
	padding:  5px 16px;
	cursor: pointer;
}

.file-uploader-button label:hover,
.file-uploader-button label:focus,
.file-uploader-button label:active {
	background-color: var(--normal-dark-background);
	color: var(--white-text);
}

.file-uploader-button label input {
	margin-left: 8px;
}
.auto-submit .file-uploader-button label input {
	display: none;
}
@-moz-document url-prefix() {
	.file-uploader-button label {
		padding:  4px 16px 6px;
	}
}

.file-uploader-items li {
	margin-right: 17px;
}
.file-uploader-items .empty { margin-right: 0; }


text:
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Ranking.Expanded;
using osu.Game.Tests.Beatmaps;
using osu.Game.Users;
using osuTK;

namespace osu.Game.Tests.Visual.Ranking
{
    public class TestSceneExpandedPanelMiddleContent : OsuTestScene
    {
        [Resolved]
        private RulesetStore rulesetStore { get; set; }

        [Test]
        public void TestMapWithKnownMapper()
        {
            var author = new User { Username = "mapper_name" };

            AddStep("show example score", () => showPanel(new TestScoreInfo(new OsuRuleset().RulesetInfo)
            {
                BeatmapInfo = createTestBeatmap(author)
            }));
        }

        [Test]
        public void TestExcessMods()
        {
            var author = new User { Username = "mapper_name" };

            AddStep("show excess mods score", () => showPanel(new TestScoreInfo(new OsuRuleset().RulesetInfo, true)
            {
                BeatmapInfo = createTestBeatmap(author)
            }));

            AddAssert("mapper name present", () => this.ChildrenOfType<OsuSpriteText>().Any(spriteText => spriteText.Current.Value == "mapper_name"));
        }

        [Test]
        public void TestMapWithUnknownMapper()
        {
            AddStep("show example score", () => showPanel(new TestScoreInfo(new OsuRuleset().RulesetInfo)
            {
                BeatmapInfo = createTestBeatmap(null)
            }));

            AddAssert("mapped by text not present", () =>
                this.ChildrenOfType<OsuSpriteText>().All(spriteText => !containsAny(spriteText.Text.ToString(), "mapped", "by")));

            AddAssert("play time displayed", () => this.ChildrenOfType<ExpandedPanelMiddleContent.PlayedOnText>().Any());
        }

        [Test]
        public void TestWithDefaultDate()
        {
            AddStep("show autoplay score", () =>
            {
                var ruleset = new OsuRuleset();

                var mods = new Mod[] { ruleset.GetAutoplayMod() };
                var beatmap = createTestBeatmap(null);

                showPanel(new TestScoreInfo(ruleset.RulesetInfo)
                {
                    Mods = mods,
                    BeatmapInfo = beatmap,
                    Date = default,
                });
            });

            AddAssert("play time not displayed", () => !this.ChildrenOfType<ExpandedPanelMiddleContent.PlayedOnText>().Any());
        }

        private void showPanel(ScoreInfo score) =>
            Child = new ExpandedPanelMiddleContentContainer(score);

        private BeatmapInfo createTestBeatmap(User author)
        {
            var beatmap = new TestBeatmap(rulesetStore.GetRuleset(0)).BeatmapInfo;

            beatmap.Metadata.Author = author;
            beatmap.Metadata.Title = "Verrrrrrrrrrrrrrrrrrry looooooooooooooooooooooooong beatmap title";
            beatmap.Metadata.Artist = "Verrrrrrrrrrrrrrrrrrry looooooooooooooooooooooooong beatmap artist";

            return beatmap;
        }

        private bool containsAny(string text, params string[] stringsToMatch) => stringsToMatch.Any(text.Contains);

        private class ExpandedPanelMiddleContentContainer : Container
        {
            public ExpandedPanelMiddleContentContainer(ScoreInfo score)
            {
                Anchor = Anchor.Centre;
                Origin = Anchor.Centre;
                Size = new Vector2(ScorePanel.EXPANDED_WIDTH, 700);
                Children = new Drawable[]
                {
                    new Box
                    {
                        RelativeSizeAxes = Axes.Both,
                        Colour = Color4Extensions.FromHex("#444"),
                    },
                    new ExpandedPanelMiddleContent(score)
                };
            }
        }
    }
}


text:
<?php

namespace Diside\SecurityBundle\Tests\Form\Processor;

use Diside\SecurityBundle\Factory\EntityFactory;
use Diside\SecurityBundle\Factory\RequestFactory;
use Diside\SecurityBundle\Entity\Page as PageEntity;
use Diside\SecurityBundle\Form\Processor\PageFormProcessor;
use Diside\SecurityBundle\Provider\LocaleProvider;
use Diside\SecurityBundle\Security\PermissionChecker;
use Diside\SecurityBundle\Tests\FormProcessorTestCase;
use Diside\SecurityBundle\Tests\Mock\InteractorMock;
use Diside\SecurityComponent\Interactor\InteractorFactory;
use Diside\SecurityComponent\Interactor\SecurityInteractorRegister;
use Diside\SecurityComponent\Model\Page;
use Diside\SecurityComponent\Model\User;
use Mockery as m;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;

class PageFormProcessorTest extends FormProcessorTestCase
{
    private $locales = array('it');

    protected function buildProcessor(
        FormFactoryInterface $formFactory,
        InteractorFactory $interactorFactory,
        SecurityContextInterface $securityContext,
        EntityFactory $entityFactory,
        RequestFactory $requestFactory,
        PermissionChecker $permissionChecker
    ) {

        $localeProvider = new LocaleProvider('en', array('en', 'it'));

        return new PageFormProcessor($formFactory, $interactorFactory, $securityContext, $entityFactory, $requestFactory, $permissionChecker, $localeProvider);
    }

    protected function getFormName()
    {
        return 'page';
    }

    /**
     * @test
     */
    public function testConstructor()
    {
        $this->assertNull($this->processor->getPage());
        $this->assertNull($this->processor->getErrors());
        $this->assertFalse($this->processor->hasErrors());
    }

    /**
     * @test
     * @expectedException \Diside\SecurityBundle\Exception\UnauthorizedException
     */
    public function whenProcessingRequestAndPageIsAnonymous_thenThrow()
    {
        $this->givenNotAuthorized();

        $request = new Request();

        $this->processor->process($request);
    }

    /**
     * @test
     */
    public function whenProcessingWithNoData_thenIsNotValid()
    {
        $this->givenLoggedSuperadmin();
        $this->givenInvalidData();

        $request = $this->givenPostRequest();

        $this->processor->process($request);
        $this->assertFalse($this->processor->hasErrors());
    }

    /**
     * @test
     */
    public function whenProcessing_thenFormDataIsSet()
    {
        $this->givenLoggedSuperadmin();
        $this->givenInvalidData();

        $expect = $this->expectFormDataIsSet();

        $request = $this->givenPostRequest();

        $this->processor->process($request);

        $expect->verify();
    }

    /**
     * @test
     */
    public function whenProcessingValidForm_thenHasNoErrors()
    {
        $page = $this->givenPage();
        $interactor = new InteractorMock($page, 'setPage');

        $this->expectInteractorFor($interactor, SecurityInteractorRegister::SAVE_PAGE);

        $this->givenLoggedSuperadmin();
        $request = $this->givenValidData();

        $this->processor->process($request);

        $page = $this->processor->getPage();

        $this->assertNotNull($page);
        $this->assertFalse($this->processor->hasErrors());
        $this->assertTrue($this->processor->isValid());
    }

    /**
     * @test
     */
    public function whenProcessingExisting_thenSaveExisting()
    {
        $page = $this->givenPage();
        $interactor = new InteractorMock($page, 'setPage');

        $expect = $this->expectInteractorFor($interactor, SecurityInteractorRegister::GET_PAGE);

        $this->givenLoggedSuperadmin();
        $request = $this->givenInvalidData();

        $this->processor->process($request, 1);

        $expect->verify();
    }

    /**
     * @test
     */
    public function whenProcessingValidFormButInteractorFails_thenHasErrors()
    {
        $this->givenErrorInteractorFor(SecurityInteractorRegister::SAVE_PAGE);

        $this->givenLoggedSuperadmin();
        $request = $this->givenValidData();

        $this->processor->process($request);

        $this->assertTrue($this->processor->hasErrors());

        $errors = $this->processor->getErrors();
        $this->assertThat($errors[0], $this->equalTo('Error'));
    }

    protected function givenPage()
    {
        return new Page(null, 'en', 'url', 'title', 'content');
    }

    protected function mockEntities()
    {
        $this->mockEntity('page', new PageEntity());
    }

    protected function buildFormData()
    {
        return new PageEntity();
    }

}


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { BigNumberDependencies } from './dependenciesBigNumberClass.generated';
import { createWeakMixingAngle } from '../../factoriesAny.js';
export var weakMixingAngleDependencies = {
  BigNumberDependencies: BigNumberDependencies,
  createWeakMixingAngle: createWeakMixingAngle
};


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>1982c9b8-300f-4c8d-b6a2-2180aa0bae4e</uuid>
    <file-application>eFapsApp-Sales</file-application>

    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Sales_BulkPaymentDefinitionTree_Contact</name>
        <target>
            <menu>Sales_BulkPaymentDefinitionTree_Contact_Menu</menu>

Sales_BulkPaymentDefinition2ContactTable

            <evaluate program="org.efaps.esjp.common.uitable.MultiPrint">
                <property name="Type">Sales_BulkPaymentDefinition2Contact</property>
                <property name="LinkFrom">FromLink</property>
            </evaluate>
        </target>

        <property name="Target">content</property>
        <property name="TargetShowCheckBoxes">true</property>
    </definition>
</ui-command>


text:
Entity parserCore(std::string input)
{
	input.erase(remove_if(input.begin(), input.end(), isspace), input.end());

	checkString(input);

	return _parserCore(input, syntaxAnalysis(input));
}

void finalProcessing()
{
	MUTEX_DESTROY;
}

#pragma mark - API

void simpleParserAPI(char * cString)
{
	std::string string = cString;
	Entity input;

	try
	{
		input = parserCore(string);
	}
	catch (const std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return;
	}
}

bool haveVariableSuggestion(std::string begining, std::string & suggestion)
{
	return Catalog::haveVariableSuggestion(begining, suggestion);
}


text:
from gui.plugins.views.abstract_viewer_plug import AbstractViewerPlugin
from PyQt4.Qt import QWidget
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QHBoxLayout, QCheckBox, QHeaderView, \
    QTableWidgetItem, QColor, QVBoxLayout, QAbstractItemView
from gui.gui_builder import GBuilder
from io_processing.result_interpreter.checkpoint_interpreter import CheckpointInterpreter, \
    CPCategory
from io_processing.result_interpreter.eventline_interpreter import EventlineInterpreter

class CheckpointViewPlugin(AbstractViewerPlugin):

    def __init__(self, *args, **kwargs):
        AbstractViewerPlugin.__init__(self, *args, **kwargs)

    def get_combobox_name(self):
        return "Checkpoints Analysis"

    def get_widget(self, parent):
        self.gui = CheckpointViewPluginGUI(parent)
        return self.gui

    def get_interpreters(self):
        return [EventlineInterpreter]

    def load(self, data):
        self.gui.load(data)

    def save(self):
        return self.gui.save()

    def update_gui(self, interpreter_input):

        self.gui.update_gui(interpreter_input)

class CheckpointViewPluginGUI(QWidget):

    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)

        self._ecu_ids = []
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1
        self._cp_collections = {}
        self._show_sets = {}
        self._ex_comps = []

    def create_widgets(self, parent):

        hbox = QHBoxLayout()

        # Left side

        # Layout and Label
        vbox_left = QtGui.QVBoxLayout()
        vbox_right = QtGui.QVBoxLayout()

        # Header
        up_hbox = QHBoxLayout()

        self._label = QtGui.QLabel(self)
        self._label.setText("Choose the communication partner")
        self._label.setFixedWidth(170)
        self._ecu_1_label = QtGui.QLabel(self)
        self._ecu_1_label.setText("   ECU 1:")
        self._ecu_1_label.setFixedWidth(50)
        self._ecu_2_label = QtGui.QLabel(self)
        self._ecu_2_label.setText("    ECU 2:")
        self._ecu_2_label.setFixedWidth(50)
        self._ecu_1_cb = GBuilder().combobox(self, [], self._on_ecu_selection_changed)
        self._ecu_1_cb.addItem("<< No Selection >>")
        self._ecu_1_cb.addItem("Unknown")
        self._ecu_2_cb = GBuilder().combobox(self, [], self._on_ecu_selection_changed)
        self._ecu_2_cb.addItem("<< No Selection >>")
        self._ecu_2_cb.addItem("Unknown")
        self._ass_cb = QCheckBox("Show only associated")
        self._ass_cb.setFixedWidth(130)
        self._ass_cb.stateChanged.connect(self._on_ecu_selection_changed)

        up_hbox.addWidget(self._label)
        up_hbox.addWidget(self._ecu_1_label)
        up_hbox.addWidget(self._ecu_1_cb)
        up_hbox.addWidget(self._ecu_2_label)
        up_hbox.addWidget(self._ecu_2_cb)
        up_hbox.addWidget(self._ass_cb)

        # Table
        self._time_table = GBuilder().table(self, 0, 3, ["Time", "ECU", 'Event'], False)
        self._time_table.setColumnWidth(0, 100)
        self._time_table.setColumnWidth(1, 170)
        self._time_table.setSortingEnabled(True)
        self._time_table.horizontalHeader().setResizeMode(0, QHeaderView.Fixed);
        self._time_table.horizontalHeader().setResizeMode(1, QHeaderView.Fixed);
        self._time_table.horizontalHeader().setResizeMode(2, QHeaderView.Stretch);

        # Layout
        vbox_left.addLayout(up_hbox)
        vbox_left.addWidget(self._time_table)

        # Right side
        v_lay = QVBoxLayout()
        self._times_gb = GBuilder().groupbox(self, "Times")
        self._times_gb.setFixedWidth(450)
        self._times_gb.setLayout(v_lay)
        vbox_right.addWidget(self._times_gb)

        self._up_info = GBuilder().label(self, self._label_up("-", "-", "-", "-", "-"))
        self._down_info = GBuilder().label(self, self._label_down("-"))
        v_lay.addWidget(self._up_info)
        v_lay.addWidget(self._down_info)

        hbox.addLayout(vbox_left)
        hbox.addLayout(vbox_right)
        self.setLayout(hbox)

    def save(self):
        data = [self._cp_collections]
        return data

    def load(self, data):
        self.update_gui([data[0]])

    def update_gui(self, monitor_input_lst):

        # add new entries
        for monitor_input in monitor_input_lst:
            self._add_missing_keys(monitor_input[1])

            self._extend_table(monitor_input)

    def _extend_table(self, monitor_input):

        # row already existing -> Continue
        txt = EventlineInterpreter().core.cp_string(eval(monitor_input[3]), monitor_input[2], monitor_input[7], monitor_input[5])

        txt_2 = str([monitor_input[0], monitor_input[1], txt])
        if txt_2 in self._ex_comps:
            return

        # insert a row at right point
        row_nr = self._get_suiting_row(self._time_table, monitor_input[0], 0)

        self._time_table.insertRow(row_nr)

        itab = TableCheckpointItem(); itab.set_checkpoint(monitor_input); itab.setText(str(monitor_input[0]));
        itab_2 = TableCheckpointItem(); itab_2.set_checkpoint(monitor_input); itab_2.setText(monitor_input[1]);
        itab_3 = TableCheckpointItem(); itab_3.set_checkpoint(monitor_input); itab_3.setText(txt);

        self._time_table.setItem(row_nr, 0, itab);
        self._time_table.setItem(row_nr, 1, itab_2);
        self._time_table.setItem(row_nr, 2, itab_3);
        self._time_table.setSelectionBehavior(QAbstractItemView.SelectRows);
        self._time_table.itemSelectionChanged.connect(self._selection_changed)

        self._set_row_color(self._time_table, EventlineInterpreter().core._category_by_tag(eval(monitor_input[3])), row_nr)

        # Add to show set
        self._show_sets[monitor_input[1]].add(row_nr, monitor_input[2])
        self._ex_comps.append(str([monitor_input[0], monitor_input[1], txt]))

    def _add_missing_keys(self, comp_id):

        if comp_id not in self._ecu_ids:
            self._show_sets[comp_id] = TableShowSet(self._time_table)

            # Add entry to comboboxes
            self._ecu_1_cb.addItem(comp_id)
            self._ecu_2_cb.addItem(comp_id)
            self._ecu_ids.append(comp_id)

    def _get_suiting_row(self, table, val, col_idx):
        ''' returns the row where val is bigger than the upper and smaller than the lower'''
        prev = 0
        for r in range(table.rowCount()):
            item = table.item(r, col_idx)
            if val < float(item.text()):
                break
            prev = r
        return prev

    def _hide_all_rows(self, table):
        for r in range(table.rowCount()):
            table.setRowHidden(r, True)
#
    def _label_up(self, msg_id, msg_ctnt, msg_size, msg_cat, msg_stream):
        return "Checkpoint Details:\n\nMessage ID:\t\t\n%s\nMessage Content:\t\t\n%s\nMessage Size\t\t\n%s\nMessage Category\t\t\n%s\n Message Stream\t\t\n%s" % (msg_id, msg_ctnt, msg_size, msg_cat, msg_stream)

    def _label_down(self, time_passed):
        return"Selection Details:\nTime passed:%s" % (time_passed)
#
    def _on_ecu_selection_changed(self):
        self._show_selection()
#
    def _selection_changed(self):

        # show the first selected
        lst = self._time_table.selectedIndexes()
        for it in lst:
            r = it.row()
            c = it.column()
            itm = self._time_table.item(r, c)
            cp = itm.checkpoint()
            self._up_info.setText(self._label_up(cp[4], cp[5], cp[6], EventlineInterpreter().core._category_by_tag(eval(cp[3])), cp[7]))
            break

        # Show the connected information
        if len(lst) > 4:
            itm_2 = self._time_table.item(lst[4].row(), lst[4].column())
            cp_2 = itm_2.checkpoint()
            self._down_info.setText(self._label_down(abs(cp.time - cp_2.time)))

        print(list)

    def _set_row_color(self, table, category, row_nr):
        red = QColor(255, 143, 143)
        green = QColor(204, 255, 204)
        blue = QColor(204, 230, 255)

        for c in range(table.columnCount()):
            item = table.item(row_nr, c)

            if category in [CPCategory.ECU_AUTHENTICATION_ENC, CPCategory.ECU_AUTHENTICATION_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, red);

            if category in [CPCategory.STREAM_AUTHORIZATION_ENC, CPCategory.STREAM_AUTHORIZATION_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, green);

            if category in [CPCategory.SIMPLE_MESSAGE_ENC, CPCategory.SIMPLE_MESSAGE_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, blue);

    def _show_selection(self):
        try:
            # Hide all sets
            self._hide_all_rows(self._time_table)

            # No selection made in either of the boxes -> show all
            if self._ecu_1_cb.currentText() == "<< No Selection >>" and self._ecu_2_cb.currentText() == "<< No Selection >>":
                for ky in self._show_sets:
                    self._show_sets[ky].show()
                return

            # one of the boxes has no selection: show other
            if self._ecu_1_cb.currentText() == "<< No Selection >>":
                self._show_sets[self._ecu_2_cb.currentText()].show()
                return
            if self._ecu_2_cb.currentText() == "<< No Selection >>":
                self._show_sets[self._ecu_1_cb.currentText()].show()
                return

            # Show all selected sets / option show only associated
            # If show associated hit: Show only associated
            if self._ass_cb.isChecked():
                self._show_sets[self._ecu_1_cb.currentText()].show_asc(self._ecu_2_cb.currentText())
                self._show_sets[self._ecu_2_cb.currentText()].show_asc(self._ecu_1_cb.currentText())

            # Show both
            else:
                self._show_sets[self._ecu_1_cb.currentText()].show()
                self._show_sets[self._ecu_2_cb.currentText()].show()

        except:
            pass

class TableShowSet(object):

    def __init__(self, table):
        self._rows = []
        self._row_asc = {}  # associates a row to a value
        self._table = table

    def add(self, row_nr, association=False):
        self._rows.append(row_nr)
        if association:
            self._row_asc[row_nr] = association

    def show(self):
        for r in self._rows:
            self._table.setRowHidden(r, False)

    def show_asc(self, asc_id):
        for r in self._rows:
            if r not in self._row_asc.keys(): return
            if self._row_asc[r] != asc_id: return
            self._table.setRowHidden(r, False)

    def hide(self):
        for r in self._rows:
            self._table.setRowHidden(r, True)

class TableCheckpointItem(QTableWidgetItem):

    def __init__(self, *args, **kwargs):
        QTableWidgetItem.__init__(self, *args, **kwargs)

        self._checkpoint = None

    def set_checkpoint(self, cp):
        self._checkpoint = cp

    def checkpoint(self):
        return self._checkpoint


text:
<ion-view>

	<ion-header-bar>

			0"
				class="button button-light"
				ng-click="adminFile()">

	</ion-header-bar>

	<ion-content has-bouncing="false">

0">

	</ion-content>
</ion-view>


text:
package org.dominokit.domino.api.client.mvp.presenter;

import static java.util.Objects.isNull;

import java.util.function.Supplier;

public class PresenterSupplier<P extends Presentable> implements Supplier<P> {

  protected P presenter;
  protected final boolean singleton;
  protected Supplier<P> presenterFactory;

  public PresenterSupplier(boolean singleton, Supplier<P> presenterFactory) {
    this.singleton = singleton;
    this.presenterFactory = presenterFactory;
  }

  @Override
  public P get() {
    if (isNull(presenter) || !singleton) {
      presenter = presenterFactory.get();
      onBeforeInitPresenter();
      presenter.init();
    }
    return presenter;
  }

  protected void onBeforeInitPresenter() {}
}


text:
from skygear.encoding import serialize_record

from .database import Database
from .decorators import (AFTER_CONVERSATION_CREATED_HOOK,
                         AFTER_CONVERSATION_DELETED_HOOK,
                         AFTER_CONVERSATION_UPDATED_HOOK,
                         AFTER_MESSAGE_DELETED_HOOK, AFTER_MESSAGE_SENT_HOOK,
                         AFTER_MESSAGE_UPDATED_HOOK,
                         AFTER_USERS_ADDED_TO_CONVERSATION_HOOK,
                         AFTER_USERS_REMOVED_FROM_CONVERSATION_HOOK,
                         TYPING_STARTED_HOOK)
from .predicate import Predicate
from .query import Query
from .utils import _get_container

def __send_hook(name, params):
    container = _get_container()
    container.send_action(name, {'args': params})

def __get_users_by_user_ids(user_ids):
    container = _get_container()
    database = Database(container, '')
    predicate = Predicate(_id__in=user_ids)
    query = Query('user', predicate=predicate, limit=10000)
    users = database.query(query)
    return [serialize_record(u) for u in users]

def send_after_message_sent_hook(message, conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    __send_hook(AFTER_MESSAGE_SENT_HOOK, {'message': message,
                                          'conversation': conversation,
                                          'participants': participants})

def send_after_message_updated_hook(message, conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    __send_hook(AFTER_MESSAGE_UPDATED_HOOK, {'message': message,
                                             'conversation': conversation,
                                             'participants': participants})

def send_after_message_deleted_hook(message, conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    __send_hook(AFTER_MESSAGE_DELETED_HOOK, {'message': message,
                                             'conversation': conversation,
                                             'participants': participants})

def send_typing_started_hook(conversation, participant_ids, events):
    participants = __get_users_by_user_ids(participant_ids)
    __send_hook(TYPING_STARTED_HOOK, {'conversation': conversation,
                                      'participants': participants,
                                      'events': events})

def send_after_conversation_created_hook(conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    data = {'conversation': conversation, 'participants': participants}
    __send_hook(AFTER_CONVERSATION_CREATED_HOOK, data)

def send_after_conversation_updated_hook(conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    data = {'conversation': conversation, 'participants': participants}
    __send_hook(AFTER_CONVERSATION_UPDATED_HOOK, data)

def send_after_conversation_deleted_hook(conversation, participant_ids):
    participants = __get_users_by_user_ids(participant_ids)
    data = {'conversation': conversation, 'participants': participants}
    __send_hook(AFTER_CONVERSATION_DELETED_HOOK, data)

def send_after_users_added_to_conversation_hook(conversation,
                                                participant_ids,
                                                new_user_ids):

    participants = __get_users_by_user_ids(participant_ids)
    new_users = __get_users_by_user_ids(new_user_ids)
    data = {'conversation': conversation,
            'participants': participants,
            'new_users': new_users}
    __send_hook(AFTER_USERS_ADDED_TO_CONVERSATION_HOOK, data)

def send_after_users_removed_from_conversation_hook(conversation,
                                                    participant_ids,
                                                    old_user_ids):
    participants = __get_users_by_user_ids(participant_ids)
    old_users = __get_users_by_user_ids(old_user_ids)
    data = {'conversation': conversation,
            'participants': participants,
            'old_users': old_users}
    __send_hook(AFTER_USERS_REMOVED_FROM_CONVERSATION_HOOK, data)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
	Copyright 2014 Cullin Moran
	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.
-->

<android.support.wearable.view.BoxInsetLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@drawable/background_wear"
	tools:context=".cgeoWear"
	tools:deviceIds="wear">

	<RelativeLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		app:layout_box="all">

		<RelativeLayout
			android:id="@+id/rl_top_portion"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:background="@color/color_transparent_grey">

			<TextView
				android:id="@+id/textview_geocode"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:layout_marginStart="@dimen/wear_text_margin"/>

			<TextView
				android:id="@+id/textview_distance"
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:layout_alignParentTop="true"
				android:layout_alignParentEnd="true"
				android:layout_marginEnd="@dimen/wear_text_margin"/>

		</RelativeLayout>

		<TextView
			android:id="@+id/textview_cache_name"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:background="@color/color_transparent_grey"
			android:layout_alignParentBottom="true"
			android:gravity="center"
			android:ellipsize="marquee"
			android:scrollHorizontally="true"/>

		<ImageView
			android:id="@+id/compass"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_above="@id/textview_cache_name"
			android:layout_below="@id/rl_top_portion"
			android:paddingTop="@dimen/compass_padding"
			android:paddingBottom="@dimen/compass_padding"
			android:layout_centerInParent="true"
			android:scaleType="centerInside"
			android:src="@drawable/compass"
			android:contentDescription="@string/description_compass"/>

	</RelativeLayout>

</android.support.wearable.view.BoxInsetLayout>


text:
using _02.Extended_Database.Contracts;
using _02.Extended_Database.Entities;
using System;
using System.Reflection;

namespace _02.Extended_Database.Factories
{
    public class CommandFactory
    {
        public IExecutable GetCommand(IDatabase<Person> db, string line, IOutputStore output)
        {
            string[] cmdArgs = line.Split();
            string cmdName = "_02.Extended_Database.Core.Commands." + cmdArgs[0];
            Type cmdType = Type.GetType(cmdName);
            string qualifiedName = cmdType.AssemblyQualifiedName;
            Type cmdQualifiedNameType = Type.GetType(qualifiedName);

            return (IExecutable)Activator.CreateInstance(cmdQualifiedNameType,
                BindingFlags.Instance | BindingFlags.Public, null, new object[] { db, cmdArgs, output }, null);
        }
    }
}


text:
package com.navercorp.pinpoint.plugin.mongo.interceptor;

import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor;
import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
import com.navercorp.pinpoint.bootstrap.context.DatabaseInfo;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
import com.navercorp.pinpoint.bootstrap.plugin.jdbc.MongoDatabaseInfo;
import com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo;
import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils;
import com.navercorp.pinpoint.plugin.mongo.MongoUtil;
import com.navercorp.pinpoint.plugin.mongo.NormalizedBson;

/**
 * @author Roy Kim
 */
public class MongoCUDSessionInterceptor extends SpanEventSimpleAroundInterceptorForPlugin {

    private final boolean collectJson;
    private final boolean traceBsonBindValue;

    public MongoCUDSessionInterceptor(TraceContext traceContext, MethodDescriptor descriptor, boolean collectJson, boolean traceBsonBindValue) {
        super(traceContext, descriptor);
        this.collectJson = collectJson;
        this.traceBsonBindValue = traceBsonBindValue;
    }

    @Override
    protected void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) {

        final DatabaseInfo databaseInfo = DatabaseInfoUtils.getDatabaseInfo(target, UnKnownDatabaseInfo.MONGO_INSTANCE);

        recorder.recordServiceType(databaseInfo.getExecuteQueryType());
        recorder.recordEndPoint(databaseInfo.getMultipleHost());
        recorder.recordDestinationId(databaseInfo.getDatabaseId());

        recorder.recordApi(methodDescriptor);
        MongoUtil.recordMongoCollection(recorder, ((MongoDatabaseInfo) databaseInfo).getCollectionName(), ((MongoDatabaseInfo) databaseInfo).getWriteConcern());
    }

    @Override
    public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
        if (collectJson) {
            final boolean success = InterceptorUtils.isSuccess(throwable);
            if (success) {
                if (args != null) {
                    NormalizedBson parsedBson = MongoUtil.parseBson(args, traceBsonBindValue);
                    MongoUtil.recordParsedBson(recorder, parsedBson);
                }
            }
        }
        recorder.recordException(throwable);

        if (isAsynchronousInvocation(target, args, result, throwable)) {
            // Trace to Disposable object
            final AsyncContext asyncContext = recorder.recordNextAsyncContext();
            ((AsyncContextAccessor) (result))._$PINPOINT$_setAsyncContext(asyncContext);
            if (isDebug) {
                logger.debug("Set AsyncContext {}, result={}", asyncContext, result);
            }
        }
    }

    private boolean isAsynchronousInvocation(final Object target, final Object[] args, Object result, Throwable throwable) {
        if (throwable != null) {
            return false;
        }

        if (!(result instanceof AsyncContextAccessor)) {
            return false;
        }

        return true;
    }
}


text:
// .NAME vtkSmartPointer - Hold a reference to a vtkObjectBase instance.
// .SECTION Description
// vtkSmartPointer is a class template that provides automatic casting
// for objects held by the vtkSmartPointerBase superclass.

#ifndef __vtkSmartPointer_h
#define __vtkSmartPointer_h

#include "vtkCommonCoreExport.h" // For export macro
#include "vtkSmartPointerBase.h"

template <class T>
class vtkSmartPointer: public vtkSmartPointerBase
{
  static T* CheckType(T* t) { return t; }
public:
  // Description:
  // Initialize smart pointer to NULL.
  vtkSmartPointer() {}

  // Description:
  // Initialize smart pointer to given object.
  vtkSmartPointer(T* r): vtkSmartPointerBase(r) {}

  // Description:
  // Initialize smart pointer with a new reference to the same object
  // referenced by given smart pointer.
  template <class U>
  vtkSmartPointer(const vtkSmartPointer<U>& r):
    vtkSmartPointerBase(CheckType(r.GetPointer())) {}

  // Description:
  // Assign object to reference.  This removes any reference to an old
  // object.
  vtkSmartPointer& operator=(T* r)
    {
    this->vtkSmartPointerBase::operator=(r);
    return *this;
    }

  // Description:
  // Assign object to reference.  This removes any reference to an old
  // object.
  template <class U>
  vtkSmartPointer& operator=(const vtkSmartPointer<U>& r)
    {
    this->vtkSmartPointerBase::operator=(CheckType(r.GetPointer()));
    return *this;
    }

  // Description:
  // Get the contained pointer.
  T* GetPointer() const
    {
    return static_cast<T*>(this->Object);
    }

  // Description:
  // Get the contained pointer.
  operator T* () const
    {
    return static_cast<T*>(this->Object);
    }

  // Description:
  // Dereference the pointer and return a reference to the contained
  // object.
  T& operator*() const
    {
    return *static_cast<T*>(this->Object);
    }

  // Description:
  // Provides normal pointer target member access using operator ->.
  T* operator->() const
    {
    return static_cast<T*>(this->Object);
    }

  // Description:
  // Transfer ownership of one reference to the given VTK object to
  // this smart pointer.  This does not increment the reference count
  // of the object, but will decrement it later.  The caller is
  // effectively passing ownership of one reference to the smart
  // pointer.  This is useful for code like:
  //
  //   vtkSmartPointer<vtkFoo> foo;
  //   foo.TakeReference(bar->NewFoo());
  //
  // The input argument may not be another smart pointer.
  void TakeReference(T* t)
    {
    *this = vtkSmartPointer<T>(t, NoReference());
    }

  // Description:
  // Create an instance of a VTK object.
  static vtkSmartPointer<T> New()
    {
    return vtkSmartPointer<T>(T::New(), NoReference());
    }

  // Description:
  // Create a new instance of the given VTK object.
  static vtkSmartPointer<T> NewInstance(T* t)
    {
    return vtkSmartPointer<T>(t->NewInstance(), NoReference());
    }

  // Description:
  // Transfer ownership of one reference to the given VTK object to a
  // new smart pointer.  The returned smart pointer does not increment
  // the reference count of the object on construction but will
  // decrement it on destruction.  The caller is effectively passing
  // ownership of one reference to the smart pointer.  This is useful
  // for code like:
  //
  //   vtkSmartPointer<vtkFoo> foo =
  //     vtkSmartPointer<vtkFoo>::Take(bar->NewFoo());
  //
  // The input argument may not be another smart pointer.
  static vtkSmartPointer<T> Take(T* t)
    {
    return vtkSmartPointer<T>(t, NoReference());
    }

  // Work-around for HP and IBM overload resolution bug.  Since
  // NullPointerOnly is a private type the only pointer value that can
  // be passed by user code is a null pointer.  This operator will be
  // chosen by the compiler when comparing against null explicitly and
  // avoid the bogus ambiguous overload error.
#if defined(__HP_aCC) || defined(__IBMCPP__)
# define VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(op) \
  vtkstd_bool operator op (NullPointerOnly*) const        \
    {                                                     \
    return ::operator op (*this, 0);                      \
    }
private:
  class NullPointerOnly {};
public:
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(==)
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(!=)
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(<)
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(<=)
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(>)
  VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND(>=)
# undef VTK_SMART_POINTER_DEFINE_OPERATOR_WORKAROUND
#endif
protected:
  vtkSmartPointer(T* r, const NoReference& n): vtkSmartPointerBase(r, n) {}
private:
  // These are purposely not implemented to prevent callers from
  // trying to take references from other smart pointers.
  void TakeReference(const vtkSmartPointerBase&);  // Not implemented.
  static void Take(const vtkSmartPointerBase&);  // Not implemented.
};

#define VTK_SMART_POINTER_DEFINE_OPERATOR(op) \
  template <class T> \
  inline vtkstd_bool \
  operator op (const vtkSmartPointer<T>& l, const vtkSmartPointer<T>& r) \
    { \
    return (l.GetPointer() op r.GetPointer()); \
    } \
  template <class T> \
  inline vtkstd_bool operator op (T* l, const vtkSmartPointer<T>& r) \
    { \
    return (l op r.GetPointer()); \
    } \
  template <class T> \
  inline vtkstd_bool operator op (const vtkSmartPointer<T>& l, T* r) \
    { \
    return (l.GetPointer() op r); \
    }
// Description:
// Compare smart pointer values.
VTK_SMART_POINTER_DEFINE_OPERATOR(==)
VTK_SMART_POINTER_DEFINE_OPERATOR(!=)
VTK_SMART_POINTER_DEFINE_OPERATOR(<)
VTK_SMART_POINTER_DEFINE_OPERATOR(<=)
VTK_SMART_POINTER_DEFINE_OPERATOR(>)
VTK_SMART_POINTER_DEFINE_OPERATOR(>=)

#undef VTK_SMART_POINTER_DEFINE_OPERATOR

// Description:
// Streaming operator to print smart pointer like regular pointers.
template <class T>
inline ostream& operator << (ostream& os, const vtkSmartPointer<T>& p)
{
  return os << static_cast<const vtkSmartPointerBase&>(p);
}

#endif


text:
/****************************************************************************
** Meta object code from reading C++ file 'clientmodel.h'
**
** Created: Mon Jun 2 12:59:03 2014
**      by: The Qt Meta Object Compiler version 63 (Qt 4.8.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "../src/qt/clientmodel.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'clientmodel.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_ClientModel[] = {

 // content:
       6,       // revision
       0,       // classname
       0,    0, // classinfo
       7,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       4,       // signalCount

 // signals: signature, parameters, type, tag, flags
      19,   13,   12,   12, 0x05,
      65,   46,   12,   12, 0x05,
     100,   91,   12,   12, 0x05,
     143,  123,   12,   12, 0x05,

 // slots: signature, parameters, type, tag, flags
     173,   12,   12,   12, 0x0a,
     202,  187,   12,   12, 0x0a,
     240,  228,   12,   12, 0x0a,

       0        // eod
};

static const char qt_meta_stringdata_ClientModel[] = {
    "ClientModel\0\0count\0numConnectionsChanged(int)\0"
    "count,countOfPeers\0numBlocksChanged(int,int)\0"
    "warnings\0alertsChanged(QString)\0"
    "title,message,style\0message(QString,QString,uint)\0"
    "updateTimer()\0numConnections\0"
    "updateNumConnections(int)\0hash,status\0"
    "updateAlert(QString,int)\0"
};

void ClientModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        Q_ASSERT(staticMetaObject.cast(_o));
        ClientModel *_t = static_cast<ClientModel *>(_o);
        switch (_id) {
        case 0: _t->numConnectionsChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: _t->numBlocksChanged((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        case 2: _t->alertsChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 3: _t->message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3]))); break;
        case 4: _t->updateTimer(); break;
        case 5: _t->updateNumConnections((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 6: _t->updateAlert((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
        default: ;
        }
    }
}

const QMetaObjectExtraData ClientModel::staticMetaObjectExtraData = {
    0,  qt_static_metacall
};

const QMetaObject ClientModel::staticMetaObject = {
    { &QObject::staticMetaObject, qt_meta_stringdata_ClientModel,
      qt_meta_data_ClientModel, &staticMetaObjectExtraData }
};

#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &ClientModel::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION

const QMetaObject *ClientModel::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}

void *ClientModel::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_ClientModel))
        return static_cast<void*>(const_cast< ClientModel*>(this));
    return QObject::qt_metacast(_clname);
}

int ClientModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 7)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 7;
    }
    return _id;
}

// SIGNAL 0
void ClientModel::numConnectionsChanged(int _t1)
{
    void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 0, _a);
}

// SIGNAL 1
void ClientModel::numBlocksChanged(int _t1, int _t2)
{
    void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
    QMetaObject::activate(this, &staticMetaObject, 1, _a);
}

// SIGNAL 2
void ClientModel::alertsChanged(const QString & _t1)
{
    void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 2, _a);
}

// SIGNAL 3
void ClientModel::message(const QString & _t1, const QString & _t2, unsigned int _t3)
{
    void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
    QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
QT_END_MOC_NAMESPACE


text:
package io.dynamos.web.rest;

import io.dynamos.services.BusinessService;
import io.dynamos.web.rest.util.HeadersUtil;
import io.dynamos.web.rest.util.RestConstants;
import io.dynamos.web.rest.util.exceptions.BusinessRuleException;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.Optional;

/**
 * Created by adelmo.pereira on 05/05/2017.
 */
public abstract class RestResource<T, ID extends Serializable> {

    private BusinessService businessService;

    public RestResource(BusinessService businessService) {
        this.businessService = businessService;
    }

    @PostMapping
    public ResponseEntity create(@RequestBody @Valid T t) throws BusinessRuleException {
        return ResponseEntity.ok().headers(HeadersUtil.successAlert()).body(businessService.save(t));
    }

    @PutMapping
    public ResponseEntity update(@RequestBody @Valid T t) throws BusinessRuleException {
        return ResponseEntity.ok().headers(HeadersUtil.successAlert()).body(businessService.save(t));
    }

    @DeleteMapping("{id}")
    public ResponseEntity delete(@PathVariable ID id) throws BusinessRuleException {
        businessService.delete(id);
        return ResponseEntity.ok().headers(HeadersUtil.successAlert()).build();
    }

    @GetMapping("{id}")
    public ResponseEntity<Object> find(@PathVariable("id") ID identifier) {
        return Optional.ofNullable(businessService.findOne(identifier)).map(ResponseEntity::ok).orElse(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
    }
}


text:
using CodeInBag.ViewModels;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using SimpleInjector;
using System;
using System.ComponentModel.Design;
using System.IO;

namespace CodeInBag.Commands
{
    internal sealed class AddToCodeInBagCommand : BaseCommand
    {
        private readonly Container container;
        private readonly Package package;

        public AddToCodeInBagCommand(Container container, IMenuCommandService commandService, Package package)
        {
            this.package = package;
            this.container = container;

            if (commandService != null)
            {
                var cmdIdForCodeWin = new CommandID(CommandSet, Constant.AddToCodeInBagCodeWinCommandId);
                var cmdForCodeWin = new MenuCommand(AddtoCodeInBagHanlder, cmdIdForCodeWin);

                var cmdIdForXamlEditor = new CommandID(CommandSet, Constant.AddToCodeInBagXamlEditorCommandId);
                var cmdForXamlEditor = new MenuCommand(AddtoCodeInBagHanlder, cmdIdForXamlEditor);

                commandService.AddCommand(cmdForCodeWin);
                commandService.AddCommand(cmdForXamlEditor);
            }
        }

        private IServiceProvider ServiceProvider => this.package;

        private void AddtoCodeInBagHanlder(object sender, EventArgs e)
        {
            var dte = ServiceProvider.GetService(typeof(DTE)) as DTE;
            if (dte.ActiveDocument != null && dte.ActiveDocument.Selection != null)
            {
                var type = CodeType.Other;
                var fileExtension = Path.GetExtension(dte.ActiveDocument.FullName).ToLower();
                switch (fileExtension)
                {
                    case ".cs":
                        type = CodeType.CSharp;
                        break;

                    case ".vb":
                        type = CodeType.VB;
                        break;

                    case ".xaml":
                        type = CodeType.Xaml;
                        break;

                    default:
                        type = CodeType.Other;
                        break;
                }
                var text = dte.ActiveDocument.Selection as TextSelection;
                if (string.IsNullOrWhiteSpace(text.Text))
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider, "No selected text", CodeInBagPackage.Name,
                        Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING,
                         Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_OK,
                          Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                        );
                    return;
                }

                // Activate the tool window before inserting new item to the list
                var toolWindow = this.package.FindToolWindow(typeof(CodeInBagToolWindow), 0, true);

                // https://social.msdn.microsoft.com/Forums/vstudio/en-US/2da1f1b1-e160-4330-b30b-3c1d3c02142b/how-to-force-activation-of-toolwindow?forum=vsx
                dte.Windows.Item(toolWindow.Caption).Activate();

                var mainViewModel = container.GetInstance<MainViewModel>();
                mainViewModel.AllCodeItems.Add(
                    new Models.CodeItem
                    {
                        Title = $"Code added at {DateTime.Now.ToString("yyyy/M/d HH:mm")}",
                        Content = text.Text,
                        Type = type
                    });

                mainViewModel.SaveData();
            }
        }
    }
}


text:
<?php

namespace Highideas\SqlToMigration\Test\Queries\Statements\Columns;

use \PHPUnit_Framework_TestCase;

use Highideas\SqlToMigration\Queries\Statements\Columns\ColumnFactory;

class ColumnFactoryTest extends PHPUnit_Framework_TestCase
{
    public function testInstantiateShouldReturnVarcharColumnObject()
    {
        $class = ColumnFactory::instantiate('`Title` varchar(128) NOT NULL');
        $this->assertInstanceOf(
            'Highideas\SqlToMigration\Queries\Statements\Columns\VarcharColumn',
            $class
        );
    }

    public function testInstantiateShouldReturnIntegerColumnObject()
    {
        $class = ColumnFactory::instantiate('`Rght` INTEGER NOT NULL');
        $this->assertInstanceOf(
            'Highideas\SqlToMigration\Queries\Statements\Columns\IntegerColumn',
            $class
        );
    }

    public function testInstantiateShouldReturnTextColumnObject()
    {
        $class = ColumnFactory::instantiate('`Description` text NOT NULL');
        $this->assertInstanceOf(
            'Highideas\SqlToMigration\Queries\Statements\Columns\TextColumn',
            $class
        );
    }

    /**
     * @expectedException        Highideas\SqlToMigration\Exceptions\InvalidColumnException
     * @expectedExceptionMessage Column Not Found.
     */
    public function testInstantiateShouldReturnInvalidColumnExceptionWhenInvalidParamPassed()
    {
        ColumnFactory::instantiate('integer');
    }

    /**
     * @expectedException        Highideas\SqlToMigration\Exceptions\InvalidColumnException
     * @expectedExceptionMessage Column Not Found.
     */
    public function testInstantiateShouldReturnInvalidColumnExceptionWhenUnknownColumnInformed()
    {
        ColumnFactory::instantiate('`Active` boolean NOT NULL');
    }
}


text:
package tracing

import (
	"github.com/troubling/hummingbird/common/srv"
	"go.uber.org/zap"
)

// TraceLogger is an adapter from LowLevelLogger to jaeger-lib Logger interface.
type TraceLogger struct {
	logger *zap.SugaredLogger
}

// NewLogger creates a new Sugared Logger.
func NewTraceLogger(logger srv.LowLevelLogger) *TraceLogger {
	return &TraceLogger{logger: logger.Sugar()}
}

// Error logs a message at error priority
func (l *TraceLogger) Error(msg string) {
	l.logger.Error(msg)
}

// Infof logs a message at info priority
func (l *TraceLogger) Infof(msg string, args ...interface{}) {
	l.logger.Infof(msg, args...)
}