text:
@interface OCMArg : NSObject

// constraining arguments

+ (id)any;
+ (SEL)anySelector;
+ (void *)anyPointer;
+ (id __autoreleasing *)anyObjectRef;
+ (id)isNil;
+ (id)isNotNil;
+ (id)isNotEqual:(id)value;
+ (id)checkWithSelector:(SEL)selector onObject:(id)anObject;
#if NS_BLOCKS_AVAILABLE
+ (id)checkWithBlock:(BOOL (^)(id obj))block;
#endif

// manipulating arguments

+ (id *)setTo:(id)value;
+ (void *)setToValue:(NSValue *)value;

// internal use only

+ (id)resolveSpecialValues:(NSValue *)value;

@end

#define OCMOCK_ANY [OCMArg any]

#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
  #define OCMOCK_VALUE(variable) \
    ({ __typeof__(variable) __v = (variable); [NSValue value:&__v withObjCType:@encode(__typeof__(__v))]; })
#else
  #define OCMOCK_VALUE(variable) [NSValue value:&variable withObjCType:@encode(__typeof__(variable))]
#endif

redpajama_set_name: RedPajamaGithub


text:
@interface EDStructFormatter : NSObject <EDValueFormatterProtocol>

@end


text:
package com.aparapi.codegen.test;

import org.junit.Test;

public class PostIncLocalStandaloneTest extends com.aparapi.codegen.CodeGenJUnitBase {

    private static final String[] expectedOpenCL = {
        "typedef struct This_s{\n"
        + "\n"
        + " int passid;\n"
        + " }This;\n"
        + " int get_pass_id(This *this){\n"
        + " return this->passid;\n"
        + " }\n"
        + "\n"
        + " __kernel void run(\n"
        + " int passid\n"
        + " ){\n"
        + " This thisStruct;\n"
        + " This* this=&thisStruct;\n"
        + " this->passid = passid;\n"
        + " {\n"
        + " int i = 0;\n"
        + " i++;\n"
        + " return;\n"
        + " }\n"
        + " }\n"
        + " "};
    private static final Class<? extends com.aparapi.internal.exception.AparapiException> expectedException = null;

    @Test
    public void PostIncLocalStandaloneTest() {
        test(com.aparapi.codegen.test.PostIncLocalStandalone.class, expectedException, expectedOpenCL);
    }

    @Test
    public void PostIncLocalStandaloneTestWorksWithCaching() {
        test(com.aparapi.codegen.test.PostIncLocalStandalone.class, expectedException, expectedOpenCL);
    }
}


text:
package com.couchbase.lite.support;

import com.couchbase.lite.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Utility that queues up objects until the queue fills up or a time interval elapses,
 * then passes objects, in groups of its capacity, to a client-supplied processor block.
 */
public class Batcher<T> {

    ///////////////////////////////////////////////////////////////////////////
    // Instance Variables
    ///////////////////////////////////////////////////////////////////////////

    private ScheduledExecutorService workExecutor;

    private int capacity = 0;
    private int delay = 0;
    private List<T> inbox;
    private boolean scheduled = false;
    private int scheduledDelay = 0;
    private BatchProcessor<T> processor;
    private long lastProcessedTime = 0;
    private ScheduledFuture pendingFuture = null;

    ///////////////////////////////////////////////////////////////////////////
    // Constructors
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Initializes a batcher.
     *
     * @param workExecutor the work executor that performs actual work
     * @param capacity     The maximum number of objects to batch up. If the queue reaches this size, the queued objects will be sent to the processor immediately.
     * @param delay        The maximum waiting time in milliseconds to collect objects before processing them. In some circumstances objects will be processed sooner.
     * @param processor    The callback/block that will be called to process the objects.
     */
    public Batcher(ScheduledExecutorService workExecutor,
                   int capacity,
                   int delay,
                   BatchProcessor<T> processor) {
        this.workExecutor = workExecutor;
        this.capacity = capacity;
        this.delay = delay;
        this.processor = processor;
        this.inbox = Collections.synchronizedList(new ArrayList<T>());
        this.scheduled = false;
        this.lastProcessedTime = System.currentTimeMillis();
    }

    ///////////////////////////////////////////////////////////////////////////
    // Instance Methods - Public
    ///////////////////////////////////////////////////////////////////////////

    public int getCapacity() {
        return capacity;
    }

    public int getDelay() {
        return delay;
    }

    /**
     * The number of objects currently in the queue.
     */
    public int count() {
        synchronized (inbox) {
            return inbox.size();
        }
    }

    /**
     * Adds an object to the queue.
     */
    public void queueObject(T object) {
        List<T> objects = Arrays.asList(object);
        queueObjects(objects);
    }

    /**
     * Adds multiple objects to the queue.
     */
    public void queueObjects(List<T> objects) {
        if (objects == null || objects.size() == 0)
            return;

        Log.v(Log.TAG_BATCHER, "%s: queueObjects called with %d objects. Thread: %s", this, objects.size(), Thread.currentThread());

        synchronized (inbox) {
            Log.v(Log.TAG_BATCHER, "%s: inbox size before adding objects: %d", this, inbox.size());
            inbox.addAll(objects);
            inbox.notify();

            if (inbox.size() < capacity) {
                // Schedule the processing. To improve latency, if we haven't processed anything
                // in at least our delay time, rush these object(s) through ASAP:
                int suggestedDelay = delay;
                if (System.currentTimeMillis() - lastProcessedTime >= suggestedDelay)
                    suggestedDelay = 0;
                scheduleWithDelay(suggestedDelay);
            } else {
                // If inbox fills up, process it immediately:
                unschedule();
                processNow();
            }
        }
    }

    /**
     * Sends queued objects to the processor block (up to the capacity).
     */
    public void flush() {
        unschedule();
        processNow();
    }

    /**
     * Sends _all_ the queued objects at once to the processor block.
     * After this method returns, the queue is guaranteed to be empty.
     */
    public void flushAll() {
        synchronized (inbox) {
            while (inbox.size() > 0) {
                unschedule();
                List<T> toProcess = new ArrayList<T>(inbox);
                inbox.clear();
                inbox.notify();
                processor.process(toProcess);
                lastProcessedTime = System.currentTimeMillis();
            }
        }
    }

    /**
     * Empties the queue without processing any of the objects in it.
     */
    public void clear() {
        unschedule();
        inbox.clear();
        inbox.notify();
    }

    public void waitForPendingFutures() {
        Log.v(Log.TAG_BATCHER, "%s: waitForPendingFutures", this);

        // wait till ongoing computation completes
        if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) {
            try {
                pendingFuture.get();
            } catch (Exception e) {
                Log.i(Log.TAG_BATCHER, "Exception from Future.get()");
            }
        }

        // wait inbox becomes empty
        synchronized (inbox) {
            while (!inbox.isEmpty()) {
                try {
                    inbox.wait();
                } catch (InterruptedException e) {
                }
            }
        }

        // wait till ongoing computation completes
        if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled()) {
            try {
                pendingFuture.get();
            } catch (Exception e) {
                Log.i(Log.TAG_BATCHER, "Exception from Future.get()");
            }
        }
        Log.v(Log.TAG_BATCHER, "%s: /waitForPendingFutures", this);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Instance Methods - protected or private
    ///////////////////////////////////////////////////////////////////////////

    private void unschedule() {
        scheduled = false;
        // cancel
        if (pendingFuture != null && !pendingFuture.isDone() && !pendingFuture.isCancelled())
            pendingFuture.cancel(false);
    }

    private void processNow() {
        synchronized (inbox) {
            Log.v(Log.TAG_BATCHER, this + ": processNow() called " + inbox.size());
            scheduled = false;
            List<T> toProcess;
            int count = inbox.size();
            if (count == 0) {
                Log.v(Log.TAG_BATCHER, this + ": processNow() called, but inbox is empty");
                return;
            } else if (count <= capacity) {
                toProcess = new ArrayList<T>(inbox);
                inbox.clear();
                inbox.notify();
            } else {
                toProcess = new ArrayList<T>(inbox.subList(0, capacity));
                for (int i = 0; i < capacity; i++)
                    inbox.remove(0);
                inbox.notify();
                // There are more objects left, so schedule them Real Soon:
                scheduleWithDelay(0);
            }

            if (toProcess != null && toProcess.size() > 0) {
                Log.v(Log.TAG_BATCHER, "%s: invoking processor %s with %d items ", this, processor, toProcess.size());
                processor.process(toProcess);

            } else {
                Log.v(Log.TAG_BATCHER, "%s: nothing to process", this);
            }
            lastProcessedTime = System.currentTimeMillis();
        }
    }

    private void scheduleWithDelay(int delay) {
        Log.v(Log.TAG_BATCHER, "scheduleWithDelay: " + delay + ", scheduled:" + scheduled);
        if (scheduled && delay < scheduledDelay)
            unschedule();
        if (!scheduled) {
            scheduled = true;
            scheduledDelay = delay;
            pendingFuture = workExecutor.schedule(new Runnable() {
                @Override
                public void run() {
                    processNow();
                }
            }, delay, TimeUnit.MILLISECONDS);
        }
    }
}


text:
from __future__ import absolute_import

import os
import re
import textwrap

from fnmatch import fnmatch
from collections import namedtuple, defaultdict

from . import utils

time_map = {
    'hour': 3600,
    'day':  86400,
    'week':    7 * 86400,
    'month':  31 * 86400,
    'year':  366 * 86400,
    'h': 3600,
    'd': 86400,
    'w':   7 * 86400,
    'm':  31 * 86400,
    'y': 366 * 86400.
}

default_colors = {
    'Canvas':        'FFFFFF',

    'FullRed':       'FF0000',
    'FullGreen':     '00E000',
    'FullBlue':      '0000FF',
    'FullYellow':    'F0A000',
    'FullCyan':      '00A0FF',
    'FullMagenta':   'A000FF',

    'HalfRed':       'F7B7B7',
    'HalfGreen':     'B7EFB7',
    'HalfBlue':      'B7B7F7',
    'HalfYellow':    'F3DFB7',
    'HalfCyan':      'B7DFF7',
    'HalfMagenta':   'DFB7F7',

    'HalfBlueGreen': '89B3C9',
}

_Statistic = namedtuple('Statistic', 'path, host, plugin, plugin_instance, type, type_instance')

class Statistic(_Statistic):
    @property
    def title(self):
        if self.plugin_instance:
            fmt = '{self.host}/{self.plugin}-{self.plugin_instance}/{self.type}'
        else:
            fmt = '{self.host}/{self.plugin}/{self.type}'
        return fmt.format(self=self)

def rglob(path, pattern):
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch(name, pattern):
                yield os.path.join(root, name)

