text:
namespace MassTransit.Tests.Configuration
{
    using System;
    using Magnum.Extensions;
    using Magnum.TestFramework;
    using Messages;
    using TestFramework;

    [Scenario]
    public class When_subscribing_a_consumer_to_the_bus
    {
        IServiceBus _bus;
        PingMessage _ping;

        [When]
        public void Subscribing_a_consumer_to_the_bus()
        {
            _bus = ServiceBusFactory.New(x =>
                {
                    x.ReceiveFrom("loopback://localhost/mt_test");

                    x.Subscribe(s => s.Consumer<ConsumerOf<PingMessage>>());
                });

            _ping = new PingMessage(Guid.NewGuid());
            _bus.Publish(_ping);
        }

        [Finally]
        public void Finally()
        {
            _bus.Dispose();
        }

        [Then]
        public void Should_have_subscribed()
        {
            _bus.ShouldHaveRemoteSubscriptionFor<PingMessage>();
        }

        [Then]
        public void Should_have_received_the_message()
        {
            ConsumerOf<PingMessage>.AnyShouldHaveReceivedMessage(_ping, 8.Seconds());
        }
    }

    [Scenario]
    public class When_subscribing_a_type_of_consumer_to_the_bus
    {
        IServiceBus _bus;
        PingMessage _ping;

        [When]
        public void Subscribing_a_consumer_to_the_bus()
        {
            _bus = ServiceBusFactory.New(x =>
                {
                    x.ReceiveFrom("loopback://localhost/mt_test");

                    x.Subscribe(s => s.Consumer(typeof (ConsumerOf<PingMessage>), Activator.CreateInstance));
                });

            _ping = new PingMessage(Guid.NewGuid());
            _bus.Publish(_ping);
        }

        [Finally]
        public void Finally()
        {
            _bus.Dispose();
        }

        [Then]
        public void Should_have_subscribed()
        {
            _bus.ShouldHaveRemoteSubscriptionFor<PingMessage>();
        }

        [Then]
        public void Should_have_received_the_message()
        {
            ConsumerOf<PingMessage>.AnyShouldHaveReceivedMessage(_ping, 12.Seconds());
        }
    }

    [Scenario]
    public class When_subscribing_a_consumer_to_the_bus_with_a_factory_method
    {
        IServiceBus _bus;
        PingMessage _ping1;
        PingMessage _ping2;

        [When]
        public void Subscribing_a_consumer_to_the_bus()
        {
            _bus = ServiceBusFactory.New(x =>
                {
                    x.ReceiveFrom("loopback://localhost/mt_test");
                    x.SetConcurrentConsumerLimit(1);

                    x.Subscribe(s => s.Consumer(GetConsumer));
                });

            _ping1 = new PingMessage(Guid.NewGuid());
            _ping2 = new PingMessage(Guid.NewGuid());
            _bus.Publish(_ping1);
            _bus.Publish(_ping2);
        }

        [Finally]
        public void Finally()
        {
            _bus.Dispose();
        }

        [Then]
        public void Should_have_subscribed()
        {
            _bus.ShouldHaveRemoteSubscriptionFor<PingMessage>();
        }

        [Then]
        public void Should_have_received_the_message()
        {
            ConsumerOf<PingMessage>.AnyShouldHaveReceivedMessage(_ping1, 12.Seconds());
        }

        [Then]
        public void Should_have_received_the_second_message()
        {
            ConsumerOf<PingMessage>.AnyShouldHaveReceivedMessage(_ping2, 12.Seconds());
        }

        ConsumerOf<PingMessage> GetConsumer()
        {
            return new ConsumerOf<PingMessage>();
        }
    }
}


text:
package com.ajjpj.afoundation.concurrent;

import com.ajjpj.afoundation.collection.immutable.ATry;

/**
 * This interface represents an {@link AFuture} with additional API for completing it explicitly, either as a success
 *  or as a failure. These methods are not part of {@link AFuture} intentionally: Most clients being handed a future
 *  should be able to wait for and handle the result, but not provide or modify it. ASettableFuture is
 *  usually not an interface applications want to pass around.

 *
 * This is the equivalent to what is called a 'Promise' in Scala. The more explicit name ASettableFuture was used because
 *  'Future' and 'Promise' are used more or less interchangeably in most contexts, and discussions about the 'right'
 *  way to use them tend to be heated.
 */
public interface ASettableFuture<T> extends AFuture<T> {
    /**
     * This creates an ASettableFuture instance. Once created, it can be passed around as an {@link AFuture} safely, and
     *  be completed concurrently from a different thread.
     */
    static <T> ASettableFuture<T> create () {
        return create (AThreadPool.SYNC_THREADPOOL);
    }

    /**
     * This creates an ASettableFuture instance with a given thread pool as its internal thread pool. Once created, it
     *  can be passed around as an {@link AFuture} safely, and be completed concurrently from a different thread.
     */
    static <T> ASettableFuture<T> create (AThreadPool pool) {
        return new AFutureImpl<> (pool);
    }

    /**
     * This method completes this ASettableFuture. The ASettableFuture can be completed only once, subsequent attempts to
     *  do so will cause an IllegalStateException to be thrown.
     */
    void complete (ATry<T> o);

    /**
     * This method completes this ASettableFuture, return {@code true} if it was previously uncompleted, and {@code false}
     *  otherwise. {@code} true means that the ASettableFuture is now completed using the parameter, while {@code false}
     *  means the parameter was ignored.
     */
    boolean tryComplete (ATry<T> o);

    /**
     * Completes the ASettableFuture as a success with the given value. The ASettableFuture can be completed only once, subsequent attempts to
     *  do so will cause an IllegalStateException to be thrown.
     */
    default void completeAsSuccess (T o) {
        complete (ATry.success (o));
    }

    /**
     * Completes the ASettableFuture as a failure with the given Throwable. The ASettableFuture can be completed only once, subsequent attempts to
     *  do so will cause an IllegalStateException to be thrown.
     */
    default void completeAsFailure (Throwable th) {
        complete (ATry.failure (th));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!--
 -  Copyright 2013 Cloud4SOA, www.cloud4soa.eu
 -
 -  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.
 -->

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ws="http://jax-ws.dev.java.net/spring/core"
    xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
    xmlns:cxf="http://cxf.apache.org/core"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-2.5.xsd
                        http://cxf.apache.org/jaxrs
                        http://cxf.apache.org/schemas/jaxrs.xsd">

    <bean class="eu.cloud4soa.api.datamodel.governance.Credentials" id="cloudbeesCredentials">
        <constructor-arg index="0" value="${cb_public_key}"/>
        <constructor-arg index="1" value="${cb_private_key}"/>
        <constructor-arg index="2" value="${cb_account_name}"/>
    </bean>

    <bean class="eu.cloud4soa.api.datamodel.governance.Credentials" id="cloudfoundryCredentials">
        <constructor-arg index="0" value="${cf_public_key}"/>
        <constructor-arg index="1" value="${cf_private_key}"/>
    </bean>

    <context:property-placeholder location="conf/credentials.properties"/>
</beans>


text:
using System;

namespace Cassandra
{
    /// <summary>
    ///  An unexpected error happened internally. This should never be raise and
    ///  indicates a bug (either in the driver or in Cassandra).
    /// </summary>
    public class DriverInternalError : Exception
    {
        public DriverInternalError(string message)
            : base(message)
        {
        }

        public DriverInternalError(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }
}


text:
"use strict";

exports.__esModule = true;
exports.waitingServices = void 0;

var _services = require("../../services");

const waitingServices = {
  runMutationBatch: _services.runMutationBatch
};
exports.waitingServices = waitingServices;
//# sourceMappingURL=services.js.map


text:
NSComparator kUploadComparator = ^(id a, id b) {
    Assert([a isKindOfClass:[TMBOUpload class]]);
    Assert([b isKindOfClass:[TMBOUpload class]]);
    Assert([[a uploadid] unsignedIntegerValue] != [[b uploadid] unsignedIntegerValue]);
    // Reverse sort: lower indexes are higher uploads
    return [[b uploadid] compare:[a uploadid]];
};

static NNLIFOOperationQueue *thumbnailOperationQueue;

@implementation TMBOUpload

@dynamic badVotes;
@dynamic comments;
@dynamic filename;
@dynamic fileURL;
@dynamic filtered;
@dynamic goodVotes;
@dynamic height;
@dynamic lastActive;
@dynamic nsfw;
@dynamic repostVotes;
@dynamic subscribed;
@dynamic thumbnailData;
@dynamic thumbURL;
@dynamic timestamp;
@dynamic tmbo;
@dynamic tmboVotes;
@dynamic type;
@dynamic uploadid;
@dynamic userid;
@dynamic username;
@dynamic width;

@synthesize thumbnail = _thumbnail;

+ (void)initialize;
{
    thumbnailOperationQueue = [[NNLIFOOperationQueue alloc] init];
}

- (UIImage *)thumbnail;
{
    if (!self.thumbnailData) return nil;

    if (!_thumbnail) {
        _thumbnail = [UIImage imageWithData:self.thumbnailData];
    }
    return _thumbnail;
}

- (void)setThumbnail:(UIImage *)image;
{
    UIImage *smallImage = image;
    _thumbnail = smallImage;
    self.thumbnailData = UIImageJPEGRepresentation(smallImage, 0.8);
}

+ (Class)typeFor:(NSString *)varname;
{
    static NSDictionary *typearray = nil;

    if (!typearray) {
        @synchronized(self) {
            if (!typearray) {
                typearray = @{@"badVotes" : [NSNumber class],
                @"comments" : [NSNumber class],
                @"filename" : [NSString class],
                @"fileURL" : [NSString class],
                @"filtered" : [NSNumber class],
                @"goodVotes" : [NSNumber class],
                @"height" : [NSNumber class],
                @"lastActive" : [NSDate class],
                @"nsfw" : [NSNumber class],
                @"repostVotes" : [NSNumber class],
                @"subscribed" : [NSNumber class],
                @"thumbnailData" : [NSData class],
                @"thumbURL" : [NSString class],
                @"timestamp" : [NSDate class],
                @"tmbo" : [NSNumber class],
                @"tmboVotes" : [NSNumber class],
                @"type" : [NSString class],
                @"uploadid" : [NSNumber class],
                @"userid" : [NSNumber class],
                @"username" : [NSString class],
                @"width" : [NSNumber class]};
            }
        }
    }

    return [typearray objectForKey:varname];
}

- (kTMBOType)kindOfUpload;
{
    if ([self.type isEqualToString:@"image"]) {
        return kTMBOTypeImage;
    } else if ([self.type isEqualToString:@"topic"]) {
        return kTMBOTypeTopic;
    } else if ([self.type isEqualToString:@"avatar"]) {
        return kTMBOTypeAvatar;
    } else if ([self.type isEqualToString:@"audio"]) {
        return kTMBOTypeAudio;
    }
    NotReached();
    return kTMBOTypeAny;
}

- (void)refreshThumbnailWithMinimumSize:(CGSize)thumbsize;
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // TODO: check this!
        // Thumbnail is not good enough. Load another!

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kTMBOBaseURLString, self.thumbURL]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            Assert([responseObject isKindOfClass:[NSData class]]);
            if ([responseObject isKindOfClass:[NSData class]]) {
                UIImage *image = [UIImage imageWithData:responseObject];
                UIImage *thumb = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:thumbsize interpolationQuality:kCGInterpolationHigh];

                if (!thumb) {
                    // TODO: this works, but it sucks.
                    Log(@"Failed to resize thumbnail image! Falling back to using the upload directly.");
                }

                // Causes a KVO notification. If a cell is currently displaying this upload, it will be updated.
                self.thumbnail = thumb ?: image;
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // Causes a KVO notification. If a cell is currently displaying this upload, it will be updated.
            self.thumbnail = nil;
            Log(@"%@ encountered error: %@", operation, error);
        }];

        [thumbnailOperationQueue addOperation:operation forKey:self.thumbURL];
    });
}

