text:
namespace Magick
{
  class Image;

  class Options
  {

  public:
    Options( void );
    Options( const Options& options_ );
    ~Options();

    // Remove pixel aliasing
    void            antiAlias( bool flag_ );
    bool            antiAlias( void ) const;

    // Join images into a single multi-image file
    void            adjoin ( bool flag_ );
    bool            adjoin ( void ) const;

    // Image background color
    void            backgroundColor ( const Color &color_ );
    Color           backgroundColor ( void ) const;

    // Name of texture image to tile onto the image background
    void            backgroundTexture ( const std::string &backgroundTexture_ );
    std::string     backgroundTexture ( void ) const;

    // Image border color
    void            borderColor ( const Color &color_ );
    Color           borderColor ( void ) const;

    // Text bounding-box base color (default none)
    void            boxColor ( const Color &boxColor_ );
    Color           boxColor ( void ) const;

    // Colors within this distance are considered equal
    void            colorFuzz ( double fuzz_ );
    double          colorFuzz ( void ) const;

    // Image colorspace scheme
    void            colorspaceType ( ColorspaceType colorspace_ );
    ColorspaceType   colorspaceType ( void ) const;

    // Compression type ( NoCompression, BZipCompression,
    // FaxCompression, JPEGCompression, LZWCompression,
    // RLECompression, or ZipCompression )
    void            compressType ( CompressionType compressType_ );
    CompressionType compressType ( void ) const;

    // Enable printing of debug messages from ImageMagick
    void            debug ( bool flag_ );
    bool            debug ( void ) const;

    // Vertical and horizontal resolution in pixels of the image
    void            density ( const Geometry &geomery_ );
    Geometry        density ( void ) const;

    // Image depth (8 or 16)
    void            depth ( size_t depth_ );
    size_t    depth ( void ) const;

    // Endianness (little like Intel or big like SPARC) for image
    // formats which support endian-specific options.
    void            endian ( EndianType endian_ );
    EndianType      endian ( void ) const;

    // Image filename to read or write
    void            file ( FILE *file_ );
    FILE*           file ( void ) const;

    // Image filename to read or write
    void            fileName ( const std::string &fileName_ );
    std::string     fileName ( void ) const;

    // Color to use when filling drawn objects
    void            fillColor ( const Color &fillColor_ );
    Color           fillColor ( void ) const;

    // Fill pattern
    void            fillPattern ( const MagickCore::Image *fillPattern_ );
    const MagickCore::Image* fillPattern ( void  ) const;

    // Rule to use when filling drawn objects
    void            fillRule ( const FillRule &fillRule_ );
    FillRule        fillRule ( void ) const;

    // Font name
    void            font ( const std::string &font_ );
    std::string     font ( void ) const;

    // Font point size
    void            fontPointsize ( double pointSize_ );
    double          fontPointsize ( void ) const;

    std::string     format ( void ) const;

    // Image interlace scheme
    void            interlaceType ( InterlaceType interlace_ );
    InterlaceType   interlaceType ( void ) const;

   // Image format to write or read
    void            magick ( const std::string &magick_ );
    std::string     magick ( void ) const;

    // Transparent color
    void            matteColor ( const Color &matteColor_ );
    Color           matteColor ( void ) const;

   // Write as a monochrome image
    void            monochrome ( bool monochromeFlag_ );
    bool            monochrome ( void ) const;

    // Preferred size and location of an image canvas.
    void            page ( const Geometry &pageSize_ );
    Geometry        page ( void ) const;

    // Desired image quality factor
    void            quality ( size_t quality_ );
    size_t    quality ( void ) const;

    // Maximum number of colors to quantize to
    void            quantizeColors ( size_t colors_ );
    size_t    quantizeColors ( void ) const;

    // Colorspace to quantize in.
    void            quantizeColorSpace ( ColorspaceType colorSpace_ );
    ColorspaceType  quantizeColorSpace ( void ) const;

    // Dither image during quantization.
    void            quantizeDither ( bool ditherFlag_ );
    bool            quantizeDither ( void ) const;

    // Quantization tree-depth
    void            quantizeTreeDepth ( size_t treeDepth_ );
    size_t    quantizeTreeDepth ( void ) const;

    // Units of resolution to interpret density
    void            resolutionUnits ( ResolutionType resolutionUnits_ );
    ResolutionType  resolutionUnits ( void ) const;

    // Image sampling factor
    void            samplingFactor ( const std::string &samplingFactor_ );
    std::string     samplingFactor ( void ) const;

    // Image size (required for raw formats)
    void            size ( const Geometry &geometry_ );
    Geometry        size ( void ) const;

    // enabled/disable stroke anti-aliasing
    void            strokeAntiAlias( bool flag_ );
    bool            strokeAntiAlias( void ) const ;

    // Color to use when drawing object outlines
    void            strokeColor ( const Color &strokeColor_ );
    Color           strokeColor ( void ) const;

    // Control the pattern of dashes and gaps used to stroke
    // paths. The strokeDashArray represents a list of numbers that
    // specify the lengths of alternating dashes and gaps in user
    // units. If an odd number of values is provided, then the list of
    // values is repeated to yield an even number of values.
    void            strokeDashArray ( const double* strokeDashArray_ );
    const double*   strokeDashArray ( void ) const;

    // While drawing using strokeDashArray, specify distance into the dash
    // pattern to start the dash (default 0).
    void            strokeDashOffset ( double strokeDashOffset_ );
    double          strokeDashOffset ( void ) const;

    // Specify the shape to be used at the end of open subpaths when
    // they are stroked. Values of LineCap are UndefinedCap, ButtCap,
    // RoundCap, and SquareCap.
    void            strokeLineCap ( LineCap lineCap_ );
    LineCap         strokeLineCap ( void ) const;

    // Specify the shape to be used at the corners of paths (or other
    // vector shapes) when they are stroked. Values of LineJoin are
    // UndefinedJoin, MiterJoin, RoundJoin, and BevelJoin.
    void            strokeLineJoin ( LineJoin lineJoin_ );
    LineJoin        strokeLineJoin ( void ) const;

    // Specify miter limit. When two line segments meet at a sharp
    // angle and miter joins have been specified for 'lineJoin', it is
    // possible for the miter to extend far beyond the thickness of
    // the line stroking the path. The miterLimit' imposes a limit on
    // the ratio of the miter length to the 'stroke_width'. The default
    // value of this parameter is 4.
    void            strokeMiterLimit ( size_t miterLimit_ );
    size_t    strokeMiterLimit ( void ) const;

    // Pattern image to use for stroked outlines
    void            strokePattern ( const MagickCore::Image *strokePattern_ );
    const MagickCore::Image* strokePattern ( void  ) const;

   // Stroke width for drawing vector objects (default one)
    void            strokeWidth ( double strokeWidth_ );
    double          strokeWidth ( void ) const;

    void            subImage ( size_t subImage_ );
    size_t    subImage ( void ) const;

    // Sub-frame number to return
    void            subRange ( size_t subRange_ );
    size_t    subRange ( void ) const;

    // Annotation text encoding (e.g. "UTF-16")
    void            textEncoding ( const std::string &encoding_ );
    std::string     textEncoding ( void ) const;

    // Image representation type
    void            type ( const ImageType type_ );
    ImageType       type ( void ) const;

    // Origin of coordinate system to use when annotating with text or drawing
    void            transformOrigin ( double tx_, double ty_ );

    // Reset transformation parameters to default
    void            transformReset ( void );

    // Rotation to use when annotating with text or drawing
    void            transformRotation ( double angle_ );

    // Scale to use when annotating with text or drawing
    void            transformScale ( double sx_, double sy_ );

    // Skew to use in X axis when annotating with text or drawing
    void            transformSkewX ( double skewx_ );

    // Skew to use in Y axis when annotating with text or drawing
    void            transformSkewY ( double skewy_ );

    // Return verbose information about an image, or an operation
    void            verbose ( bool verboseFlag_ );
    bool            verbose ( void ) const;

    void            view ( const std::string &view_ );
    std::string     view ( void ) const;

    // X11 display name
    void            x11Display ( const std::string &display_ );
    std::string     x11Display ( void ) const;

    //
    // Internal implementation methods.  Please do not use.
    //

    MagickCore::DrawInfo*       drawInfo( void );
    MagickCore::ImageInfo *     imageInfo( void );
    MagickCore::QuantizeInfo *  quantizeInfo( void );

    // Construct using raw structures
    Options( const MagickCore::ImageInfo* imageInfo_,
             const MagickCore::QuantizeInfo* quantizeInfo_,
             const MagickCore::DrawInfo* drawInfo_ );

  protected:

  private:

    // Assignment not supported
    Options& operator= ( const Options& );

    MagickCore::ImageInfo*        _imageInfo;
    MagickCore::QuantizeInfo*     _quantizeInfo;
    MagickCore::DrawInfo*         _drawInfo;
  };
} // namespace Magick

#endif // Magick_Options_header


text:
package io.datakernel.dns;

import io.datakernel.bytebuf.ByteBuf;
import io.datakernel.common.Check;
import io.datakernel.common.inspector.AbstractInspector;
import io.datakernel.common.inspector.BaseInspector;
import io.datakernel.common.parse.ParseException;
import io.datakernel.eventloop.Eventloop;
import io.datakernel.eventloop.jmx.EventloopJmxBeanEx;
import io.datakernel.eventloop.net.DatagramSocketSettings;
import io.datakernel.jmx.api.attribute.JmxAttribute;
import io.datakernel.jmx.stats.EventStats;
import io.datakernel.net.AsyncUdpSocket;
import io.datakernel.net.AsyncUdpSocketNio;
import io.datakernel.net.UdpPacket;
import io.datakernel.promise.Promise;
import io.datakernel.promise.SettablePromise;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import static io.datakernel.common.Preconditions.checkState;
import static io.datakernel.promise.Promises.TIMEOUT_EXCEPTION;
import static io.datakernel.promise.Promises.timeout;

/**
 * Implementation of {@link AsyncDnsClient} that asynchronously
 * connects to some <i>real</i> DNS server and gets the response from it.
 */
public final class RemoteAsyncDnsClient implements AsyncDnsClient, EventloopJmxBeanEx {
	private final Logger logger = LoggerFactory.getLogger(RemoteAsyncDnsClient.class);
	private static final Boolean CHECK = Check.isEnabled(RemoteAsyncDnsClient.class);