def list_datadir(datadir):
    '''Wraps every rrd file in the collectd datadir in a Statistic object.'''

    for path in rglob(datadir, '*.rrd'):
        relpath = os.path.relpath(path, datadir)
        relpath = relpath.replace('.rrd', '')

        host, plugin, p_type = relpath.split('/')
        plugin, _, plugin_instance = plugin.partition('-')
        p_type, _, p_type_instance = p_type.partition('-')

        stat = Statistic(path, host, plugin, plugin_instance, p_type, p_type_instance)
        yield stat

def match_stats(stats, definitions):
    by_plugin = defaultdict(list)
    for stat in stats:
        by_plugin[stat.plugin].append(stat)

    matches = {
        'callable': defaultdict(list),
        'single':   defaultdict(list),
        'stacked':  defaultdict(list),
    }

    for plugin, value in definitions['single'].items():
        if plugin in by_plugin:
            for stat in by_plugin[plugin]:
                yield stat, 'single', value

    for plugin, value in definitions['stacked'].items():
        if plugin in by_plugin:
            stats = by_plugin[plugin]
            yield stats, 'stacked', value

def sanitize_type_instance(name):
    name = re.sub(r'[^A-Za-z0-9\-_]', '_', name)
    return name

def graph_generic_stack(stats, opts):
    rrdargs = []

    if 'title' in opts:
        rrdargs += ['-t', opts['title']]

    if 'rrd_args' in opts:
        rrdargs += opts['rrd_args']

    if 'field_order' in opts:
        stats = utils.ordered(stats, opts['field_order'])

    vname = None
    for n, stat in enumerate(stats):
        vname = str(n) + sanitize_type_instance(stats.type_instance)

        defs = r'''
        DEF:{vname}_min={file}:value:MIN
        DEF:{vname}_avg={file}:value:AVERAGE
        DEF:{vname}_max={file}:value:MAX
        CDEF:{vname}_nnl={vname}_avg,UN,0,{vname}_avg,IF
        '''

        defs = defs.format(vname=vname, file=stat.file)
        defs = textwrap.dedent(defs.strip())
        rrdargs += defs.splitlines()

    cdef = 'CDEF:${vname}_stk=${vname}_nnl'
    rrdargs.append(cdef)

def rrdgraph_cmd(output, imgformat, args, rrdtool='rrdtool'):
    cmd = [rrdtool, 'graph', output, '--imgformat', imgformat]
    cmd.extend(args)
    return cmd


text:
namespace Google.Cloud.Gaming.V1.Snippets
{
    // [START gameservices_v1_generated_RealmsService_GetRealm_async_flattened]
    using Google.Cloud.Gaming.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedRealmsServiceClientSnippets
    {
        /// <summary>Snippet for GetRealmAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetRealmAsync()
        {
            // Create client
            RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
            // Make the request
            Realm response = await realmsServiceClient.GetRealmAsync(name);
        }
    }
    // [END gameservices_v1_generated_RealmsService_GetRealm_async_flattened]
}


text:
MAGE exposes different metrics out of the box.

## Configuration

<aside class="notice">
This is not configured by default by a MAGE bootstrap.
</aside>

> config/default.yaml

```yaml
sampler:
    sampleMage: false
    intervals:
        metrics: 1000 # Sampling time window, in milliseconds
```

There are essentially two configuration elements which you can set
in your configuration:

  * **sampleMage**: activate or deactivate MAGE's internal metrics
  * **intervals**: define endpoint(s) where to expose the metrics.

Depending on your needs, you may wish to configure multiple endpoints, but
in many cases, one will suffice.

## Accessing metrics

> Query sampler

```shell
curl http://localhost:8080/savvy/sampler/metrics
```

```powershell
 Invoke-RestMethod -Method Get -Uri "http://localhost:8080/savvy/sampler/metrics"
```

> Response

```json
{
  "id": 0,
  "name": "metrics",
  "interval": 1,
  "data": {}
}
```

Unless you turn `sampleMage` to true (and you really should!), the amount
of data that will be returned will be minimal.

However, when turning `sampleMage` on, you will be able to see things such as number
of state errors, mean latency per user command, and so on.

## Adding custom metrics

> lib/modules/players/usercommands/countClicks.js

```javascript
var mage = require('mage');
var sampler = mage.core.sampler;

exports.acl = ['*']

exports.execute = function (state, callback) {
	sampler.inc(['players', 'clicks'], 'count', 1);
	callback();
};
```

> Trigger clicks

```shell
curl -X POST http://127.0.0.1:8080/game/players.countClicks \
--data-binary @- << EOF
[]
{}
EOF
```

```powershell
 Invoke-RestMethod -Method Post -Uri "http://127.0.0.1:8080/game/players.countClicks" -Body '[]
{}'
```

> New sampler output

```plaintext
[...]
  "data": {
    "players": {
      "clicks": {
        "count": {
          "type": "inc",
          "values": {
            "1": {
              "val": 4,
              "timeStamp": 1491400000000
[...]
```

Here we can see a full example of how we can create our own custom metrics and then
access them.

Sampler values are defined on-the-fly; therefore, you must be careful when
choosing a sampler key for your metrics, so to avoid overlaps.

See [the sampler API documentation](./api/interfaces/_mage_d_.imagecore.html#sampler) for more documentation.


text:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class ExperimentConfiguration(Base):
    """
    Definition of ExperimentConfiguration object. It will be used by SQLAlchemy's ORM to map the object to
    the experiment_configuration table.
    Methods:
        setFromData(data) - sets all data fields
    """
    __tablename__ = 'experiment_configuration'
    id = Column('id',Integer, primary_key=True)
    experiment_id = Column('experiment_id',Integer)
    parameter_name = Column('parameter_name',String)
    parameter_value = Column('parameter_value',String)
    keyCol = 'id'
    editCols = ['parameter_name', 'parameter_value']
    editColsLabels = ['Parameter Name', 'Parameter Value']
    editColsTypes = ['string', 'string']
    displayTableName = 'Experiment Configuration'

    def setFromData(self,data):
        """
        Sets all of the object fields
        Arguments:
            data - Dictionary containing the data
        """
        # self.id = data['id']
        self.experiment_id = data['experiment_id']
        self.parameter_name = data['parameter_name']
        self.parameter_value = data['parameter_value']

    def __json__(self, request):
        return {'id':self.id, 'experiment_id':self.experiment_id, 'parameter_name':self.parameter_name, 'parameter_value':self.parameter_value }

    def __repr__(self):
        return "<Algorithm(id='%d', experiment_id='%s', parameter_name='%s', parameter_value='%s')>" % (self.id, self.experiment_id, self.parameter_name, self.parameter_value)


text:
package entities.vehicles.motor.ship_entities;

import javax.persistence.*;
import java.math.BigDecimal;

@Entity
@Table(name = "cruise_ships")
@DiscriminatorValue(value = "cruise")
public class CruiseShip extends Ship{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "passengers_capactiy")
    private Integer passengersCapacity;

    public CruiseShip(Integer enginesCount, Double tankCapacity, String manufacturer, String model, BigDecimal price,
                      Double maxSpeed, String nation, String captainName, Integer crewCount, Integer passengersCapacity) {
        super(enginesCount, tankCapacity, manufacturer, model, price, maxSpeed, nation, captainName, crewCount);
        this.passengersCapacity = passengersCapacity;
    }

    public CruiseShip(){
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    public Integer getPassengersCapacity() {
        return passengersCapacity;
    }

    public void setPassengersCapacity(Integer passengersCapacity) {
        this.passengersCapacity = passengersCapacity;
    }
}


text:
/**
* Benchmark `is_allowed_data_type_cast`.
*/
#include "stdlib/ndarray/base/assert/is_allowed_data_type_cast.h"
#include "stdlib/ndarray/casting_modes.h"
#include "stdlib/ndarray/dtypes.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>

#define NAME "is-allowed-data-type-cast"
#define ITERATIONS 1000000
#define REPEATS 3

/**
* Prints the TAP version.
*/
void print_version() {
	printf( "TAP version 13\n" );
}

/**
* Prints the TAP summary.
*
* @param total     total number of tests
* @param passing   total number of passing tests
*/
void print_summary( int total, int passing ) {
	printf( "#\n" );
	printf( "1..%d\n", total ); // TAP plan
	printf( "# total %d\n", total );
	printf( "# pass  %d\n", passing );
	printf( "#\n" );
	printf( "# ok\n" );
}

/**
* Prints benchmarks results.
*
* @param elapsed   elapsed time in seconds
*/
void print_results( double elapsed ) {
	double rate = (double)ITERATIONS / elapsed;
	printf( "  ---\n" );
	printf( "  iterations: %d\n", ITERATIONS );
	printf( "  elapsed: %0.9f\n", elapsed );
	printf( "  rate: %0.9f\n", rate );
	printf( "  ...\n" );
}

/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
	struct timeval now;
	gettimeofday( &now, NULL );
	return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}

/**
* Generates a random double on the interval [0,1].
*
* @return random double
*/
double rand_double() {
	int r = rand();
	return (double)r / ( (double)RAND_MAX + 1.0 );
}

/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
	double elapsed;
	int8_t b;
	double t;
	int i;

	t = tic();
	for ( i = 0; i < ITERATIONS; i++ ) {
		b = stdlib_ndarray_is_allowed_data_type_cast( i%STDLIB_NDARRAY_NDTYPES, (i%STDLIB_NDARRAY_NDTYPES)+1, STDLIB_NDARRAY_SAME_KIND_CASTING );
		if ( b != 0 && b!= 1 ) {
			printf( "unexpected result\n" );
			break;
		}
	}
	elapsed = tic() - t;
	if ( b != 0 && b != 1 ) {
		printf( "unexpected result\n" );
	}
	return elapsed;
}

/**
* Main execution sequence.
*/
int main( void ) {
	double elapsed;
	int i;

	// Use the current time to seed the random number generator:
	srand( time( NULL ) );

	print_version();
	for ( i = 0; i < REPEATS; i++ ) {
		printf( "# c::native::%s\n", NAME );
		elapsed = benchmark();
		print_results( elapsed );
		printf( "ok %d benchmark finished\n", i+1 );
	}
	print_summary( REPEATS, REPEATS );
}


text:
package lib

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	_ "github.com/cznic/ql/driver"
)

type Server struct {
	UUID      string    `json:"uuid"`
	Path      string    `json:"path"`
	Source    string    `json:"source"`
	CreatedAt time.Time `json:"created_at"`
	ListIps   []string  `json:"list_ips"`
	Flags     []string  `json:"flags"`
}

var settings *SettingsShare

func OpenDatabase() (*sql.DB, error) {
	destDb, err := sql.Open("ql", settings.ShareDaemon.DatabaseFilePath)
	if err != nil {
		return nil, err
	}
	destDb.Ping()

	return destDb, nil
}

func InitDB(settings_params SettingsShare) error {
	settings = &settings_params
	err2 := CreateTable()
	if err2 != nil {
		return err2
	}

	return nil
}