- (void)getFileWithSuccess:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success
                   failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure
                  progress:(void ( ^ ) ( NSUInteger bytesRead , long long totalBytesRead , long long totalBytesExpectedToRead ))progress;
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *errorString;
        void(^bail)(void) = ^{
            if (failure)
                failure(nil, [NSError errorWithDomain:@"FIXMEDomain" code:42 userInfo:@{ @"FIXME" : errorString }]);
        };

        errorString = @"Upload type does not have a backing file";
        BailWithBlockUnless([self kindOfUpload] & ~kTMBOTypeTopic, bail);
        errorString = @"Upload does not have a backing file";
        BailWithBlockUnless(self.fileURL, bail);

        NSURLRequest *request = [[TMBOAPIClient sharedClient] requestWithMethod:@"GET" path:self.fileURL parameters:nil];
        Assert(request);

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        [operation setCompletionBlockWithSuccess:success failure:failure];
        [operation setDownloadProgressBlock:progress];

        [operation start];
    });
}

#pragma mark - TMBOObject

- (NSInteger)objectid;
{
    Assert(self.uploadid);
    return [self.uploadid integerValue];
}

@end


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/clk/msm-clk.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include <linux/usb/phy.h>
#include <linux/usb/msm_hsusb.h>

static int ss_phy_override_deemphasis;
module_param(ss_phy_override_deemphasis, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(ss_phy_override_deemphasis, "Override SSPHY demphasis value");

/* QSCRATCH SSPHY control registers */
#define SS_PHY_CTRL_REG			0x30
#define SS_PHY_PARAM_CTRL_1		0x34
#define SS_PHY_PARAM_CTRL_2		0x38
#define SS_CR_PROTOCOL_DATA_IN_REG	0x3C
#define SS_CR_PROTOCOL_DATA_OUT_REG	0x40
#define SS_CR_PROTOCOL_CAP_ADDR_REG	0x44
#define SS_CR_PROTOCOL_CAP_DATA_REG	0x48
#define SS_CR_PROTOCOL_READ_REG		0x4C
#define SS_CR_PROTOCOL_WRITE_REG	0x50

/* SS_PHY_CTRL_REG bits */
#define SS_PHY_RESET			BIT(7)
#define REF_SS_PHY_EN			BIT(8)
#define LANE0_PWR_PRESENT		BIT(24)
#define TEST_POWERDOWN			BIT(26)
#define REF_USE_PAD			BIT(28)

#define USB_SSPHY_1P8_VOL_MIN		1800000 /* uV */
#define USB_SSPHY_1P8_VOL_MAX		1800000 /* uV */
#define USB_SSPHY_1P8_HPM_LOAD		23000	/* uA */

struct msm_ssphy {
	struct usb_phy		phy;
	void __iomem		*base;
	struct clk		*core_clk;	/* USB3 master clock */
	struct clk		*com_reset_clk;	/* PHY common block reset */
	struct clk		*reset_clk;	/* SS PHY reset */
	struct regulator	*vdd;
	struct regulator	*vdda18;
	atomic_t		active_count;	/* num of active instances */
	bool			suspended;
	int			vdd_levels[3]; /* none, low, high */
	int			deemphasis_val;
};

static int msm_ssusb_config_vdd(struct msm_ssphy *phy, int high)
{
	int min, ret;

	min = high ? 1 : 0; /* low or none? */
	ret = regulator_set_voltage(phy->vdd, phy->vdd_levels[min],
				    phy->vdd_levels[2]);
	if (ret) {
		dev_err(phy->phy.dev, "unable to set voltage for ssusb vdd\n");
		return ret;
	}

	dev_dbg(phy->phy.dev, "%s: min_vol:%d max_vol:%d\n", __func__,
		phy->vdd_levels[min], phy->vdd_levels[2]);
	return ret;
}

static int msm_ssusb_ldo_enable(struct msm_ssphy *phy, int on)
{
	int rc = 0;

	dev_dbg(phy->phy.dev, "reg (%s)\n", on ? "HPM" : "LPM");

	if (!on)
		goto disable_regulators;

	rc = regulator_set_optimum_mode(phy->vdda18, USB_SSPHY_1P8_HPM_LOAD);
	if (rc < 0) {
		dev_err(phy->phy.dev, "Unable to set HPM of vdda18\n");
		return rc;
	}

	rc = regulator_set_voltage(phy->vdda18, USB_SSPHY_1P8_VOL_MIN,
						USB_SSPHY_1P8_VOL_MAX);
	if (rc) {
		dev_err(phy->phy.dev, "unable to set voltage for vdda18\n");
		goto put_vdda18_lpm;
	}

	rc = regulator_enable(phy->vdda18);
	if (rc) {
		dev_err(phy->phy.dev, "Unable to enable vdda18\n");
		goto unset_vdda18;
	}

	return 0;

disable_regulators:
	rc = regulator_disable(phy->vdda18);
	if (rc)
		dev_err(phy->phy.dev, "Unable to disable vdda18\n");

unset_vdda18:
	rc = regulator_set_voltage(phy->vdda18, 0, USB_SSPHY_1P8_VOL_MAX);
	if (rc)
		dev_err(phy->phy.dev, "unable to set voltage for vdda18\n");

put_vdda18_lpm:
	rc = regulator_set_optimum_mode(phy->vdda18, 0);
	if (rc < 0)
		dev_err(phy->phy.dev, "Unable to set LPM of vdda18\n");

	return rc < 0 ? rc : 0;
}

static void msm_usb_write_readback(void *base, u32 offset,
					const u32 mask, u32 val)
{
	u32 write_val, tmp = readl_relaxed(base + offset);

	tmp &= ~mask;		/* retain other bits */
	write_val = tmp | val;

	writel_relaxed(write_val, base + offset);

	/* Read back to see if val was written */
	tmp = readl_relaxed(base + offset);
	tmp &= mask;		/* clear other bits */

	if (tmp != val)
		pr_err("%s: write: %x to QSCRATCH: %x FAILED\n",
			__func__, val, offset);
}

/**
 * Write SSPHY register with debug info.
 *
 * @base - base virtual address.
 * @addr - SSPHY address to write.
 * @val - value to write.
 *
 */
static void msm_ssusb_write_phycreg(void *base, u32 addr, u32 val)
{
	writel_relaxed(addr, base + SS_CR_PROTOCOL_DATA_IN_REG);
	writel_relaxed(0x1, base + SS_CR_PROTOCOL_CAP_ADDR_REG);
	while (readl_relaxed(base + SS_CR_PROTOCOL_CAP_ADDR_REG))
		cpu_relax();

	writel_relaxed(val, base + SS_CR_PROTOCOL_DATA_IN_REG);
	writel_relaxed(0x1, base + SS_CR_PROTOCOL_CAP_DATA_REG);
	while (readl_relaxed(base + SS_CR_PROTOCOL_CAP_DATA_REG))
		cpu_relax();

	writel_relaxed(0x1, base + SS_CR_PROTOCOL_WRITE_REG);
	while (readl_relaxed(base + SS_CR_PROTOCOL_WRITE_REG))
		cpu_relax();
}

/**
 * Read SSPHY register with debug info.
 *
 * @base - base virtual address.
 * @addr - SSPHY address to read.
 *
 */
static u32 msm_ssusb_read_phycreg(void *base, u32 addr)
{
	bool first_read = true;

	writel_relaxed(addr, base + SS_CR_PROTOCOL_DATA_IN_REG);
	writel_relaxed(0x1, base + SS_CR_PROTOCOL_CAP_ADDR_REG);
	while (readl_relaxed(base + SS_CR_PROTOCOL_CAP_ADDR_REG))
		cpu_relax();

	/*
	 * Due to hardware bug, first read of SSPHY register might be
	 * incorrect. Hence as workaround, SW should perform SSPHY register
	 * read twice, but use only second read and ignore first read.
	 */
retry:
	writel_relaxed(0x1, base + SS_CR_PROTOCOL_READ_REG);
	while (readl_relaxed(base + SS_CR_PROTOCOL_READ_REG))
		cpu_relax();

	if (first_read) {
		readl_relaxed(base + SS_CR_PROTOCOL_DATA_OUT_REG);
		first_read = false;
		goto retry;
	}

	return readl_relaxed(base + SS_CR_PROTOCOL_DATA_OUT_REG);
}

/* SSPHY Initialization */
static int msm_ssphy_init(struct usb_phy *uphy)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);
	u32 val;

	/* Ensure clock is on before accessing QSCRATCH registers */
	clk_prepare_enable(phy->core_clk);

	/* read initial value */
	val = readl_relaxed(phy->base + SS_PHY_CTRL_REG);

	/* Use clk reset, if available; otherwise use SS_PHY_RESET bit */
	if (phy->com_reset_clk) {
		clk_reset(phy->com_reset_clk, CLK_RESET_ASSERT);
		clk_reset(phy->reset_clk, CLK_RESET_ASSERT);
		udelay(10); /* 10us required before de-asserting */
		clk_reset(phy->com_reset_clk, CLK_RESET_DEASSERT);
		clk_reset(phy->reset_clk, CLK_RESET_DEASSERT);
	} else {
		writel_relaxed(val | SS_PHY_RESET, phy->base + SS_PHY_CTRL_REG);
		udelay(10); /* 10us required before de-asserting */
		writel_relaxed(val, phy->base + SS_PHY_CTRL_REG);
	}

	/* Use ref_clk from pads and set its parameters */
	val |= REF_USE_PAD;
	writel_relaxed(val, phy->base + SS_PHY_CTRL_REG);
	msleep(30);

	/* Ref clock must be stable now, enable ref clock for HS mode */
	val |= LANE0_PWR_PRESENT | REF_SS_PHY_EN;
	writel_relaxed(val, phy->base + SS_PHY_CTRL_REG);
	usleep_range(2000, 2200);

	clk_disable_unprepare(phy->core_clk);

	return 0;
}

