text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * The Ext.grid.plugin.RowEditing plugin injects editing at a row level for a Grid. When editing begins,
 * a small floating dialog will be shown for the appropriate row. Each editable column will show a field
 * for editing. There is a button to save or cancel all changes for the edit.
 *
 * The field that will be used for the editor is defined at the
 * {@link Ext.grid.column.Column#editor editor}. The editor can be a field instance or a field configuration.
 * If an editor is not specified for a particular column then that column won't be editable and the value of
 * the column will be displayed. To provide a custom renderer for non-editable values, use the
 * {@link Ext.grid.column.Column#editRenderer editRenderer} configuration on the column.
 *
 * The editor may be shared for each column in the grid, or a different one may be specified for each column.
 * An appropriate field type should be chosen to match the data structure that it will be editing. For example,
 * to edit a date, it would be useful to specify {@link Ext.form.field.Date} as the editor.
 *
 *     @example
 *     Ext.create('Ext.data.Store', {
 *         storeId:'simpsonsStore',
 *         fields:['name', 'email', 'phone'],
 *         data: [
 *             {"name":"Lisa", "email":"lisa@simpsons.com", "phone":"555-111-1224"},
 *             {"name":"Bart", "email":"bart@simpsons.com", "phone":"555-222-1234"},
 *             {"name":"Homer", "email":"home@simpsons.com", "phone":"555-222-1244"},
 *             {"name":"Marge", "email":"marge@simpsons.com", "phone":"555-222-1254"}
 *         ]
 *     });
 *
 *     Ext.create('Ext.grid.Panel', {
 *         title: 'Simpsons',
 *         store: Ext.data.StoreManager.lookup('simpsonsStore'),
 *         columns: [
 *             {header: 'Name',  dataIndex: 'name', editor: 'textfield'},
 *             {header: 'Email', dataIndex: 'email', flex:1,
 *                 editor: {
 *                     xtype: 'textfield',
 *                     allowBlank: false
 *                 }
 *             },
 *             {header: 'Phone', dataIndex: 'phone'}
 *         ],
 *         selType: 'rowmodel',
 *         plugins: [
 *             Ext.create('Ext.grid.plugin.RowEditing', {
 *                 clicksToEdit: 1
 *             })
 *         ],
 *         height: 200,
 *         width: 400,
 *         renderTo: Ext.getBody()
 *     });
 *
 */
Ext.define('Ext.grid.plugin.RowEditing', {
    extend: 'Ext.grid.plugin.Editing',
    alias: 'plugin.rowediting',

    requires: [
        'Ext.grid.RowEditor'
    ],

    lockableScope: 'top',

    editStyle: 'row',

    /**
     * @cfg {Boolean} autoCancel
     * `true` to automatically cancel any pending changes when the row editor begins editing a new row.
     * `false` to force the user to explicitly cancel the pending changes.
     */
    autoCancel: true,

    /**
     * @cfg {Number} clicksToMoveEditor
     * The number of clicks to move the row editor to a new row while it is visible and actively editing another row.
     * This will default to the same value as {@link Ext.grid.plugin.Editing#clicksToEdit clicksToEdit}.
     */

    /**
     * @cfg {Boolean} errorSummary
     * True to show a {@link Ext.tip.ToolTip tooltip} that summarizes all validation errors present
     * in the row editor. Set to false to prevent the tooltip from showing.
     */
    errorSummary: true,

    constructor: function() {
        var me = this;

        me.callParent(arguments);

        if (!me.clicksToMoveEditor) {
            me.clicksToMoveEditor = me.clicksToEdit;
        }

        me.autoCancel = !!me.autoCancel;
    },

    /**
     * @private
     * AbstractComponent calls destroy on all its plugins at destroy time.
     */
    destroy: function() {
        Ext.destroy(this.editor);
        this.callParent(arguments);
    },

    onBeforeReconfigure: function() {
        this.callParent(arguments);
        this.cancelEdit();
    },

    onReconfigure: function(grid, store, columns) {
        var ed = this.editor;
        this.callParent(arguments);
        // Only need to adjust column widths if we have new columns
        if (columns && ed && ed.rendered) {
            ed.needsSyncFieldWidths = true;
        }
    },

    /**
     * Starts editing the specified record, using the specified Column definition to define which field is being edited.
     * @param {Ext.data.Model} record The Store data record which backs the row to be edited.
     * @param {Ext.grid.column.Column/Number} columnHeader The Column object defining the column field to be focused, or index of the column.
     * @return {Boolean} `true` if editing was started, `false` otherwise.
     */
    startEdit: function(record, columnHeader) {
        var me = this,
            editor = me.getEditor(),
            context;

        if (Ext.isEmpty(columnHeader)) {
            columnHeader = me.grid.getTopLevelVisibleColumnManager().getHeaderAtIndex(0);
        }

        if (editor.beforeEdit() !== false) {
            context = me.callParent([record, columnHeader]);
            if (context) {
                me.context = context;

                // If editing one side of a lockable grid, cancel any edit on the other side.
                if (me.lockingPartner) {
                    me.lockingPartner.cancelEdit();
                }
                editor.startEdit(context.record, context.column, context);
                me.editing = true;
                return true;
            }
        }
        return false;
    },

    // @private
    cancelEdit: function() {
        var me = this;

        if (me.editing) {
            me.getContextFieldValues();
            me.getEditor().cancelEdit();
            me.callParent(arguments);
            return;
        }
        // If we aren't editing, return true to allow the event to bubble
        return true;
    },

    // @private
    completeEdit: function() {
        var me = this;

        if (me.editing && me.validateEdit()) {
            me.editing = false;
            me.fireEvent('edit', me, me.context);
        }
    },

    onEnterKey: function() {
        if (this.getEditor().getForm().isValid()) {
            this.completeEdit();
        }
    },

    // @private
    validateEdit: function() {
        this.getContextFieldValues();
        this.editing = this.callParent(arguments) && this.getEditor().completeEdit();
        return this.editing;
    },

    // @private
    getEditor: function() {
        var me = this;

        if (!me.editor) {
            me.editor = me.initEditor();
        }
        return me.editor;
    },

    getContextFieldValues: function () {
        var editor         = this.editor,
            context        = this.context,
            record         = context.record,
            newValues      = {},
            originalValues = {},
            editors        = editor.query('>[isFormField]'),
            len            = editors.length,
            i, name, item;

        for (i = 0; i < len; i++) {
            item = editors[i];
            name = item.name;

            newValues[name]      = item.getValue();
            originalValues[name] = record.get(name);
        }

        Ext.apply(context, {
            newValues      : newValues,
            originalValues : originalValues
        });
    },

    // @private
    initEditor: function() {
        return new Ext.grid.RowEditor(this.initEditorConfig());
    },

    initEditorConfig: function(){
        var me       = this,
            grid     = me.grid,
            view     = me.view,
            headerCt = grid.headerCt,
            btns     = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'],
            b,
            bLen     = btns.length,
            cfg      = {
                autoCancel: me.autoCancel,
                errorSummary: me.errorSummary,
                fields: headerCt.getGridColumns(),
                hidden: true,
                view: view,
                // keep a reference..
                editingPlugin: me
            },
            item;

        for (b = 0; b < bLen; b++) {
            item = btns[b];

            if (Ext.isDefined(me[item])) {
                cfg[item] = me[item];
            }
        }
        return cfg;
    },

    // @private
    initEditTriggers: function() {
        var me = this,
            view = me.view,
            moveEditorEvent = me.clicksToMoveEditor === 1 ? 'click' : 'dblclick';

        me.callParent(arguments);

        if (me.clicksToMoveEditor !== me.clicksToEdit) {
            me.mon(view, 'cell' + moveEditorEvent, me.moveEditorByClick, me);
        }

        view.on({
            render: function() {
                me.mon(me.grid.headerCt, {
                    scope: me,
                    columnresize: me.onColumnResize,
                    columnhide: me.onColumnHide,
                    columnshow: me.onColumnShow
                });
            },
            single: true
        });
    },

    startEditByClick: function() {
        var me = this;
        if (!me.editing || me.clicksToMoveEditor === me.clicksToEdit) {
            me.callParent(arguments);
        }
    },

    moveEditorByClick: function() {
        var me = this;
        if (me.editing) {
            me.superclass.onCellClick.apply(me, arguments);
        }
    },

    // @private
    onColumnAdd: function(ct, column) {
        if (column.isHeader) {
            var me = this,
                editor;

            me.initFieldAccessors(column);

            // Only inform the editor about a new column if the editor has already been instantiated,
            // so do not use getEditor which instantiates the editor if not present.
            editor = me.editor;
            if (editor) {
                editor.onColumnAdd(column);
            }
        }
    },

    // @private
    onColumnRemove: function(ct, column) {
        if (column.isHeader) {
            var me = this,
                editor = me.getEditor();

            if (editor) {
                editor.onColumnRemove(ct, column);
            }
            me.removeFieldAccessors(column);
        }
    },

    // @private
    onColumnResize: function(ct, column, width) {
        if (column.isHeader) {
            var me = this,
                editor = me.getEditor();

            if (editor) {
                editor.onColumnResize(column, width);
            }
        }
    },

    // @private
    onColumnHide: function(ct, column) {
        // no isHeader check here since its already a columnhide event.
        var me = this,
            editor = me.getEditor();

        if (editor) {
            editor.onColumnHide(column);
        }
    },

    // @private
    onColumnShow: function(ct, column) {
        // no isHeader check here since its already a columnshow event.
        var me = this,
            editor = me.getEditor();

        if (editor) {
            editor.onColumnShow(column);
        }
    },

    // @private
    onColumnMove: function(ct, column, fromIdx, toIdx) {
        // no isHeader check here since its already a columnmove event.
        var me = this,
            editor = me.getEditor();

        // Inject field accessors on move because if the move FROM the main headerCt and INTO a grouped header,
        // the accessors will have been deleted but not added. They are added conditionally.
        me.initFieldAccessors(column);

        if (editor) {
            // Must adjust the toIdx to account for removal if moving rightwards
            // because RowEditor.onColumnMove just calls Container.move which does not do this.
            editor.onColumnMove(column, fromIdx, toIdx);
        }
    },

    // @private
    setColumnField: function(column, field) {
        var me = this,
            editor = me.getEditor();

        if (editor) {
            // Remove the old editor and destroy it.
            editor.removeColumnEditor(column, true);
        }

        me.callParent(arguments);

        if (editor) {
            editor.insertColumnEditor(column);
        }
    },

    createColumnField: function(column, defaultField) {
        var editor = this.editor,
            def;

        if (editor) {
            def = editor.getDefaultFieldCfg();
        }

        return this.callParent([column, defaultField || def]);
    }
});


text:
package io.datarouter.aws.memcached.web;

import static j2html.TagCreator.div;
import static j2html.TagCreator.ul;

import java.util.List;

import javax.inject.Inject;

import io.datarouter.aws.memcached.client.MemcachedClientMode;
import io.datarouter.aws.memcached.client.options.AwsMemcachedOptions;
import io.datarouter.client.memcached.web.MemcachedWebInspector;
import io.datarouter.scanner.Scanner;
import io.datarouter.storage.client.ClientId;
import io.datarouter.web.html.j2html.J2HtmlTable;
import j2html.TagCreator;
import j2html.tags.ContainerTag;
import j2html.tags.specialized.DivTag;
import j2html.tags.specialized.LiTag;

public class AwsMemcachedWebInspector extends MemcachedWebInspector{

	@Inject
	private AwsMemcachedOptions options;

	@Override
	protected MemcachedDetail getDetails(ClientId clientId){
		MemcachedClientMode mode = options.getClientMode(clientId.getName());
		if(mode == MemcachedClientMode.DYNAMIC){
			List<AwsMemcachedNodeEndpointDto> nodeEndpointDtos = Scanner.of(getSpyClient(clientId)
							.getAllNodeEndPoints())
					.map(nodeEndPoint -> new AwsMemcachedNodeEndpointDto(
							nodeEndPoint.getHostName(),
							nodeEndPoint.getIpAddress(),
							nodeEndPoint.getPort()))
					.list();
			var table = new J2HtmlTable<AwsMemcachedNodeEndpointDto>()
					.withClasses("sortable table table-sm table-striped my-4 border")
					.withColumn("HostName", AwsMemcachedNodeEndpointDto::hostName)
					.withColumn("IpAddress", AwsMemcachedNodeEndpointDto::ipAddress)
					.withColumn("Port", AwsMemcachedNodeEndpointDto::port)
					.build(nodeEndpointDtos);
			DivTag divTable = div(table)
					.withClass("container-fluid my-4")
					.withStyle("padding-left: 0px");
			return new MemcachedDetail(nodeEndpointDtos.size(), divTable);
		}
		List<LiTag> socketAddresses = Scanner.of(getSpyClient(clientId).getAvailableServers())
				.map(Object::toString)
				.map(TagCreator::li)
				.list();
		DivTag div = div(ul(socketAddresses.toArray(new ContainerTag[0])));
		return new MemcachedDetail(socketAddresses.size(), div);
	}

	private record AwsMemcachedNodeEndpointDto(
			String hostName,
			String ipAddress,
			int port){
	}

}

redpajama_set_name: RedPajamaGithub


text:
@interface DiscountPriceView ()
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) UILabel *discountLabel;
@property (nonatomic, strong) UIView *lines;
@end

@implementation DiscountPriceView

- (instancetype)init{
    if (self = [super init]) {
        _moneyLabel = [[UILabel alloc]init];
        _moneyLabel.font = [UIFont systemFontOfSize:13];
        _moneyLabel.textColor = [UIColor redColor];
        [self addSubview:_moneyLabel];

        _discountLabel = [[UILabel alloc]init];
        _discountLabel.font = [UIFont systemFontOfSize:12];
        _discountLabel.textColor = [UIColor grayColor];
        [self addSubview:_discountLabel];

        _lines = [[UIView alloc]init];
        _lines.backgroundColor = [UIColor grayColor];
        [self addSubview:_lines];

        [_moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self).offset(5);
            make.centerY.equalTo(self);
        }];

        [_discountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(_moneyLabel.mas_trailing).offset(1);
            make.centerY.equalTo(self);
        }];
        [_lines mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_discountLabel);
            make.height.equalTo(@1);
            make.leading.equalTo(_discountLabel);
            make.centerY.equalTo(self);
        }];
    }
    return self;
}