func CreateTable() error {
	// create table if not exists
	sql_table := `
	CREATE TABLE IF NOT EXISTS Servers(
		UUID string,
		Path string,
		Source string,
		Flags string,
		CreatedAt time
	);
	`

	destDb, err := OpenDatabase()
	if err != nil {
		return err
	}

	defer destDb.Close()

	tx, err := destDb.Begin()
	if err != nil {
		return err
	}

	if _, err = tx.Exec(sql_table); err != nil {
		return err
	}

	if err = tx.Commit(); err != nil {
		return err
	}

	return nil
}

func StoreServer(server Server) error {
	sqlAdd := `
	INSERT INTO Servers(
		UUID,
		Path,
		Source,
		Flags,
		CreatedAt,
	) values($1, $2, $3, $4, $5)
	`

	destDb, err := OpenDatabase()
	if err != nil {
		return err
	}
	defer destDb.Close()

	tx, err := destDb.Begin()
	if err != nil {
		return err
	}

	stmt, err := tx.Prepare(sqlAdd)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(server.UUID, server.Path, server.Source, strings.Join(server.Flags, "||"), server.CreatedAt)
	if err != nil {
		return err
	}

	if err = tx.Commit(); err != nil {
		return err
	}

	return nil
}

func FindServer(uuid string) (Server, error) {
	return Server{}, nil
}

func RemoveServer(uuid string) error {
	sqlRemove := `
	delete from Servers where
	UUID == $1
	`

	if _, err := FindServer(uuid); err != nil {
		return err
	}

	destDb, err := OpenDatabase()
	if err != nil {
		return err
	}
	defer destDb.Close()

	tx, err := destDb.Begin()
	if err != nil {
		return err
	}

	stmt, err := tx.Prepare(sqlRemove)
	if err != nil {
		return err
	}
	defer stmt.Close()

	if _, err = stmt.Exec(uuid); err != nil {
		return err
	}

	if err = tx.Commit(); err != nil {
		return err
	}

	return nil
}

func ListServers() ([]Server, error) {
	var results []Server

	sqlSelect := `
	select UUID, Path, Source, Flags, CreatedAt from Servers order by CreatedAt
	`

	destDb, err := OpenDatabase()
	if err != nil {
		return results, err
	}
	defer destDb.Close()

	rows, err := destDb.Query(sqlSelect)
	if err != nil {
		return results, err
	}

	for rows.Next() {
		item := Server{}
		listFlags := ""
		if err = rows.Scan(&item.UUID, &item.Path, &item.Source, &listFlags, &item.CreatedAt); err == nil {
			item.Flags = strings.Split(listFlags, "||")
			results = append(results, item)
		}
	}

	return results, nil
}

func SearchServerByUUID(uuid string) (Server, error) {
	servers, err := ListServers()

	if err != nil {
		return Server{}, err
	}

	for _, server := range servers {
		if server.UUID == uuid {
			return server, nil
		}
	}

	return Server{}, fmt.Errorf("Server not found with UUID: %s", uuid)
}

func SearchServerByPath(path string) (Server, error) {
	servers, err := ListServers()

	if err != nil {
		return Server{}, err
	}

	for _, server := range servers {
		if server.Path == path {
			return server, nil
		}
	}

	return Server{}, fmt.Errorf("Server not found with path: %s", path)
}


text:
using Microsoft.Xunit.Performance;
using Xunit;

namespace System.Memory.Tests
{
    public class Perf_Span_IndexOf
    {
        private const int InnerCount = 100000;

        [Benchmark(InnerIterationCount = InnerCount)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public void SpanIndexOfChar(int size)
        {
            Span<char> charSpan = new char[size];
            charSpan[size/2] = '5';

            int index = 0;
            foreach (BenchmarkIteration iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    for (int i = 0; i < Benchmark.InnerIterationCount; i++)
                    {
                        index |= charSpan.IndexOf('5');
                    }
                }
            }
            Assert.Equal(size/2, index);
        }

        [Benchmark(InnerIterationCount = InnerCount)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public void SpanIndexOfCharAsBytes(int size)
        {
            Span<char> charSpan = new char[size];
            charSpan[size/2] = '5';
            Span<byte> byteSpan = charSpan.AsBytes();

            int index = 0;
            foreach (BenchmarkIteration iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    for (int i = 0; i < Benchmark.InnerIterationCount; i++)
                    {
                        index |= byteSpan.IndexOf<byte>(53);        // '5' = 53
                    }
                }
            }
            Assert.Equal(size > 1 ? size : 0, index);
        }

        [Benchmark(InnerIterationCount = InnerCount)]
        [InlineData(1)]
        [InlineData(10)]
        [InlineData(100)]
        [InlineData(1000)]
        public void StringIndexOfChar(int size)
        {
            string str = new string('0', size/2) + "5";
            if (size > 1)
            {
                str += new string('0', size/2 - 1);
            }

            int index = 0;
            foreach (BenchmarkIteration iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    for (int i = 0; i < Benchmark.InnerIterationCount; i++)
                    {
                        index |= str.IndexOf('5');
                    }
                }
            }
            Assert.Equal(size/2, index);
        }
    }
}


text:
namespace ShortBus
{
    public interface IRequest<TResponseData> {}
}


text:
<?php

namespace VehiculosBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * TipoFactura
 *
 * @ORM\Table(name="tipo_factura")
 * @ORM\Entity
 */