static int msm_ssphy_set_params(struct usb_phy *uphy)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);
	u32 data = 0;

	/*
	 * WORKAROUND: There is SSPHY suspend bug due to which USB enumerates
	 * in HS mode instead of SS mode. Workaround it by asserting
	 * LANE0.TX_ALT_BLOCK.EN_ALT_BUS to enable TX to use alt bus mode
	 */
	data = msm_ssusb_read_phycreg(phy->base, 0x102D);
	data |= (1 << 7);
	msm_ssusb_write_phycreg(phy->base, 0x102D, data);

	data = msm_ssusb_read_phycreg(phy->base, 0x1010);
	data &= ~0xFF0;
	data |= 0x20;
	msm_ssusb_write_phycreg(phy->base, 0x1010, data);

	/*
	 * Fix RX Equalization setting as follows
	 * LANE0.RX_OVRD_IN_HI. RX_EQ_EN set to 0
	 * LANE0.RX_OVRD_IN_HI.RX_EQ_EN_OVRD set to 1
	 * LANE0.RX_OVRD_IN_HI.RX_EQ set to 3
	 * LANE0.RX_OVRD_IN_HI.RX_EQ_OVRD set to 1
	 */
	data = msm_ssusb_read_phycreg(phy->base, 0x1006);
	data &= ~(1 << 6);
	data |= (1 << 7);
	data &= ~(0x7 << 8);
	data |= (0x3 << 8);
	data |= (0x1 << 11);
	msm_ssusb_write_phycreg(phy->base, 0x1006, data);

	/*
	 * Set EQ and TX launch amplitudes as follows
	 * LANE0.TX_OVRD_DRV_LO.PREEMPH set to 22
	 * LANE0.TX_OVRD_DRV_LO.AMPLITUDE set to 127
	 * LANE0.TX_OVRD_DRV_LO.EN set to 1.
	 */
	data = msm_ssusb_read_phycreg(phy->base, 0x1002);
	data &= ~0x3F80;
	if (ss_phy_override_deemphasis)
		phy->deemphasis_val = ss_phy_override_deemphasis;
	if (phy->deemphasis_val)
		data |= (phy->deemphasis_val << 7);
	else
		data |= (0x16 << 7);
	data &= ~0x7F;
	data |= (0x7F | (1 << 14));
	msm_ssusb_write_phycreg(phy->base, 0x1002, data);

	/*
	 * Set the QSCRATCH SS_PHY_PARAM_CTRL1 parameters as follows
	 * TX_FULL_SWING [26:20] amplitude to 127
	 * TX_DEEMPH_3_5DB [13:8] to 22
	 * LOS_BIAS [2:0] to 0x5
	 */
	msm_usb_write_readback(phy->base, SS_PHY_PARAM_CTRL_1,
				0x07f03f07, 0x07f01605);

	return 0;
}

static int msm_ssphy_post_init(struct usb_phy *uphy)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);
	u32 val;

	/* read initial value */
	val = readl_relaxed(phy->base + SS_PHY_CTRL_REG);
	val &= ~LANE0_PWR_PRESENT;
	writel_relaxed(val, phy->base + SS_PHY_CTRL_REG);

	return 0;
}

static int msm_ssphy_set_suspend(struct usb_phy *uphy, int suspend)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);
	void __iomem *base = phy->base;
	int count;

	/* Ensure clock is on before accessing QSCRATCH registers */
	clk_prepare_enable(phy->core_clk);

	if (suspend) {
		count = atomic_dec_return(&phy->active_count);
		if (count > 0 || phy->suspended) {
			dev_dbg(uphy->dev, "Skipping suspend, active_count=%d phy->suspended=%d\n",
					count, phy->suspended);
			goto done;
		}

		if (count < 0) {
			dev_WARN(uphy->dev, "Suspended too many times!  active_count=%d\n",
					count);
			atomic_set(&phy->active_count, 0);
		}

		/* Clear REF_SS_PHY_EN */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, REF_SS_PHY_EN, 0);
		/* Clear REF_USE_PAD */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, REF_USE_PAD, 0);
		/* Set TEST_POWERDOWN (enables PHY retention) */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, TEST_POWERDOWN,
								TEST_POWERDOWN);
		if (phy->com_reset_clk &&
			!(phy->phy.flags & ENABLE_SECONDARY_PHY)) {
			/* leave these asserted until resuming */
			clk_reset(phy->com_reset_clk, CLK_RESET_ASSERT);
			clk_reset(phy->reset_clk, CLK_RESET_ASSERT);
		}

		msm_ssusb_ldo_enable(phy, 0);
		msm_ssusb_config_vdd(phy, 0);
		phy->suspended = true;
	} else {
		count = atomic_inc_return(&phy->active_count);
		if (count > 1 || !phy->suspended) {
			dev_dbg(uphy->dev, "Skipping resume, active_count=%d phy->suspended=%d\n",
					count, phy->suspended);
			goto done;
		}

		phy->suspended = false;
		msm_ssusb_config_vdd(phy, 1);
		msm_ssusb_ldo_enable(phy, 1);

		if (phy->phy.flags & ENABLE_SECONDARY_PHY) {
			dev_err(uphy->dev, "secondary PHY, skipping reset\n");
			goto done;
		}

		if (phy->com_reset_clk) {
			clk_reset(phy->com_reset_clk, CLK_RESET_DEASSERT);
			clk_reset(phy->reset_clk, CLK_RESET_DEASSERT);
		} else {
			/* Assert SS PHY RESET */
			msm_usb_write_readback(base, SS_PHY_CTRL_REG,
						SS_PHY_RESET, SS_PHY_RESET);
		}

		/* Set REF_USE_PAD */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, REF_USE_PAD,
								REF_USE_PAD);
		/* Set REF_SS_PHY_EN */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, REF_SS_PHY_EN,
								REF_SS_PHY_EN);
		/* Clear TEST_POWERDOWN */
		msm_usb_write_readback(base, SS_PHY_CTRL_REG, TEST_POWERDOWN,
								0);
		if (!phy->com_reset_clk) {
			udelay(10); /* 10us required before de-asserting */
			msm_usb_write_readback(base, SS_PHY_CTRL_REG,
						SS_PHY_RESET, 0);
		}

		/*
		 * Reinitialize SSPHY parameters as SS_PHY RESET will reset
		 * the internal registers to default values.
		 */
		msm_ssphy_set_params(uphy);
	}

done:
	clk_disable_unprepare(phy->core_clk);
	return 0;
}

static int msm_ssphy_notify_connect(struct usb_phy *uphy,
				       enum usb_device_speed speed)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);

	if (uphy->flags & PHY_HOST_MODE)
		return 0;

	if (uphy->flags & PHY_VBUS_VALID_OVERRIDE)
		/* Indicate power present to SS phy */
		msm_usb_write_readback(phy->base, SS_PHY_CTRL_REG,
					LANE0_PWR_PRESENT, LANE0_PWR_PRESENT);

	return 0;
}

static int msm_ssphy_notify_disconnect(struct usb_phy *uphy,
				       enum usb_device_speed speed)
{
	struct msm_ssphy *phy = container_of(uphy, struct msm_ssphy, phy);

	if (uphy->flags & PHY_HOST_MODE)
		return 0;

	if (uphy->flags & PHY_VBUS_VALID_OVERRIDE)
		/* Clear power indication to SS phy */
		msm_usb_write_readback(phy->base, SS_PHY_CTRL_REG,
					LANE0_PWR_PRESENT, 0);

	return 0;
}

static int msm_ssphy_probe(struct platform_device *pdev)
{
	struct msm_ssphy *phy;
	struct device *dev = &pdev->dev;
	struct resource *res;
	int ret = 0;

	phy = devm_kzalloc(dev, sizeof(*phy), GFP_KERNEL);
	if (!phy)
		return -ENOMEM;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		dev_err(dev, "missing memory base resource\n");
		return -ENODEV;
	}

	phy->base = devm_ioremap_nocache(dev, res->start, resource_size(res));
	if (!phy->base) {
		dev_err(dev, "ioremap failed\n");
		return -ENODEV;
	}

	phy->core_clk = devm_clk_get(dev, "core_clk");
	if (IS_ERR(phy->core_clk)) {
		dev_err(dev, "unable to get core_clk\n");
		return PTR_ERR(phy->core_clk);
	}

	phy->com_reset_clk = devm_clk_get(dev, "com_reset_clk");
	if (IS_ERR(phy->com_reset_clk)) {
		dev_dbg(dev, "com_reset_clk unavailable\n");
		phy->com_reset_clk = NULL;
	}

	phy->reset_clk = devm_clk_get(dev, "reset_clk");
	if (IS_ERR(phy->reset_clk)) {
		dev_dbg(dev, "reset_clk unavailable\n");
		phy->reset_clk = NULL;
	}

	if (of_get_property(dev->of_node, "qcom,primary-phy", NULL)) {
		dev_dbg(dev, "secondary HSPHY\n");
		phy->phy.flags |= ENABLE_SECONDARY_PHY;
	}

	ret = of_property_read_u32_array(dev->of_node, "qcom,vdd-voltage-level",
					 (u32 *) phy->vdd_levels,
					 ARRAY_SIZE(phy->vdd_levels));
	if (ret) {
		dev_err(dev, "error reading qcom,vdd-voltage-level property\n");
		return ret;
	}

	phy->phy.dev = dev;
	phy->vdd = devm_regulator_get(dev, "vdd");
	if (IS_ERR(phy->vdd)) {
		dev_err(dev, "unable to get vdd supply\n");
		return PTR_ERR(phy->vdd);
	}

	phy->vdda18 = devm_regulator_get(dev, "vdda18");
	if (IS_ERR(phy->vdda18)) {
		dev_err(dev, "unable to get vdda18 supply\n");
		return PTR_ERR(phy->vdda18);
	}

	ret = msm_ssusb_config_vdd(phy, 1);
	if (ret) {
		dev_err(dev, "ssusb vdd_dig configuration failed\n");
		return ret;
	}

	ret = regulator_enable(phy->vdd);
	if (ret) {
		dev_err(dev, "unable to enable the ssusb vdd_dig\n");
		goto unconfig_ss_vdd;
	}

	ret = msm_ssusb_ldo_enable(phy, 1);
	if (ret) {
		dev_err(dev, "ssusb vreg enable failed\n");
		goto disable_ss_vdd;
	}

	platform_set_drvdata(pdev, phy);

	if (of_property_read_bool(dev->of_node, "qcom,vbus-valid-override"))
		phy->phy.flags |= PHY_VBUS_VALID_OVERRIDE;

	if (of_property_read_u32(dev->of_node, "qcom,deemphasis-value",
						&phy->deemphasis_val))
		dev_dbg(dev, "unable to read ssphy deemphasis value\n");

	phy->phy.init			= msm_ssphy_init;
	phy->phy.set_suspend		= msm_ssphy_set_suspend;
	phy->phy.set_params		= msm_ssphy_set_params;
	phy->phy.post_init		= msm_ssphy_post_init;
	phy->phy.notify_connect		= msm_ssphy_notify_connect;
	phy->phy.notify_disconnect	= msm_ssphy_notify_disconnect;
	phy->phy.type			= USB_PHY_TYPE_USB3;

	ret = usb_add_phy_dev(&phy->phy);
	if (ret)
		goto disable_ss_ldo;

	return 0;