- (void)setGoods:(Goods *)goods{
    self.goods = goods;
    self.moneyLabel.text = [NSString stringWithFormat:@"¥%@",goods.price];
    self.discountLabel.text = [NSString stringWithFormat:@"¥%@",goods.market_price];;
    [self.moneyLabel sizeToFit];
    [self.discountLabel sizeToFit];
    if ([goods.price isEqualToString:goods.market_price]) {
        self.discountLabel.hidden = YES;
        self.lines.hidden = YES;
    }else{
        self.discountLabel.hidden = NO;
        self.lines.hidden = NO;
    }
}

@end


text:
'use strict'

/**
 * Implement simple two-way binding between model objects and DOM elements.
 */
function Bind(data, _model) {
    var model = {};
    if ( _model ) model = _model; // To be able to extend existing model _model

    /* Iterate over the key of data object. */
    var keys = Object.keys(data),
        len = keys.length,
        i = 0,
        key,
        value;
    while (i < len) {
        key = keys[i];
        value = data[key];

        /* Binding DOM elements to model. */
        (function() {
            var _key = key,
                _value = value,
                _elArray,
                _len,
                _i = 0,
                _done = false;

            Object.defineProperty(model, _key, {
                get: function() {
                    //console.log('GET: ' + _key)
                    return _value;
                },
                set: function(newValue) {
                    _value = newValue;
                    /* We cache queried DOM elements - makes sense only for static pages. */
                    if (!_done) {
                        _elArray = document.querySelectorAll( "[bind='" + _key +"']" );
                        _len = _elArray.length;
                        _done = true;
                    }

                    _i = 0;
                    while ( _i < _len ) {
                        _elArray[_i].innerHTML = _value;
                        _i += 1;
                    }
                },
                configurable: true,
                enumerable: true
            });

            /* Copy data to model. */
            model[_key] = _value;

            /* Binding model to DOM elements (we query elements by the id attribute). */
            var el = document.querySelector('#' + _key);

            if ( el !== null ) {
                function handler() {
                    if ( this.value ) {
                        model[_key] = (this.value) ? (this.value) : data[_key]; // for <div> elements
                    } else if ( this.textContent ) {
                        model[_key] = (this.textContent ) ? (this.textContent ) : data[_key]; // for <table> cells
                    }
                }
                el.addEventListener('input', handler);
                el.addEventListener('change', handler);
            }
        })();

        i += 1;
    }
    return model;
}

module.exports = Bind;


text:
using System.Collections.Generic;
using System.Xml.Serialization;
using NewRelicSharp.Commands;
using NewRelicSharp.Items;

namespace NewRelicSharp
{
    using System;
    using System.IO;
    using System.Net.Http;

    using NewRelicSharp.Commands.Post;

    /// <summary>
    /// Used to access New Relic using custom classes
    /// </summary>
    public class NewRelicAccessor : IDisposable
    {
        private readonly NewRelicConnector newRelicConnector;
        private readonly IApiCommandBuilder apiCommandBuilder;
        private bool isDisposed;

        /// <summary>
        /// Creates an HttpClient to access New Relic rest API in strongly typed manner
        /// </summary>
        /// <param name="configuration"></param>
        public NewRelicAccessor(NewRelicConfiguration configuration, IApiCommandBuilder apiCommandBuilder)
        {
            newRelicConnector = new NewRelicConnector(configuration);
            this.apiCommandBuilder = apiCommandBuilder;
        }

        public Metrics GetMetricNames()
        {
            Metrics result;

            var command = apiCommandBuilder.CreateGetMetricNames();

            var response = Run(command);

            var content = response.Content.ReadAsStringAsync();

            using (var sr = new StringReader(content.Result))
            {
                var serializer = new XmlSerializer(typeof(Metrics));
                result = (Metrics)serializer.Deserialize(sr);
            }

            return result;
        }

        public ApplicationsResponse GetApplicationIds()
        {
            ApplicationsResponse result;

            var command = apiCommandBuilder.CreateGetApplicationIds();

            var response = Run(command);

            var content = response.Content.ReadAsStringAsync();

            using (var sr = new StringReader(content.Result))
            {
                var serializer = new XmlSerializer(typeof(ApplicationsResponse));
                result = (ApplicationsResponse)serializer.Deserialize(sr);
            }

            return result;

        }

        /// <summary>
        /// Send data to New Relic rest API
        /// </summary>
        /// <param name="apiCommand"></param>
        /// <returns></returns>
        private HttpResponseMessage Run(IApiCommand apiCommand)
        {
            switch (apiCommand.Method.Method)
            {
                case "GET":
                    return newRelicConnector.GetData(apiCommand.GetQuery());
                case "POST":
                    return newRelicConnector.PostData(apiCommand.GetQuery(), apiCommand.GetContent());
            }

            throw new NotSupportedException(String.Format("HTTM method '{0}' is not supported", apiCommand.Method.Method));
        }