	public static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(3);
	private static final int DNS_SERVER_PORT = 53;
	public static final InetSocketAddress GOOGLE_PUBLIC_DNS = new InetSocketAddress("8.8.8.8", DNS_SERVER_PORT);
	public static final InetSocketAddress LOCAL_DNS = new InetSocketAddress("192.168.0.1", DNS_SERVER_PORT);

	private final Eventloop eventloop;
	private final Map<DnsTransaction, SettablePromise<DnsResponse>> transactions = new HashMap<>();

	private DatagramSocketSettings datagramSocketSettings = DatagramSocketSettings.create();
	private InetSocketAddress dnsServerAddress = GOOGLE_PUBLIC_DNS;
	private Duration timeout = DEFAULT_TIMEOUT;

	@Nullable
	private AsyncUdpSocket socket;

	@Nullable
	private AsyncUdpSocketNio.Inspector socketInspector;
	@Nullable
	private Inspector inspector;

	// region creators
	private RemoteAsyncDnsClient(Eventloop eventloop) {
		this.eventloop = eventloop;
	}

	public static RemoteAsyncDnsClient create(Eventloop eventloop) {
		return new RemoteAsyncDnsClient(eventloop);
	}

	public RemoteAsyncDnsClient withDatagramSocketSetting(DatagramSocketSettings setting) {
		this.datagramSocketSettings = setting;
		return this;
	}

	public RemoteAsyncDnsClient withTimeout(Duration timeout) {
		this.timeout = timeout;
		return this;
	}

	public RemoteAsyncDnsClient withDnsServerAddress(InetSocketAddress address) {
		this.dnsServerAddress = address;
		return this;
	}

	public RemoteAsyncDnsClient withDnsServerAddress(InetAddress address) {
		this.dnsServerAddress = new InetSocketAddress(address, DNS_SERVER_PORT);
		return this;
	}

	public RemoteAsyncDnsClient withInspector(Inspector inspector) {
		this.inspector = inspector;
		return this;
	}

	public RemoteAsyncDnsClient setSocketInspector(AsyncUdpSocketNio.Inspector socketInspector) {
		this.socketInspector = socketInspector;
		return this;
	}

	// endregion

	@NotNull
	@Override
	public Eventloop getEventloop() {
		return eventloop;
	}

	@Override
	public void close() {
		if (CHECK) checkState(eventloop.inEventloopThread());
		if (socket == null) {
			return;
		}
		socket.close();
		socket = null;
		transactions.values().forEach(s -> s.setException(TIMEOUT_EXCEPTION));
	}

	private Promise<AsyncUdpSocket> getSocket() {
		AsyncUdpSocket socket = this.socket;
		if (socket != null) {
			return Promise.of(socket);
		}
		try {
			logger.trace("Incoming query, opening UDP socket");
			DatagramChannel channel = Eventloop.createDatagramChannel(datagramSocketSettings, null, dnsServerAddress);
			return AsyncUdpSocketNio.connect(eventloop, channel)
					.map(s -> this.socket = s.withInspector(socketInspector));
		} catch (IOException e) {
			logger.error("UDP socket creation failed.", e);
			return Promise.ofException(e);
		}
	}

	@Override
	public Promise<DnsResponse> resolve(DnsQuery query) {
		if (CHECK) checkState(eventloop.inEventloopThread());
		DnsResponse fromQuery = AsyncDnsClient.resolveFromQuery(query);
		if (fromQuery != null) {
			logger.trace("{} already contained an IP address within itself", query);
			return Promise.of(fromQuery);
		}
		// ignore the result because soon or later it will be sent and just completed
		// here we use that transactions map because it easily could go completely out of order and we should be ok with that
		return getSocket()
				.then(socket -> {
					logger.trace("Resolving {} with DNS server {}", query, dnsServerAddress);

					DnsTransaction transaction = DnsTransaction.of(DnsProtocol.generateTransactionId(), query);
					SettablePromise<DnsResponse> promise = new SettablePromise<>();

					transactions.put(transaction, promise);

					ByteBuf payload = DnsProtocol.createDnsQueryPayload(transaction);
					if (inspector != null) {
						inspector.onDnsQuery(query, payload);
					}

					// ignore the result because soon or later it will be sent and just completed
					socket.send(UdpPacket.of(payload, dnsServerAddress));

					// here we use that transactions map because it easily could go completely out of order and we should be ok with that
					socket.receive()
							.whenResult(packet -> {
								try {
									DnsResponse queryResult = DnsProtocol.readDnsResponse(packet.getBuf());
									SettablePromise<DnsResponse> cb = transactions.remove(queryResult.getTransaction());
									if (cb == null) {
										logger.warn("Received a DNS response that had no listener (most likely because it timed out) : {}", queryResult);
										return;
									}
									if (queryResult.isSuccessful()) {
										cb.set(queryResult);
									} else {
										cb.setException(new DnsQueryException(RemoteAsyncDnsClient.class, queryResult));
									}
									closeIfDone();
								} catch (ParseException e) {
									logger.warn("Received a UDP packet than cannot be parsed as a DNS server response.", e);
								} finally {
									packet.recycle();
								}
							});

					return timeout(timeout, promise)
							.thenEx((queryResult, e) -> {
								if (e == null) {
									if (inspector != null) {
										inspector.onDnsQueryResult(query, queryResult);
									}
									logger.trace("DNS query {} resolved as {}", query, queryResult.getRecord());
									return Promise.of(queryResult);
								}
								if (e == TIMEOUT_EXCEPTION) {
									if (inspector != null) {
										inspector.onDnsQueryExpiration(query);
									}
									logger.trace("{} timed out", query);
									e = new DnsQueryException(RemoteAsyncDnsClient.class, DnsResponse.ofFailure(transaction, DnsProtocol.ResponseErrorCode.TIMED_OUT));
									transactions.remove(transaction);
									closeIfDone();
								} else if (inspector != null) {
									inspector.onDnsQueryError(query, e);
								}
								return Promise.ofException(e);
							});
				});
	}

	private void closeIfDone() {
		if (!transactions.isEmpty()) {
			return;
		}
		logger.trace("All queries are completed, closing UDP socket");
		close(); // transactions is empty so no loops here
	}

	// region JMX
	public interface Inspector extends BaseInspector<Inspector> {
		void onDnsQuery(DnsQuery query, ByteBuf payload);

		void onDnsQueryResult(DnsQuery query, DnsResponse result);

		void onDnsQueryError(DnsQuery query, Throwable e);

		void onDnsQueryExpiration(DnsQuery query);
	}

	public abstract static class ForwardingInspector implements Inspector {
		protected final @Nullable Inspector next;

		public ForwardingInspector(@Nullable Inspector next) {this.next = next;}

		@Override
		public void onDnsQuery(DnsQuery query, ByteBuf payload) {
			if (next != null) next.onDnsQuery(query, payload);
		}

		@Override
		public void onDnsQueryResult(DnsQuery query, DnsResponse result) {
			if (next != null) next.onDnsQueryResult(query, result);
		}

		@Override
		public void onDnsQueryError(DnsQuery query, Throwable e) {
			if (next != null) next.onDnsQueryError(query, e);
		}

		@Override
		public void onDnsQueryExpiration(DnsQuery query) {
			if (next != null) next.onDnsQueryExpiration(query);
		}

		@SuppressWarnings("unchecked")
		@Override
		public <T extends Inspector> @Nullable T lookup(Class<T> type) {
			return type.isAssignableFrom(this.getClass()) ? (T) this : next != null ? next.lookup(type) : null;
		}
	}

	public static class JmxInspector extends AbstractInspector<Inspector> implements Inspector {
		private static final Duration SMOOTHING_WINDOW = Duration.ofMinutes(1);

		private final EventStats queries = EventStats.create(SMOOTHING_WINDOW);
		private final EventStats failedQueries = EventStats.create(SMOOTHING_WINDOW);
		private final EventStats expirations = EventStats.create(SMOOTHING_WINDOW);

		@Override
		public void onDnsQuery(DnsQuery query, ByteBuf payload) {
			queries.recordEvent();
		}

		@Override
		public void onDnsQueryResult(DnsQuery query, DnsResponse result) {
			if (!result.isSuccessful()) {
				failedQueries.recordEvent();
			}
		}

		@Override
		public void onDnsQueryError(DnsQuery query, Throwable e) {
			failedQueries.recordEvent();
		}

		@Override
		public void onDnsQueryExpiration(DnsQuery query) {
			expirations.recordEvent();
		}

		@JmxAttribute
		public EventStats getQueries() {
			return queries;
		}

		@JmxAttribute
		public EventStats getFailedQueries() {
			return failedQueries;
		}

		@JmxAttribute
		public EventStats getExpirations() {
			return expirations;
		}
	}
	// endregion

	@JmxAttribute
	@Nullable
	public AsyncUdpSocketNio.JmxInspector getSocketStats() {
		return BaseInspector.lookup(socketInspector, AsyncUdpSocketNio.JmxInspector.class);
	}

	@JmxAttribute(name = "")
	@Nullable
	public JmxInspector getStats() {
		return BaseInspector.lookup(inspector, JmxInspector.class);
	}
}

redpajama_set_name: RedPajamaGithub


text:
@extends('layouts.admin')
@section('pageTitle') Dashboard @stop
@section('breadcumb')

    Dashboard

@stop

@section('content')

		    {!! Form::model($material_user, array('route' => ['admin.update.material_user', Crypt::encrypt($material_user->id)], 'id' => 'department_update', 'class' => 'form-horizontal row-border')) !!}

		        @include('admin.users.material._form')

has('material_user_role_id') ? 'has-error' : ''}}">
				  {!! Form::label('material_user_role_id', 'Role', array('class' => 'col-md-3 control-label')) !!}

				    <select multiple="multiple" name="material_user_role_ids[]" id="material_user_role_ids" class="multi-select">

				      	@foreach($roles_arr as $k => $v)
							<option value="{{ $v['material_user_role_id'] }}" @if($v['is_selected']) selected="selected" @endif >{{ $v['material_user_role_name'] }}</option>
				      	@endforeach

				    </select>

				  {!! $errors->first('material_user_role_id', ':message') !!}

		        {!! Form::label('', '', array('class' => 'col-md-2 control-label')) !!}
		        {!! Form:: submit('Update', ['class' => 'btn btn-success']) !!}
		    {!!form::close()!!}

@endsection


text:
namespace FileGenerator
{
    using System.Collections.Generic;

    using Parts.Models;
    using XmlPartsParser;
    using ImpotFileGenerator;