disable_ss_ldo:
	msm_ssusb_ldo_enable(phy, 0);
disable_ss_vdd:
	regulator_disable(phy->vdd);
unconfig_ss_vdd:
	msm_ssusb_config_vdd(phy, 0);

	return ret;
}

static int msm_ssphy_remove(struct platform_device *pdev)
{
	struct msm_ssphy *phy = platform_get_drvdata(pdev);

	if (!phy)
		return 0;

	usb_remove_phy(&phy->phy);
	msm_ssusb_ldo_enable(phy, 0);
	regulator_disable(phy->vdd);
	msm_ssusb_config_vdd(phy, 0);
	kfree(phy);

	return 0;
}

static const struct of_device_id msm_usb_id_table[] = {
	{
		.compatible = "qcom,usb-ssphy",
	},
	{ },
};
MODULE_DEVICE_TABLE(of, msm_usb_id_table);

static struct platform_driver msm_ssphy_driver = {
	.probe		= msm_ssphy_probe,
	.remove		= msm_ssphy_remove,
	.driver = {
		.name	= "msm-usb-ssphy",
		.of_match_table = of_match_ptr(msm_usb_id_table),
	},
};

module_platform_driver(msm_ssphy_driver);

MODULE_DESCRIPTION("MSM USB SS PHY driver");
MODULE_LICENSE("GPL v2");


text:
/********************************************************************
	Filename:	ColumnTypesVarchar255.sql
	Author:		Omid Afzalalghom
	Date:		09/09/15
	Comments:	Finds tables that have more than one column
				defined as varchar(255).
	Revisions:
********************************************************************/

SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SELECT
	 OBJECT_SCHEMA_NAME(object_id) AS 'Schema_Name'
	,OBJECT_NAME(object_id) 'Table_Name'
	,COUNT(*) Num_Cols
FROM sys.columns
WHERE OBJECTPROPERTY(object_id, 'IsUserTable') = 1
GROUP BY object_id
HAVING SUM(system_type_id) % 167 = 0
	AND SUM(max_length) % 255 = 0
	AND COUNT(*) > 1
ORDER BY 'Schema_Name', 'Table_Name';


text:
package org.apach3.http.nio;

import org.apach3.http.nio.reactor.IOSession;

/**
 * Factory for {@link NHttpConnection} instances.
 *
 * @since 4.2
 */
public interface NHttpConnectionFactory<T extends NHttpConnection> {

    T createConnection(IOSession session);

}


text:
package org.apache.jackrabbit.test.api.nodetype;

import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.jackrabbit.test.NotExecutableException;

import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.Session;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

/**
 * Test of NodeType.canSetProperty(String propertyName, Value[]
 * values)
 *
 * @test
 * @sources CanSetPropertyMultipleTest.java
 * @executeClass org.apache.jackrabbit.test.api.nodetype.CanSetPropertyMultipleTest
 * @keywords level2
 */
public class CanSetPropertyMultipleTest extends AbstractJCRTest {
    /**
     * The session we use for the tests
     */
    private Session session;

    /**
     * Sets up the fixture for the test cases.
     */
    protected void setUp() throws Exception {
        isReadOnly = true;
        super.setUp();

        session = getHelper().getReadOnlySession();
    }

    /**
     * Releases the session aquired in {@link #setUp()}.
     */
    protected void tearDown() throws Exception {
        if (session != null) {
            session.logout();
            session = null;
        }
        super.tearDown();
    }

    /**
     * Tests if NodeType.canSetProperty(String propertyName, Value[] values)
     * returns false if the property is protected.
     */
    public void testReturnFalseBecauseIsProtected()
            throws NotExecutableException, RepositoryException {

        PropertyDefinition propDef =
                NodeTypeUtil.locatePropertyDef(session, NodeTypeUtil.ANY_PROPERTY_TYPE, true, true, false, false);

        // will never happen since at least jcr:mixinTypes of nt:base accomplish the request
        if (propDef == null) {
            throw new NotExecutableException("No protected, multiple property def found");
        }

        NodeType nodeType = propDef.getDeclaringNodeType();
        Value value = NodeTypeUtil.getValueOfType(superuser, propDef.getRequiredType());
        Value values[] = new Value[] {value, value};

        assertFalse("canSetProperty(String propertyName, Value[] values) must " +
                "return true if the property is protected.",
                nodeType.canSetProperty(propDef.getName(), values));
    }

    /**
     * Tests if NodeType.canSetProperty(String propertyName, Value[] values)
     * returns false if the property is not multiple
     */
    public void testReturnFalseBecauseIsNotMultiple()
            throws NotExecutableException, RepositoryException {

        PropertyDefinition propDef =
                NodeTypeUtil.locatePropertyDef(session, NodeTypeUtil.ANY_PROPERTY_TYPE, false, false, false, false);

        if (propDef == null) {
            throw new NotExecutableException("No not multiple, not protected property def found");
        }

        NodeType nodeType = propDef.getDeclaringNodeType();
        Value value = NodeTypeUtil.getValueOfType(superuser, propDef.getRequiredType());
        Value values[] = new Value[] {value};

        assertFalse("canSetProperty(String propertyName, Value[] values) must " +
                "return false if the property is not multiple",
                nodeType.canSetProperty(propDef.getName(), values));
    }

    /**
     * Tests if canSetProperty(String propertyName, Value[] values) where values
     * is null returns the same as canRemoveItem
     */
    public void testMultipleValuesNull()
            throws NotExecutableException, RepositoryException {

        PropertyDefinition propDef =
                NodeTypeUtil.locatePropertyDef(session, NodeTypeUtil.ANY_PROPERTY_TYPE, true, false, false, false);

        if (propDef == null) {
            throw new NotExecutableException("No not protected, multiple property def found");
        }

        NodeType nodeType = propDef.getDeclaringNodeType();

        assertEquals("nodeType.canSetProperty(String propertyName, Value[] values) " +
                "where values is null must return the same result as " +
                "nodeType.canRemoveItem(String propertyName)",
                nodeType.canRemoveItem(propDef.getName()),
                nodeType.canSetProperty(propDef.getName(), (Value[]) null));
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Bootstrap Examples</title>
    <link rel="stylesheet" href="../css/bootstrap.css">
    <link rel="stylesheet" href="../css/bootstrap-theme.css">

Standard Table with Context

Country	Capital City

United Kingdom	London

France	Paris

Spain	Madrid

Striped, Bordered and Highlighted Table

Country	Capital City

United Kingdom	London

France	Paris

Spain	Madrid


text:
package protocol

import (
	"fmt"
	"github.com/pkg/errors"
)

func ValidateUserAgent(useAgent string) error {
	if len(useAgent) > MaxUserAgentLen {
		str := fmt.Sprintf("userAgent len : %v,max : %v", len(useAgent), MaxUserAgentLen)
		return errors.New(str)

	}
	return nil

}


text:
package com.cowthan.concurrent.c11;

import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueTest {

	public interface Queue<E> extends Collection<E> {
	    boolean add(E e);
	    boolean offer(E e);

	    /**
	     * 移除并返回,空则抛异常
	     */
	    E remove();

	    /**
	     * 移除并返回,空则返回null
	     */
	    E poll();

	    /**
	     * 返回,不移除
	     */
	    E element();

	    /**
	     * 返回,并移除,空则返回null
	     */
	    E peek();
	}

	public interface BlockingQueue<E> extends Queue<E> {

		/**
		 * 添加,如果没有空间,会阻塞等待
		 * @param e
		 * @throws InterruptedException
		 */
		void put(E e) throws InterruptedException;

		/**
	     * 移除并返回,如果empty,则阻塞等待
	     */
	    E take() throws InterruptedException;

	    /**
	     * 移除并返回,如果empty,会等待指定时间
	     * @param timeout
	     * @param unit
	     * @return
	     */
	    E poll(long timeout, TimeUnit unit);

	    /**
	     * Returns the number of additional elements that this queue can ideally
	     * (in the absence of memory or resource constraints) accept without
	     * blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic
	     * limit.
	     *
	     *
Note that you cannot always tell if an attempt to insert
	     * an element will succeed by inspecting {@code remainingCapacity}
	     * because it may be the case that another thread is about to
	     * insert or remove an element.
	     *
	     * @return the remaining capacity
	     */
	    int remainingCapacity();

	    public boolean contains(Object o);

	    /**
	     * 把队列里的元素都移到Collection里
	     * @param c
	     * @return
	     */
	    int drainTo(Collection<? super E> c);
	    int drainTo(Collection<? super E> c, int maxElements);

	}

	public static class Message implements Delayed{

		@Override
		public int compareTo(Delayed o) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public long getDelay(TimeUnit unit) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

	public static void main(String[] args) {
		//java.util.concurrent.BlockingQueue<Message> queue =
				//new ArrayBlockingQueue<BlockingQueueTest.Message>(10, true); //true是access policy,表示FIFO,先进先出
				//new LinkedBlockingDeque<BlockingQueueTest.Message>(10);
				//new DelayQueue<BlockingQueueTest.Message>();
				//new PriorityBlockingQueue<BlockingQueueTest.Message>();
				//new SynchronousQueue<BlockingQueueTest.Message>(true);
				//new LinkedTransferQueue<BlockingQueueTest.Message>();

	}

}


text:
package com.gregacucnik;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by Grega on 23/11/15.
 */
public class ETT_EditText extends EditText {

    private OnEditTextListener mListener;

    public interface OnEditTextListener{
        void onEditTextKeyboardDismissed();
        void onEditTextKeyboardDone();
    }

    public ETT_EditText(Context context) {
        super(context);

        init();
    }

    public ETT_EditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public ETT_EditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init(){
        setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    if(mListener != null)
                        mListener.onEditTextKeyboardDone();

                    return true;
                }
                return false;
            }
        });
    }

    public void setOnKeyboardDismissedListener(OnEditTextListener listener){
        this.mListener = listener;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {

            if(mListener != null)
                mListener.onEditTextKeyboardDismissed();

            return false;
        }

        return super.dispatchKeyEvent(event);
    }

}