        public void Dispose()
        {
            if (isDisposed)
            {
                return;
            }
            this.newRelicConnector.Dispose();
            this.isDisposed = true;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/default_margin"
            android:layout_marginRight="@dimen/default_margin"
            android:textSize="18sp"
            android:textStyle="bold"
            android:background="#45000000" />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxHeight="400dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="@dimen/default_margin"
            android:layout_marginStart="@dimen/default_margin"
            android:layout_marginRight="@dimen/default_margin"
            android:layout_marginEnd="@dimen/default_margin"
            android:layout_marginBottom="@dimen/default_margin"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop" />
    </LinearLayout>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:textAlignment="center"
        android:layout_alignParentBottom="true"
        android:background="#BBFFFFFF"/>
</RelativeLayout>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RosSharp.Message;
using RosSharp.Service;
using RosSharp.std_msgs;
namespace RosSharp.std_msgs
{
    ///<exclude/>
    public class Char : IMessage
    {
        ///<exclude/>
        public Char()
        {
        }
        ///<exclude/>
        public Char(BinaryReader br)
        {
            Deserialize(br);
        }
        ///<exclude/>
        public sbyte data { get; set; }
        ///<exclude/>
        public string MessageType
        {
            get { return "std_msgs/Char"; }
        }
        ///<exclude/>
        public string Md5Sum
        {
            get { return "1bf77f25acecdedba0e224b162199717"; }
        }
        ///<exclude/>
        public string MessageDefinition
        {
            get { return "char data"; }
        }
        ///<exclude/>
        public bool HasHeader
        {
            get { return false; }
        }
        ///<exclude/>
        public void Serialize(BinaryWriter bw)
        {
            bw.Write(data);
        }
        ///<exclude/>
        public void Deserialize(BinaryReader br)
        {
            data = br.ReadSByte();
        }
        ///<exclude/>
        public int SerializeLength
        {
            get { return 1; }
        }
        ///<exclude/>
        public bool Equals(Char other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return other.data.Equals(data);
        }
        ///<exclude/>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof(Char)) return false;
            return Equals((Char)obj);
        }
        ///<exclude/>
        public override int GetHashCode()
        {
            unchecked
            {
                int result = 0;
                result = (result * 397) ^ data.GetHashCode();
                return result;
            }
        }
    }
}


text:
<!DOCTYPE html>
<html>
    {% include head.html %}
    <body id="page-top" class="index">
    {% include nav.html %}
    {% include header.html %}
    {% include apartments.html %}
    {% include about.html %}
    {% include apply.html %}
    {% include residents.html %}

    {% include contact_static.html %}

    {% include footer.html %}
    {% include modals.html %}
    {% include info_modal.html %}
    {% include coupon_modal.html %}
    {% include js.html %}
    </body>
</html>


text:
<?php
/**
 * BatchCreateSchemaFieldsRequestTest
 *
 * PHP version 7.2
 *
 * @category Class
 * @package  Sajari
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Sajari API
 *
 * Sajari is a smart, highly-configurable, real-time search service that enables thousands of businesses worldwide to provide amazing search experiences on their websites, stores, and applications.
 *
 * The version of the OpenAPI document: v4
 * Contact: support@sajari.com
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 5.0.0-SNAPSHOT
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Please update the test case below to test the model.
 */

namespace Sajari\Test\Model;

use PHPUnit\Framework\TestCase;

/**
 * BatchCreateSchemaFieldsRequestTest Class Doc Comment
 *
 * @category    Class
 * @description BatchCreateSchemaFieldsRequest
 * @package     Sajari
 * @author      OpenAPI Generator team
 * @link        https://openapi-generator.tech
 */
class BatchCreateSchemaFieldsRequestTest extends TestCase
{
    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass(): void
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp(): void
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown(): void
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass(): void
    {
    }

    /**
     * Test "BatchCreateSchemaFieldsRequest"
     */
    public function testBatchCreateSchemaFieldsRequest()
    {
        // TODO: implement
        $this->markTestIncomplete("Not implemented");
    }

    /**
     * Test attribute "fields"
     */
    public function testPropertyFields()
    {
        // TODO: implement
        $this->markTestIncomplete("Not implemented");
    }
}


text:
package net.coding.program.common.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import net.coding.program.R;

/**
 * Created by chenchao on 16/4/11.
 * loadingView 控件, 某些界面取代 dialog loading
 */
public class LoadingView extends FrameLayout {

    public LoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.loading_view, this);

        initAnimator();
    }

    private void initAnimator() {
    }
}


text:
using Microsoft.SCP;
using Microsoft.SCP.Topology;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AzureHDInsightHBaseWriterStormApplication
{
    /// <summary>
    /// A topology example of reading data from spout and writing into HBase
    /// Uncomment Active attribute to deploy this topology and comment out Active attribute of any other topologies in this project.
    /// </summary>
    [Active(true)]
    public class HBaseWriterTopology : TopologyDescriptor
    {
        public ITopologyBuilder GetTopologyBuilder()
        {
            var topologyBuilder = new TopologyBuilder(typeof(HBaseWriterTopology).Name + DateTime.Now.ToString("yyyyMMddHHmmss"));

            topologyBuilder.SetSpout(
                typeof(VehicleRecordGeneratorSpoutForHBase).Name, //Set task name
                VehicleRecordGeneratorSpoutForHBase.Get, //Set task constructor delegate
                new Dictionary<string, List<string>>() {
                { Constants.DEFAULT_STREAM_ID, VehicleRecordGeneratorSpoutForHBase.OutputFields } },
                1, //Set number of tasks
                true //Set enableAck
                );

            var boltConfig = new StormConfig();
            boltConfig.Set("topology.tick.tuple.freq.secs", "5");

            topologyBuilder.SetBolt(
                typeof(HBaseBolt).Name, //Set task name
                HBaseBolt.Get, //Set task constructor delegate
                new Dictionary<string, List<string>>(), //Leave empty if the task has no outputSchema defined i.e. no outgoing tuples
                1, //Set number of tasks
                true //Set enableAck
                ).
                globalGrouping(typeof(VehicleRecordGeneratorSpoutForHBase).Name).
                addConfigurations(boltConfig);

            //Set the topology config
            var topologyConfig = new StormConfig();
            topologyConfig.setNumWorkers(1); //Set number of worker processes
            topologyConfig.setMaxSpoutPending(512); //Set maximum pending tuples from spout
            topologyConfig.setWorkerChildOps("-Xmx768m"); //Set Java Heap Size

            topologyBuilder.SetTopologyConfig(topologyConfig);

            return topologyBuilder;
        }
    }
}


text:
import { EditorModel } from 'vs/workbench/common/editor';
import { URI } from 'vs/base/common/uri';
import { IFileService } from 'vs/platform/files/common/files';
import { MIME_BINARY } from 'vs/base/common/mime';

/**
 * An editor model that just represents a resource that can be loaded.
 */
export class BinaryEditorModel extends EditorModel {
	private size: number | undefined;
	private etag: string | undefined;
	private readonly mime: string;

	constructor(
		public readonly resource: URI,
		private readonly name: string,
		@IFileService private readonly fileService: IFileService
	) {
		super();

		this.resource = resource;
		this.name = name;
		this.mime = MIME_BINARY;
	}

	/**
	 * The name of the binary resource.
	 */
	getName(): string {
		return this.name;
	}

	/**
	 * The size of the binary resource if known.
	 */
	getSize(): number | undefined {
		return this.size;
	}

	/**
	 * The mime of the binary resource if known.
	 */
	getMime(): string {
		return this.mime;
	}

	/**
	 * The etag of the binary resource if known.
	 */
	getETag(): string | undefined {
		return this.etag;
	}

	async load(): Promise<BinaryEditorModel> {

		// Make sure to resolve up to date stat for file resources
		if (this.fileService.canHandleResource(this.resource)) {
			const stat = await this.fileService.resolve(this.resource, { resolveMetadata: true });
			this.etag = stat.etag;
			if (typeof stat.size === 'number') {
				this.size = stat.size;
			}
		}

		return this;
	}
}


text:
using System;
using System.Text.RegularExpressions;

class ReplaceATag
{
    static void Main()
    {
        string input = Console.ReadLine();
        string pattern = @"<a\s+href=([^>]+)>([^<]+)</a>";
        Regex regex = new Regex(pattern);
        string replacement = "[$2]($1)";
        string result = Regex.Replace(input, pattern, replacement);

        result = result.Replace("(\"", "(");
        result = result.Replace("\")", ")");
        Console.WriteLine(result);
    }
}


text:
/* ccapi/server/ccs_client.h */
/*
 * Copyright 2006 Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 * require a specific license from the United States Government.
 * It is the responsibility of any person or organization contemplating
 * export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 */

#ifndef CCS_CLIENT_H
#define CCS_CLIENT_H

#include "ccs_types.h"

cc_int32 ccs_client_new (ccs_client_t *out_client,
                         ccs_pipe_t    in_client_pipe);

cc_int32 ccs_client_release (ccs_client_t io_client);

cc_int32 ccs_client_add_callback (ccs_client_t   io_client,
				  ccs_callback_t in_lock);

cc_int32 ccs_client_remove_callback (ccs_client_t   io_client,
				     ccs_callback_t in_lock);

cc_int32 ccs_client_add_iterator (ccs_client_t                io_client,
				  ccs_generic_list_iterator_t in_iterator);

cc_int32 ccs_client_remove_iterator (ccs_client_t                io_client,
				     ccs_generic_list_iterator_t in_iterator);

cc_int32 ccs_client_uses_pipe (ccs_client_t  in_client,
                               ccs_pipe_t    in_pipe,
                               cc_uint32    *out_uses_pipe);

#endif /* CCS_CLIENT_H */


text:
//#ifndef _WEBSOCKETPP_CPP11_STL_
//    #define _WEBSOCKETPP_CPP11_STL_
//#endif

#include <random>
#include <boost/timer/timer.hpp>