class TipoFactura
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="tipo", type="string", length=255)
     */
    private $tipo;

    /**
     * @var string
     *
     * @ORM\Column(name="descripcion", type="string", length=255)
     */
    private $descripcion;

    /**
     * @var datetime $creado
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="creado", type="datetime")
     */
    private $creado;

    /**
     * @var datetime $actualizado
     *
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(name="actualizado",type="datetime")
     */
    private $actualizado;

    /**
     * @var integer $creadoPor
     *
     * @Gedmo\Blameable(on="create")
     * @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
     * @ORM\JoinColumn(name="creado_por", referencedColumnName="id", nullable=true)
     */
    private $creadoPor;

    /**
     * @var integer $actualizadoPor
     *
     * @Gedmo\Blameable(on="update")
     * @ORM\ManyToOne(targetEntity="UsuariosBundle\Entity\Usuario")
     * @ORM\JoinColumn(name="actualizado_por", referencedColumnName="id", nullable=true)
     */
    private $actualizadoPor;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set tipo
     *
     * @param string $tipo
     *
     * @return TipoFactura
     */
    public function setTipo($tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return string
     */
    public function getTipo()
    {
        return $this->tipo;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     *
     * @return TipoFactura
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set creado
     *
     * @param \DateTime $creado
     *
     * @return TipoFactura
     */
    public function setCreado($creado)
    {
        $this->creado = $creado;

        return $this;
    }

    /**
     * Get creado
     *
     * @return \DateTime
     */
    public function getCreado()
    {
        return $this->creado;
    }

    /**
     * Set actualizado
     *
     * @param \DateTime $actualizado
     *
     * @return TipoFactura
     */
    public function setActualizado($actualizado)
    {
        $this->actualizado = $actualizado;

        return $this;
    }

    /**
     * Get actualizado
     *
     * @return \DateTime
     */
    public function getActualizado()
    {
        return $this->actualizado;
    }

    /**
     * Set creadoPor
     *
     * @param \UsuariosBundle\Entity\Usuario $creadoPor
     *
     * @return TipoFactura
     */
    public function setCreadoPor(\UsuariosBundle\Entity\Usuario $creadoPor = null)
    {
        $this->creadoPor = $creadoPor;

        return $this;
    }

    /**
     * Get creadoPor
     *
     * @return \UsuariosBundle\Entity\Usuario
     */
    public function getCreadoPor()
    {
        return $this->creadoPor;
    }

    /**
     * Set actualizadoPor
     *
     * @param \UsuariosBundle\Entity\Usuario $actualizadoPor
     *
     * @return TipoFactura
     */
    public function setActualizadoPor(\UsuariosBundle\Entity\Usuario $actualizadoPor = null)
    {
        $this->actualizadoPor = $actualizadoPor;

        return $this;
    }

    /**
     * Get actualizadoPor
     *
     * @return \UsuariosBundle\Entity\Usuario
     */
    public function getActualizadoPor()
    {
        return $this->actualizadoPor;
    }

    public function __toString() {
        return $this->tipo;
    }
}


text:
// @flow
/* eslint-env mocha */
/* global suite, benchmark */

import getQuarter from '.'
import moment from 'moment'

suite('getQuarter', function () {
  benchmark('date-fns', function () {
    return getQuarter(this.date)
  })

  benchmark('Moment.js', function () {
    return this.moment.quarter()
  })
}, {
  setup: function () {
    this.date = new Date()
    this.moment = moment()
  }
})


text:
#ifndef __TBB_concurrent_skip_list_H
#define __TBB_concurrent_skip_list_H

#if !defined(__TBB_concurrent_map_H) && !defined(__TBB_concurrent_set_H)
#error Do not #include this internal file directly; use public TBB headers instead.
#endif

#include "../tbb_config.h"
#include "../tbb_stddef.h"
#include "../tbb_allocator.h"
#include "../spin_mutex.h"
#include "../tbb_exception.h"
#include "../enumerable_thread_specific.h"
#include "_allocator_traits.h"
#include "_template_helpers.h"
#include "_node_handle_impl.h"
#include <utility> // Need std::pair
#include <functional>
#include <initializer_list>
#include <memory> // Need std::allocator_traits
#include <atomic>
#include <mutex>
#include <vector>
#include <array>
#include <type_traits>
#include <cstdlib>
#include <random>
#include <tuple>

#if _MSC_VER
#pragma warning(disable: 4189) // warning 4189 -- local variable is initialized but not referenced
#pragma warning(disable: 4127) // warning 4127 -- while (true) has a constant expression in it
#endif

namespace tbb {
namespace interface10 {
namespace internal {

template <typename Value, typename Mutex>
class skip_list_node {

public:
    using value_type = Value;
    using size_type = std::size_t;
    using reference = value_type & ;
    using const_reference = const value_type & ;
    using pointer = value_type * ;
    using const_pointer = const value_type *;
    using node_pointer = skip_list_node * ;
    using atomic_node_pointer = std::atomic<node_pointer>;

    using mutex_type = Mutex;
    using lock_type = std::unique_lock<mutex_type>;

    skip_list_node(size_type levels) : my_height(levels), my_fullyLinked(false) {
        for (size_type lev = 0; lev < my_height; ++lev)
            new(&my_next(lev)) atomic_node_pointer(nullptr);
        __TBB_ASSERT(height() == levels, "Wrong node height");
    }

    ~skip_list_node() {
        for(size_type lev = 0; lev < my_height; ++lev)
            my_next(lev).~atomic();
    }

    skip_list_node(const skip_list_node&) = delete;

    skip_list_node(skip_list_node&&) = delete;

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

    pointer storage() {
        return reinterpret_cast<pointer>(&my_val);
    }

    reference value() {
        return *storage();
    }

    node_pointer next(size_type level) const {
        __TBB_ASSERT(level < height(), "Cannot get next on the level greater than height");
        return my_next(level).load(std::memory_order_acquire);
    }

    void set_next(size_type level, node_pointer next) {
        __TBB_ASSERT(level < height(), "Cannot set next on the level greater than height");

        my_next(level).store(next, std::memory_order_release);
    }

    /** @return number of layers */
    size_type height() const {
        return my_height;
    }

    bool fully_linked() const {
        return my_fullyLinked.load(std::memory_order_acquire);
    }

    void mark_linked() {
        my_fullyLinked.store(true, std::memory_order_release);
    }

    lock_type acquire() {
        return lock_type(my_mutex);
    }

private:
    using aligned_storage_type = typename std::aligned_storage<sizeof(value_type), alignof(value_type)>::type;

    atomic_node_pointer& my_next(size_type level) {
        atomic_node_pointer* arr = reinterpret_cast<atomic_node_pointer*>(this + 1);
        return arr[level];
    }

    const atomic_node_pointer& my_next(size_type level) const {
        const atomic_node_pointer* arr = reinterpret_cast<const atomic_node_pointer*>(this + 1);
        return arr[level];
    }

    mutex_type my_mutex;
    aligned_storage_type my_val;
    size_type my_height;
    std::atomic_bool my_fullyLinked;
};

template <typename NodeType, bool is_const>
class skip_list_iterator {
    using node_type = NodeType;
    using node_ptr = node_type*;
public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = typename node_type::value_type;
    using difference_type = std::ptrdiff_t;
    using pointer = typename std::conditional<is_const, typename node_type::const_pointer,
                                                        typename node_type::pointer>::type;
    using reference = typename std::conditional<is_const, typename node_type::const_reference,
                                                          typename node_type::reference>::type;

    skip_list_iterator() : my_node_ptr(nullptr) {}

    // TODO: the code above does not compile in VS2015 (seems like a bug) - consider enabling it for all other platforms
    // template <typename T = void, typename = typename std::enable_if<is_const, T>::type>
    // skip_list_iterator(const skip_list_iterator<node_type, false>& other) : my_node_ptr(other.my_node_ptr) {}

    // skip_list_iterator(const skip_list_iterator& other) : my_node_ptr(other.my_node_ptr) {}

    skip_list_iterator(const skip_list_iterator<node_type, false>& other) : my_node_ptr(other.my_node_ptr) {}

    skip_list_iterator& operator=(const skip_list_iterator<node_type, false>& other) {
         my_node_ptr = other.my_node_ptr;
         return *this;
    }

    template <typename T = void, typename = typename std::enable_if<is_const, T>::type>
    skip_list_iterator(const skip_list_iterator<node_type, true>& other) : my_node_ptr(other.my_node_ptr) {}

    reference operator*() const { return *(my_node_ptr->storage()); }
    pointer operator->() const { return &**this; }

    skip_list_iterator& operator++() {
        __TBB_ASSERT(my_node_ptr != nullptr, NULL);
        my_node_ptr = my_node_ptr->next(0);
        return *this;
    }

    skip_list_iterator operator++(int) {
        skip_list_iterator tmp = *this;
        ++*this;
        return tmp;
    }

private:
    skip_list_iterator(node_type* n) : my_node_ptr(n) {}

    node_ptr my_node_ptr;

    template <typename Traits>
    friend class concurrent_skip_list;

    friend class skip_list_iterator<NodeType, true>;

    friend class const_range;
    friend class range;

    template <typename T, bool M, bool U>
    friend bool operator==(const skip_list_iterator<T, M>&, const skip_list_iterator<T, U>&);

    template <typename T, bool M, bool U>
    friend bool operator!=(const skip_list_iterator<T, M>&, const skip_list_iterator<T, U>&);
};

template <typename NodeType, bool is_const1, bool is_const2>
bool operator==(const skip_list_iterator<NodeType, is_const1>& lhs, const skip_list_iterator<NodeType, is_const2>& rhs) {
    return lhs.my_node_ptr == rhs.my_node_ptr;
}

template <typename NodeType, bool is_const1, bool is_const2>
bool operator!=(const skip_list_iterator<NodeType, is_const1>& lhs, const skip_list_iterator<NodeType, is_const2>& rhs) {
    return lhs.my_node_ptr != rhs.my_node_ptr;
}

template <typename Traits>
class concurrent_skip_list {
protected:
    using traits_type = Traits;
    using allocator_type = typename traits_type::allocator_type;
    using allocator_traits_type = std::allocator_traits<allocator_type>;
    using key_compare = typename traits_type::compare_type;
    using value_compare = typename traits_type::value_compare;
    using key_type = typename traits_type::key_type;
    using value_type = typename traits_type::value_type;
    using node_type = typename traits_type::node_type;
    using list_node_type = skip_list_node<value_type, typename traits_type::mutex_type>;

    using iterator = skip_list_iterator<list_node_type, /*is_const=*/false>;
    using const_iterator = skip_list_iterator<list_node_type, /*is_const=*/true>;
    using reverse_iterator = std::reverse_iterator<iterator>;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;

    using reference = value_type&;
    using const_reference = const value_type&;
    using pointer = typename allocator_traits_type::pointer;
    using const_pointer = typename allocator_traits_type::const_pointer;
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;

    using random_level_generator_type = typename traits_type::random_level_generator_type;
    using node_allocator_type = typename std::allocator_traits<allocator_type>::template rebind_alloc<uint8_t>;
    using node_allocator_traits = typename std::allocator_traits<allocator_type>::template rebind_traits<uint8_t>;
    using node_ptr = list_node_type*;

    static constexpr size_type MAX_LEVEL = traits_type::MAX_LEVEL;

    using array_type = std::array<node_ptr, MAX_LEVEL>;
    using lock_array = std::array<typename list_node_type::lock_type, MAX_LEVEL>;

public:
    static bool const allow_multimapping = traits_type::allow_multimapping;

    /**
     * Default constructor. Construct empty skip list.
     */
    concurrent_skip_list() : my_size(0) {
        create_dummy_head();
    }

    explicit concurrent_skip_list(const key_compare& comp, const allocator_type& alloc = allocator_type())
        : my_node_allocator(alloc), my_compare(comp), my_size(0)
    {
        create_dummy_head();
    }

    template<class InputIt>
    concurrent_skip_list(InputIt first, InputIt last, const key_compare& comp = key_compare(),
                         const allocator_type& alloc = allocator_type())
        : my_node_allocator(alloc), my_compare(comp), my_size(0)
    {
        create_dummy_head();
        internal_copy(first, last);
    }

    /** Copy constructor */
    concurrent_skip_list(const concurrent_skip_list& other)
        : my_node_allocator(node_allocator_traits::select_on_container_copy_construction(other.get_allocator())),
          my_compare(other.my_compare), my_rnd_generator(other.my_rnd_generator), my_size(0)
    {
        create_dummy_head();
        internal_copy(other);
        __TBB_ASSERT(my_size == other.my_size, "Wrong size of copy-constructed container");
    }

    concurrent_skip_list(const concurrent_skip_list& other, const allocator_type& alloc)
        : my_node_allocator(alloc), my_compare(other.my_compare),
          my_rnd_generator(other.my_rnd_generator), my_size(0)
    {
        create_dummy_head();
        internal_copy(other);
        __TBB_ASSERT(my_size == other.my_size, "Wrong size of copy-constructed container");
    }

    concurrent_skip_list(concurrent_skip_list&& other)
        : my_node_allocator(std::move(other.my_node_allocator)), my_compare(other.my_compare),
          my_rnd_generator(other.my_rnd_generator)
    {
        internal_move(std::move(other));
    }

    concurrent_skip_list(concurrent_skip_list&& other, const allocator_type& alloc)
        : my_node_allocator(alloc), my_compare(other.my_compare),
          my_rnd_generator(other.my_rnd_generator)
    {
        if (alloc == other.get_allocator()) {
            internal_move(std::move(other));
        } else {
            my_size = 0;
            create_dummy_head();
            internal_copy(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()));
        }
    }

    ~concurrent_skip_list() {
        clear();
        delete_dummy_head();
    }

    concurrent_skip_list& operator=(const concurrent_skip_list& other) {
        if (this != &other) {
            using pocca_type = typename node_allocator_traits::propagate_on_container_copy_assignment;
            clear();
            tbb::internal::allocator_copy_assignment(my_node_allocator, other.my_node_allocator, pocca_type());
            my_compare = other.my_compare;
            my_rnd_generator = other.my_rnd_generator;
            internal_copy(other);
        }
        return *this;
    }

    concurrent_skip_list& operator=(concurrent_skip_list&& other) {
        if (this != &other) {
            using pocma_type = typename node_allocator_traits::propagate_on_container_move_assignment;
            clear();
            my_compare = other.my_compare;
            my_rnd_generator = other.my_rnd_generator;
            internal_move_assign(std::move(other), pocma_type());
        }
        return *this;
    }

    concurrent_skip_list& operator=(std::initializer_list<value_type> il)
    {
        clear();
        insert(il.begin(),il.end());
        return *this;
    }

    std::pair<iterator, bool> insert(const value_type& value) {
        return internal_insert(value);
    }

    std::pair<iterator, bool> insert(value_type&& value) {
        return internal_insert(std::move(value));
    }

    iterator insert(const_iterator, const_reference value) {
        // Ignore hint
        return insert(value).first;
    }

    iterator insert(const_iterator, value_type&& value) {
        // Ignore hint
        return insert(std::move(value)).first;
    }

    template<typename InputIterator>
    void insert(InputIterator first, InputIterator last) {
        for (InputIterator it = first; it != last; ++it)
            insert(*it);
    }

    void insert(std::initializer_list<value_type> init) {
        insert(init.begin(), init.end());
    }

    std::pair<iterator, bool> insert(node_type&& nh) {
        if(!nh.empty()) {
            std::pair<iterator, bool> insert_result = internal_insert_node(nh.my_node);
            if(insert_result.second) {
                nh.deactivate();
            }
            return insert_result;
        }
        return std::pair<iterator, bool>(end(), false);
    }

    iterator insert(const_iterator, node_type&& nh) {
        // Ignore hint
        return insert(std::move(nh)).first;
    }

    template<typename... Args >
    std::pair<iterator, bool> emplace(Args&&... args) {
        return internal_insert(std::forward<Args>(args)...);
    }

    template<typename... Args>
    iterator emplace_hint(const_iterator, Args&&... args) {
        // Ignore hint
        return emplace(std::forward<Args>(args)...).first;
    }

    iterator unsafe_erase(iterator pos) {
        std::pair<node_ptr, node_ptr> extract_result = internal_extract(pos);
        if(extract_result.first) { // node was extracted
            delete_node(extract_result.first);
            return iterator(extract_result.second);
        }
        return end();
    }

    iterator unsafe_erase(const_iterator pos) {
        return unsafe_erase(get_iterator(pos));
    }

    template <typename K, typename = tbb::internal::is_transparent<key_compare, K>,
                          typename = typename std::enable_if<!std::is_convertible<K, iterator>::value &&
                                                             !std::is_convertible<K, const_iterator>::value>::type>
    size_type unsafe_erase(const K& key) {
        std::pair<iterator, iterator> range = equal_range(key);
        size_type sz = std::distance(range.first, range.second);
        unsafe_erase(range.first, range.second);
        return sz;
    }

    iterator unsafe_erase(const_iterator first, const_iterator last) {
        while(first != last) {
            first = unsafe_erase(get_iterator(first));
        }
        return get_iterator(first);
    }

    size_type unsafe_erase(const key_type& key) {
        std::pair<iterator, iterator> range = equal_range(key);
        size_type sz = std::distance(range.first, range.second);
        unsafe_erase(range.first, range.second);
        return sz;
    }

    node_type unsafe_extract(const_iterator pos) {
        std::pair<node_ptr, node_ptr> extract_result = internal_extract(pos);
        return extract_result.first ? node_type(extract_result.first) : node_type();
    }

    node_type unsafe_extract(const key_type& key) {
        return unsafe_extract(find(key));
    }

    iterator lower_bound(const key_type& key) {
        return internal_get_bound(key, my_compare);
    }

    const_iterator lower_bound(const key_type& key) const {
        return internal_get_bound(key, my_compare);
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    iterator lower_bound(const K& key) {
        return internal_get_bound(key, my_compare);
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    const_iterator lower_bound(const K& key) const {
        return internal_get_bound(key, my_compare);
    }

    iterator upper_bound(const key_type& key) {
        return internal_get_bound(key, not_greater_compare(my_compare));
    }

    const_iterator upper_bound(const key_type& key) const {
        return internal_get_bound(key, not_greater_compare(my_compare));
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    iterator upper_bound(const K& key) {
        return internal_get_bound(key, not_greater_compare(my_compare));
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    const_iterator upper_bound(const K& key) const {
        return internal_get_bound(key, not_greater_compare(my_compare));
    }

    iterator find(const key_type& key) {
        return internal_find(key);
    }

    const_iterator find(const key_type& key) const {
        return internal_find(key);
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    iterator find(const K& key) {
        return internal_find(key);
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    const_iterator find(const K& key) const {
        return internal_find(key);
    }

    size_type count( const key_type& key ) const {
        return internal_count(key);
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    size_type count(const K& key) const {
        return internal_count(key);
    }

    bool contains(const key_type& key) const {
        return find(key) != end();
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    bool contains(const K& key) const {
        return find(key) != end();
    }

    void clear() noexcept {
        __TBB_ASSERT(dummy_head->height() > 0, NULL);

        node_ptr current = dummy_head->next(0);
        while (current) {
            __TBB_ASSERT(current->height() > 0, NULL);
            node_ptr next = current->next(0);
            delete_node(current);
            current = next;
        }

        my_size = 0;
        for (size_type i = 0; i < dummy_head->height(); ++i) {
            dummy_head->set_next(i, nullptr);
        }
    }

    iterator begin() {
        return iterator(dummy_head->next(0));
    }

    const_iterator begin() const {
        return const_iterator(dummy_head->next(0));
    }

    const_iterator cbegin() const {
        return const_iterator(dummy_head->next(0));
    }

    iterator end() {
        return iterator(nullptr);
    }

    const_iterator end() const {
        return const_iterator(nullptr);
    }

    const_iterator cend() const {
        return const_iterator(nullptr);
    }

    size_type size() const {
        return my_size.load(std::memory_order_relaxed);
    }

    size_type max_size() const {
        return my_node_allocator.max_size();
    }

    bool empty() const {
        return 0 == size();
    }

    allocator_type get_allocator() const {
        return my_node_allocator;
    }

    void swap(concurrent_skip_list& other) {
        using std::swap;
        using pocs_type = typename node_allocator_traits::propagate_on_container_swap;
        tbb::internal::allocator_swap(my_node_allocator, other.my_node_allocator, pocs_type());
        swap(my_compare, other.my_compare);
        swap(my_rnd_generator, other.my_rnd_generator);
        swap(dummy_head, other.dummy_head);

        size_type tmp = my_size;
        my_size.store(other.my_size);
        other.my_size.store(tmp);
    }

    std::pair<iterator, iterator> equal_range(const key_type& key) {
        return std::pair<iterator, iterator>(lower_bound(key), upper_bound(key));
    }

    std::pair<const_iterator, const_iterator> equal_range(const key_type& key) const {
        return std::pair<const_iterator, const_iterator>(lower_bound(key), upper_bound(key));
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    std::pair<iterator, iterator> equal_range(const K& key) {
        return std::pair<iterator, iterator>(lower_bound(key), upper_bound(key));
    }

    template <typename K, typename = typename tbb::internal::is_transparent<key_compare, K> >
    std::pair<const_iterator, const_iterator> equal_range(const K& key) const {
        return std::pair<const_iterator, const_iterator>(lower_bound(key), upper_bound(key));
    }

    key_compare key_comp() const { return my_compare; }

    value_compare value_comp() const { return traits_type::value_comp(my_compare); }

    class const_range_type : tbb::internal::no_assign {
    public:
        using size_type = typename concurrent_skip_list::size_type;
        using value_type = typename concurrent_skip_list::value_type;
        using iterator = typename concurrent_skip_list::const_iterator;
    private:
        const_iterator my_end;
        const_iterator my_begin;
        size_type my_level;

    public:

        bool empty() const {
            return my_begin.my_node_ptr->next(0) == my_end.my_node_ptr;
        }

        bool is_divisible() const {
            return my_level != 0 ? my_begin.my_node_ptr->next(my_level - 1) != my_end.my_node_ptr : false;
        }

        size_type size() const { return std::distance(my_begin, my_end);}

        const_range_type( const_range_type& r, split)
            : my_end(r.my_end) {
            my_begin = iterator(r.my_begin.my_node_ptr->next(r.my_level - 1));
            my_level = my_begin.my_node_ptr->height();
            r.my_end = my_begin;
        }

        const_range_type( const concurrent_skip_list& l)
            : my_end(l.end()), my_begin(l.begin()), my_level(my_begin.my_node_ptr->height() ) {}

        iterator begin() const { return my_begin; }
        iterator end() const { return my_end; }
        size_t grainsize() const { return 1; }

    }; // class const_range_type

    class range_type : public const_range_type {
    public:
        using iterator = typename concurrent_skip_list::iterator;

        range_type(range_type& r, split) : const_range_type(r, split()) {}
        range_type(const concurrent_skip_list& l) : const_range_type(l) {}

        iterator begin() const {
            node_ptr node = const_range_type::begin().my_node_ptr;
            return iterator(node);
        }

        iterator end() const {
            node_ptr node = const_range_type::end().my_node_ptr;
            return iterator(node); }
    }; // class range_type

    range_type range() { return range_type(*this); }
    const_range_type range() const { return const_range_type(*this); }

private:
    void internal_move(concurrent_skip_list&& other) {
        dummy_head = other.dummy_head;
        other.dummy_head = nullptr;
        other.create_dummy_head();

        my_size = other.my_size.load();
        other.my_size = 0;
    }

    static const key_type& get_key(node_ptr n) {
        __TBB_ASSERT(n, NULL);
        return traits_type::get_key(n->value());
    }

    template <typename K>
    iterator internal_find(const K& key) {
        iterator it = lower_bound(key);
        return (it == end() || my_compare(key, traits_type::get_key(*it))) ? end() : it;
    }

    template <typename K>
    const_iterator internal_find(const K& key) const {
        const_iterator it = lower_bound(key);
        return (it == end() || my_compare(key, traits_type::get_key(*it))) ? end() : it;
    }

    template <typename K>
    size_type internal_count( const K& key ) const {
        if (allow_multimapping) {
            std::pair<const_iterator, const_iterator> range = equal_range(key);
            return std::distance(range.first, range.second);
        }
        return (find(key) == end()) ? size_type(0) : size_type(1);
    }

    /**
     * Finds position on the @param level using @param cmp
     * @param level - on which level search prev node
     * @param prev - pointer to the start node to search
     * @param key - key to search
     * @param cmp - callable object to compare two objects
     *  (my_compare member is default comparator)
     * @returns pointer to the node which is not satisfy the comparison with @param key
     */
    template <typename K, typename pointer_type, typename comparator>
    pointer_type internal_find_position( size_type level, pointer_type& prev, const K& key,
                                         const comparator& cmp) const {
        __TBB_ASSERT(level < prev->height(), "Wrong level to find position");
        pointer_type curr = prev->next(level);

        while (curr && cmp(get_key(curr), key)) {
            prev = curr;
            __TBB_ASSERT(level < prev->height(), NULL);
            curr = prev->next(level);
        }

        return curr;
    }

    template <typename comparator>
    void fill_prev_next_arrays(array_type& prev_nodes, array_type& next_nodes, node_ptr prev, const key_type& key,
                               const comparator& cmp) {
        prev_nodes.fill(dummy_head);
        next_nodes.fill(nullptr);

        for (size_type h = prev->height(); h > 0; --h) {
            node_ptr next = internal_find_position(h - 1, prev, key, cmp);
            prev_nodes[h - 1] = prev;
            next_nodes[h - 1] = next;
        }
    }

    template <typename comparator>
    void fill_prev_next_by_ptr(array_type& prev_nodes, array_type& next_nodes, const_iterator it, const key_type& key,
                               const comparator& cmp) {
        node_ptr prev = dummy_head;
        node_ptr erase_node = it.my_node_ptr;
        size_type node_height = erase_node->height();

        for (size_type h = prev->height(); h >= node_height; --h) {
            internal_find_position(h - 1, prev, key, cmp);
        }

        for (size_type h = node_height; h > 0; --h) {
            node_ptr curr = prev->next(h - 1);
            while (const_iterator(curr) != it) {
                prev = curr;
                curr = prev->next(h - 1);
            }
            prev_nodes[h - 1] = prev;
        }

        std::fill(next_nodes.begin(), next_nodes.begin() + node_height, erase_node);
    }

    template<typename... Args>
    std::pair<iterator, bool> internal_insert(Args&&... args) {
        node_ptr new_node = create_node(std::forward<Args>(args)...);
        std::pair<iterator, bool> insert_result = internal_insert_node(new_node);
        if(!insert_result.second) {
            delete_node(new_node);
        }
        return insert_result;
    }

    std::pair<iterator, bool> internal_insert_node(node_ptr new_node) {
        array_type prev_nodes;
        array_type next_nodes;
        __TBB_ASSERT(dummy_head->height() >= new_node->height(), "Wrong height for new node");

        do {
            if (allow_multimapping) {
                fill_prev_next_arrays(prev_nodes, next_nodes, dummy_head, get_key(new_node),
                                      not_greater_compare(my_compare));
            } else {
                fill_prev_next_arrays(prev_nodes, next_nodes, dummy_head, get_key(new_node), my_compare);
            }

            node_ptr next = next_nodes[0];
            if (next && !allow_multimapping && !my_compare(get_key(new_node), get_key(next))) {
                // TODO: do we really need to wait?
                while (!next->fully_linked()) {
                    // TODO: atomic backoff
                }

                return std::pair<iterator, bool>(iterator(next), false);
            }
            __TBB_ASSERT(allow_multimapping || !next || my_compare(get_key(new_node), get_key(next)),
                         "Wrong elements order");

        } while (!try_insert_node(new_node, prev_nodes, next_nodes));

        __TBB_ASSERT(new_node, NULL);
        return std::pair<iterator, bool>(iterator(new_node), true);
    }

    bool try_insert_node(node_ptr new_node, array_type& prev_nodes, array_type& next_nodes) {
        __TBB_ASSERT(dummy_head->height() >= new_node->height(), NULL);

        lock_array locks;

        if (!try_lock_nodes(new_node->height(), prev_nodes, next_nodes, locks)) {
            return false;
        }

        __TBB_ASSERT(allow_multimapping ||
                    ((prev_nodes[0] == dummy_head ||
                      my_compare(get_key(prev_nodes[0]), get_key(new_node))) &&
                      (next_nodes[0] == nullptr || my_compare(get_key(new_node), get_key(next_nodes[0])))),
                    "Wrong elements order");

        for (size_type level = 0; level < new_node->height(); ++level) {
            __TBB_ASSERT(prev_nodes[level]->height() > level, NULL);
            __TBB_ASSERT(prev_nodes[level]->next(level) == next_nodes[level], NULL);
            new_node->set_next(level, next_nodes[level]);
            prev_nodes[level]->set_next(level, new_node);
        }
        new_node->mark_linked();

        ++my_size;

        return true;
    }

    bool try_lock_nodes(size_type height, array_type& prevs, array_type& next_nodes, lock_array& locks) {
        for (size_type l = 0; l < height; ++l) {
            if (l == 0 || prevs[l] != prevs[l - 1])
                locks[l] = prevs[l]->acquire();

            node_ptr next = prevs[l]->next(l);
            if ( next != next_nodes[l]) return false;
        }

        return true;
    }

    template <typename K, typename comparator>
    const_iterator internal_get_bound(const K& key, const comparator& cmp) const {
        node_ptr prev = dummy_head;
        __TBB_ASSERT(dummy_head->height() > 0, NULL);
        node_ptr next = nullptr;

        for (size_type h = prev->height(); h > 0; --h) {
            next = internal_find_position(h - 1, prev, key, cmp);
        }

        return const_iterator(next);
    }

    template <typename K, typename comparator>
    iterator internal_get_bound(const K& key, const comparator& cmp){
        node_ptr prev = dummy_head;
        __TBB_ASSERT(dummy_head->height() > 0, NULL);
        node_ptr next = nullptr;

        for (size_type h = prev->height(); h > 0; --h) {
            next = internal_find_position(h - 1, prev, key, cmp);
        }

        return iterator(next);
    }

    // Returns node_ptr to the extracted node and node_ptr to the next node after the extracted
    std::pair<node_ptr, node_ptr> internal_extract(const_iterator it) {
        if ( it != end() ) {
            key_type key = traits_type::get_key(*it);
            __TBB_ASSERT(dummy_head->height() > 0, NULL);

            array_type prev_nodes;
            array_type next_nodes;

            fill_prev_next_by_ptr(prev_nodes, next_nodes, it, key, my_compare);

            node_ptr erase_node = next_nodes[0];
            __TBB_ASSERT(erase_node != nullptr, NULL);
            node_ptr next_node = erase_node->next(0);

            if (!my_compare(key, get_key(erase_node))) {
                for(size_type level = 0; level < erase_node->height(); ++level) {
                    __TBB_ASSERT(prev_nodes[level]->height() > level, NULL);
                    __TBB_ASSERT(next_nodes[level] == erase_node, NULL);
                    prev_nodes[level]->set_next(level, erase_node->next(level));
                }
                --my_size;
                return std::pair<node_ptr, node_ptr>(erase_node, next_node);
            }
        }
        return std::pair<node_ptr, node_ptr>(nullptr, nullptr);
    }

protected:
    template<typename SourceType>
    void internal_merge(SourceType&& source) {
        using source_type = typename std::decay<SourceType>::type;
        using source_iterator = typename source_type::iterator;
        __TBB_STATIC_ASSERT((std::is_same<node_type, typename source_type::node_type>::value), "Incompatible containers cannot be merged");

        for(source_iterator it = source.begin(); it != source.end();) {
            source_iterator where = it++;
            if (allow_multimapping || !contains(traits_type::get_key(*where))) {
                std::pair<node_ptr, node_ptr> extract_result = source.internal_extract(where);

                //If the insertion fails - return the node into source
                node_type handle(extract_result.first);
                __TBB_ASSERT(!handle.empty(), "Extracted handle in merge is empty");

                if (!insert(std::move(handle)).second) {
                    source.insert(std::move(handle));
                }
                handle.deactivate();
            }
        }
    }

private:
    void internal_copy(const concurrent_skip_list& other) {
        internal_copy(other.begin(), other.end());
    }

    template<typename Iterator>
    void internal_copy(Iterator first, Iterator last) {
        clear();
        try {
            for (auto it = first; it != last; ++it)
                insert(*it);
        }
        catch (...) {
            clear();
            delete_dummy_head();
            throw;
        }
    }

    /** Generate random level */
    size_type random_level() {
        return my_rnd_generator();
    }

    static size_type calc_node_size(size_type height) {
        return sizeof(list_node_type) + height*sizeof(typename list_node_type::atomic_node_pointer);
    }

    /** Creates new node */
    template <typename... Args>
    node_ptr create_node(Args&&... args) {
        size_type levels = random_level();

        size_type sz = calc_node_size(levels);

        node_ptr node = reinterpret_cast<node_ptr>(node_allocator_traits::allocate(my_node_allocator, sz));

        try {
            node_allocator_traits::construct(my_node_allocator, node, levels);

        }
        catch(...) {
            deallocate_node(node, sz);
            throw;
        }

        try {
            node_allocator_traits::construct(my_node_allocator, node->storage(), std::forward<Args>(args)...);
        }
        catch (...) {
            node_allocator_traits::destroy(my_node_allocator, node);
            deallocate_node(node, sz);
            throw;
        }

        return node;
    }

    void create_dummy_head() {
        size_type sz = calc_node_size(MAX_LEVEL);

        dummy_head = reinterpret_cast<node_ptr>(node_allocator_traits::allocate(my_node_allocator, sz));
        // TODO: investigate linkage fail in debug without this workaround
        auto max_level = MAX_LEVEL;

        try {
            node_allocator_traits::construct(my_node_allocator, dummy_head, max_level);
        }
        catch(...) {
            deallocate_node(dummy_head, sz);
            throw;
        }
    }

    template <bool is_dummy = false>
    void delete_node(node_ptr node) {
        size_type sz = calc_node_size(node->height());
        // Destroy value
        if (!is_dummy) node_allocator_traits::destroy(my_node_allocator, node->storage());
        // Destroy node
        node_allocator_traits::destroy(my_node_allocator, node);
        // Deallocate memory
        deallocate_node(node, sz);
    }

    void deallocate_node(node_ptr node, size_type sz) {
        node_allocator_traits::deallocate(my_node_allocator, reinterpret_cast<uint8_t*>(node), sz);
    }

    void delete_dummy_head() {
        delete_node<true>(dummy_head);
    }

    static iterator get_iterator(const_iterator it) {
        return iterator(it.my_node_ptr);
    }

    void internal_move_assign(concurrent_skip_list&& other, /*POCMA=*/std::true_type) {
        delete_dummy_head();
        tbb::internal::allocator_move_assignment(my_node_allocator, other.my_node_allocator, std::true_type());
        internal_move(std::move(other));
    }

    void internal_move_assign(concurrent_skip_list&& other, /*POCMA=*/std::false_type) {
        if (my_node_allocator == other.my_node_allocator) {
            delete_dummy_head();
            internal_move(std::move(other));
        } else {
            internal_copy(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()));
        }
    }

    struct not_greater_compare {
        const key_compare& my_less_compare;

        not_greater_compare(const key_compare& less_compare) : my_less_compare(less_compare) {}

        template <typename K1, typename K2>
        bool operator()(const K1& first, const K2& second) const {
            return !my_less_compare(second, first);
        }
    };

    node_allocator_type my_node_allocator;
    key_compare my_compare;
    random_level_generator_type my_rnd_generator;
    node_ptr dummy_head;

    template<typename OtherTraits>
    friend class concurrent_skip_list;

    std::atomic<size_type> my_size;
}; // class concurrent_skip_list

template <size_t MAX_LEVEL>
class concurrent_geometric_level_generator {
public:
    static constexpr size_t max_level = MAX_LEVEL;

    concurrent_geometric_level_generator() : engines(time(NULL)) {}

    size_t operator()() {
        return (distribution(engines.local()) % MAX_LEVEL) + 1;
    }

private:
    tbb::enumerable_thread_specific<std::mt19937_64> engines;
    std::geometric_distribution<size_t> distribution;
};

} // namespace internal
} // namespace interface10
} // namespace tbb

#endif // __TBB_concurrent_skip_list_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 - Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
 -
 - 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.
 -->
<switchyard
    xmlns="urn:switchyard-config:switchyard:1.0"
    xmlns:sca="http://docs.oasis-open.org/ns/opencsa/sca/200912"
    xmlns:jca="urn:switchyard-component-jca:config:1.0"
    xmlns:bean="urn:switchyard-component-bean:config:1.0">

    <sca:composite name="JCAJMSTest" targetNamespace="urn:jca:test:1.0">
        <sca:reference name="JCAJMSService" promote="ComponentName/JCAJMSService">
            <binding.jca xmlns="urn:switchyard-component-jca:config:1.0">
               <outboundConnection>
                   <resourceAdapter name="hornetq-ra.rar">
                       <property name="prop1" value="value1"/>
                   </resourceAdapter>
                   <connection>
                       <property name="prop2" value="value2"/>
                   </connection>
               </outboundConnection>
               <outboundInteraction>
                   <connectionSpec>
                       <property name="prop3" value="value3"/>
                   </connectionSpec>
                   <interactionSpec>
                       <property name="prop4" value="value4"/>
                   </interactionSpec>
                   <operation name="operationName">
                        <interactionSpec>
                            <property name="prop5" value="value5"/>
                        </interactionSpec>
                   </operation>
                   <processor type="org.switchyard.component.jca.processor.CCIProcessor">
                       <property name="prop6" value="value6"/>
                   </processor>
               </outboundInteraction>
            </binding.jca>
        </sca:reference>
    </sca:composite>
</switchyard>


text:
This will provide an external service proxy for Kubernetes Pods discovered via label queries.

Currently a work in progress.

## Installation

```
go install github.com/kelseyhightower/kubernetes-external-proxy
```

## Usage

Configure the server:

```
export KUBERNETES_API_SERVER="192.168.12.20:8080"
```

Start the server:

```
kubernetes-external-proxy
```

### Add a service

Create an add service RPC request:

```
{
    "method": "ServiceManager.Add",
    "params":[{
        "id": "hello",
        "selector": {
            "environment": "production"
        },
        "containerPort": "80",
        "protocol": "tcp",
        "port": "5000"
    }],
    "id": 0
}
```

```
curl -i -d @add-hello-service.json http://127.0.0.1:8000
```

```
{"id":0,"result":"0.0.0.0:5000","error":null}
```

### Delete a service

Create a delete service RPC request:

```
{
    "method": "ServiceManager.Del",
    "params":["hello"],
    "id": 0
}
```

```
curl -i -d @delete-hello-service.json http://127.0.0.1:8000
```

```
{"id":0,"result":true,"error":null}
```


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.physicalweb;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.text.Html;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.NativePage;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.components.location.LocationUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * Provides diagnostic information about the Physical Web feature.
 */
public class PhysicalWebDiagnosticsPage implements NativePage {
    private final Context mContext;
    private final int mBackgroundColor;
    private final int mThemeColor;
    private final String mSuccessColor;
    private final String mFailureColor;
    private final String mIndeterminateColor;
    private final View mPageView;
    private final Button mLaunchButton;
    private final TextView mDiagnosticsText;

    public PhysicalWebDiagnosticsPage(Context context) {
        mContext = context;

        Resources resources = mContext.getResources();
        mBackgroundColor = ApiCompatibilityUtils.getColor(resources, R.color.ntp_bg);
        mThemeColor = ApiCompatibilityUtils.getColor(resources, R.color.default_primary_color);
        mSuccessColor = colorToHexValue(ApiCompatibilityUtils.getColor(resources,
                R.color.physical_web_diags_success_color));
        mFailureColor = colorToHexValue(ApiCompatibilityUtils.getColor(resources,
                R.color.physical_web_diags_failure_color));
        mIndeterminateColor = colorToHexValue(ApiCompatibilityUtils.getColor(resources,
                R.color.physical_web_diags_indeterminate_color));

        LayoutInflater inflater = LayoutInflater.from(mContext);
        mPageView = inflater.inflate(R.layout.physical_web_diagnostics, null);

        mLaunchButton = (Button) mPageView.findViewById(R.id.physical_web_launch);
        mLaunchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(createListUrlsIntent(mContext));
            }
        });

        mDiagnosticsText = (TextView) mPageView.findViewById(R.id.physical_web_diagnostics_text);
        mDiagnosticsText.setAutoLinkMask(Linkify.WEB_URLS);
        mDiagnosticsText.setText(Html.fromHtml(createDiagnosticsReportHtml()));
    }

    private void appendResult(StringBuilder sb, boolean success, String successMessage,
            String failureMessage) {
        int successValue = (success ? Utils.RESULT_SUCCESS : Utils.RESULT_FAILURE);
        appendResult(sb, successValue, successMessage, failureMessage, null);
    }

    private void appendResult(StringBuilder sb, int successValue, String successMessage,
            String failureMessage, String indeterminateMessage) {
        String color;
        String message;
        switch (successValue) {
            case Utils.RESULT_SUCCESS:
                color = mSuccessColor;
                message = successMessage;
                break;
            case Utils.RESULT_FAILURE:
                color = mFailureColor;
                message = failureMessage;
                break;
            case Utils.RESULT_INDETERMINATE:
                color = mIndeterminateColor;
                message = indeterminateMessage;
                break;
            default:
                return;
        }

        sb.append(String.format("%s
", color, message));
    }

    private void appendPrerequisitesReport(StringBuilder sb) {
        boolean isSdkVersionCorrect = isSdkVersionCorrect();
        boolean isDataConnectionActive = Utils.isDataConnectionActive(mContext);
        int bluetoothStatus = Utils.getBluetoothEnabledStatus(mContext);
        LocationUtils locationUtils = LocationUtils.getInstance();
        boolean isLocationServicesEnabled = locationUtils.isSystemLocationSettingEnabled();
        boolean isLocationPermissionGranted = locationUtils.hasAndroidLocationPermission();
        boolean isPreferenceEnabled = PhysicalWeb.isPhysicalWebPreferenceEnabled();
        boolean isOnboarding = PhysicalWeb.isOnboarding();

        int prerequisitesResult = Utils.RESULT_SUCCESS;
        if (!isSdkVersionCorrect
                || !isDataConnectionActive
                || bluetoothStatus == Utils.RESULT_FAILURE
                || !isLocationServicesEnabled
                || !isLocationPermissionGranted
                || !isPreferenceEnabled) {
            prerequisitesResult = Utils.RESULT_FAILURE;
        } else if (bluetoothStatus == Utils.RESULT_INDETERMINATE) {
            prerequisitesResult = Utils.RESULT_INDETERMINATE;
        }

        sb.append("
Status
");

        sb.append("Physical Web is ");
        appendResult(sb, prerequisitesResult != Utils.RESULT_FAILURE, "ON", "OFF");

        sb.append("
Prerequisites
");

        sb.append("Android SDK version: ");
        appendResult(sb, isSdkVersionCorrect, "Compatible", "Incompatible");

        sb.append("Data connection: ");
        appendResult(sb, isDataConnectionActive, "Connected", "Not connected");

        sb.append("Location services: ");
        appendResult(sb, isLocationServicesEnabled, "Enabled", "Disabled");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            sb.append("Location app permission: ");
            appendResult(sb, isLocationPermissionGranted, "Granted", "Not granted");
        }

        sb.append("Physical Web privacy settings: ");
        String preferenceDisabledMessage = (isOnboarding ? "Default (off)" : "Off");
        appendResult(sb, isPreferenceEnabled, "On", preferenceDisabledMessage);

        sb.append("Bluetooth: ");
        appendResult(sb, bluetoothStatus, "Enabled", "Disabled", "Unknown");

        // Append instructions for how to verify Bluetooth is enabled when we are unable to check
        // programmatically.
        if (bluetoothStatus == Utils.RESULT_INDETERMINATE) {
            sb.append("
To verify Bluetooth is enabled on this device, check that the "
                    + "Bluetooth icon is shown in the status bar.");
        }
    }

    private void appendUrlManagerReport(StringBuilder sb) {
        UrlManager urlManager = UrlManager.getInstance();

        Set<String> nearbyUrls = new HashSet<>(urlManager.getNearbyUrls());
        Set<String> resolvedUrls = new HashSet<>(urlManager.getResolvedUrls());
        Set<String> union = new HashSet<>(nearbyUrls);
        union.addAll(resolvedUrls);

        sb.append("
Nearby web pages
");

        if (union.isEmpty()) {
            sb.append("No nearby web pages found
");
        } else {
            for (String url : union) {
                boolean isNearby = nearbyUrls.contains(url);
                boolean isResolved = resolvedUrls.contains(url);

                sb.append(url);
                if (!isNearby) {
                    sb.append(" : LOST");
                } else if (!isResolved) {
                    sb.append(" : UNRESOLVED");
                }
                sb.append("
");
            }
        }
    }

    private String createDiagnosticsReportHtml() {
        StringBuilder sb = new StringBuilder();
        appendPrerequisitesReport(sb);
        sb.append("
");
        appendUrlManagerReport(sb);
        return sb.toString();
    }

    private boolean isSdkVersionCorrect() {
        return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT);
    }

    private static Intent createListUrlsIntent(Context context) {
        Intent intent = new Intent(context, ListUrlsActivity.class);
        intent.putExtra(ListUrlsActivity.REFERER_KEY, ListUrlsActivity.DIAGNOSTICS_REFERER);
        return intent;
    }

    private static String colorToHexValue(int color) {
        return "#" + Integer.toHexString(color & 0x00ffffff);
    }

    // NativePage overrides

    @Override
    public void destroy() {
        // nothing to do
    }

    @Override
    public String getUrl() {
        return UrlConstants.PHYSICAL_WEB_URL;
    }

    @Override
    public String getTitle() {
        return "Physical Web Diagnostics";
    }

    @Override
    public int getBackgroundColor() {
        return mBackgroundColor;
    }

    @Override
    public int getThemeColor() {
        return mThemeColor;
    }

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

    @Override
    public View getView() {
        return mPageView;
    }

    @Override
    public String getHost() {
        return UrlConstants.PHYSICAL_WEB_HOST;
    }

    @Override
    public void updateForUrl(String url) {
        // nothing to do
    }
}


text:
'use strict';

var database = require('../database');
var getId = require('../utils/getId');
var indexAction = require('./index');
var loginAction = require('./login');

module.exports = function del(req, res) {
    if(!req.session.isLogined){
        loginAction(req,res);
        return;
    }
    getId(req, id=> {
        database.del(id);
        indexAction(req, res);
    });
};


text:
.. :changelog:

Changelog
=========

Please refer to :doc:`backward-compatibility` for details on deprecations and backward-incompatible changes.

15.1.0 (UNRELEASED)
-------------------

Backward-incompatible changes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

*none*

Deprecations:
^^^^^^^^^^^^^

*none*

Changes:
^^^^^^^^

*none*

15.0.0 (2015-07-10)
-------------------

Backward-incompatible changes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

*none*

Deprecations:
^^^^^^^^^^^^^

- The usage of Twisted helpers from the pem module is deprecated.
  Use their pendants from the ``pem.twisted`` module now.
- The usage of the backport of ephemeral Diffie-Hellman support is hereby deprecated.
  Nobody should use a Twisted release that is older than 14.0.0 because it contains essential SSL/TLS fixes.

Changes:
^^^^^^^^

- Support PEM strings that do not end with a new line. [`12 <https://github.com/hynek/pem/pull/12>`_]
- Support PEM strings that end with ``\r\n``.
- The Twisted-related helpers have been moved to ``pem.twisted``.

0.3.0 (2014-04-15)
------------------

- Load PEM files as UTF-8 to allow for non-ASCII comments (like in certifi).
- Allow keys, primary certificates, and chain certificates to occur in any order.

0.2.0 (2014-03-13)
------------------

- Add forward-compatible support for DHE.

0.1.0 (2013-07-18)
------------------

- Initial release.


text:
import pycurl
import StringIO
from urllib import urlencode
import urllib
from BeautifulSoup import BeautifulSoup
import reg_get_sms_code

def reg_post_spider(url,post_data,cookie_file,referer_url,proxy):
	#url = "http://www.bjguahao.gov.cn/comm/reg1.php"
	#cookie_file = './Cookie/cookie.txt'

	ch = pycurl.Curl()
	buffer_con = StringIO.StringIO()

	header = [
		"Content-Type: application/x-www-form-urlencoded;",
		"Accept: */*",
		"Cache-Control:max-age=0",
		"Connection:keep-alive",
		"Host:www.bjguahao.gov.cn",
		"User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
		"X-Requested-With:XMLHttpRequest",
		"Referer:"+referer_url,
		"Origin:http://www.bjguahao.gov.cn",
	]
	post_data = urlencode(post_data)
	#print post_data
	ch.setopt(ch.URL, url)
	#ch.setopt(ch.VERBOSE, 1)		#查看http信息
	ch.setopt(ch.FOLLOWLOCATION, 1)
	ch.setopt(ch.HTTPHEADER, header)
	ch.setopt(ch.WRITEFUNCTION, buffer_con.write)
	ch.setopt(ch.POSTFIELDS, post_data)	#发送的数据
	ch.setopt(ch.COOKIEFILE, cookie_file)
	ch.setopt(ch.COOKIEJAR, cookie_file)	#保存cookie
	if proxy: ch.setopt(ch.PROXY, proxy)      #设置代理服务器
	ch.perform()
	html=buffer_con.getvalue()
	buffer_con.close()
	ch.close()
	return html
def reg_confirm(cookie_file,data,proxy):
	truenamereg = unicode(data['truename'],'utf8').encode('gbk')
	sex= unicode(data['gender'],'utf8').encode('gbk')
	post_data = {
		"truenamereg":truenamereg,
		"sex":sex,
		"cardtype":1,
		"sfzhmreg":data['idcard_num'],
		"qrsfzhm":data['idcard_num'],
		"province":unicode("北京市",'utf8').encode('gbk'),
		"yzmreg":data['code'],
		"flagmib":"mibok",
		"reg_mib":data['phone_num'],
		"mib":data['phone_num'],
		"reg_dxcode":data['sms_code'],
		"dxcode":data['sms_code'],
		"box":1
	}
	reg_confirm_url = "http://www.bjguahao.gov.cn/comm/reg1.php"
	referer_url = 'http://www.bjguahao.gov.cn/comm/index.html'
	html = reg_post_spider(reg_confirm_url,post_data,cookie_file,referer_url,proxy)
	return html
def reg_post(cookie_file,data,proxy):
	truenamereg = unicode(data['truename'],'utf8').encode('gbk')
	sex= unicode(data['gender'],'utf8').encode('gbk')
	reg_confirm_html = reg_confirm(cookie_file,data,proxy)
	soup = BeautifulSoup(reg_confirm_html)
	action_flag = soup.find('input',{'name':'action_flag'})['value'].encode('gbk')
	post_data = {
		"action_flag":action_flag,
		"truenamereg":truenamereg,
		"sex":sex,
		"cardtype":1,
		"sfzhmreg":data['idcard_num'],
		"province":unicode("北京市",'utf8').encode('gbk'),
		"yzmreg":data['code'],
		"mib":data['phone_num'],
		"dxcode":data['sms_code'],
	}
	reg_post_url = "http://www.bjguahao.gov.cn/comm/register.php"
	referer_url = 'http://www.bjguahao.gov.cn/comm/reg1.php'
	html = reg_post_spider(reg_post_url,post_data,cookie_file,referer_url,proxy)
	#fo = open('reg_post_rs..html','w')
	#fo.write(html)
	#fo.close()
	soup_2 = BeautifulSoup(html)
	try:
		result = soup_2.find('div',{'class':'logtxtwtr'}).find('h1').text.encode('utf8')
	except:
		result = soup_2.find('div',{'class':'erroralltxt'}).text.encode('utf8')
	return result

if __name__ == '__main__':
	data = {
		'truename':'张佳',
		'gender':'男',
		'idcard_num':'640321199001020977',
		'code':'9692',
		'phone_num':'15210860284',
		'sms_code':'2526'
	}
	html = reg_post('cookie.txt',data,False)
	print html
#	html = unicode(html,'gbk').encode('utf8')
	fo = open('reg_response.html', 'w')
	fo.write(html)
	fo.close()


text:
'use strict';

module.exports = function(grunt) {
// Unified Watch Object
//var bowerFiles = require('bower-files')();
var watchFiles = {
  clientViews: ['public/modules/**/views/**/*.html'],
  clientJS: ['public/*.js','public/modules/*/js/*.js', 'public/modules/*/js/**/*.js'],
  clientCSS: ['public/modules/**/*.css'],
  tests: [
  'public/lib/bower_components/angular-mocks/angular-mocks.js',
  'public/modules/*/tests/unit/**/*.js'
  ],
  serverJS: ['gruntfile.js', 'config/**/*.js'],
  serverJSON: ['harp.json', 'package.json', 'bower.json', 'public/**/*.json', 'config/**/*.json' ],
  serverViews: ['public/*.ejs', 'public/views/**/*.ejs'],
  bowerJS: require('./config/grunt/files'),
  bowerCSS: require('./config/grunt/bower-css-files')
};

// Project Configuration
grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    meta:{
      reports: '.reports',
      files: watchFiles
    },
    watch: {
      serverJSON: {
        files: watchFiles.serverJSON,
        tasks: ['jsonlint'],
        options: {
          livereload: true
        }
      },
      clientViews: {
        files: watchFiles.clientViews,
        options: {
          livereload: true,
        }
      },
      serverViews: {
        files: watchFiles.serverViews,
        tasks: ['inject'],
        options: {
          livereload: true,
        }
      },
      clientJS: {
        files: watchFiles.clientJS,
        tasks: ['jshint', 'inject'],
        options: {
          livereload: true
        }
      },
      clientCSS: {
        files: watchFiles.clientCSS,
        tasks: ['csslint', 'inject'],
        options: {
          livereload: true
        }
      }
    },
    jshint: {
      all: {
        src: watchFiles.clientJS.concat(watchFiles.serverJS),
        options: {
          jshintrc: true
        }
      }
    },
    jsonlint: {
      server: {
        src:watchFiles.serverJSON
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc',
      },
      all: {
        src: watchFiles.clientCSS
      }
    },
    uglify: {
      production: {
        options: {
          mangle: false
        },
        files: {
          'public/dist/application.min.js': 'public/dist/application.js',
          'public/dist/vendor.min.js': '<%= meta.files.bowerJS %>'
        }
      }
    },
    cssmin: {
      combine: {
        files: {
          'public/dist/application.min.css': '<%= meta.files.clientCSS %>',
          'public/dist/vendor.min.css': '<%= meta.files.bowerCSS %>'
        }
      }
    },
    ngAnnotate: {
      options: {
        singleQuotes: true,
      },
      production: {
        files: {
          'public/dist/application.js': ['<%= meta.files.clientJS %>']
        }
      }
    },
    concurrent: {
      docs: ['ngdocs', 'plato'],
      serve: ['startApp', 'watch'],
      test: ['test'],
      options: {
        logConcurrentOutput: true,
        limit: 6
      }
    },
    env: {
      test: {
        NODE_ENV: 'test'
      },
      dev: {
        NODE_ENV: 'development',
        COVERAGE: 'true'
      }
    },
    karma: {
      unit: {
        configFile: './config/karma.conf.js'
      }
    },
    ngdocs: {
      options: {
        dest: '<%= meta.reports %>/docs/ngdocs',
        scripts: [
        'public/lib/bower_components/angular/angular.js',
        'public/lib/bower_components/angular-animate/angular-animate.js'
        ],
        html5Mode: false,
        startPage: '/api',
        title: 'NgApp Documentation',
      },
      api: {
        src: watchFiles.clientJS,
        title: 'API Documentation'
      }
    },
    clean: {
      docs: ['<%= meta.reports %>/docs'],
      coverage: ['<%= meta.reports %>/coverage']
    },
    plato: {
      ui: {
        options:{
          //generate patterns: http://www.jslab.dk/tools.regex.php
          // regex's separated by pipe |
          // this pattern excludes tests, distributions and public libs
          exclude: /public\/lib|public\/modules\/([^/]+)\/tests|public\/dist/,
          jshint : grunt.file.readJSON('.jshintrc')
        },
        files: {
          '<%= meta.reports %>/plato/ui': [ 'public/**/*.js']
        }
      }
    },
    bump: {
      options: {
        files: ['package.json', 'bower.json'],
        updateConfigs: [],
        commit: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json','bower.json', 'CHANGELOG.md', 'gruntfile.js'],
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        push: true,
        pushTo: '<%= pkg.repository.url %>',
        gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
        globalReplace: false
      }
    },
    changelog:{
      options: {
        // Task-specific options go here.
      }
    },
    bowerInstall: {
      index:{
        src:['public/_layout.ejs'],
        ignorePath: ['public/']
      }
    },
    usemin: {
      html: 'public/_layout.ejs'
    },
    injector: require('./config/grunt/inject')(watchFiles)

  });

  // Load NPM tasks
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);
  require('./config/grunt/customTasks')(grunt);

  // Making grunt default to force in order not to break the project.
  //grunt.option('force', true);

  // Default task(s).
  grunt.registerTask('default', ['lint', 'inject', 'inject:resources']);
  grunt.registerTask('serve', ['default', 'concurrent:serve']);

  grunt.registerTask('build', ['lint','inject', 'inject:resources', 'ngAnnotate', 'uglify', 'cssmin', 'usemin']);

  // Lint task(s).
  grunt.registerTask('lint', ['jshint', 'csslint', 'jsonlint']);

  // Injection tasks
  grunt.registerTask('inject', ['injector:appfiles', 'bowerInstall']);
  grunt.registerTask('inject:resources', ['injector:testfiles', 'injector:bowerCSS']);

  // Test task.
  grunt.registerTask('test', ['env:test', 'injector:testfiles', 'clean:coverage', 'lint', 'karma:unit']);

  grunt.registerTask('docs', ['clean:docs', 'concurrent:docs' ]);

  //release
  grunt.registerTask('pre-release', ['changelog', 'bump:prerelease']);
  grunt.registerTask('patch-release', ['changelog', 'bump']);
  grunt.registerTask('minor-release', ['changelog', 'bump:minor']);
  grunt.registerTask('major-release', ['changelog', 'bump:major']);

};