text:
        <link href="style.css" rel="stylesheet" />

        2nd-level illusion

        Casting Time:  1 action

        Range:  Touch

        Components:  V, S, M (an eyelash encased in gum arabic)

        Duration:  Concentration, up to 1 hour

            A creature you touch becomes invisible until the spell
            ends. Anything the target is w earing or carrying is
            invisible as long as it is on the target's person. The spell
            ends for a target that attacks or casts a spell.

            At Higher Levels. When you cast this spell using
            a spell slot of 3rd level or higher, you can target one
            additional creature for each slot level above 2nd.


text:
@implementation ProjectTemlatePlistGenerator

+ (BOOL)generatorToPath:(NSString *)path {
    ProjectTemlatePlistGenerator *generator = [ProjectTemlatePlistGenerator new];
    NSDictionary *dict = [generator createInfoPlist];
    BOOL flag = [dict writeToFile:path atomically:YES];
    NSLog(@"flag %@", @(flag));
    return flag;
}

- (NSMutableDictionary *)createInfoPlist {
    NSMutableDictionary *plist = [NSMutableDictionary dictionary];
    [plist setObject:[self createAncestors] forKey:@"Ancestors"];
    [plist setObject:[self createNodes] forKey:@"Nodes"];
    [plist setObject:[self createDefinitions] forKey:@"Definitions"];
    //YES的模板才可以显示在new project的dialog中,此时这个模板不能被其他模板继承。
    [plist setObject:@(YES) forKey:@"Concrete"];
    //显示在new project的dialog中的位置索引
    [plist setObject:@(99) forKey:@"SortOrder"];
    //Kind:项目模板为Xcode.Xcode3.ProjectTemplateUnitKind,文件模板为Xcode.IDEKit.TextSubstitutionFileTemplateKind。
    [plist setObject:@"Xcode.Xcode3.ProjectTemplateUnitKind" forKey:@"Kind"];
    //模版描述
    [plist setObject:@"Toraysoft iOS Project Template 1.0" forKey:@"Description"];
    //模版唯一标示
    [plist setObject:@"com.apple.dt.unit.TorayApplication" forKey:@"Identifier"];
    //选项
    [plist setObject:[self createOptions] forKey:@"Options"];
    return plist;
}

//继承的模版
- (NSArray *)createAncestors {
    NSMutableArray *ancestors = [NSMutableArray array];
    [ancestors addObject:@"com.apple.dt.unit.coreDataCocoaTouchApplication"];
    [ancestors addObject:@"com.apple.dt.unit.storyboardApplication"];
    return ancestors;
}

//定义要添加到项目中的文件
- (NSArray *)createNodes {
    NSMutableArray *nodes = [NSMutableArray array];
    //Application
    [nodes addObject:kAppDelegateH];
    [nodes addObject:kAppDelegateM];
    [nodes addObject:kAppConfigH];
    [nodes addObject:kAppConstantsH];
    [nodes addObject:kAppMarcosH];
    [nodes addObject:kAppNotificationH];
    //Categories
    [nodes addObject:kMBProgressHUDAdditionsH];
    [nodes addObject:kMBProgressHUDAdditionsM];
    [nodes addObject:kJsonSerializationH];
    [nodes addObject:kJsonSerializationM];
    [nodes addObject:kUIButtonAdditionsH];
    [nodes addObject:kUIButtonAdditionsM];
    [nodes addObject:kUILabelAdditionsH];
    [nodes addObject:kUILabelAdditionsM];
    //Utils
    [nodes addObject:kGestureHelperH];
    [nodes addObject:kGestureHelperM];
    //CellObjects
    [nodes addObject:kCellObjects];
    //Cells
    [nodes addObject:kBaseTableViewCellH];
    [nodes addObject:kBaseTableViewCellM];
    [nodes addObject:kBaseCollectionViewCellH];
    [nodes addObject:kBaseCollectionViewCellM];
    //Components
    //    [nodes addObject:kComponents];
    [nodes addObject:kAPNSAgentH];
    [nodes addObject:kAPNSAgentM];
    [nodes addObject:kAPNSAgentInternalH];
    [nodes addObject:kAPNSAgentInternalM];
    //Controllers
    [nodes addObject:kBaseViewControllerH];
    [nodes addObject:kBaseViewControllerM];
    [nodes addObject:kTSNavigationControllerH];
    [nodes addObject:kTSNavigationControllerM];
    //Engines
    [nodes addObject:kDataEngineH];
    [nodes addObject:kDataEngineM];
    //Images
    [nodes addObject:kImages];
    //Managers
    [nodes addObject:kAuthenticationManagerH];
    [nodes addObject:kAuthenticationManagerM];
    //Models
    [nodes addObject:kBaseModelH];
    [nodes addObject:kBaseModelM];
    //SDK
    [nodes addObject:kSDK];
    //Views
    [nodes addObject:kMaskViewH];
    [nodes addObject:kMaskViewM];
    //PrefixHeader
    [nodes addObject:kPrefixHeader];
    //Podfile
    [nodes addObject:kPodfile];
    return nodes;
}