#include <websocketpp/config/core.hpp>

//#include <websocketpp/security/none.hpp>

//#include <websocketpp/concurrency/none.hpp>
//#include <websocketpp/concurrency/stl.hpp>

//#include <websocketpp/transport/iostream.hpp>
#include <websocketpp/server.hpp>

#include <iostream>
#include <sstream>

//typedef websocketpp::concurrency::stl concurrency;
//typedef websocketpp::transport::iostream<concurrency> transport;
//typedef websocketpp::server<concurrency,transport> server;
typedef websocketpp::server<websocketpp::config::core> server;

/*class handler : public server::handler {
    bool validate(connection_ptr con) {
        std::cout << "handler validate" << std::endl;
        if (con->get_origin() != "http://www.example.com") {
            con->set_status(websocketpp::http::status_code::FORBIDDEN);
            return false;
        }
        return true;
    }

    void http(connection_ptr con) {
        std::cout << "handler http" << std::endl;
    }

    void on_load(connection_ptr con, ptr old_handler) {
        std::cout << "handler on_load" << std::endl;
    }
    void on_unload(connection_ptr con, ptr new_handler) {
        std::cout << "handler on_unload" << std::endl;
    }

    void on_open(connection_ptr con) {
        std::cout << "handler on_open" << std::endl;
    }
    void on_fail(connection_ptr con) {
        std::cout << "handler on_fail" << std::endl;
    }

    void on_message(connection_ptr con, message_ptr msg) {
        std::cout << "handler on_message" << std::endl;

    }

    void on_close(connection_ptr con) {
        std::cout << "handler on_close" << std::endl;
    }
};*/

int main() {
    typedef websocketpp::message_buffer::message<websocketpp::message_buffer::alloc::con_msg_manager>
        message_type;
    typedef websocketpp::message_buffer::alloc::con_msg_manager<message_type>
        con_msg_man_type;

    con_msg_man_type::ptr manager = websocketpp::lib::make_shared<con_msg_man_type>();

    size_t foo = 1024;

    message_type::ptr input = manager->get_message(websocketpp::frame::opcode::TEXT,foo);
    message_type::ptr output = manager->get_message(websocketpp::frame::opcode::TEXT,foo);
    websocketpp::frame::masking_key_type key;

    std::random_device dev;

    key.i = 0x12345678;

    double m = 18094238402394.0824923;

    /*std::cout << "Some Math" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        for (int i = 0; i < foo; i++) {
            m /= 1.001;
        }

    }*/

    std::cout << m << std::endl;

    std::cout << "Random Gen" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        input->get_raw_payload().replace(0,foo,foo,'\0');
        output->get_raw_payload().replace(0,foo,foo,'\0');
    }

    std::cout << "Out of place accelerated" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::word_mask_exact(reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), reinterpret_cast<uint8_t*>(const_cast<char*>(output->get_raw_payload().data())), foo, key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');

    std::cout << "In place accelerated" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::word_mask_exact(reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), reinterpret_cast<uint8_t*>(const_cast<char*>(input->get_raw_payload().data())), foo, key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');
    std::cout << "Out of place byte by byte" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::byte_mask(input->get_raw_payload().begin(), input->get_raw_payload().end(), output->get_raw_payload().begin(), key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'\0');
    output->get_raw_payload().replace(0,foo,foo,'\0');
    std::cout << "In place byte by byte" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        websocketpp::frame::byte_mask(input->get_raw_payload().begin(), input->get_raw_payload().end(), input->get_raw_payload().begin(), key);
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    input->get_raw_payload().replace(0,foo,foo,'a');
    output->get_raw_payload().replace(0,foo,foo,'b');
    std::cout << "Copy" << std::endl;
    {
        boost::timer::auto_cpu_timer t;

        std::copy(input->get_raw_payload().begin(), input->get_raw_payload().end(), output->get_raw_payload().begin());
    }

    std::cout << websocketpp::utility::to_hex(input->get_payload().c_str(),20) << std::endl;
    std::cout << websocketpp::utility::to_hex(output->get_payload().c_str(),20) << std::endl;

    /*server::handler::ptr h(new handler());

    server test_server(h);
    server::connection_ptr con;

    std::stringstream output;

    test_server.register_ostream(&output);

    con = test_server.get_connection();

    con->start();

    //foo.handle_accept(con,true);

    std::stringstream input;
    input << "GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: http://www.example.com\r\n\r\n";
    //input << "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n";
    input >> *con;

    std::stringstream input2;
    input2 << "messageabc2";
    input2 >> *con;

    std::stringstream input3;
    input3 << "messageabc3";
    input3 >> *con;

    std::stringstream input4;
    input4 << "close";
    input4 >> *con;

    std::cout << "connection output:" << std::endl;
    std::cout << output.str() << std::endl;*/
}


text:
from setuptools import setup, find_packages

DESCRIPTION = 'A simple search engine for non-relational databases. Supports stemming and search-as-you-type.'

LONG_DESCRIPTION = None
try:
    LONG_DESCRIPTION = open('README.rst').read()
except:
    pass

setup(name='nonrel-search',
      version='0.1',
      packages=find_packages(exclude=('tests', 'tests.*',
                                      'base_project', 'base_project.*')),
      author='Thomas Wanschik',
      author_email='twanschik@googlemail.com',
      url='http://www.allbuttonspressed.com/projects/nonrel-search',
      description=DESCRIPTION,
      long_description=LONG_DESCRIPTION,
      platforms=['any'],
      classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Web Environment',
          'Framework :: Django',
          'Intended Audience :: Developers',
          'Operating System :: OS Independent',
          'Programming Language :: Python',
          'Topic :: Software Development :: Libraries :: Application Frameworks',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'License :: OSI Approved :: BSD License',
      ],
)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
  Provides the framework's main(String args[]) method as well as abstract
  class that should be implemented/extended to create an application's entry
  point.

  {@link com.jettmarks.base.ArgParsingMain} is the application's entry point
  from a java perspective.

  {@link com.jettmarks.base.ArgParsingEntryPoint} is the class extended by the
  application to provide the list of options recognized by the app and also
  the entry point for the first thread of execution.
</body>
</html>


text:
import os
import sys
import random
import numpy as np

from agent import RandomAgent
from sge.mazeenv import MazeEnv
from sge.utils import KEY

###################

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--game_name', default='mining',
                        help='MazeEnv/config/%s.lua')
    parser.add_argument('--graph_param', default='train_1',
                        help='difficulty of subtask graph')
    parser.add_argument('--game_len', default=70,
                        type=int, help='episode length')
    parser.add_argument('--seed', default=1, type=int,
                        help='random seed')
    parser.add_argument('--gamma', default=0.99, type=float,
                        help='discount factor')
    args = parser.parse_args()

    env = MazeEnv(args, args.game_name, args.graph_param,
                  args.game_len, args.gamma)
    agent = RandomAgent(args, env)

    state, info = env.reset()
    step, done = 0, False
    while not done:
      action = agent.act(state)
      state, rew, done, info = env.step(action)

      string = 'Step={:02d}, Action={}, Reward={:.2f}, Done={}'
      print(string.format(step, action, rew, done))
      step += 1


text:
"""Platform window focus."""
from .. import util
import os
import subprocess

MAC_RAISE_OSASCRIPT = '''\
tell application "System Events"
  set procName to name of first process whose unix id is %s
end tell
tell application procName to activate
'''

def platform_window_focus(frame):
    """Set focus to the window frame."""

    # General window raising
    if frame.IsIconized():
        frame.Iconize(False)
    if not frame.IsShown():
        frame.Show(True)
    frame.Raise()

    # macOS specific extra to ensure raise
    if util.platform() == "macos":
        subprocess.Popen(['osascript', '-e', MAC_RAISE_OSASCRIPT % os.getpid()])


text:
require 'network_drawer'
require 'ostruct'

require 'gviz'

module NetworkDrawer
  module Element
    # Replesent of element
    class Element < OpenStruct
      DEFAULT_STYLE = {}

      class << self
        def generate_id
          @ids ? @ids += 1 : @ids = 0
        end
      end

      def initialize(initial_values = {}, style = {})
        super(initial_values)
        self.id = self.class.generate_id
        @default_style = DEFAULT_STYLE
        @style = style
      end

      def to_hash
        hash = {}
        self.each_pair do |k, v|
          hash.merge!(k.to_sym => v) unless k.to_sym == name
        end
        hash
      end

      private

      def style(type)
        # TODO: select multiple types
        type = type.to_sym if type
        style = @style ? @style[type] : {}
        style ? @default_style.merge(style) : @default_style
      end
    end
  end
end


text:
param(
    [string]$buildCorePowershellUrl = "https://opbuildstorageperf.blob.core.windows.net/opps1container/.openpublishing.buildcore.ps1",
    [string]$parameters
)
# Main
$errorActionPreference = 'Stop'

# Step-1: Download buildcore script to local
echo "download build core script to local with source url: $buildCorePowershellUrl"
$repositoryRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
$buildCorePowershellDestination = "$repositoryRoot\.openpublishing.buildcore.ps1"
Invoke-WebRequest $buildCorePowershellUrl -OutFile "$buildCorePowershellDestination"