    class GenerateImportFile
    {
        static void Main(string[] args)
        {
            PartsParser xmlParser = new PartsParser();
            var partsInfo = xmlParser.FromXml("export.xml");

            IImportFileGenerator generator = new ExcelImportFileGenerator();
            generator.GenerateImportFile(partsInfo);
        }
    }
}


text:
Localizing our website and apps is a very important part of making elementary OS available to as many people as possible. Instead of relying solely on an internal translation team, we use crowdsourcing so that anyone can submit translations with little to no technical knowledge. In order to keep our voice consistent across the entire platform, and to help new translators get started, we've put together this translation guide.

## Translating Applications {#translating-applications}

Apps are translated through Rosetta: the translation interface hosted on Launchpad. In order to submit translations, you should:

* Have a [Launchpad account](https://launchpad.net/+login)
* Set your [language preferences](https://launchpad.net/people/+me/+editlanguages)
* Browse our [translatable projects](https://translations.launchpad.net/elementary)

Once you've made a selection, you can provide suggestions for strings that have not yet been translated, or suggest changes to strings that have already been translated. These suggestions will be evaluated by a translation team member and they will choose the most appropriate one. For a more information about Rosetta, you can refer to their [documentation](https://help.launchpad.net/Translations/StartingToTranslate).

When translating you may encounter a situation where you have to decide between several ways of saying the same thing. In these situations we refer to the Ubuntu [general translator guide](https://help.launchpad.net/Translations/Guide), and for language specific issues we follow Ubuntu's [team translation guidelines](https://translations.launchpad.net/+groups/ubuntu-translators). Following these guides ensure uniform translations, while also allowing anyone to contribute.

If you don't want to use Rosetta, or want to make a lot a changes at once, you can also translate offline. To do so:

* Go to a project you want to translate
* Choose your language
* Click on "Download translation"

You are now able to request an e-mail, which gives you the right link to download the translations. Now:

* Choose your favorite text- or po-editor (e.g. [Poedit](https://apps.ubuntu.com/cat/applications//poedit/))
* Start translating

Once you've finished, use the "Upload translation" option on the same page that you downloaded them from.

## Translating our Website {#translating-our-website}

Our website is translated through [Transifex](https://www.transifex.com/projects/p/elementary-mvp/). In order to submit translations, you should:

* Have a [Transifex account](https://www.transifex.com/signup/)
* Join our [translation team](https://www.transifex.com/projects/p/elementary-mvp/)

For more information about Transifex, you can refer to their [documentation](http://docs.transifex.com/tutorials/txeditor).

As with our apps, we follow Ubuntu's [general translator guide](https://help.launchpad.net/Translations/Guide), and for language specific issues we follow Ubuntu's [team translation guidelines](https://translations.launchpad.net/+groups/ubuntu-translators).


text:
<?php

namespace DoctrineDbalIbmi\Platform;

use Doctrine\DBAL\Platforms\DB2Platform;

class DB2IBMiPlatform extends DB2Platform
{
    /**
     * {@inheritDoc}
     */
    public function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
            'smallint'      => 'smallint',
            'bigint'        => 'bigint',
            'integer'       => 'integer',
            'rowid'         => 'integer',
            'time'          => 'time',
            'date'          => 'date',
            'varchar'       => 'string',
            'character'     => 'string',
            'char'          => 'string',
            'nvarchar'          => 'string',
            'nchar'          => 'string',
            'char () for bit data' => 'string',
            'varchar () for bit data' => 'string',
            'varg'          => 'string',
            'vargraphic'          => 'string',
            'graphic'       => 'string',
            'varbinary'     => 'binary',
            'binary'        => 'binary',
            'varbin'        => 'binary',
            'clob'          => 'text',
            'nclob'          => 'text',
            'dbclob'        => 'text',
            'blob'          => 'blob',
            'decimal'       => 'decimal',
            'numeric'       => 'float',
            'double'        => 'float',
            'real'          => 'float',
            'float'         => 'float',
            'timestamp'     => 'datetime',
            'timestmp'      => 'datetime',
        );
    }

    /**
     * {@inheritDoc}
     */
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
            : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
    }

    /**
     * {@inheritDoc}
     */
    public function getListTableColumnsSQL($table, $database = null)
    {
        return "
            SELECT DISTINCT
               c.column_def as default,
               c.table_schem as tabschema,
               c.table_name as tabname,
               c.column_name as colname,
               c.ordinal_position as colno,
               c.type_name as typename,
               c.is_nullable as nulls,
               c.column_size as length,
               c.decimal_digits as scale,
               CASE
                   WHEN c.pseudo_column = 2 THEN 'YES'
                   ELSE 'NO'
               END as identity,
               pk.constraint_type AS tabconsttype,
               pk.key_seq as colseq,
               CASE
                   WHEN c.HAS_DEFAULT = 'J' THEN 1
                   ELSE 0
               END AS autoincrement
             FROM SYSIBM.sqlcolumns as c
             LEFT JOIN
             (
                SELECT
                tc.TABLE_SCHEMA,
                tc.TABLE_NAME,
                tc.CONSTRAINT_TYPE,
                spk.COLUMN_NAME,
                spk.KEY_SEQ
                FROM SYSIBM.TABLE_CONSTRAINTS tc
                LEFT JOIN SYSIBM.SQLPRIMARYKEYS spk
                    ON tc.CONSTRAINT_NAME = spk.PK_NAME AND tc.TABLE_SCHEMA = spk.TABLE_SCHEM AND tc.TABLE_NAME = spk.TABLE_NAME
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                AND UPPER(tc.TABLE_NAME) = UPPER('" . $table . "')
                ". ($database !== null ? "AND tc.TABLE_SCHEMA = UPPER('" . $database . "')" : '') ."
             ) pk ON
                c.TABLE_SCHEM = pk.TABLE_SCHEMA
                AND c.TABLE_NAME = pk.TABLE_NAME
                AND c.COLUMN_NAME = pk.COLUMN_NAME
             WHERE
                UPPER(c.TABLE_NAME) = UPPER('" . $table . "')
                ". ($database  !== null ? "AND c.TABLE_SCHEM = UPPER('" . $database . "')" : '') ."
             ORDER BY c.ordinal_position
        ";
    }

    /**
     * {@inheritDoc}
     */
    public function getListTablesSQL($database = null)
    {
        return "
            SELECT
              DISTINCT NAME
            FROM
                SYSIBM.tables t
            WHERE
              table_type='BASE TABLE'
              ". ($database !== null ? "AND t.TABLE_SCHEMA = UPPER('" . $database . "')" : '') ."
            ORDER BY NAME
        ";
    }

    /**
     * {@inheritDoc}
     */
    public function getListViewsSQL($database = null)
    {
        return "
            SELECT
              DISTINCT NAME,
              TEXT
            FROM QSYS2.sysviews v
            WHERE 1=1
            ". ($database !== null ? "AND v.TABLE_SCHEMA = UPPER('" . $database . "')" : '') ."
            ORDER BY NAME
        ";
    }

    /**
     * {@inheritDoc}
     */
    public function getListTableIndexesSQL($table, $database = null)
    {
        return  "
            SELECT
                  scc.CONSTRAINT_NAME as key_name,
                  scc.COLUMN_NAME as column_name,
                  CASE
                      WHEN sc.CONSTRAINT_TYPE = 'PRIMARY KEY' THEN 1
                      ELSE 0
                  END AS primary,
                  CASE
                      WHEN sc.CONSTRAINT_TYPE = 'UNIQUE' THEN 0
                      ELSE 1
                  END AS non_unique
              FROM
              QSYS2.syscstcol scc
              LEFT JOIN QSYS2.syscst sc ON
                  scc.TABLE_SCHEMA = sc.TABLE_SCHEMA AND scc.TABLE_NAME = sc.TABLE_NAME AND scc.CONSTRAINT_NAME = sc.CONSTRAINT_NAME
            WHERE scc.TABLE_NAME = UPPER('" . $table . "')
            ". ($database !== null ? "AND scc.TABLE_SCHEMA = UPPER('" . $database . "')" : '') ."
        ";
    }

    /**
     * {@inheritDoc}
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
        return "
            SELECT DISTINCT
                fk.COLUMN_NAME AS local_column,
                pk.TABLE_NAME AS foreign_table,
                pk.COLUMN_NAME AS foreign_column,
                fk.CONSTRAINT_NAME AS index_name,
                rc.UPDATE_RULE AS on_update,
                rc.DELETE_RULE AS on_delete
            FROM QSYS2.REFERENTIAL_CONSTRAINTS rc
            LEFT JOIN QSYS2.SYSCSTCOL fk ON
                rc.CONSTRAINT_SCHEMA = fk.CONSTRAINT_SCHEMA AND
                rc.CONSTRAINT_NAME = fk.CONSTRAINT_NAME
            LEFT JOIN QSYS2.SYSCSTCOL pk ON
                rc.UNIQUE_CONSTRAINT_SCHEMA = pk.CONSTRAINT_SCHEMA AND
                rc.UNIQUE_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
            WHERE fk.TABLE_NAME = UPPER('" . $table . "')
            " . ($database !== null ? "AND fk.TABLE_SCHEMA = UPPER('" . $database . "')" : '') . "
        ";
    }

    /**
     * @return string
     *
     * @throws \Doctrine\DBAL\DBALException If not supported on this platform.
     */
    public function getListDatabasesSQL()
    {
        return "
            SELECT
              DISTINCT TABLE_SCHEMA
            FROM
                SYSIBM.tables t
            ORDER BY TABLE_SCHEMA
        ";
    }

    /**
     * {@inheritDoc}
     */
    public function getCreateDatabaseSQL($database)
    {
        return "CREATE COLLECTION ".$database;
    }

    /**
     * {@inheritDoc}
     */
    protected function doModifyLimitQuery($query, $limit, $offset = null)
    {
        if ($limit === null && $offset <= 0) {
            return $query;
        }

        $limit = (int) $limit;
        $offset = (int) (($offset)?:0);

        // In cases where an offset isn't required, we can use the much simpler FETCH FIRST (as the ROW_NUMBER() method
        // leaves a lot to be desired (i.e. breaks in some cases)
        if ($offset === 0) {
            return sprintf('%s FETCH FIRST %d ROWS ONLY', $query, $limit);
        }

        $orderBy = stristr($query, 'ORDER BY');

        $orderByBlocks = preg_split('/\s*ORDER\s+BY/', $orderBy );

        // Reversing arrays beacause external order by is more important
        $orderByBlocks = array_reverse($orderByBlocks);

        // Splitting ORDER BY
        $orderByParts = array();
        foreach ($orderByBlocks as $orderByBlock){
            $blockArray   = explode(',', $orderByBlock);
            foreach ($blockArray as $block) {
                $block = trim($block);
                if (!empty($block)) {
                    $orderByParts[] = $block;
                }
            }
        }

        // Clear ORDER BY
        foreach ($orderByParts as &$orderByPart) {

            $orderByPart = preg_replace('/ORDER\s+BY\s+([^\)]*)(.*)/', '$1', 'ORDER BY '.$orderByPart);
        }

        $orderByColumns = array();

        // Split ORDER BY into parts
        foreach ($orderByParts as &$part) {

            if (preg_match('/(([^\s]*)\.)?([^\.\s]*)\s*(ASC|DESC)?/i', trim($part), $matches)) {
                $orderByColumns[] = array(
                    'column'    => $matches[3],
                    'hasTable'  => ( !empty($matches[2])),
                    'sort'      => isset($matches[4]) ? $matches[4] : null,
                    'table'     => empty($matches[2]) ? '[^\.\s]*' : $matches[2]
                );
            }
        }

        // Find alias for each colum used in ORDER BY
        if ( ! empty($orderByColumns)) {
            foreach ($orderByColumns as $column) {

                $pattern = sprintf('/%s\.%s\s+(?:AS\s+)?([^,\s)]+)/i', $column['table'], $column['column']);
                $overColumn = preg_match($pattern, $query, $matches)
                    ? ($column['hasTable'] ? $column['table']  . '.' : '') . $column['column']
                    : $column['column'];

                if (isset($column['sort'])) {
                    $overColumn .= ' ' . $column['sort'];
                }

                $overColumns[] = $overColumn;
            }
        }

        // Replace only first occurrence of FROM with $over to prevent changing FROM also in subqueries.
        if ( ! $orderBy) {
            $over = '';
        }
        else
        {
            $over  = 'ORDER BY ' . implode(', ', $overColumns);
        }

        $sql = 'SELECT DOCTRINE_TBL.* FROM (SELECT DOCTRINE_TBL1.*, ROW_NUMBER() OVER(' . $over . ') AS DOCTRINE_ROWNUM '.
            'FROM (' . $query . ') DOCTRINE_TBL1) DOCTRINE_TBL WHERE DOCTRINE_TBL.DOCTRINE_ROWNUM BETWEEN ' . ($offset+1) .' AND ' . ($offset+$limit);

        return $sql;
    }

    /**
     * {@inheritDoc}
     */
    public function getDateTimeFormatString()
    {
        return 'Y-m-d-H.i.s.u';
    }
}


text:
import {bind} from 'hyperhtml';
import {MDCTextfield} from '@material/textfield';

/**
 * A sample dummy
 */
export default class Search {
  /**
   * Default constructor for setting the values
   *
   * @param {HTMLElement} element - The HTML element to bind/adopt
   */
  constructor(element) {
    this.element = element;
  }

  /**
   * Renders the player.
   *
   * @return {HTMLElement} The rendered element
   */
  render() {
    console.log(`Render Search`);

    const element = bind(this.element)`

Näyttelijän nimi

          <input
            type="text"
            class="mdc-textfield__input"
            id="my-textfield"
            aria-controls="my-textfield-helptext"
            data-demo-no-auto-js="">

              Etunimi, sukunimi tai molemmat

        <button
          class="mdc-button mdc-button--raised mdc-button--accent mdc-card__action"
          id="searchButton">
            Suorita haku
        </button>

LeffaLegendat Tiimi

Taina, Kaisa, Eero ja Teemu

Käytimme kahta APIa

            <button
              class="
                mdc-button
                mdc-button--raised
                mdc-button--accent
                mdc-card__action"
              onclick="window.location.href='http://developer.yle.fi/'"
            >
                YLE API
            </button>
            <button
              class="
                mdc-button
                mdc-button--raised
                mdc-button--accent
                mdc-card__action"
                onclick="window.location.href='https://www.themoviedb.org/documentation/api'"
                target="_blank"
            >
              The Movide DB
            </button>

    `;
    const textField = element.querySelector('.mdc-textfield');
    //console.log('heippa', MDCTextfield);
    MDCTextfield.attachTo(textField);

    document.getElementById("searchButton").addEventListener("click", function() { document.location.hash = "#haku/" + document.getElementById("my-textfield").value }, false);

    return element;
  }
}


text:
package com.mm.engine.framework.data.persistence.orm.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 定义列名
 *
 * @author huangyong
 * @since 1.0
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {

    String value();
}


text:
class SecurityHeaders
  HEADERS = {
    'X-XSS-Protection' => '1; mode=block',
    'X-Frame-Options' => 'deny',
  }

  SKIP_PATHS = %w(
  )

  def initialize(app)
    @app = app
  end

  def call(env)
    response = @app.call env
    response[1].merge!(HEADERS) unless SKIP_PATHS.any?{ |p| env['PATH_INFO'].start_with? p }
    response[1].delete 'X-Runtime' # NOTE https://github.com/rails/rails/issues/1043
    response
  end
end


text:
#include <aws/migration-hub-refactor-spaces/model/ServiceQuotaExceededException.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MigrationHubRefactorSpaces
{
namespace Model
{

ServiceQuotaExceededException::ServiceQuotaExceededException() :
    m_messageHasBeenSet(false),
    m_quotaCodeHasBeenSet(false),
    m_resourceIdHasBeenSet(false),
    m_resourceTypeHasBeenSet(false),
    m_serviceCodeHasBeenSet(false)
{
}

ServiceQuotaExceededException::ServiceQuotaExceededException(JsonView jsonValue) :
    m_messageHasBeenSet(false),
    m_quotaCodeHasBeenSet(false),
    m_resourceIdHasBeenSet(false),
    m_resourceTypeHasBeenSet(false),
    m_serviceCodeHasBeenSet(false)
{
  *this = jsonValue;
}

ServiceQuotaExceededException& ServiceQuotaExceededException::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Message"))
  {
    m_message = jsonValue.GetString("Message");

    m_messageHasBeenSet = true;
  }

  if(jsonValue.ValueExists("QuotaCode"))
  {
    m_quotaCode = jsonValue.GetString("QuotaCode");

    m_quotaCodeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ResourceId"))
  {
    m_resourceId = jsonValue.GetString("ResourceId");

    m_resourceIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ResourceType"))
  {
    m_resourceType = jsonValue.GetString("ResourceType");

    m_resourceTypeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ServiceCode"))
  {
    m_serviceCode = jsonValue.GetString("ServiceCode");

    m_serviceCodeHasBeenSet = true;
  }

  return *this;
}

JsonValue ServiceQuotaExceededException::Jsonize() const
{
  JsonValue payload;

  if(m_messageHasBeenSet)
  {
   payload.WithString("Message", m_message);

  }

  if(m_quotaCodeHasBeenSet)
  {
   payload.WithString("QuotaCode", m_quotaCode);

  }

  if(m_resourceIdHasBeenSet)
  {
   payload.WithString("ResourceId", m_resourceId);

  }

  if(m_resourceTypeHasBeenSet)
  {
   payload.WithString("ResourceType", m_resourceType);

  }

  if(m_serviceCodeHasBeenSet)
  {
   payload.WithString("ServiceCode", m_serviceCode);

  }

  return payload;
}

} // namespace Model
} // namespace MigrationHubRefactorSpaces
} // namespace Aws


text:
package describe

import (
	"reflect"
	"strings"
	"testing"
	"time"

	kapi "k8s.io/kubernetes/pkg/api"
	ktestclient "k8s.io/kubernetes/pkg/client/testclient"
	"k8s.io/kubernetes/pkg/kubectl"
	"k8s.io/kubernetes/pkg/labels"
	kutil "k8s.io/kubernetes/pkg/util"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	buildapi "github.com/openshift/origin/pkg/build/api"
	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/client/testclient"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	deployapitest "github.com/openshift/origin/pkg/deploy/api/test"
	deployutil "github.com/openshift/origin/pkg/deploy/util"
	imageapi "github.com/openshift/origin/pkg/image/api"
	oauthapi "github.com/openshift/origin/pkg/oauth/api"
	projectapi "github.com/openshift/origin/pkg/project/api"
	sdnapi "github.com/openshift/origin/pkg/sdn/api"
)

type describeClient struct {
	T         *testing.T
	Namespace string
	Err       error
	*testclient.Fake
}

// DescriberCoverageExceptions is the list of API types that do NOT have corresponding describers
// If you add something to this list, explain why it doesn't need validation.  waaaa is not a valid
// reason.
var DescriberCoverageExceptions = []reflect.Type{
	reflect.TypeOf(&buildapi.BuildLogOptions{}),                       // normal users don't ever look at these
	reflect.TypeOf(&buildapi.BuildRequest{}),                          // normal users don't ever look at these
	reflect.TypeOf(&imageapi.DockerImage{}),                           // not a top level resource
	reflect.TypeOf(&oauthapi.OAuthAccessToken{}),                      // normal users don't ever look at these
	reflect.TypeOf(&oauthapi.OAuthAuthorizeToken{}),                   // normal users don't ever look at these
	reflect.TypeOf(&oauthapi.OAuthClientAuthorization{}),              // normal users don't ever look at these
	reflect.TypeOf(&deployapi.DeploymentConfigRollback{}),             // normal users don't ever look at these
	reflect.TypeOf(&projectapi.ProjectRequest{}),                      // normal users don't ever look at these
	reflect.TypeOf(&authorizationapi.IsPersonalSubjectAccessReview{}), // not a top level resource

	// these resources can't be "GET"ed, so you can't make a describer for them
	reflect.TypeOf(&authorizationapi.SubjectAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.SubjectAccessReview{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReview{}),
	reflect.TypeOf(&authorizationapi.LocalSubjectAccessReview{}),
	reflect.TypeOf(&authorizationapi.LocalResourceAccessReview{}),
}

// MissingDescriberCoverageExceptions is the list of types that were missing describer methods when I started
// You should never add to this list
// TODO describers should be added for these types
var MissingDescriberCoverageExceptions = []reflect.Type{
	reflect.TypeOf(&imageapi.ImageStreamMapping{}),
	reflect.TypeOf(&oauthapi.OAuthClient{}),
	reflect.TypeOf(&sdnapi.ClusterNetwork{}),
	reflect.TypeOf(&sdnapi.HostSubnet{}),
	reflect.TypeOf(&sdnapi.NetNamespace{}),
}

func TestDescriberCoverage(t *testing.T) {
	c := &client.Client{}

main:
	for _, apiType := range kapi.Scheme.KnownTypes("") {
		if !strings.Contains(apiType.PkgPath(), "openshift/origin") {
			continue
		}
		// we don't describe lists
		if strings.HasSuffix(apiType.Name(), "List") {
			continue
		}

		ptrType := reflect.PtrTo(apiType)
		for _, exception := range DescriberCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}
		for _, exception := range MissingDescriberCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}

		_, ok := DescriberFor(apiType.Name(), c, &ktestclient.Fake{}, "")
		if !ok {
			t.Errorf("missing printer for %v.  Check pkg/cmd/cli/describe/describer.go", apiType)
		}
	}
}

func TestDescribers(t *testing.T) {
	fake := &testclient.Fake{}
	fakeKube := &ktestclient.Fake{}
	c := &describeClient{T: t, Namespace: "foo", Fake: fake}

	testDescriberList := []kubectl.Describer{
		&BuildDescriber{c, fakeKube},
		&BuildConfigDescriber{c, ""},
		&BuildLogDescriber{c},
		&ImageDescriber{c},
		&ImageStreamDescriber{c},
		&ImageStreamTagDescriber{c},
		&ImageStreamImageDescriber{c},
		&RouteDescriber{c},
		&ProjectDescriber{c, fakeKube},
		&PolicyDescriber{c},
		&PolicyBindingDescriber{c},
		&TemplateDescriber{c, nil, nil, nil},
	}

	for _, d := range testDescriberList {
		out, err := d.Describe("foo", "bar")
		if err != nil {
			t.Errorf("unexpected error for %v: %v", d, err)
		}
		if !strings.Contains(out, "Name:") || !strings.Contains(out, "Labels:") {
			t.Errorf("unexpected out: %s", out)
		}
	}
}

func TestDeploymentConfigDescriber(t *testing.T) {
	config := deployapitest.OkDeploymentConfig(1)
	deployment, _ := deployutil.MakeDeployment(config, kapi.Codec)
	podList := &kapi.PodList{}
	eventList := &kapi.EventList{}
	deploymentList := &kapi.ReplicationControllerList{}

	d := &DeploymentConfigDescriber{
		client: &genericDeploymentDescriberClient{
			getDeploymentConfigFunc: func(namespace, name string) (*deployapi.DeploymentConfig, error) {
				return config, nil
			},
			getDeploymentFunc: func(namespace, name string) (*kapi.ReplicationController, error) {
				return deployment, nil
			},
			listDeploymentsFunc: func(namespace string, selector labels.Selector) (*kapi.ReplicationControllerList, error) {
				return deploymentList, nil
			},
			listPodsFunc: func(namespace string, selector labels.Selector) (*kapi.PodList, error) {
				return podList, nil
			},
			listEventsFunc: func(deploymentConfig *deployapi.DeploymentConfig) (*kapi.EventList, error) {
				return eventList, nil
			},
		},
	}

	describe := func() {
		if output, err := d.Describe("test", "deployment"); err != nil {
			t.Fatalf("unexpected error: %v", err)
		} else {
			t.Logf("describer output:\n%s\n", output)
		}
	}

	podList.Items = []kapi.Pod{*mkPod(kapi.PodRunning, 0)}
	describe()

	config.Triggers = append(config.Triggers, deployapitest.OkConfigChangeTrigger())
	describe()

	config.Template.Strategy = deployapitest.OkCustomStrategy()
	describe()

	config.Triggers[0].ImageChangeParams.RepositoryName = ""
	config.Triggers[0].ImageChangeParams.From = kapi.ObjectReference{Name: "imageRepo"}
	describe()

	config.Template.Strategy = deployapitest.OkStrategy()
	config.Template.Strategy.RecreateParams = &deployapi.RecreateDeploymentStrategyParams{
		Pre: &deployapi.LifecycleHook{
			FailurePolicy: deployapi.LifecycleHookFailurePolicyAbort,
			ExecNewPod: &deployapi.ExecNewPodHook{
				ContainerName: "container",
				Command:       []string{"/command1", "args"},
				Env: []kapi.EnvVar{
					{
						Name:  "KEY1",
						Value: "value1",
					},
				},
			},
		},
		Post: &deployapi.LifecycleHook{
			FailurePolicy: deployapi.LifecycleHookFailurePolicyIgnore,
			ExecNewPod: &deployapi.ExecNewPodHook{
				ContainerName: "container",
				Command:       []string{"/command2", "args"},
				Env: []kapi.EnvVar{
					{
						Name:  "KEY2",
						Value: "value2",
					},
				},
			},
		},
	}
	describe()
}

func TestDescribeBuildDuration(t *testing.T) {
	type testBuild struct {
		build  *buildapi.Build
		output string
	}

	creation := kutil.Date(2015, time.April, 9, 6, 0, 0, 0, time.Local)
	// now a minute ago
	minuteAgo := kutil.Unix(kutil.Now().Rfc3339Copy().Time.Unix()-60, 0)
	start := kutil.Date(2015, time.April, 9, 6, 1, 0, 0, time.Local)
	completion := kutil.Date(2015, time.April, 9, 6, 2, 0, 0, time.Local)
	duration := completion.Rfc3339Copy().Time.Sub(start.Rfc3339Copy().Time)
	zeroDuration := time.Duration(0)

	tests := []testBuild{
		{ // 0 - build new
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: minuteAgo},
				Status: buildapi.BuildStatus{
					Phase:    buildapi.BuildPhaseNew,
					Duration: zeroDuration,
				},
			},
			"waiting for 1m0s",
		},
		{ // 1 - build pending
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: minuteAgo},
				Status: buildapi.BuildStatus{
					Phase:    buildapi.BuildPhasePending,
					Duration: zeroDuration,
				},
			},
			"waiting for 1m0s",
		},
		{ // 2 - build running
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					StartTimestamp: &start,
					Phase:          buildapi.BuildPhaseRunning,
					Duration:       duration,
				},
			},
			"running for 1m0s",
		},
		{ // 3 - build completed
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					StartTimestamp:      &start,
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseComplete,
					Duration:            duration,
				},
			},
			"1m0s",
		},
		{ // 4 - build failed
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					StartTimestamp:      &start,
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseFailed,
					Duration:            duration,
				},
			},
			"1m0s",
		},
		{ // 5 - build error
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					StartTimestamp:      &start,
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseError,
					Duration:            duration,
				},
			},
			"1m0s",
		},
		{ // 6 - build cancelled before running, start time wasn't set yet
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseCancelled,
					Duration:            duration,
				},
			},
			"waited for 2m0s",
		},
		{ // 7 - build cancelled while running, start time is set already
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					StartTimestamp:      &start,
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseCancelled,
					Duration:            duration,
				},
			},
			"1m0s",
		},
		{ // 8 - build failed before running, start time wasn't set yet
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseFailed,
					Duration:            duration,
				},
			},
			"waited for 2m0s",
		},
		{ // 9 - build error before running, start time wasn't set yet
			&buildapi.Build{
				ObjectMeta: kapi.ObjectMeta{CreationTimestamp: creation},
				Status: buildapi.BuildStatus{
					CompletionTimestamp: &completion,
					Phase:               buildapi.BuildPhaseError,
					Duration:            duration,
				},
			},
			"waited for 2m0s",
		},
	}

	for i, tc := range tests {
		if actual, expected := describeBuildDuration(tc.build), tc.output; actual != expected {
			t.Errorf("(%d) expected duration output %s, got %s", i, expected, actual)
		}
	}
}