//将Nodes中定义的文件添加到项目中
- (NSDictionary *)createDefinitions {
    NSMutableDictionary *definitions = [NSMutableDictionary dictionary];

    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppDelegateH] forKey:kAppDelegateH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppDelegateM] forKey:kAppDelegateM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppConfigH] forKey:kAppConfigH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppConstantsH] forKey:kAppConstantsH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppMarcosH] forKey:kAppMarcosH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Application" path:kAppNotificationH] forKey:kAppNotificationH];

    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kMBProgressHUDAdditionsH] forKey:kMBProgressHUDAdditionsH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kMBProgressHUDAdditionsM] forKey:kMBProgressHUDAdditionsM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kJsonSerializationH] forKey:kJsonSerializationH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kJsonSerializationM] forKey:kJsonSerializationM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kUIButtonAdditionsH] forKey:kUIButtonAdditionsH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kUIButtonAdditionsM] forKey:kUIButtonAdditionsM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kUILabelAdditionsH] forKey:kUILabelAdditionsH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Categories" path:kUILabelAdditionsM] forKey:kUILabelAdditionsM];

    [definitions setObject:[self groupDefinitionWithGroup:@"Utils" path:kGestureHelperH] forKey:kGestureHelperH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Utils" path:kGestureHelperM] forKey:kGestureHelperM];

    [definitions setObject:[self groupDefinitionWithGroup:nil path:kCellObjects] forKey:kCellObjects];

    [definitions setObject:[self groupDefinitionWithGroup:@"Cells/TableViewCell" path:kBaseTableViewCellH] forKey:kBaseTableViewCellH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Cells/TableViewCell" path:kBaseTableViewCellM] forKey:kBaseTableViewCellM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Cells/CollectionViewCell" path:kBaseCollectionViewCellH] forKey:kBaseCollectionViewCellH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Cells/CollectionViewCell" path:kBaseCollectionViewCellM] forKey:kBaseCollectionViewCellM];

    //    [definitions setObject:[self groupDefinitionWithGroup:nil path:kComponents] forKey:kComponents];
    [definitions setObject:[self groupDefinitionWithGroup:@"Components/APNSAgent" path:kAPNSAgentH] forKey:kAPNSAgentH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Components/APNSAgent" path:kAPNSAgentM] forKey:kAPNSAgentM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Components/APNSAgent" path:kAPNSAgentInternalH] forKey:kAPNSAgentInternalH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Components/APNSAgent" path:kAPNSAgentInternalM] forKey:kAPNSAgentInternalM];

    [definitions setObject:[self groupDefinitionWithGroup:@"Controllers" path:kBaseViewControllerH] forKey:kBaseViewControllerH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Controllers" path:kBaseViewControllerM] forKey:kBaseViewControllerM];
    [definitions setObject:[self groupDefinitionWithGroup:@"Controllers" path:kTSNavigationControllerH] forKey:kTSNavigationControllerH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Controllers" path:kTSNavigationControllerM] forKey:kTSNavigationControllerM];

    [definitions setObject:[self groupDefinitionWithGroup:@"Engines" path:kDataEngineH] forKey:kDataEngineH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Engines" path:kDataEngineM] forKey:kDataEngineM];

    [definitions setObject:[self groupDefinitionWithGroup:nil path:kImages] forKey:kImages];

    [definitions setObject:[self groupDefinitionWithGroup:@"Managers" path:kAuthenticationManagerH] forKey:kAuthenticationManagerH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Managers" path:kAuthenticationManagerM] forKey:kAuthenticationManagerM];

    [definitions setObject:[self groupDefinitionWithGroup:@"Models" path:kBaseModelH] forKey:kBaseModelH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Models" path:kBaseModelM] forKey:kBaseModelM];

    [definitions setObject:[self groupDefinitionWithGroup:nil path:kSDK] forKey:kSDK];

    [definitions setObject:[self groupDefinitionWithGroup:@"Views" path:kMaskViewH] forKey:kMaskViewH];
    [definitions setObject:[self groupDefinitionWithGroup:@"Views" path:kMaskViewM] forKey:kMaskViewM];

    [definitions setObject:[self groupDefinitionWithGroup:@"Supporting Files" path:kPrefixHeader] forKey:kPrefixHeader];

    [definitions setObject:[self groupDefinitionWithGroup:nil path:@"Podfile"] forKey:kPodfile];
    return definitions;
}

- (NSArray *)createOptions {
    NSDictionary *dict1 = @{@"Identifier" : @"universalDeviceFamily",
                            @"Units" : @{
                                    @"Universal" : @{
                                            @"Definitions" : @{
                                                    @"Base.lproj/Main.storyboard" : @{
                                                            @"Path" : @"Main_Universal.storyboard",
                                                            @"SortOrder" : @(99)
                                                            }
                                                    }
                                            },
                                    @"iPad" : @{
                                            @"Definitions" : @{
                                                    @"Base.lproj/Main.storyboard" : @{
                                                            @"Path" : @"Main_iPad.storyboard",
                                                            @"SortOrder" : @(99)
                                                            }
                                                    }
                                            },
                                    @"iPhone" : @{
                                            @"Definitions" : @{
                                                    @"Base.lproj/Main.storyboard" : @{
                                                            @"Path" : @"Main_iPhone.storyboard",
                                                            @"SortOrder" : @(99)
                                                            }
                                                    }
                                            }
                                    },
                            };

    NSMutableArray *options = [NSMutableArray array];
    [options addObject:dict1];
    return options;
}

- (NSDictionary *)groupDefinitionWithGroup:(NSString *)group path:(NSString *)path {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (group) {
        NSArray *groups = [group componentsSeparatedByString:@"/"];
        [dict setObject:groups forKey:@"Group"];
    }
    if (path) {
        [dict setObject:path forKey:@"Path"];
    }
    return dict;
}

@end


text:
namespace realsense {
namespace enhanced_photography {

using xwalk::common::XWalkExtensionFunctionInfo;
using namespace jsapi::xdm_utils; // NOLINT

class XDMUtilsObject : public xwalk::common::BindingObject {
 public:
  explicit XDMUtilsObject(EnhancedPhotographyInstance* instance,
                          bool isRSSDKInstalled);
  ~XDMUtilsObject() override;

 private:
  void OnIsXDM(scoped_ptr<XWalkExtensionFunctionInfo> info);
  void OnLoadXDM(scoped_ptr<XWalkExtensionFunctionInfo> info);
  void OnSaveXDM(scoped_ptr<XWalkExtensionFunctionInfo> info);

  void CreateFileWithBinaryValue(const base::BinaryValue& value,
                                 base::FilePath* file_path);

  bool isRSSDKInstalled_;
  EnhancedPhotographyInstance* instance_;
  PXCSession* session_;
  scoped_ptr<uint8[]> binary_message_;
  size_t binary_message_size_;
};

}  // namespace enhanced_photography
}  // namespace realsense

#endif  // REALSENSE_ENHANCED_PHOTOGRAPHY_WIN_XDM_UTILS_OBJECT_H_


text:
namespace toggl {

const std::string Feedback::filename() const {
    Poco::Path p(true);
    bool ok = p.tryParse(attachment_path_);
    if (!ok) {
        return "";
    }
    return p.getFileName();
}

toggl::error Feedback::Validate() const {
    if (subject_.empty()) {
        return toggl::error("Missing topic");
    }
    if (details_.empty()) {
        return toggl::error("Missing details");
    }
    return toggl::noError;
}

}  // namespace toggl


text:
package com.mapsindoors.stdapp.ui.common.listeners;

import com.mapsindoors.mapssdk.Route;

public interface RouteTrackingAdapter {

    void routeSegmentPathChanged(Route route, int legIndex, int stepIndex);

    void selectRouteLeg(Route route, int legIndex);
}


text:
package org.yy.mongodb.orm;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.NestedIOException;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.yy.mongodb.exception.StatementException;
import org.yy.mongodb.orm.builder.Nodelet;
import org.yy.mongodb.orm.builder.NodeletParser;
import org.yy.mongodb.orm.builder.statement.AggregateStatement;
import org.yy.mongodb.orm.builder.statement.CommandStatement;
import org.yy.mongodb.orm.builder.statement.DeleteStatement;
import org.yy.mongodb.orm.builder.statement.GroupStatement;
import org.yy.mongodb.orm.builder.statement.InsertStatement;
import org.yy.mongodb.orm.builder.statement.MapReduceStatement;
import org.yy.mongodb.orm.builder.statement.MappingStatement;
import org.yy.mongodb.orm.builder.statement.SelectStatement;
import org.yy.mongodb.orm.builder.statement.UpdateStatement;
import org.yy.mongodb.orm.engine.Config;
import org.yy.mongodb.orm.engine.config.MappingConfig;
import org.yy.mongodb.util.NodeletUtils;

/**
 * MQL map config parser
 * @author yy
 */
public class MqlMapConfigParser {

  private NodeletParser parser = new NodeletParser( );

  private MqlMapConfiguration configuration = new MqlMapConfiguration();

  public MqlMapConfigParser() {
    parser.setValidation(true);
    parser.setEntityResolver(new MqlMapEntityResolver());

    addMapNodelets();
    addSelectNodelets();
    addUpdateNodelets();
    addInsertNodelets();
    addDeleteNodelets();
    addCommandNodelets();
    addGroupNodelets();
    addAggregateNodelets();
    addMapReduceNodelets();
  }

  /**
   * Parse resource.
   *
   * @param inputStream
   * @throws NestedIOException
   */
  public void parse(InputStream inputStream) throws NestedIOException {
    parser.parse(inputStream);
  }

  /**
   * Validate mql mapping configuration.
   */
  public void validateMapping() {
    Map<String, Config> mappings = configuration.getMappings();
    for(Map.Entry<String, Config> entry : mappings.entrySet()) {
      MappingConfig value = (MappingConfig)entry.getValue();
      getMappingExtendsNode(value);
      if(value.getNodes().isEmpty()) {
        throw new StatementException("MQL mapping config can not empty property. Mapping id '"+value.getId()+"'");
      }
    }
  }

  /**
   * Return the mql configuration.
   */
  public MqlMapConfiguration getConfiguration() {
    return configuration;
  }

  private void addMapNodelets() {
    parser.addNodelet("/mql/mapping", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addMapping(namespace, id, new MappingStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [mapping] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addSelectNodelets() {
    parser.addNodelet("/mql/select", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new SelectStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [select] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addUpdateNodelets() {
    parser.addNodelet("/mql/update", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new UpdateStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [update] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addInsertNodelets() {
    parser.addNodelet("/mql/insert", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new InsertStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [insert] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addDeleteNodelets() {
    parser.addNodelet("/mql/delete", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new DeleteStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [delete] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addCommandNodelets() {
    parser.addNodelet("/mql/command", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new CommandStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [command] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addGroupNodelets() {
    parser.addNodelet("/mql/group", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new GroupStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [group] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addAggregateNodelets() {
    parser.addNodelet("/mql/aggregate", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new AggregateStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [aggregate] '" + id + "' has finished.");
        }
      }
    });
  }

  private void addMapReduceNodelets() {
    parser.addNodelet("/mql/mapreduce", new Nodelet() {
      @Override
      public void process(String namespace, Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node);
        String id = attributes.getProperty("id");

        configuration.addConfig(namespace, id, new MapReduceStatement(id).handler(namespace, node));
        if (logger.isDebugEnabled()) {
          logger.debug("Mql configuration load [mapreduce] '" + id + "' has finished.");
        }
      }
    });
  }

  private void getMappingExtendsNode(MappingConfig target) {
    String extend = target.getExtend();
    if(extend != null) {
      MappingConfig mc = (MappingConfig)configuration.getMapping(target.getNamespace(), extend);
      if(mc == null) {
        throw new StatementException("This extends mapping '"+extend+"' not found. Mapping id '"+target.getId()+"'");
      }

      if(mc.getId().equals(target.getId())) {
        throw new StatementException("This extends mapping can not inherit their own. Mapping id '"+target.getId()+"'");
      }
      getMappingExtendsNode(mc);
      target.merge(mc.getNodes());
      if(target.getTypeHandler() == null) {
        target.setTypeHandler(mc.getTypeHandler());
      }
    }
  }

  /**
   * Offline entity resolver for the mongodb DTDs
   */
  private static class MqlMapEntityResolver implements EntityResolver {

    private static final String MQL_MAP_DTD = "https://raw.githubusercontent.com/yuxiangping/repository/master/mongodb-mql.dtd";

    private static final Map<String, String> doctypeMap = new HashMap<String, String>(2);

    static {
      doctypeMap.put("mongodb-mql.dtd".toUpperCase(), MQL_MAP_DTD);
      doctypeMap.put("-//eason.xp.yu@gmail.com//DTD MONGODB QL Config 1.0//zh-CN".toUpperCase(), MQL_MAP_DTD);
    }

    /**
     * Converts a public DTD into a local one
     *
     * @param publicId Unused but required by EntityResolver interface
     * @param systemId The DTD that is being requested
     * @return The InputSource for the DTD
     * @throws SAXException If anything goes wrong
     */
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
      if (publicId != null) {
        publicId = publicId.toUpperCase();
      }

      if (systemId != null) {
        systemId = systemId.toUpperCase();
      }

      InputSource source = null;
      try {
        String path = (String) doctypeMap.get(publicId);
        source = getInputSource(path);
        if (source == null) {
          path = (String) doctypeMap.get(systemId);
          source = getInputSource(path);
        }

        if (source == null) {
          throw new SAXException("Resolve entiry error. PID:" + publicId + ", SID:" + systemId);
        }
      } catch (Exception e) {
        throw new SAXException("Resolve entiry error. PID:"+publicId+", SID:"+systemId, e);
      }
      return source;
    }

    private InputSource getInputSource(String path) throws Exception {
      InputSource source = null;
      if (path != null) {
        InputStream in = ClassLoader.getSystemResourceAsStream(path);
        source = new InputSource(in);
      }

      if(source.getByteStream() == null) {
        URL location = new URL(path);
        URLConnection connect = location.openConnection();
        source = new InputSource(connect.getInputStream());
      }
      return source;
    }
  }

}


text:
<?php

namespace Doctrine\ODM\MongoDB\Mapping\Annotations;

use Doctrine\Common\Annotations\Annotation;

/**
 * Must be set on a document class to instruct Doctrine to check for lifecycle
 * callback annotations on public methods.
 *
 * @Annotation
 */
final class HasLifecycleCallbacks extends Annotation
{
}


text:
@interface MainViewController () <UIScrollViewDelegate>
{
    REMenu *navMenu;
    NSArray *dataArray;
    NSArray *yearsArray;
    NSMutableArray *imagesArray;
    NSArray *streetsArray;
    UIView *loadingHudView;
    BOOL initialLoaded;
}

-(void)loadNearbyItems;
-(void)refreshPulled:(id)sender;
-(void)hideLoadingView;
-(void)updateInitialLocationFromNotification:(NSNotification *)note;
@end

@implementation MainViewController

-(void)loadMomentFromId:(NSString *)identifier {
    [self createLoadingView];
    [[APIClient client] findMoment:identifier success:^(NSDictionary *moment) {
        [self hideLoadingView];
        MomentViewController *mvc = [[MomentViewController alloc] initWithMoment:moment];
        [self.navigationController pushViewController:mvc animated:YES];
    }];
}

-(void)updateInitialLocationFromNotification:(NSNotification *)note {
    if(initialLoaded) return;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UpdatedLocation" object:nil];
    NSLog(@"Got location, loading initial.");
    initialLoaded = YES;
    [self hideLoadingView];
    [self loadNearbyItems];
}

-(void)hideLoadingView {
    [loadingHudView removeFromSuperview];
    loadingHudView = nil;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint scrollViewPoint;
    scrollViewPoint.y = scrollView.contentOffset.y;
    loadingHudView.frame = CGRectMake((self.view.frame.size.width / 2) - 50,
                                      (self.view.frame.size.height / 2) - 80 + scrollViewPoint.y,
                                      100, 100);
}
-(void)loadNearbyItems {
    if(loadingHudView != nil) return;
    [self createLoadingView];
    [[APIClient client] findNearbyMoments:^(NSArray *array) {
        dataArray = [NSArray arrayWithArray:array];
        // load botom footer padding
        UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        UIImageView *bottomIconImage = [[UIImageView alloc] initWithFrame:CGRectMake((tableFooterView.frame.size.width/2) - 15, 40, 30, 25)];
        bottomIconImage.image = [UIImage imageNamed:@"PixtoryBottomIcon"];
        [tableFooterView addSubview:bottomIconImage];
        self.tableView.tableFooterView = tableFooterView;
        [self.tableView reloadData];
        [self hideLoadingView];

    }];
}

-(void)refreshPulled:(id)sender {
    [self.refreshControl endRefreshing];
    [self loadNearbyItems];
}

- (void)viewDidLoad
{
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ContentBackground.png"]];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;

    self.refreshControl = [UIRefreshControl new];
    [self.refreshControl addTarget:self action:@selector(refreshPulled:) forControlEvents:UIControlEventValueChanged];

    initialLoaded = [Locator locator].lastLocation != nil;

    [super viewDidLoad];

    self.navigationItem.title = @"Pixtory";

    [self createNavigationMenu];

    // TODO: Wait until we get a location, then render it.
    NSLog(@"Waiting for location...");
    [self createLoadingView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInitialLocationFromNotification:) name:@"UpdatedLocation" object:nil];

}
- (void)createLoadingView
{
    if(loadingHudView != nil) return;
    NSArray *animationArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"01"],[UIImage imageNamed:@"02"],[UIImage imageNamed:@"03"],[UIImage imageNamed:@"04"],[UIImage imageNamed:@"05"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"],[UIImage imageNamed:@"01"], nil];

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ContentBackground"]];

    loadingHudView = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width / 2) - 50,
                                                                      (self.view.frame.size.height / 2) - 80,
                                                                      100, 100)];
    loadingHudView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.8f];
    [self.view addSubview:loadingHudView];
    UIImageView *animationView = [[UIImageView alloc]initWithFrame:CGRectMake((loadingHudView.frame.size.width / 2) - 20,
                                                                              (loadingHudView.frame.size.height / 2) - 20,
                                                                              40, 40)];
    animationView.backgroundColor = [UIColor clearColor];
    animationView.animationImages = animationArray;
    animationView.animationDuration = 0.9;
    animationView.animationRepeatCount = 0;
    [animationView startAnimating];
    [loadingHudView addSubview:animationView];
}

- (void)createNavigationMenu
{

    UIImageView *navigationView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"PixtoryNavigation"]];

    navigationView.frame = CGRectMake(0, 7,98, 30);

    self.navigationItem.titleView = navigationView;

    // RE Menu
    REMenuItem *homeItem = [[REMenuItem alloc] initWithTitle:@"Home"
                                                    subtitle:nil
                                                       image:[UIImage imageNamed:@"Icon_Home"]
                                            highlightedImage:nil
                                                      action:^(REMenuItem *item) {
                                                          NSLog(@"Item: %@", item);
                                                      }];

    REMenuItem *exploreItem = [[REMenuItem alloc] initWithTitle:@"Explore"
                                                       subtitle:nil
                                                          image:[UIImage imageNamed:@"Icon_Explore"]
                                               highlightedImage:nil
                                                         action:^(REMenuItem *item) {
                                                             NSLog(@"Item: %@", item);
                                                         }];

    REMenuItem *settingsItem = [[REMenuItem alloc] initWithTitle:@"Settings"
                                                        subtitle:nil
                                                           image:[UIImage imageNamed:@"Icon_Activity"]
                                                highlightedImage:nil
                                                          action:^(REMenuItem *item) {
                                                              NSLog(@"Item: %@", item);
                                                          }];

    REMenuItem *aboutItem = [[REMenuItem alloc] initWithTitle:@"About Us"
                                                          image:[UIImage imageNamed:@"Icon_Profile"]
                                               highlightedImage:nil
                                                         action:^(REMenuItem *item) {
                                                             AboutViewController *aboutViewController = [[AboutViewController alloc] init];
                                                             [self.navigationController pushViewController: aboutViewController animated:YES];
                                                         }];

    navMenu = [[REMenu alloc] initWithItems:@[aboutItem]];

    UIBarButtonItem *menuBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"MenuIcon"] style:UIBarButtonItemStyleBordered target:self action:@selector(toggleNavigationMenu)];
    [UIBarButtonItem configureFlatButtonsWithColor:[UIColor whiteColor]
                                  highlightedColor:[UIColor whiteColor]
                                      cornerRadius:3
                                   whenContainedIn:[UINavigationController class], nil];

    self.navigationItem.leftBarButtonItem = menuBarButtonItem;
}

- (void)toggleNavigationMenu
{
    if (navMenu.isOpen)
        return [navMenu close];

    [navMenu showFromNavigationController:self.navigationController];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 340;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView registerClass:[MainViewTableCell class] forCellReuseIdentifier:@"Cell"];
    static NSString *CellIdentifier = @"Cell";
    MainViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSDictionary *data = [dataArray objectAtIndex:indexPath.row];
    cell.moment = data;
    [cell.pictureView setImageWithURL:[NSURL URLWithString:[data valueForKeyPath:@"image.primary.url"]]];
    cell.streetLabel.text = [data valueForKeyPath:@"location.name"];
    cell.yearLabel.text = [data objectForKey:@"formatted_timestamp"];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *moment = [dataArray objectAtIndex:indexPath.row];
    MomentViewController *mvc = [[MomentViewController alloc] initWithMoment:moment];
    [self.navigationController pushViewController:mvc animated:YES];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NearbyListScrolling" object:self];
}

@end


text:
package org.topcat.store.entity;

import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * @author topcat
 *
 */
@Entity
@Table(name = "st_order_list")
public class OrderList extends IdEntity {

	private Date createDate;
	private Long orderNum;
	private List<Order> orders;
	private int status;
	private User operator;
	private Date modifyDate;
	private User modifier;

	public OrderList() {
		this.orderNum = System.currentTimeMillis();
	}

	@OneToMany
	@JoinColumn(name = "order_id")
	public List<Order> getOrders() {
		return orders;
	}

	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@OneToOne
	@JoinColumn(name = "op_user_id")
	public User getOperator() {
		return operator;
	}

	public void setOperator(User operator) {
		this.operator = operator;
	}

	public Date getModifyDate() {
		return modifyDate;
	}

	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}

	@OneToOne
	@JoinColumn(name = "mo_user_id")
	public User getModifier() {
		return modifier;
	}

	public void setModifier(User modifier) {
		this.modifier = modifier;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public Long getOrderNum() {
		return orderNum;
	}

	public void setOrderNum(Long orderNum) {
		this.orderNum = orderNum;
	}
}


text:
package org.wikimark;

import java.io.IOException;
import java.util.List;
import static java.util.stream.Collectors.toList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

/**
 *
 * @author Martín Straus
 */
public class IndexServlet extends HttpServlet {

    private final TemplateEngine thymeleaf;
    private final Context context;
    private final Pages pages;

    public IndexServlet(ServletContext ctx, TemplateEngine thymeleaf, Context context, Pages pages) {
        this.thymeleaf = thymeleaf;
        this.context = context;
        this.pages = pages;
        ctx.addServlet(IndexServlet.class.getName(), this).addMapping("/index.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type", "text/html; charset=utf-8");
        WebContext ctx = new WebContext(req, resp, req.getServletContext());
        ctx.setVariable("pages", pages());
        thymeleaf.process("/index.html", ctx, resp.getWriter());
    }

    private List<PageContext> pages() {
        return pages.findLatest(20).stream().map((p) -> p.pageContext()).collect(toList());
    }

}


text:
namespace Core {
    class Processor;
}; // namespace Core

namespace Debug {
namespace Logger {
    // generic log
    void Log(const std::string prefix, const std::string& msg);
    // Log processor register states
    void LogRegisters(const Core::Processor& processor);
    // Log IO Registers in memory
    void LogIORegisters(std::shared_ptr<Memory::MemoryBus>& memory_bus);
    // Log a chunk of memory specified by the caller
    void LogMemory(std::shared_ptr<Memory::MemoryBus>& memory_bus,
                   u16 address, u16 bytes);
    // Disassembles instructions and logs the result
    void LogDisassembly(std::shared_ptr<Memory::MemoryBus>& memory_bus,
                        u16 address, u16 bytes);
}; // namespace Logger
}; // namespace Debug

// Quick macros for messages
#define LOG_MSG(msg)    \
    Debug::Logger::Log("INFO: ", msg);
#define LOG_WARN(msg)   \
    Debug::Logger::Log("WARN: ", msg);
#define LOG_ERROR(msg)  \
    Debug::Logger::Log("ERROR: ", msg);
#define LOG_VRAM(memory_bus)                          \
    LOG_MSG("VRAM: 8000h - BFFFh\n");   \
    LogMemory(memory_bus, 0x8000, 0x4000);


text:
#ifndef ZORBA_VERSION_API_H
#define ZORBA_VERSION_API_H

#include <string>

#include <zorba/config.h>

namespace zorba {

  /**
   * Provide access to the version of %Zorba that is used
   */
  class ZORBA_DLL_PUBLIC Version
  {
    protected:
      static int theMajorVersion;
      static int theMinorVersion;
      static int thePatchVersion;

    public:
      /** \brief Get the major version
       */
      static int
      getMajorVersion();

      /** \brief Get the minor version
       */
      static int
      getMinorVersion();

      /** \brief Get the patch version
       */
      static int
      getPatchVersion();

      /** \brief Get the %Zorba version as std::string
       *
       * Form: MajorVersion.MinorVersion.PatchVersion
       */
      static std::string
      getVersion();

  };

  /** \brief Write the result of calling aVersiongetVersion() to the given
   *         output stream.
   */
  ZORBA_DLL_PUBLIC
  std::ostream&
  operator<< (std::ostream& os, const Version& aVersion);

} /* end namespace zorba */
#endif
/* vim:set et sw=2 ts=2: */


text:
package de.undercouch.citeproc.csl.internal.rendering;

import de.undercouch.citeproc.csl.internal.RenderContext;
import de.undercouch.citeproc.csl.internal.SElement;
import de.undercouch.citeproc.csl.internal.behavior.Affixes;
import de.undercouch.citeproc.csl.internal.behavior.StripPeriods;
import de.undercouch.citeproc.csl.internal.locale.LTerm;
import de.undercouch.citeproc.helper.NodeHelper;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Node;

/**
 * A date-part element from a style file
 * @author Michel Kraemer
 */
public class SDatePart implements SElement {
    private int[] date;

    private final String name;
    private final String form;
    private final Affixes affixes;
    private final StripPeriods stripPeriods;

    /**
     * Creates the date-part element from an XML node
     * @param node the XML node
     */
    public SDatePart(Node node) {
        name = NodeHelper.getAttrValue(node, "name");
        if (name == null) {
            throw new IllegalStateException("Missing date part name");
        }
        if (!name.equals("year") && !name.equals("month") && !name.equals("day")) {
            throw new IllegalStateException("Unknown date part name: " + name);
        }

        form = NodeHelper.getAttrValue(node, "form");
        affixes = new Affixes(node);
        stripPeriods = new StripPeriods(node);
    }

    /**
     * Construct a date-part element from a name and a form
     * @param name the name
     * @param form the form
     */
    public SDatePart(String name, String form) {
        this.name = name;
        this.form = form;
        affixes = new Affixes();
        stripPeriods = new StripPeriods();
    }

    @Override
    public void render(RenderContext ctx) {
        affixes.wrap(stripPeriods.wrap(this::renderInternal)).accept(ctx);
    }

    private void renderInternal(RenderContext ctx) {
        String value = null;
        switch (name) {
            case "year":
                if (date.length > 0) {
                    value = renderYear(date[0]);
                }
                break;

            case "month":
                if (date.length > 1) {
                    value = renderMonth(date[1], ctx);
                }
                break;

            case "day":
                if (date.length > 2) {
                    value = renderDay(date[2]);
                }
                break;
        }

        if (value != null) {
            ctx.emit(value);
        }
    }

    private String renderYear(int year) {
        return String.valueOf(year);
    }

    private String renderMonth(int month, RenderContext ctx) {
        String value;
        String p = StringUtils.leftPad(String.valueOf(month), 2, '0');
        if ("short".equals(form)) {
            value = ctx.getTerm("month-" + p, LTerm.Form.SHORT);
        } else if ("numeric".equals(form)) {
            value = String.valueOf(month);
        } else if ("numeric-leading-zeros".equals(form)) {
            value = p;
        } else {
            value = ctx.getTerm("month-" + p);
        }
        return value;
    }

    private String renderDay(int day) {
        String value = String.valueOf(day);
        if ("numeric-leading-zeros".equals(form)) {
            value = StringUtils.leftPad(value, 2, '0');
        }
        return value;
    }

    /**
     * Get the name of the date part to render (i.e. {@code year}, {@code month},
     * or {@code day})
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * Set the date to render
     * @param date the date
     */
    public void setDate(int[] date) {
        this.date = date;
    }
}


text:
class Admin::RepresentativesController < AdminController
  EDITABLE_ATTRIBUTES = [:twitter_id, :email, :opted_out]

  before_filter :fetch_representative, except: [:index]
  before_filter :authorize_user, except: [:index]

  def index
    @representatives = Representative.order(:external_id)
  end

  def edit
  end

  def update
    attrs = params[:representative].slice(*EDITABLE_ATTRIBUTES)
    normalize_blanks(attrs)

    if @representative.update_attributes(attrs)
      Rails.cache.delete('question-form/representatives')
      redirect_to admin_representatives_path, notice: t('app.updated.representative')
    else
      redirect_to edit_admin_representative_path(@representative), alert: @representative.errors.full_messages.to_sentence
    end
  end

  def activate
    with_representative do
      @representative.send_confirmation_instructions
      redirect_to admin_representatives_path, notice: t('app.questions_and_answers.representative.confirmation_mail_sent', name: @representative.name)
    end
  end

  def reset_password
    with_representative do
      @representative.send_reset_password_instructions
      redirect_to admin_representatives_path, notice: t('app.questions_and_answers.representative.passwd_reset_mail_sent', name: @representative.name)
    end
  end

  private

  def authorize_user
    unless policy(@representative).edit?
      redirect_to admin_representatives_path, alert: t('app.errors.unauthorized')
      return
    end
  end

  def fetch_representative
    @representative = Representative.find(params[:id] || params[:representative_id])
  end

  def with_representative(&block)
    if @representative && @representative.email
      yield
    else
      redirect_to admin_representatives_path, alert: t('app.questions_and_answers.representative.not_found')
    end
  end
end


text:
namespace SceneEngine
{
    MetricsBox::MetricsBox(const Desc& desc)
    {
        using namespace RenderCore;
        using namespace RenderCore::Metal;
        using namespace BufferUploads;

        auto& uploads = GetBufferUploads();
        BufferUploads::BufferDesc metricsBufferDesc;
        metricsBufferDesc._type = BufferUploads::BufferDesc::Type::LinearBuffer;
        metricsBufferDesc._bindFlags = BindFlag::UnorderedAccess|BindFlag::StructuredBuffer|BindFlag::ShaderResource;
        metricsBufferDesc._cpuAccess = 0;
        metricsBufferDesc._gpuAccess = GPUAccess::Read|GPUAccess::Write;
        metricsBufferDesc._allocationRules = 0;
        metricsBufferDesc._linearBufferDesc._structureByteSize = sizeof(unsigned)*16;
        metricsBufferDesc._linearBufferDesc._sizeInBytes = metricsBufferDesc._linearBufferDesc._structureByteSize;
        auto metricsBuffer = uploads.Transaction_Immediate(metricsBufferDesc)->AdoptUnderlying();

        UnorderedAccessView  metricsBufferUAV(metricsBuffer.get());
        ShaderResourceView   metricsBufferSRV(metricsBuffer.get());

        _metricsBufferResource = std::move(metricsBuffer);
        _metricsBufferUAV = std::move(metricsBufferUAV);
        _metricsBufferSRV = std::move(metricsBufferSRV);
    }

    MetricsBox::~MetricsBox() {}
}


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

namespace DungeonDigger.Generation
{
    public class GeneratorOption
    {
        /// <summary>
        /// The text to show in the textblock for the option.
        /// </summary>
        public string Label { get; internal set; }

        /// <summary>
        /// The type of control to show the user.
        /// </summary>
        public ControlType Control { get; internal set; }

        /// <summary>
        /// The choices to give the user, if the chosen ControlType only gives the possibility of specific answers (such as a dropdown).
        /// </summary>
        public IReadOnlyList<Tuple<string, object>> ControlOptions { get; internal set; }

        /// <summary>
        /// The key to use in the response-dictionary to get the user-provided response from the chosen ControlType.
        /// Must be unique among the options that a generator provides.
        /// </summary>
        public string Key { get; internal set; }

        /// <summary>
        /// The default content of the control.
        /// For ControlType.Checkbox, use bool.TrueString or bool.FalseString.
        /// For Dropdown, specify the index as a string. E.g. "0"
        /// </summary>
        public string DefaultContent { get; internal set; }

        public enum ControlType
        {
            /// <summary>
            /// The option returned through the option-dictionary for this ControlType is the object associated with the selected item, as specified in the ControlOptions-property.
            /// </summary>
            Dropdown,
            /// <summary>
            /// The option returned through the option-dictionary for this ControlType is of type boolean.
            /// </summary>
            Checkbox,
            /// <summary>
            /// The option returned through the option-dictionary for this ControlType is of type string.
            /// </summary>
            TextField,
            /// <summary>
            /// The option returned through the option-dictionary for this ControlType is of type integer.
            /// </summary>
            IntegerField
        }
    }

}


text:
using System;
using System.Linq;
using Couchbase.Core.IO.Serializers;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;

namespace Couchbase.Linq.UnitTests.QueryGeneration
{
    [TestFixture]
    class NullHandlingTests : N1QLTestBase
    {

        [Test]
        public void Test_IsoDateTime_HasValue()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class1>(mockBucket.Object)
                    .Where(e => e.Updated.HasValue)
                    .Select(e => new { e.Updated});

            const string expected =
                "SELECT `Extent1`.`Updated` as `Updated` FROM `default` as `Extent1` WHERE (`Extent1`.`Updated` IS NOT NULL)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        [Test]
        public void Test_IsoDateTime_NotHasValue()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class1>(mockBucket.Object)
                    .Where(e => !e.Updated.HasValue)
                    .Select(e => new { e.Updated });

            const string expected =
                "SELECT `Extent1`.`Updated` as `Updated` FROM `default` as `Extent1` WHERE NOT (`Extent1`.`Updated` IS NOT NULL)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        [Test]
        public void Test_IsoDateTime_Value()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class1>(mockBucket.Object)
                    .Where(e => e.Updated.Value < new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                    .Select(e => new { e.Updated });

            const string expected =
                "SELECT `Extent1`.`Updated` as `Updated` FROM `default` as `Extent1` " +
                "WHERE (STR_TO_MILLIS(`Extent1`.`Updated`) < 946684800000)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        [Test]
        public void Test_UnixDateTime_HasValue()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class2>(mockBucket.Object)
                    .Where(e => e.Updated.HasValue)
                    .Select(e => new { e.Updated });

            const string expected =
                "SELECT MILLIS_TO_STR(`Extent1`.`Updated`) as `Updated` FROM `default` as `Extent1` WHERE (`Extent1`.`Updated` IS NOT NULL)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        [Test]
        public void Test_UnixDateTime_NotHasValue()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class2>(mockBucket.Object)
                    .Where(e => !e.Updated.HasValue)
                    .Select(e => new { e.Updated });

            const string expected =
                "SELECT MILLIS_TO_STR(`Extent1`.`Updated`) as `Updated` FROM `default` as `Extent1` WHERE NOT (`Extent1`.`Updated` IS NOT NULL)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        [Test]
        public void Test_UnixDateTime_Value()
        {
            var mockBucket = new Mock<IBucket>();
            mockBucket.SetupGet(e => e.Name).Returns("default");

            var query =
                QueryFactory.Queryable<Class2>(mockBucket.Object)
                    .Where(e => e.Updated.Value < new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                    .Select(e => new { e.Updated });

            const string expected =
                "SELECT MILLIS_TO_STR(`Extent1`.`Updated`) as `Updated` FROM `default` as `Extent1` " +
                "WHERE (`Extent1`.`Updated` < 946684800000)";

            var n1QlQuery = CreateN1QlQuery(mockBucket.Object, query.Expression);

            Assert.AreEqual(expected, n1QlQuery);
        }

        #region Helpers

        private class Class1
        {
            // ReSharper disable once UnusedAutoPropertyAccessor.Local
            public DateTime? Updated { get; set; }
        }

        private class Class2
        {
            // ReSharper disable once UnusedAutoPropertyAccessor.Local
            [JsonConverter(typeof(UnixMillisecondsConverter))]
            public DateTime? Updated { get; set; }
        }

        #endregion

    }
}