# Step-2: Run build core
echo "run build core script with parameters: $parameters"
& "$buildCorePowershellDestination" "$parameters"
exit $LASTEXITCODE


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FiniteStateMachine
{
    public class Sheriff : Agent
    {
        public Boolean OutlawSpotted = false;

        // Here is the StateMachine that the Sheriff uses to drive the agent's behaviour
        private StateMachine<Sheriff> stateMachine;
        public StateMachine<Sheriff> StateMachine
        {
            get { return stateMachine; }
            set { stateMachine = value; }
        }

        // And it knows its bank balance at any point in time
        private int moneyInBank;
        public int MoneyInBank
        {
            get { return moneyInBank; }
            set { moneyInBank = value; }
        }

        public Sheriff()
            : base()
        {
            stateMachine = new StateMachine<Sheriff>(this);
            stateMachine.CurrentState = new PatrolRandomLocation();
            stateMachine.GlobalState = new SheriffGlobalState();

            Location = Location.sheriffsOffice;
        }

        // This method is invoked by the Game object as a result of XNA updates
        public override void Update()
        {
            stateMachine.Update();
        }

        // This method is invoked when the agent receives a message
        public override bool HandleMessage(Telegram telegram)
        {
            return stateMachine.HandleMessage(telegram);
        }

        // This method is invoked when the agent senses
        public override bool HandleSenseEvent(Sense sense)
        {
            return stateMachine.HandleSenseEvent(sense);
        }

        static Random rand = new Random();
        public Location ChooseNextLocation()
        {
            Location nextLocation = Location;
            while (nextLocation == Location.outlawCamp || nextLocation == Location)
                nextLocation = (Location)rand.Next(Enum.GetNames(typeof(Location)).Length);

            return nextLocation;
        }
    }
}


text:
package supernode

import (
	"errors"
	"fmt"

	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
	datastore "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"

	peer "github.com/ipfs/go-ipfs/p2p/peer"
	dhtpb "github.com/ipfs/go-ipfs/routing/dht/pb"
	record "github.com/ipfs/go-ipfs/routing/record"
	proxy "github.com/ipfs/go-ipfs/routing/supernode/proxy"
	util "github.com/ipfs/go-ipfs/util"
)

// Server handles routing queries using a database backend
type Server struct {
	local           peer.ID
	routingBackend  datastore.ThreadSafeDatastore
	peerstore       peer.Peerstore
	*proxy.Loopback // so server can be injected into client
}

// NewServer creates a new Supernode routing Server
func NewServer(ds datastore.ThreadSafeDatastore, ps peer.Peerstore, local peer.ID) (*Server, error) {
	s := &Server{local, ds, ps, nil}
	s.Loopback = &proxy.Loopback{
		Handler: s,
		Local:   local,
	}
	return s, nil
}

func (_ *Server) Bootstrap(ctx context.Context) error {
	return nil
}

// HandleLocalRequest implements the proxy.RequestHandler interface. This is
// where requests are received from the outside world.
func (s *Server) HandleRequest(ctx context.Context, p peer.ID, req *dhtpb.Message) *dhtpb.Message {
	_, response := s.handleMessage(ctx, p, req) // ignore response peer. it's local.
	return response
}

func (s *Server) handleMessage(
	ctx context.Context, p peer.ID, req *dhtpb.Message) (peer.ID, *dhtpb.Message) {

	defer log.EventBegin(ctx, "routingMessageReceived", req, p).Done()

	var response = dhtpb.NewMessage(req.GetType(), req.GetKey(), req.GetClusterLevel())
	switch req.GetType() {

	case dhtpb.Message_GET_VALUE:
		rawRecord, err := getRoutingRecord(s.routingBackend, util.Key(req.GetKey()))
		if err != nil {
			return "", nil
		}
		response.Record = rawRecord
		return p, response

	case dhtpb.Message_PUT_VALUE:
		// FIXME: verify complains that the peer's ID is not present in the
		// peerstore. Mocknet problem?
		// if err := verify(s.peerstore, req.GetRecord()); err != nil {
		// 	log.Event(ctx, "validationFailed", req, p)
		// 	return "", nil
		// }
		putRoutingRecord(s.routingBackend, util.Key(req.GetKey()), req.GetRecord())
		return p, req

	case dhtpb.Message_FIND_NODE:
		p := s.peerstore.PeerInfo(peer.ID(req.GetKey()))
		pri := []dhtpb.PeerRoutingInfo{
			{
				PeerInfo: p,
				// Connectedness: TODO
			},
		}
		response.CloserPeers = dhtpb.PeerRoutingInfosToPBPeers(pri)
		return p.ID, response

	case dhtpb.Message_ADD_PROVIDER:
		for _, provider := range req.GetProviderPeers() {
			providerID := peer.ID(provider.GetId())
			if providerID == p {
				store := []*dhtpb.Message_Peer{provider}
				storeProvidersToPeerstore(s.peerstore, p, store)
				if err := putRoutingProviders(s.routingBackend, util.Key(req.GetKey()), store); err != nil {
					return "", nil
				}
			} else {
				log.Event(ctx, "addProviderBadRequest", p, req)
			}
		}
		return "", nil

	case dhtpb.Message_GET_PROVIDERS:
		providers, err := getRoutingProviders(s.routingBackend, util.Key(req.GetKey()))
		if err != nil {
			return "", nil
		}
		response.ProviderPeers = providers
		return p, response

	case dhtpb.Message_PING:
		return p, req
	default:
	}
	return "", nil
}

var _ proxy.RequestHandler = &Server{}
var _ proxy.Proxy = &Server{}

func getRoutingRecord(ds datastore.Datastore, k util.Key) (*dhtpb.Record, error) {
	dskey := k.DsKey()
	val, err := ds.Get(dskey)
	if err != nil {
		return nil, err
	}
	recordBytes, ok := val.([]byte)
	if !ok {
		return nil, fmt.Errorf("datastore had non byte-slice value for %v", dskey)
	}
	var record dhtpb.Record
	if err := proto.Unmarshal(recordBytes, &record); err != nil {
		return nil, errors.New("failed to unmarshal dht record from datastore")
	}
	return &record, nil
}

func putRoutingRecord(ds datastore.Datastore, k util.Key, value *dhtpb.Record) error {
	data, err := proto.Marshal(value)
	if err != nil {
		return err
	}
	dskey := k.DsKey()
	// TODO namespace
	if err := ds.Put(dskey, data); err != nil {
		return err
	}
	return nil
}

func putRoutingProviders(ds datastore.Datastore, k util.Key, newRecords []*dhtpb.Message_Peer) error {
	log.Event(context.Background(), "putRoutingProviders", &k)
	oldRecords, err := getRoutingProviders(ds, k)
	if err != nil {
		return err
	}
	mergedRecords := make(map[string]*dhtpb.Message_Peer)
	for _, provider := range oldRecords {
		mergedRecords[provider.GetId()] = provider // add original records
	}
	for _, provider := range newRecords {
		mergedRecords[provider.GetId()] = provider // overwrite old record if new exists
	}
	var protomsg dhtpb.Message
	protomsg.ProviderPeers = make([]*dhtpb.Message_Peer, 0, len(mergedRecords))
	for _, provider := range mergedRecords {
		protomsg.ProviderPeers = append(protomsg.ProviderPeers, provider)
	}
	data, err := proto.Marshal(&protomsg)
	if err != nil {
		return err
	}
	return ds.Put(providerKey(k), data)
}

func storeProvidersToPeerstore(ps peer.Peerstore, p peer.ID, providers []*dhtpb.Message_Peer) {
	for _, provider := range providers {
		providerID := peer.ID(provider.GetId())
		if providerID != p {
			log.Errorf("provider message came from third-party %s", p)
			continue
		}
		for _, maddr := range provider.Addresses() {
			// as a router, we want to store addresses for peers who have provided
			ps.AddAddr(p, maddr, peer.AddressTTL)
		}
	}
}

func getRoutingProviders(ds datastore.Datastore, k util.Key) ([]*dhtpb.Message_Peer, error) {
	e := log.EventBegin(context.Background(), "getProviders", &k)
	defer e.Done()
	var providers []*dhtpb.Message_Peer
	if v, err := ds.Get(providerKey(k)); err == nil {
		if data, ok := v.([]byte); ok {
			var msg dhtpb.Message
			if err := proto.Unmarshal(data, &msg); err != nil {
				return nil, err
			}
			providers = append(providers, msg.GetProviderPeers()...)
		}
	}
	return providers, nil
}

func providerKey(k util.Key) datastore.Key {
	return datastore.KeyWithNamespaces([]string{"routing", "providers", k.String()})
}

func verify(ps peer.Peerstore, r *dhtpb.Record) error {
	v := make(record.Validator)
	v["pk"] = record.PublicKeyValidator
	p := peer.ID(r.GetAuthor())
	pk := ps.PubKey(p)
	if pk == nil {
		return fmt.Errorf("do not have public key for %s", p)
	}
	if err := record.CheckRecordSig(r, pk); err != nil {
		return err
	}
	if err := v.VerifyRecord(r); err != nil {
		return err
	}
	return nil
}


text:
'use strict';

var assert = require('assert');
var helpers = require('./helpers');
var runJSON = helpers.runMochaJSON;
var args = [];
var bang = require('../../lib/reporters/base').symbols.bang;