func mkPod(status kapi.PodPhase, exitCode int) *kapi.Pod {
	return &kapi.Pod{
		ObjectMeta: kapi.ObjectMeta{Name: "PodName"},
		Status: kapi.PodStatus{
			Phase: status,
			ContainerStatuses: []kapi.ContainerStatus{
				{
					State: kapi.ContainerState{
						Terminated: &kapi.ContainerStateTerminated{ExitCode: exitCode},
					},
				},
			},
		},
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<package format="2">
  <name>bitbots_ipm</name>
  <version>1.0.0</version>
  <description>This sets up the inverse perspective mapping nodes</description>

  <maintainer email="florian.vahl@informatik.uni-hamburg.de">Florian Vahl</maintainer>
  <maintainer email="info@bit-bots.de">Hamburg Bit-Bots</maintainer>
  <author email="info@bit-bots.de">Hamburg Bit-Bots</author>
  <license>MIT</license>

  <depend>soccer_ipm</depend>
  <depend>ipm_image_node</depend>
  <depend>soccer_vision_3d_rviz_markers</depend>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>


text:
<!---
  language: cs
-->

# Time-specific salutation

Generates a simple greeting based on the time of day.

```C#
public static string Salutation()
{
    var now = System.DateTime.Now;
    return
        now.Hour < 12 ? "Good morning" :
        now.Hour < 18 ? "Good afternoon" :
        now.Hour < 21 ? "Good evening" :
        /* otherwise */ "Good night";
}
```

## Usage

```C#
 System.Diagnostics.Debug.WriteLine(Salutation());
 ```

## See also

[DateTime](https://msdn.microsoft.com/library/windows/apps/windows.foundation.datetime.aspx)
[?: operator](https://msdn.microsoft.com/library/ty67wk28.aspx)


text:
/**
 * Created by Sundresh H D on 23-10-2014.
 */
var User = require('../models/user');

module.exports = function(req, res){
    User.update({ 'username' :  req.user.username }, {$set: {status: 'offline'}}, function(err, user){
        if(err){ throw err }
        else {
            console.log(user.username + ' is now ' + user.status);
            req.logout();
            res.redirect('/');
        }
    });
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.webside.aop (webside 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2017-07-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

com.webside.aop

类

LogAspect


text:
package cn.newcapec.foundation.privilege.dao;

import org.springframework.stereotype.Repository;

import cn.newcapec.foundation.privilege.dao.base.BaseResourcetypeDAO;

/**
 * 资源类型接口类
 * @author andy.li
 *
 */
@Repository("resourcetypeDAO")
public class ResourcetypeDAO  extends BaseResourcetypeDAO{

}


text:
import tests.model_control.test_ozone_custom_models_enabled as testmod

testmod.build_model( ['Fisher'] , ['PolyTrend'] , ['BestCycle'] , ['SVR'] );


text:
package action

import (
	"flag"
	"fmt"
)

type sessionInfo struct {
	*config
}

func SessionInfoAction() Action {
	return &sessionInfo{
		config: &gConfig,
	}
}

func (s *sessionInfo) CommandFlags() *flag.FlagSet {
	return s.newFlagSet(FLAG_DATACENTER, FLAG_OUTPUT, FLAG_CONSISTENCY)
}

func (s *sessionInfo) Run(args []string) error {
	if len(args) != 1 {
		return fmt.Errorf("A single session Id must be specified")
	}
	sessionid := args[0]

	client, err := s.newSession()
	if err != nil {
		return err
	}

	queryOpts := s.queryOptions()

	session, _, err := client.Info(sessionid, queryOpts)
	if err != nil {
		return err
	}

	return s.Output(session)
}


text:
package ddf.minim.ugens;

import ddf.minim.UGen;

/**
 * Just outputs a constant value.
 *
 * @example Synthesis/constantExample
 *
 * @author Anderson Mills
 *
 * @related UGen
 *
 */
public class Constant extends UGen
{
	private float value;

	/**
	 * Empty constructor for Constant.
	 * Sets value to 1.0.
	 */
	public Constant()
	{
		this( 1.0f );
	}

	/**
	 * Constructor for Constant.
	 * Sets value to val.
	 * @param val
	 * 			float: the constant value this will output
	 */
	public Constant( float val )
	{
		super();
		value = val;
	}

	/**
	 * Sets the value of the Constant during execution.
	 *
	 * @param val
	 * 			float: the constant value this will output
	 *
	 * @example Synthesis/constantExample
	 *
	 * @related Constant
	 */
	public void setConstant( float val )
	{
		value = val;
	}

	@Override
	protected void uGenerate( float[] channels )
	{
		for(int i = 0; i < channels.length; i++)
		{
			channels[ i ] = value;
		}
	}
}


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.resources.commerce.catalog.admin.attributedefinition;

import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang3.StringUtils;
import com.mozu.api.DataViewMode;
/**
 * Use the Product Types resource to manage the types for your product catalog. Product types act as configuration templates, which store a set of attributes common to all products associated with that type. Unlike categories, products can only be associated with a single product type.
 *
 */
public class ProductTypeResource {
	///
	/// <see cref="Mozu.Api.ApiContext"/>
	///
	private ApiContext _apiContext;

	private DataViewMode _dataViewMode;

	public ProductTypeResource(ApiContext apiContext)
	{
		_apiContext = apiContext;
		_dataViewMode = DataViewMode.Live;
	}

	public ProductTypeResource(ApiContext apiContext, DataViewMode dataViewMode)
	{
		_apiContext = apiContext;
		_dataViewMode = dataViewMode;
	}

	/**
	 * Retrieves a list of product types according to any specified filter criteria and sort options.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductTypeCollection productTypeCollection = producttype.getProductTypes();
	 *

	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.productadmin.ProductTypeCollection
	 * @see com.mozu.api.contracts.productadmin.ProductTypeCollection
	 */
	public com.mozu.api.contracts.productadmin.ProductTypeCollection getProductTypes() throws Exception
	{
		return getProductTypes( null,  null,  null,  null,  null);
	}

	/**
	 * Retrieves a list of product types according to any specified filter criteria and sort options.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductTypeCollection productTypeCollection = producttype.getProductTypes( startIndex,  pageSize,  sortBy,  filter,  responseFields);
	 *

	 * @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. You can filter product type search results by any of its properties. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=Name+cont+shoes"
	 * @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param sortBy
	 * @param startIndex
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.productadmin.ProductTypeCollection
	 * @see com.mozu.api.contracts.productadmin.ProductTypeCollection
	 */
	public com.mozu.api.contracts.productadmin.ProductTypeCollection getProductTypes(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.productadmin.ProductTypeCollection> client = com.mozu.api.clients.commerce.catalog.admin.attributedefinition.ProductTypeClient.getProductTypesClient(_dataViewMode,  startIndex,  pageSize,  sortBy,  filter,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Retrieves the details of the product type specified in the request.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.getProductType( productTypeId);
	 *

	 * @param productTypeId Identifier of the product type to retrieve.
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType getProductType(Integer productTypeId) throws Exception
	{
		return getProductType( productTypeId,  null);
	}

	/**
	 * Retrieves the details of the product type specified in the request.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.getProductType( productTypeId,  responseFields);
	 *

	 * @param productTypeId Identifier of the product type to retrieve.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param dataViewMode DataViewMode
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType getProductType(Integer productTypeId, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.productadmin.ProductType> client = com.mozu.api.clients.commerce.catalog.admin.attributedefinition.ProductTypeClient.getProductTypeClient(_dataViewMode,  productTypeId,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Creates a new product type based on the information supplied in the request.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.addProductType( productType);
	 *

	 * @param dataViewMode DataViewMode
	 * @param productType Properties of the product type to create.
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType addProductType(com.mozu.api.contracts.productadmin.ProductType productType) throws Exception
	{
		return addProductType( productType,  null);
	}

	/**
	 * Creates a new product type based on the information supplied in the request.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.addProductType( productType,  responseFields);
	 *

	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param dataViewMode DataViewMode
	 * @param productType Properties of the product type to create.
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType addProductType(com.mozu.api.contracts.productadmin.ProductType productType, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.productadmin.ProductType> client = com.mozu.api.clients.commerce.catalog.admin.attributedefinition.ProductTypeClient.addProductTypeClient(_dataViewMode,  productType,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Updates one or more properties of a product type.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.updateProductType( productType,  productTypeId);
	 *

	 * @param productTypeId Identifier of the product type to update.
	 * @param dataViewMode DataViewMode
	 * @param productType The details of the product type to update.
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType updateProductType(com.mozu.api.contracts.productadmin.ProductType productType, Integer productTypeId) throws Exception
	{
		return updateProductType( productType,  productTypeId,  null);
	}

	/**
	 * Updates one or more properties of a product type.
	 *

	 *	ProductType producttype = new ProductType();
	 *	ProductType productType = producttype.updateProductType( productType,  productTypeId,  responseFields);
	 *

	 * @param productTypeId Identifier of the product type to update.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param dataViewMode DataViewMode
	 * @param productType The details of the product type to update.
	 * @return com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 * @see com.mozu.api.contracts.productadmin.ProductType
	 */
	public com.mozu.api.contracts.productadmin.ProductType updateProductType(com.mozu.api.contracts.productadmin.ProductType productType, Integer productTypeId, String responseFields) throws Exception
	{
		MozuClient<com.mozu.api.contracts.productadmin.ProductType> client = com.mozu.api.clients.commerce.catalog.admin.attributedefinition.ProductTypeClient.updateProductTypeClient(_dataViewMode,  productType,  productTypeId,  responseFields);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Deletes the product type by providing the product type ID.
	 *

	 *	ProductType producttype = new ProductType();
	 *	producttype.deleteProductType( productTypeId);
	 *

	 * @param productTypeId Identifier of the product type to delete.
	 * @param dataViewMode DataViewMode
	 * @return
	 */
	public void deleteProductType(Integer productTypeId) throws Exception
	{
		MozuClient client = com.mozu.api.clients.commerce.catalog.admin.attributedefinition.ProductTypeClient.deleteProductTypeClient(_dataViewMode,  productTypeId);
		client.setContext(_apiContext);
		client.executeRequest();
		client.cleanupHttpConnection();

	}

}


text:
package com.aptima.netstorm.algorithms.aptima.bp.hive.driver.old;

//import org.apache.hadoop.hive.cli.CliDriver;

public class HiveDriverBitcoin {

	public static void main(String[] myArgs) throws Exception {
		//CliDriver.run(myArgs);
	}
}


text:
describe("Unit tests for BC base collection class.", function() {
	var oldSiteHelper = undefined,
		siteToken = "123",
		rootUrl = "https://secure.businesscatalyst.com/";

	beforeEach(function() {
		oldSiteHelper = BCAPI.Helper.Site;

		BCAPI.Mocks.Helper.Site(siteToken, rootUrl);
	});

	afterEach(function() {
		expect(oldSiteHelper).not.toBe(undefined);

		BCAPI.Helper.Site = oldSiteHelper;
	});

	it("Check correct collection instantiation.", function() {
		var collection = new BCAPI.Mocks.Models.PersonCollection();

		expect(collection.model).toBe(BCAPI.Mocks.Models.PersonModel);
		expect(collection._defaultLimit).toBe(BCAPI.Config.Pagination.limit);
		expect(collection._defaultSkip).toBe(BCAPI.Config.Pagination.skip);
	});

	it("Check correct collection url.", function() {
		var person = new BCAPI.Mocks.Models.PersonModel();
		var collection = new BCAPI.Mocks.Models.PersonCollection(),
			personUrl = person.urlRoot();

		expect(collection.url().substring(0, personUrl.length)).toBe(personUrl);
	});

	/**
	 * This method provides a test template for collection fetch.
	 *
	 * @params {List} expectedItems A list of items containing person data.
	 * @param {Object} options Options required for filtering, ordering, pagination.
	 * @param {Integer} numQueryParams The total number of query params we expect api url to have.
	 * @param {Integer} options.skip The number of records we want to skip from data set.
	 * @param {Integer} options.limit The total number of records we want to include in data set.
	 * @param {Object} options.where An object describing a filtering criteria passed to API.
	 * @param {String} options.order The order expression used.
	 * @param {function} options.error The error handler we want to invoke.
	 */
	function _testCollectionFetchWithParams(expectedItems, numQueryParams, options) {
		options = options || {};

		var personModel = new BCAPI.Mocks.Models.PersonModel(),
			collection = new BCAPI.Mocks.Models.PersonCollection(),
			callbackCalled = false,
			errorHandler = options.error,
			waitMsg = !errorHandler ? "Success callback not called." : "Error callback not called.";

		if(errorHandler) {
			options.error = function(model, xhr, options) {
				errorHandler(model, xhr, options);

				callbackCalled = true;
			};
		}

		function successHandler(returnedCollection, response, options) {
			var idx = 0;

			returnedCollection.each(function(item) {
				var expectedItem = expectedItems[idx++];

				expect(item.get("firstName")).toBe(expectedItem.firstName);
				expect(item.get("lastName")).toBe(expectedItem.lastName);
			});

			callbackCalled = true;
		}

		spyOn($, "ajax").andCallFake(function(request) {
			var urlRoot = personModel.urlRoot(),
				expectedLimit = options.limit || BCAPI.Config.Pagination.limit,
				expectedSkip = options.skip || BCAPI.Config.Pagination.skip,
				expectedWhere = options.where,
				expectedOrder = options.order,
				totalAnd = request.url.split("&").length;

			console.log(request.url);

			expect(request.url.substring(0, urlRoot.length + 1)).toBe(urlRoot + "?");
			expect(request.url).toContain("limit=" + expectedLimit);
			expect(request.url).toContain("skip=" + expectedSkip);

			if(expectedWhere) {
				expect(request.url).toContain("where=" + JSON.stringify(expectedWhere));
			} else {
				expect(request.url).not.toContain("where=");
			}

			if(expectedOrder) {
				expect(request.url).toContain("order=" + expectedOrder);
			} else {
				expect(request.url).not.toContain("order=");
			}

			expect(totalAnd).toBe(numQueryParams);
			expect(request.type).toBe("GET");
			expect(request.dataType).toBe("json");
			expect(request.headers.Authorization).toBe(siteToken);

			if(!errorHandler) {
				request.success({"items": expectedItems});
			} else {
				request.error(errorHandler);
			}
		});

		runs(function() {
			var fetchArgs = {success: successHandler};

			for(var key in options) {
				fetchArgs[key] = options[key];
			}

			collection.fetch(fetchArgs);
		});

		waitsFor(function() {
			return callbackCalled;
		}, waitMsg, 50);
	}

	it("Check correct collection fetch with default values..", function() {
		var expectedItems = [{"firstName": "John",
			  				  "lastName": "Doe"},
			  				 {"firstName": "Triple",
			  			      "lastName": "X"}];

		_testCollectionFetchWithParams(expectedItems, 2);
	});

	it("Check correct collection fetch pagination.", function() {
		var expectedItems = [{"firstName": "John",
							  "lastName": "Doe"}],
			options = {skip: 10, limit: 1};

		_testCollectionFetchWithParams(expectedItems, 2, options);
	});

	it("Check correct collection fetch ordering.", function() {
		var expectedItems = [{"firstName": "Triple", "lastName": "X"},
		                     {"firstName": "John", "lastName": "Doe"}],
		    options = {"order": "-lastName"};

		_testCollectionFetchWithParams(expectedItems, 3, options);
	});

	it("Check correct collection fetch where.", function() {
		var expectedItems = [{"firstName": "John", "lastName": "Doe"}],
		    where = {"firstName": "John",
					 "lastName": {"$contains": "Doe"}};

		_testCollectionFetchWithParams(expectedItems, 3, {"where": where});
	});

	it("Check correct collection fetch with pagination, filtering and sorting specified.", function() {
		var expectedItems = [{"firstName": "John", "lastName": "Doe"},
		                     {"firstName": "Joan", "lastName": "Doe"}],
		    options = {skip: 2,
					   limit: 5,
					   order: "firstName",
					   where: {"firstName": {"$beginsWith": "Jo"},
						   	   "lastName": "Doe"}};

		_testCollectionFetchWithParams(expectedItems, 4, options);
	});

	it("Check correct collection fetch error handling.", function() {
		function errorHandler(collection, xhr, options) {
			expect(collection).not.toBe(undefined);
			expect(collection._defaultLimit).toBe(BCAPI.Config.Pagination.limit);
			expect(collection._defaultSkip).toBe(BCAPI.Config.Pagination.skip);

			expect(xhr).not.toBe(undefined);
			expect(options).not.toBe(undefined);
			expect(options.testKey).toBe("1234");
		}

		var options = {error: errorHandler,
					   testKey: "1234"};

		_testCollectionFetchWithParams(undefined, 2, options);
	});
});


text:
namespace DotNetty.Codecs.Mqtt.Packets
{
    public class SubscriptionRequest
    {
        public SubscriptionRequest(string topicFilter, QualityOfService qualityOfService)
        {
            this.TopicFilter = topicFilter;
            this.QualityOfService = qualityOfService;
        }

        public string TopicFilter { get; private set; }

        public QualityOfService QualityOfService { get; private set; }

        public override string ToString()
        {
            return string.Format("{0}[TopicFilter={1}, QualityOfService={2}]", this.GetType().Name, this.TopicFilter, this.QualityOfService);
        }
    }
}


text:
class SkillsController < ApplicationController

  def create
    @user = (params[:user_id] && User.find(params[:user_id])) || current_user
    return head(:forbidden) unless current_user == @user
    if params[:skill][:name] == "skills separated by comma"
      skill_names = []
    else
      skill_names = params[:skill][:name].split(",")
    end
    correct_skill_names = []
    skill_names.each do |skill_name|
      skill_name = ActionController::Base.helpers.sanitize(skill_name)
      skill      = @user.add_skill(skill_name)
      unless skill.nil?
        correct_skill_names << skill.name
      end
    end
    if correct_skill_names.blank?
      flash[:error] = "Hmm...couldn't recognize '#{skill_names.flatten.join(',')}'"
    else
      flash[:notice] = "Whoa...you're good at #{correct_skill_names.to_sentence}? Awesome!"
    end
    redirect_to(badge_url(username: @user.username))
  end

  def destroy
    redirect_to_signup_if_unauthenticated do
      @skill = current_user.skills.find(params[:id])
      if @skill

        #record_event('deleted skill', :skill => @skill.tokenized)
        flash[:notice] = "Ok got it...you're no longer into #{@skill.name}"
        @skill.destroy
        redirect_to(badge_url(username: @skill.user.username))
      end
    end
  end

end


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**reply_info** | [**\Alfaview\Model\CommonReplyInfo**](CommonReplyInfo.md) |  | [optional]
**quotas** | [**\Alfaview\Model\QuotaServiceQuota[]**](QuotaServiceQuota.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.jitstatic</groupId>
        <artifactId>jitstatic-parent</artifactId>
        <version>0.40.2-SNAPSHOT</version>
    </parent>
    <artifactId>version</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <executions>
                    <execution>
                        <id>get-the-git-infos</id>
                        <goals>
                            <goal>revision</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <injectAllReactorProjects>false</injectAllReactorProjects>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="ognl">
  <resources>
    <artifact name="${ognl:ognl}" />
  </resources>
  <dependencies>
    <module name="org.javassist" />
  </dependencies>
</module>


text: rsync -av --delete --exclude-from localfiles.txt --exclude-from .gitignore ../atlas/code/ .


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>radiotap decoder: PCAP NG JAVA File parser</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

radiotap decoder
    1.0

Main Page

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

 All Classes Namespaces Functions Pages

PCAP NG JAVA File parser

COMMAND LINE SYNTAX

java -cp ../lib/pcapngdecoder-1.0.jar:radiotapdecoder-1.0.jar fr.bmartel.radiotapdecoder.main.DecodeMain -f ../radiotap_file/exemple.pcapng -v

-f <file.pcapng> : input file

-v : verbose, will show all section parsing content

This exemple is launched from release folder

PROGRAM SYNTAX

byte[] radioTapData = packet.getPacketData();

RadioTap radioTap = new RadioTap(radioTapData);

You can then look at all fields that are in the radiotap data with radioTap.getRadioTapFlagList()

Go check fr.bmartel.protocol.radiotap.inter.IRadiotapFlags interface to see all list.

radioTap.getRadioTapFlagList().getRadioTapData() will give you all the data you can grab according to flags above.

Go check fr.bmartel.protocol.radiotap.inter.IRadiotapData to see all data available.

Project is JRE 1.7 compliant You can build it with ant => build.xml Development on Eclipse Specification from http://www.radiotap.org

<address class="footer">
Generated on Mon May 4 2015 00:00:43 for radiotap decoder by

 1.8.4
</address>


text:
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR
import sys
PORT_NUMBER = 5000
SIZE = 1024

hostName = gethostbyname('localhost')

mySocket = socket(SOCK_DGRAM)
mySocket.bind((hostName, PORT_NUMBER))
mySocket.listen(1)
while True:
        client, addr = mySocket.accept()
        data = client.send("Connection Established: ")
sys.exit()


text:
- Initial release.

[Unreleased]: https://github.com/ceilfors/cookbook-daun/compare/v0.1.0...HEAD


text:
package bridlensis;

public class ParserException extends Exception {

	private static final long serialVersionUID = 1L;

	private final Integer line;
	private final String filename;

	public ParserException(String fileName, Integer line, Throwable cause) {
		super(cause);
		this.line = line;
		this.filename = fileName;
	}

	@Override
	public String getMessage() {
		StringBuilder sb = new StringBuilder();
		if (getCause() instanceof InvalidSyntaxException) {
			sb.append("Syntax error: ");
		}
		if (filename != null)
			sb.append(String.format("\"%s\" ", filename));
		if (line != null)
			sb.append(String.format("on line %d -- ", line));
		sb.append(getCause().getMessage());
		return sb.toString();
	}

}


text:
from textwrap import dedent
from twisted.trial import unittest

from pymeta.builder import TreeBuilder, writePython

def dd(txt):
    return dedent(txt).strip()

class PythonWriterTests(unittest.TestCase):
    """
    Tests for generating Python source from an AST.
    """

    def setUp(self):
        """
        Create a L{PythonBuilder}.
        """

        self.builder = TreeBuilder("BuilderTest")

    def test_exactly(self):
        """
        Test generation of code for the 'exactly' pattern.
        """

        x = self.builder.exactly("x")
        self.assertEqual(writePython(x),
                         dd("""
                            _G_exactly_1, lastError = self.exactly('x')
                            self.considerError(lastError)
                            _G_exactly_1
                            """))

    def test_apply(self):
        """
        Test generation of code for rule application.
        """

        one = self.builder.expr("1")
        x = self.builder.expr("x")
        a = self.builder.apply("foo", "main", one, x)
        self.assertEqual(writePython(a),
                         dd("""
                            _G_python_1, lastError = eval('1', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_python_2, lastError = eval('x', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_apply_3, lastError = self._apply(self.rule_foo, "foo", [_G_python_1, _G_python_2])
                            self.considerError(lastError)
                            _G_apply_3
                            """))

    def test_superApply(self):
        """
        Test generation of code for calling the superclass' implementation of
        the current rule.
        """
        one = self.builder.expr("1")
        x = self.builder.expr("x")
        a = self.builder.apply("super", "main", one, x)
        self.assertEqual(writePython(a),
                         dd("""
                            _G_python_1, lastError = eval('1', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_python_2, lastError = eval('x', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_apply_3, lastError = self.superApply("main", _G_python_1, _G_python_2)
                            self.considerError(lastError)
                            _G_apply_3
                            """))

    def test_many(self):
        """
        Test generation of code for matching zero or more instances of
        a pattern.
        """

        xs = self.builder.many(self.builder.exactly("x"))
        self.assertEqual(writePython(xs),
                         dd("""
                            def _G_many_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_many_2, lastError = self.many(_G_many_1)
                            self.considerError(lastError)
                            _G_many_2
                            """))

    def test_many1(self):
        """
        Test generation of code for matching one or more instances of
        a pattern.
        """

        xs = self.builder.many1(self.builder.exactly("x"))
        self.assertEqual(writePython(xs),
                         dd("""
                            def _G_many1_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_many1_2, lastError = self.many(_G_many1_1, _G_many1_1())
                            self.considerError(lastError)
                            _G_many1_2
                            """))

    def test_or(self):
        """
        Test code generation for a sequence of alternatives.
        """

        xy = self.builder._or([self.builder.exactly("x"),
                               self.builder.exactly("y")])
        self.assertEqual(writePython(xy),
                         dd("""
                            def _G_or_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            def _G_or_2():
                                _G_exactly_1, lastError = self.exactly('y')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_or_3, lastError = self._or([_G_or_1, _G_or_2])
                            self.considerError(lastError)
                            _G_or_3
                            """))

    def test_singleOr(self):
        """
        Test code generation for a sequence of alternatives.
        """

        x1 = self.builder._or([self.builder.exactly("x")])
        x = self.builder.exactly("x")
        self.assertEqual(writePython(x), writePython(x1))

    def test_optional(self):
        """
        Test code generation for optional terms.
        """
        x = self.builder.optional(self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def _G_optional_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            def _G_optional_2():
                                return (None, self.input.nullError())
                            _G_or_3, lastError = self._or([_G_optional_1, _G_optional_2])
                            self.considerError(lastError)
                            _G_or_3
                            """))

    def test_not(self):
        """
        Test code generation for negated terms.
        """
        x = self.builder._not(self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def _G_not_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_not_2, lastError = self._not(_G_not_1)
                            self.considerError(lastError)
                            _G_not_2
                            """))

    def test_lookahead(self):
        """
        Test code generation for lookahead expressions.
        """
        x = self.builder.lookahead(self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def _G_lookahead_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_lookahead_2, lastError = self.lookahead(_G_lookahead_1)
                            self.considerError(lastError)
                            _G_lookahead_2
                            """))

    def test_sequence(self):
        """
        Test generation of code for sequence patterns.
        """
        x = self.builder.exactly("x")
        y = self.builder.exactly("y")
        z = self.builder.sequence([x, y])
        self.assertEqual(writePython(z),
                         dd("""
                            _G_exactly_1, lastError = self.exactly('x')
                            self.considerError(lastError)
                            _G_exactly_2, lastError = self.exactly('y')
                            self.considerError(lastError)
                            _G_exactly_2
                            """))

    def test_bind(self):
        """
        Test code generation for variable assignment.
        """
        x = self.builder.exactly("x")
        b = self.builder.bind(x, "var")
        self.assertEqual(writePython(b),
                         dd("""
                            _G_exactly_1, lastError = self.exactly('x')
                            self.considerError(lastError)
                            _locals['var'] = _G_exactly_1
                            _locals['var']
                            """))

    def test_pred(self):
        """
        Test code generation for predicate expressions.
        """
        x = self.builder.pred(self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def _G_pred_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_pred_2, lastError = self.pred(_G_pred_1)
                            self.considerError(lastError)
                            _G_pred_2
                            """))

    def test_action(self):
        """
        Test code generation for semantic actions.
        """
        x = self.builder.action("doStuff()")
        self.assertEqual(writePython(x),
                         dd("""
                            _G_python_1, lastError = eval('doStuff()', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_python_1
                            """))

    def test_expr(self):
        """
        Test code generation for semantic predicates.
        """
        x = self.builder.expr("returnStuff()")
        self.assertEqual(writePython(x),
                         dd("""
                            _G_python_1, lastError = eval('returnStuff()', self.globals, _locals), None
                            self.considerError(lastError)
                            _G_python_1
                            """))

    def test_listpattern(self):
        """
        Test code generation for list patterns.
        """
        x = self.builder.listpattern(self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def _G_listpattern_1():
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            _G_listpattern_2, lastError = self.listpattern(_G_listpattern_1)
                            self.considerError(lastError)
                            _G_listpattern_2
                            """))

    def test_rule(self):
        """
        Test generation of entire rules.
        """

        x = self.builder.rule("foo", self.builder.exactly("x"))
        self.assertEqual(writePython(x),
                         dd("""
                            def rule_foo(self):
                                _locals = {'self': self}
                                self.locals['foo'] = _locals
                                _G_exactly_1, lastError = self.exactly('x')
                                self.considerError(lastError)
                                return (_G_exactly_1, self.currentError)
                            """))

    def test_grammar(self):
        """
        Test generation of an entire grammar.
        """
        r1 = self.builder.rule("foo", self.builder.exactly("x"))
        r2 = self.builder.rule("baz", self.builder.exactly("y"))
        x = self.builder.makeGrammar([r1, r2])
        self.assertEqual(writePython(x),
                         dd("""
                            class BuilderTest(GrammarBase):
                                def rule_foo(self):
                                    _locals = {'self': self}
                                    self.locals['foo'] = _locals
                                    _G_exactly_1, lastError = self.exactly('x')
                                    self.considerError(lastError)
                                    return (_G_exactly_1, self.currentError)

                                def rule_baz(self):
                                    _locals = {'self': self}
                                    self.locals['baz'] = _locals
                                    _G_exactly_1, lastError = self.exactly('y')
                                    self.considerError(lastError)
                                    return (_G_exactly_1, self.currentError)
                            """))


text:
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MultiSafepay.Model;
using Newtonsoft.Json;

namespace MultiSafepay.UnitTests.Model
{
    [TestClass]
    [ExcludeFromCodeCoverage]
    public class ShoppingCartTests
    {
        [TestMethod]
        public void ShoppingCart_Serialize_PropertyNamesAsExpected()
        {
            // Arrange
            var shoppingCart = new ShoppingCart();

            // Act
            var serializedObject = JsonConvert.SerializeObject(shoppingCart);

            // Assert
            Assert.AreEqual(@"{
 		        ""items"": null
			}".RemoveWhiteSpace(), serializedObject.RemoveWhiteSpace());
        }
    }
}


text:
import unittest

from iobeam.endpoints import devices
from iobeam.resources import device
from tests.http import dummy_backend
from tests.http import request

_DEVICE_ID = "test_id"
_TOKEN = dummy_backend.TOKEN

_TIMESTAMP = 5

_NONE_DEVICE_ID = "dummy_id"
_NONE_DEVICE_NAME = "dummy_name"

DeviceService = devices.DeviceService
Device = device.Device
DummyBackend = dummy_backend.DummyBackend

class TestDeviceService(unittest.TestCase):

    def test_createService(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))
        self.assertEqual(_TOKEN, service.token)
        self.assertTrue(service.requester() is not None)
        self.assertTrue(isinstance(service.requester(), request.DummyRequester))

    def test_getTimestamp(self):
        dummy = DummyBackend(timestampReturn=_TIMESTAMP)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))

        ret = service.getTimestamp()
        self.assertEqual(_TIMESTAMP, ret)
        self.assertEqual(1, dummy.calls)

    def test_getTimestampBadToken(self):
        dummy = DummyBackend(timestampReturn=_TIMESTAMP)
        service = DeviceService("wrong", requester=request.DummyRequester(dummy))

        ret = service.getTimestamp()
        self.assertEqual(-1, ret)
        self.assertEqual(1, dummy.calls)

    def _checkDevice(self, ret, pid, did, dname):
        self.assertTrue(isinstance(ret, Device))
        self.assertEqual(pid, ret.projectId)
        self.assertEqual(did, ret.deviceId)
        self.assertEqual(dname, ret.deviceName)

    def test_registerDeviceNone(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))

        ret = service.registerDevice(1)
        self._checkDevice(ret, 1, _NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        self.assertEqual(1, dummy.calls)

    def test_registerDevice(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))

        ret = service.registerDevice(1, deviceId="a_given_id")
        self._checkDevice(ret, 1, "a_given_id", _NONE_DEVICE_NAME)
        self.assertEqual(1, dummy.calls)
        body = dummy.lastJson
        self.assertEqual("a_given_id", body["device_id"])

        ret = service.registerDevice(
            1, deviceId="a_given_id2", deviceName="a_given_name")
        self._checkDevice(ret, 1, "a_given_id2", "a_given_name")
        self.assertEqual(2, dummy.calls)
        body = dummy.lastJson
        self.assertEqual("a_given_id2", body["device_id"])
        self.assertEqual("a_given_name", body["device_name"])

        ret = service.registerDevice(1, deviceName="a_given_name2")
        self._checkDevice(ret, 1, _NONE_DEVICE_ID, "a_given_name2")
        self.assertEqual(3, dummy.calls)
        body = dummy.lastJson
        self.assertEqual("a_given_name2", body["device_name"])

    def test_registerDeviceDupeId(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))

        regId = "a_given_id"
        ret = service.registerDevice(1, deviceId=regId)
        self._checkDevice(ret, 1, regId, _NONE_DEVICE_NAME)
        self.assertEqual(1, dummy.calls)
        body = dummy.lastJson
        self.assertEqual(regId, body["device_id"])

        try:
            ret = service.registerDevice(1, deviceId=regId)
            self.assertTrue(False)
        except devices.DuplicateIdError as e:
            self.assertTrue(isinstance(e, devices.DuplicateIdError))
            self.assertEqual(2, dummy.calls)
            self.assertEqual("Device ID already registered.", str(e))

    def test_registerDeviceDupeName(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService(_TOKEN, requester=request.DummyRequester(dummy))

        regName = "a_given_name"
        ret = service.registerDevice(1, deviceName=regName)
        self._checkDevice(ret, 1, _NONE_DEVICE_ID, regName)
        self.assertEqual(1, dummy.calls)
        body = dummy.lastJson
        self.assertEqual(regName, body["device_name"])

        try:
            ret = service.registerDevice(1, deviceId="another",
                                         deviceName=regName)
            self.assertTrue(False)
        except request.Error as e:
            self.assertEqual(2, dummy.calls)
            self.assertTrue(str(e).startswith("Received unexpected code: 422"))

    def test_registerBadToken(self):
        registerReturn = (_NONE_DEVICE_ID, _NONE_DEVICE_NAME)
        dummy = DummyBackend(registerReturn=registerReturn)
        service = DeviceService("wrong", requester=request.DummyRequester(dummy))

        regId = "a_given_id"
        try:
            ret = service.registerDevice(1, deviceId=regId)
            self.assertTrue(False)
        except request.UnauthorizedError:
            self.assertEqual(1, dummy.calls)