describe('retries', function () {
  it('are ran in correct order', function (done) {
    helpers.runMocha(
      'retries/hooks.fixture.js',
      ['--reporter', 'dot'],
      function (err, res) {
        var lines, expected;

        if (err) {
          done(err);
          return;
        }

        lines = res.output
          .split(helpers.SPLIT_DOT_REPORTER_REGEXP)
          .map(function (line) {
            return line.trim();
          })
          .filter(function (line) {
            return line.length;
          })
          .slice(0, -1);

        expected = [
          'before',
          'before each 0',
          'TEST 0',
          'after each 1',
          'before each 1',
          'TEST 1',
          'after each 2',
          'before each 2',
          'TEST 2',
          'after each 3',
          'before each 3',
          'TEST 3',
          'after each 4',
          'before each 4',
          'TEST 4',
          bang + 'after each 5',
          'after'
        ];

        expected.forEach(function (line, i) {
          assert.strictEqual(lines[i], line);
        });

        assert.strictEqual(res.code, 1);
        done();
      }
    );
  });

  it('should exit early if test passes', function (done) {
    runJSON('retries/early-pass.fixture.js', args, function (err, res) {
      if (err) {
        return done(err);
      }

      expect(res, 'to have passed')
        .and('to have passed test count', 2)
        .and('to have failed test count', 0)
        .and('to have retried test', 'should pass after 1 retry', 1);

      done();
    });
  });

  it('should let test override', function (done) {
    runJSON('retries/nested.fixture.js', args, function (err, res) {
      if (err) {
        done(err);
        return;
      }
      assert.strictEqual(res.stats.passes, 0);
      assert.strictEqual(res.stats.failures, 1);
      assert.strictEqual(res.stats.tests, 1);
      assert.strictEqual(res.tests[0].currentRetry, 1);
      assert.strictEqual(res.code, 1);
      done();
    });
  });

  it('should not hang w/ async test', function (done) {
    helpers.runMocha(
      'retries/async.fixture.js',
      ['--reporter', 'dot'],
      function (err, res) {
        var lines, expected;

        if (err) {
          done(err);
          return;
        }

        lines = res.output
          .split(helpers.SPLIT_DOT_REPORTER_REGEXP)
          .map(function (line) {
            return line.trim();
          })
          .filter(function (line) {
            return line.length;
          })
          .slice(0, -1);

        expected = [
          'before',
          'before each 0',
          'TEST 0',
          'after each 1',
          'before each 1',
          'TEST 1',
          'after each 2',
          'before each 2',
          'TEST 2',
          'after each 3',
          'after'
        ];

        expected.forEach(function (line, i) {
          assert.strictEqual(lines[i], line);
        });

        assert.strictEqual(res.code, 0);
        done();
      }
    );
  });
});


text:
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-sysdeps.h Wrappers around system/libc features (internal to D-Bus implementation)
 *
 * Copyright (C) 2002, 2003  Red Hat, Inc.
 * Copyright (C) 2003 CodeFactory AB
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifndef DBUS_PIPE_H
#define DBUS_PIPE_H

#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif

#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif

#include <dbus/dbus-types.h>
#include <dbus/dbus-errors.h>
#include <dbus/dbus-string.h>
#include <dbus/dbus-sysdeps.h>

struct DBusPipe {
  int fd;
};

void        _dbus_pipe_init                (DBusPipe         *pipe,
                                            int               fd);
void        _dbus_pipe_init_stdout         (DBusPipe         *pipe);
int         _dbus_pipe_write               (DBusPipe         *pipe,
                                            const DBusString *buffer,
                                            int               start,
                                            int               len,
                                            DBusError        *error);
int         _dbus_pipe_close               (DBusPipe         *pipe,
                                            DBusError        *error);
dbus_bool_t _dbus_pipe_is_valid            (DBusPipe         *pipe);
void        _dbus_pipe_invalidate          (DBusPipe         *pipe);
dbus_bool_t _dbus_pipe_is_stdout_or_stderr (DBusPipe         *pipe);

#endif


text:
$(function () {
	$.get('/books', function (bookList) {
		var list = [];
		if (bookList) {
			bookList.forEach(function (book) {
				list.push('

X' + book.title + '
');
			});
			$('.books-list').append(list);
		}
	});

	$('form').on('submit', function (evt) {
		evt.preventDefault();
		var $form = $(this);

		// serialize will transform our form data into urlencoded notation
		var bookData = $form.serialize();

		$.ajax({
			method: 'POST',
			url: '/books',
			data: bookData
		})
		.done(function (book) {
			var list = [];
			list.push('
X' + book.title + '
');
			$('.books-list').append(list);
			$form.trigger('reset');
		});
	});

	$('.books-list').on('click', '[data-book]', function (evt) {
		if (!confirm('Delete book?')) {
			return false;
		}
		var $target = $(evt.currentTarget);

		$.ajax({
			method: 'DELETE',
			url: '/books/' + $target.data('book'),
		})
		.done(function () {
			$target.closest('li').remove();
		});
	});
});


text:
@interface DummyViewController : UIViewController

@end


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.ResolvedTargets;
import com.google.devtools.build.lib.cmdline.TargetParsingException;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.pkgcache.TargetProvider;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Utility functions over test Targets that don't really belong in the base {@link Target}
 * interface.
 */
public final class TestTargetUtils {

  /**
   * Returns whether a test with the specified tags matches a filter (as specified by the set
   * of its positive and its negative filters).
   */
  public static boolean testMatchesFilters(
      Collection<String> testTags,
      Collection<String> requiredTags,
      Collection<String> excludedTags,
      boolean mustMatchAllPositive) {
    for (String tag : excludedTags) {
      if (testTags.contains(tag)) {
        return false;
      }
    }

    // Check required tags, if there are any.
    if (requiredTags.isEmpty()) {
      return true;
    } else if (mustMatchAllPositive) {
      // Require all tags to be present.
      for (String tag : requiredTags) {
        if (!testTags.contains(tag)) {
          return false;
        }
      }
      return true;
    } else {
      // Require at least one positive tag. If the two collections are not disjoint, then they have
      // at least one element in common.
      return !Collections.disjoint(requiredTags, testTags);
    }
  }

  /**
   * Decides whether to include a test in a test_suite or not.
   * @param testTags Collection of all tags exhibited by a given test.
   * @param requiredTags Tags declared by the suite. A Test must match ALL of these.
   * @param excludedTags Tags declared by the suite. A Test must match NONE of these.
   * @return false is the test is to be removed.
   */
  public static boolean testMatchesFilters(
      Collection<String> testTags,
      Collection<String> requiredTags,
      Collection<String> excludedTags) {
    return testMatchesFilters(
        testTags, requiredTags, excludedTags, /* mustMatchAllPositive= */ true);
  }

  /**
   * Decides whether to include a test in a test_suite or not.
   * @param testTarget A given test target.
   * @param requiredTags Tags declared by the suite. A Test must match ALL of these.
   * @param excludedTags Tags declared by the suite. A Test must match NONE of these.
   * @return false is the test is to be removed.
   */
  private static boolean testMatchesFilters(
      Rule testTarget,
      Collection<String> requiredTags,
      Collection<String> excludedTags) {
    AttributeMap nonConfigurableAttrs = NonconfigurableAttributeMapper.of(testTarget);
    Set<String> testTags = new HashSet<>(nonConfigurableAttrs.get("tags", Type.STRING_LIST));
    testTags.add(nonConfigurableAttrs.get("size", Type.STRING));
    return testMatchesFilters(testTags, requiredTags, excludedTags);
  }

  /**
   * Filters 'tests' (by mutation) according to the 'tags' attribute, specifically those that
   * match ALL of the tags in tagsAttribute.
   *
   * @precondition {@code env.getAccessor().isTestSuite(testSuite)}
   * @precondition {@code env.getAccessor().isTestRule(test)} for all test in tests
   */
  public static void filterTests(Rule testSuite, Set<Target> tests) {
    List<String> tagsAttribute =
        NonconfigurableAttributeMapper.of(testSuite).get("tags", Type.STRING_LIST);
    // Split the tags list into positive and negative tags
    Pair<Collection<String>, Collection<String>> tagLists = sortTagsBySense(tagsAttribute);
    Collection<String> positiveTags = tagLists.first;
    Collection<String> negativeTags = tagLists.second;
    tests.removeIf((Target t) -> !testMatchesFilters((Rule) t, positiveTags, negativeTags));
  }

  /**
   * Separates a list of text "tags" into a Pair of Collections, where
   * the first element are the required or positive tags and the second element
   * are the excluded or negative tags.
   * This should work on tag list provided from the command line
   * --test_tags_filters flag or on tag filters explicitly declared in the
   * suite.
   *
   * @param tagList A collection of text targets to separate.
   */
  public static Pair<Collection<String>, Collection<String>> sortTagsBySense(
      Iterable<String> tagList) {
    Collection<String> requiredTags = new HashSet<>();
    Collection<String> excludedTags = new HashSet<>();

    for (String tag : tagList) {
      if (tag.startsWith("-")) {
        excludedTags.add(tag.substring(1));
      } else if (tag.startsWith("+")) {
        requiredTags.add(tag.substring(1));
      } else if (tag.equals("manual")) {
        // Ignore manual attribute because it is an exception: it is not a filter
        // but a property of test_suite
        continue;
      } else {
        requiredTags.add(tag);
      }
    }
    return Pair.of(requiredTags, excludedTags);
  }

  /**
   * Returns the (new, mutable) set of test rules, expanding all 'test_suite' rules into the
   * individual tests they group together and preserving other test target instances.
   *
   * <p>Method assumes that passed collection contains only *_test and test_suite rules. While, at
   * this point it will successfully preserve non-test rules as well, there is no guarantee that
   * this behavior will be kept in the future.
   *
   * @param targetProvider a target provider
   * @param eventHandler a failure eventHandler to report loading failures to
   * @param targets Collection of the *_test and test_suite configured targets
   * @return a duplicate-free iterable of the tests under the specified targets
   */
  public static ResolvedTargets<Target> expandTestSuites(
      TargetProvider targetProvider,
      ExtendedEventHandler eventHandler,
      Iterable<? extends Target> targets,
      boolean strict,
      boolean keepGoing)
      throws TargetParsingException {
    Closure closure = new Closure(targetProvider, eventHandler, strict, keepGoing);
    ResolvedTargets.Builder<Target> result = ResolvedTargets.builder();
    for (Target target : targets) {
      if (TargetUtils.isTestRule(target)) {
        result.add(target);
      } else if (TargetUtils.isTestSuiteRule(target)) {
        result.addAll(closure.getTestsInSuite((Rule) target));
      } else {
        result.add(target);
      }
    }
    if (closure.hasError) {
      result.setError();
    }
    return result.build();
  }

  // TODO(bazel-team): This is a copy of TestsExpression.Closure with some minor changes; this
  // should be unified.
  private static final class Closure {
    private final TargetProvider targetProvider;

    private final ExtendedEventHandler eventHandler;

    private final boolean keepGoing;

    private final boolean strict;

    private final Map<Target, Set<Target>> testsInSuite = new HashMap<>();

    private boolean hasError;

    public Closure(
        TargetProvider targetProvider,
        ExtendedEventHandler eventHandler,
        boolean strict,
        boolean keepGoing) {
      this.targetProvider = targetProvider;
      this.eventHandler = eventHandler;
      this.strict = strict;
      this.keepGoing = keepGoing;
    }

    /**
     * Computes and returns the set of test rules in a particular suite.  Uses
     * dynamic programming---a memoized version of {@link #computeTestsInSuite}.
     */
    private Set<Target> getTestsInSuite(Rule testSuite) throws TargetParsingException {
      Set<Target> tests = testsInSuite.get(testSuite);
      if (tests == null) {
        tests = new HashSet<>();
        testsInSuite.put(testSuite, tests); // break cycles by inserting empty set early.
        computeTestsInSuite(testSuite, tests);
      }
      return tests;
    }

    /**
     * Populates 'result' with all the tests associated with the specified
     * 'testSuite'.  Throws an exception if any target is missing.
     *
     * CAUTION!  Keep this logic consistent with {@code TestSuite} and {@code TestsInSuiteFunction}!
     */
    private void computeTestsInSuite(Rule testSuite, Set<Target> result)
        throws TargetParsingException {
      List<Target> testsAndSuites = new ArrayList<>();
      // Note that testsAndSuites can contain input file targets; the test_suite rule does not
      // restrict the set of targets that can appear in tests or suites.
      testsAndSuites.addAll(getPrerequisites(testSuite, "tests"));

      // 1. Add all tests
      for (Target test : testsAndSuites) {
        if (TargetUtils.isTestRule(test)) {
          result.add(test);
        } else if (strict && !TargetUtils.isTestSuiteRule(test)) {
          // If strict mode is enabled, then give an error for any non-test, non-test-suite targets.
          eventHandler.handle(Event.error(testSuite.getLocation(),
              "in test_suite rule '" + testSuite.getLabel()
              + "': expecting a test or a test_suite rule but '" + test.getLabel()
              + "' is not one."));
          hasError = true;
          if (!keepGoing) {
            throw new TargetParsingException("Test suite expansion failed.");
          }
        }
      }

      // 2. Add implicit dependencies on tests in same package, if any.
      for (Target target : getPrerequisites(testSuite, "$implicit_tests")) {
        // The Package construction of $implicit_tests ensures that this check never fails, but we
        // add it here anyway for compatibility with future code.
        if (TargetUtils.isTestRule(target)) {
          result.add(target);
        }
      }

      // 3. Filter based on tags, size, env.
      filterTests(testSuite, result);

      // 4. Expand all suites recursively.
      for (Target suite : testsAndSuites) {
        if (TargetUtils.isTestSuiteRule(suite)) {
          result.addAll(getTestsInSuite((Rule) suite));
        }
      }
    }

    /**
     * Returns the set of rules named by the attribute 'attrName' of test_suite rule 'testSuite'.
     * The attribute must be a list of labels. If a target cannot be resolved, then an error is
     * reported to the environment (which may throw an exception if {@code keep_going} is disabled).
     */
    private Collection<Target> getPrerequisites(Rule testSuite, String attrName)
        throws TargetParsingException {
      try {
        List<Target> targets = new ArrayList<>();
        // TODO(bazel-team): This serializes package loading in some cases. We might want to make
        // this multi-threaded.
        for (Label label :
            NonconfigurableAttributeMapper.of(testSuite).get(attrName, BuildType.LABEL_LIST)) {
          targets.add(targetProvider.getTarget(eventHandler, label));
        }
        return targets;
      } catch (NoSuchThingException e) {
        if (keepGoing) {
          hasError = true;
          eventHandler.handle(Event.error(e.getMessage()));
          return ImmutableList.of();
        }
        throw new TargetParsingException(e.getMessage(), e);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new TargetParsingException("interrupted", e);
      }
    }
  }
}


text:
<?xml version="1.0"?>
<!--
   $Id: build.xml,v 1.21 2009/12/18 20:28:00 karsten Exp $

   This is a build file for use with the Jakarta Ant build tool, see
   http://jakarta.apache.org/ant/index.html

   To build, go to the directory where this file is located and run
     ant <target>
   with one of the following targets:

     clean               removes temporary files and directories
     compile             compiles the core, extras, tutorial and tests
     javadoc             creates the API documentation
     test                compiles and runs the unit tests
     jar                 creates a library jar
     create-dist-dir     creates a distribution tree: docs, sources, jar
     create-dist-zip     creates a zipped distribution
     create-maven-bundle creates a Maven bundle
     create-all          creates the distribution zip and Maven bundle

   To compile, you MUST set the property "build.boot.classpath",
   for example in your user build.properties file a line like:
   build.boot.classpath=C:/Java/Jdk1.5.0_11/jre/lib/rt.jar

   To run the unit tests you MUST set the junit.jar property,
   for example in your user build.properties file.

-->

<project default="create-all" basedir="." name="JGoodies Forms" >

    <!-- ***************************************************************** -->
    <!-- Give users a chance to override build properties.                 -->
    <!-- ***************************************************************** -->
    <property file="${user.home}/forms.build.properties" />
    <property file="${user.home}/build.properties" />
    <property file="${basedir}/build.properties" />
    <property file="${basedir}/default.properties" />

    <!-- ***************************************************************** -->
    <!-- P A T H S                                                         -->
    <!-- ***************************************************************** -->
    <path id="classpath.core">
        <pathelement location="${build.core.dir}" 	/>
    </path>

    <path id="classpath.extras">
        <pathelement location="${build.core.dir}" 	/>
        <pathelement location="${build.extras.dir}" />
    </path>

    <path id="classpath.tests">
        <pathelement location="${build.core.dir}" 	/>
        <pathelement location="${build.extras.dir}" />
        <pathelement location="${build.test.dir}" 	/>
        <pathelement location="${junit4.jar}" 		/>
    </path>

    <path id="classpath.tutorial">
        <pathelement location="${build.core.dir}"   />
        <pathelement location="${build.extras.dir}" />
    </path>

    <!-- ***************************************************************** -->
    <!-- C L E A N                                                         -->
    <!-- ***************************************************************** -->
	<target name="clean"
		    description="Removes all temporary files and directories." >

		<delete dir="${build.dir}" />
		<delete dir="${dist.dir}"  />
	</target>

    <!-- ***************************************************************** -->
    <!-- P R E P A R A T I O N                                             -->
    <!-- ***************************************************************** -->
	<target name="prepare"
	        description="Prepares the build and distribution targets." >

        <tstamp>
           <format property="DATE" pattern="yyyy-MM-dd hh:mm:ss" />
        </tstamp>

		<mkdir dir="${build.core.dir}"		/>
		<mkdir dir="${build.extras.dir}"	/>
		<mkdir dir="${build.tutorial.dir}"	/>

        <available
            property="junit.task.present"
            classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask"
        />
        <available
            property="junit.jar.present"
            file="${junit.jar}"
        />
	</target>

    <!-- ***************************************************************** -->
    <!-- C O M P I L A T I O N                                             -->
    <!-- ***************************************************************** -->
	<target name="compile"
	        depends="compile-core, compile-extras, compile-tests, compile-tutorial"
	        description="Compiles the framework, extras, tests and tutorial." />

    <!-- ***************************************************************** -->
	<target name="compile-core" depends="prepare"
	        description="Compiles the core sources." >
		<javac
			srcdir       ="${src.core.dir}"
			destdir      ="${build.core.dir}"
        	encoding     ="${build.encoding}"
        	executable   ="${build.compile.executable}"
        	fork         ="${build.compile.fork}"
			debug        ="${build.compile.debug}"
			depend       ="${build.compile.depend}"
			deprecation  ="${build.compile.deprecation}"
			nowarn       ="${build.compile.nowarn}"
			optimize     ="${build.compile.optimize}"
            source       ="${build.compile.source}"
			target       ="${build.compile.target}"
			verbose      ="${build.compile.verbose}"
			bootclasspath="${build.boot.classpath}" />
	</target>

    <!-- ***************************************************************** -->
	<target name="compile-extras" depends="compile-core"
	        description="Compiles the extra sources." >
		<javac
			srcdir       ="${src.extras.dir}"
			destdir      ="${build.extras.dir}"
        	encoding     ="${build.encoding}"
        	executable   ="${build.compile.executable}"
        	fork         ="${build.compile.fork}"
			debug        ="${build.compile.debug}"
			depend       ="${build.compile.depend}"
			deprecation  ="${build.compile.deprecation}"
			nowarn       ="${build.compile.nowarn}"
			optimize     ="${build.compile.optimize}"
            source       ="${build.compile.source}"
			target       ="${build.compile.target}"
			verbose      ="${build.compile.verbose}"
			bootclasspath="${build.boot.classpath}"
			classpathref ="classpath.core" />
	</target>

    <!-- ***************************************************************** -->
    <target name="compile-tests" depends="compile-extras" if="junit.jar.present"
            description="Compiles the unit tests." >
        <mkdir dir="${build.test.dir}"/>
        <javac
            srcdir       ="${src.test.dir}"
            destdir      ="${build.test.dir}"
            encoding     ="${build.encoding}"
            executable   ="${build.compile.executable}"
            fork         ="${build.compile.fork}"
            debug        ="${build.compile.debug}"
            depend       ="${build.compile.depend}"
            deprecation  ="${build.compile.deprecation}"
            nowarn       ="${build.compile.nowarn}"
            optimize     ="${build.compile.optimize}"
            source       ="${build.compile.source}"
            target       ="${build.compile.target}"
            verbose      ="${build.compile.verbose}"
            bootclasspath="${build.boot.classpath}"
            classpathref ="classpath.tests" />
    </target>

    <!-- ***************************************************************** -->
	<target name="compile-tutorial" depends="compile-extras"
	        description="Compiles the tutorial." >
		<javac
			srcdir       ="${src.tutorial.dir}"
			destdir      ="${build.tutorial.dir}"
        	encoding     ="${build.encoding}"
        	executable   ="${build.compile.executable}"
        	fork         ="${build.compile.fork}"
			debug        ="${build.compile.debug}"
			depend       ="${build.compile.depend}"
			deprecation  ="${build.compile.deprecation}"
			nowarn       ="${build.compile.nowarn}"
			optimize     ="${build.compile.optimize}"
            source       ="${build.compile.source}"
			target       ="${build.compile.target}"
			verbose      ="${build.compile.verbose}"
			bootclasspath="${build.boot.classpath}"
			classpathref ="classpath.tutorial" />
	</target>

    <!-- ***************************************************************** -->
    <!-- J A V A D O C                                                     -->
    <!-- ***************************************************************** -->
    <target name="javadoc" depends="prepare"
            description="Creates the API documentation using JavaDoc." >
		<mkdir dir="${build.javadocs.dir}"	/>
        <javadoc
        	sourcepath="${src.core.dir}:${src.extras.dir}"
            packagenames="${javadoc.packages}"
        	destdir="${build.javadocs.dir}"
        	encoding="${build.encoding}"
            access="protected"
            author="true"
            version="true"
            use="true"
            link="${javadoc.link}"
            overview="${javadoc.overview}"
            windowtitle="${Name} ${spec.version} API"
            doctitle="${Name} ${spec.version} API"
            bottom="${copyright.message}" >
         </javadoc>
    </target>

    <!-- ***************************************************************** -->
    <!-- U N I T   T E S T S                                               -->
    <!-- ***************************************************************** -->
	<target name="test" depends="compile-tests" if="junit.task.present"
	        description="Compiles and runs the unit tests." >
        <mkdir dir="${build.reports.dir}"/>
        <junit printsummary="yes" haltonfailure="no" >
            <classpath refid="classpath.tests"/>
            <formatter type="plain" />
            <batchtest fork="yes" todir="${build.reports.dir}">
                <fileset dir="${src.test.dir}" includes="**/*Test.java" />
            </batchtest>
        </junit>
	</target>

    <!-- ***************************************************************** -->
    <!-- J A R                                       				       -->
    <!-- ***************************************************************** -->
	<target name="jar" depends="compile-core"
	        description="Creates the library jar." >
		<jar
			destfile="${build.core.jar}" >
			<fileset dir="${build.core.dir}" />
            <manifest>
                <attribute name ="Built-By"
                           value="${user.name}"/>
                <attribute name ="Specification-Title"
                           value="${spec.title}" />
                <attribute name ="Specification-Vendor"
                           value="${spec.vendor}" />
                <attribute name ="Specification-Version"
                           value="${spec.version}" />
         		<attribute name ="Implementation-Title"
                           value="${impl.title}" />
                <attribute name ="Implementation-Vendor"
                           value="${impl.vendor}" />
                <attribute name ="Implementation-Version"
                           value="${impl.version} ${DATE}" />
           </manifest>
		</jar>
	</target>

    <!-- ***************************************************************** -->
    <!-- C R E A T E                                                       -->
    <!-- ***************************************************************** -->
    <target name="create-all" depends="create-dist-zip, create-maven-bundle"
            description="Creates the distribution zip and Maven bundle." >
    </target>

    <target name="create-dist-dir" depends="clean, compile, javadoc, test, jar"
            description="Creates the distribution directory tree." >

        <mkdir dir="${dist.dir}" />

		<!-- Compile the documentation. -->
		<copy todir="${dist.docs.dir}" >
			<fileset dir="${docs.dir}"
			         excludes="**/*.psd, **/*.sxw"     />
		</copy>
        <move todir="${dist.docs.dir}" file="${build.javadocs.dir}" />

        <!-- Copy the source directories. -->
        <copy todir="${dist.src.dir}" >
            <fileset dir="${src.dir}"
                     excludes="unused,
                               unused/**/*"      />
        </copy>

		<!-- Copy the distribution files. -->
		<copy todir="${dist.dir}" >
			<fileset dir="${top.dir}"
				     includes="*.txt, *.html, *.xml, *.properties"
				     excludes="todo.txt" />
		</copy>

		<!-- Copy the library jar file. -->
		<copy tofile="${dist.core.jar}" file="${build.core.jar}" />

	</target>

    <!-- ***************************************************************** -->
    <target name="create-dist-zip" depends="create-dist-dir"
            description="Packages the distribution as a zip file." >

        <zip
            destfile="${dist.zip}"
            basedir="${dist.root.dir}"
            includes="${dist.subdir}/**/*" />
    </target>

    <!-- ***************************************************************** -->
    <target name="create-maven-bundle" depends="create-dist-dir"
            description="Creates a Maven bundle for the Ibiblio upload." >

        <!-- Copy the Maven pom template. -->
        <copy tofile="${dist.maven.pom}" file="${build.maven.pom.template}" />
        <!-- Replace the version in the pom.xml. -->
        <replace file="${dist.maven.pom}"
            token="@impl.version"
            value="${impl.version}" />

        <copy tofile="${dist.maven.bin.jar}" file="${build.core.jar}" />
        <jar
            destfile="${dist.maven.src.jar}"
            basedir="${dist.src.dir}" />
        <jar
            destfile="${dist.maven.bundle}"
            basedir="${build.maven.dir}" />
    </target>

</project>


text:
{% if is_paginated %}

        {% if page_obj.has_previous %}

«

        {% else %}

«

        {% endif %}

        {% for i in paginator.page_range %}
          {% if page_obj.number == i %}

{{ i }} (current)

          {% else %}

{{ i }}

          {% endif %}
        {% endfor %}

        {% if page_obj.has_next %}

»

        {% else %}

»

        {% endif %}

    {% endif %}


text:
#include "qwindowsnativeimage.h"
#include "qwindowscontext.h"

#include <QtGui/private/qpaintengine_p.h>
#include <QtGui/private/qpaintengine_raster_p.h>

QT_BEGIN_NAMESPACE

typedef struct {
    BITMAPINFOHEADER bmiHeader;
    DWORD redMask;
    DWORD greenMask;
    DWORD blueMask;
} BITMAPINFO_MASK;

/*!
    \class QWindowsNativeImage
    \brief Windows Native image

    Note that size can be 0 (widget autotests with zero size), which
    causes CreateDIBSection() to fail.

    \sa QWindowsBackingStore
    \internal
    \ingroup qt-lighthouse-win
*/

static inline HDC createDC()
{
    HDC display_dc = GetDC(0);
    HDC hdc = CreateCompatibleDC(display_dc);
    ReleaseDC(0, display_dc);
    Q_ASSERT(hdc);
    return hdc;
}

static inline HBITMAP createDIB(HDC hdc, int width, int height,
                                QImage::Format format,
                                uchar **bitsIn)
{
    BITMAPINFO_MASK bmi;
    memset(&bmi, 0, sizeof(bmi));
    bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth       = width;
    bmi.bmiHeader.biHeight      = -height; // top-down.
    bmi.bmiHeader.biPlanes      = 1;
    bmi.bmiHeader.biSizeImage   = 0;

    if (format == QImage::Format_RGB16) {
        bmi.bmiHeader.biBitCount = 16;
        bmi.bmiHeader.biCompression = BI_BITFIELDS;
        bmi.redMask = 0xF800;
        bmi.greenMask = 0x07E0;
        bmi.blueMask = 0x001F;
    } else {
        bmi.bmiHeader.biBitCount    = 32;
        bmi.bmiHeader.biCompression = BI_RGB;
        bmi.redMask = 0;
        bmi.greenMask = 0;
        bmi.blueMask = 0;
    }

    void *bits = 0;
    HBITMAP bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi),
                                      DIB_RGB_COLORS, &bits, 0, 0);
    if (!bitmap || !bits)
        qFatal("%s: CreateDIBSection failed.", __FUNCTION__);

    *bitsIn = (uchar*)bits;
    return bitmap;
}

QWindowsNativeImage::QWindowsNativeImage(int width, int height,
                                         QImage::Format format) :
    m_hdc(createDC()),
    m_bitmap(0),
    m_null_bitmap(0)
{
    if (width != 0 && height != 0) {
        uchar *bits;
        m_bitmap = createDIB(m_hdc, width, height, format, &bits);
        m_null_bitmap = (HBITMAP)SelectObject(m_hdc, m_bitmap);
        m_image = QImage(bits, width, height, format);
        Q_ASSERT(m_image.paintEngine()->type() == QPaintEngine::Raster);
        static_cast<QRasterPaintEngine *>(m_image.paintEngine())->setDC(m_hdc);
    } else {
        m_image = QImage(width, height, format);
    }

#ifndef Q_OS_WINCE
    GdiFlush();
#endif
}

QWindowsNativeImage::~QWindowsNativeImage()
{
    if (m_hdc) {
        if (m_bitmap) {
            if (m_null_bitmap)
                SelectObject(m_hdc, m_null_bitmap);
            DeleteObject(m_bitmap);
        }
        DeleteDC(m_hdc);
    }
}

QImage::Format QWindowsNativeImage::systemFormat()
{
    static const int depth = QWindowsContext::instance()->screenDepth();
    return depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32;
}

QT_END_NAMESPACE