text:
// Copyright 2014 Runtime.JS project authors
//
// 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.

var pciDrivers = require('./pci-drivers');
var resources = require('../resources')();
var vfs = require('../vfs');

var acpi = resources.acpi;
var io = resources.ioRange;
var irqRange = resources.irqRange;
var memrange = resources.memoryRange;
var allocator = resources.allocator;

var acpiDevices = acpi.getPciDevices();

var address_port = io.port(0xCF8);
var data_port = io.port(0xCFC);

var sizeof = {
  BYTE: 1,
  UINT8: 1,
  UINT16: 2,
  UINT32: 4,
  UINT64: 8,
};

var pciAccessorFactory = (function(address_port, data_port) {
  var accessorCache = new Map();

  /**
   * Available PCI configuration space fields for all types
   * of devices
   */
  var fields = {
    VENDOR_ID:      {offset: 0x00, shift: 0, mask: 0xffff},
    DEVICE_ID:      {offset: 0x00, shift: 2, mask: 0xffff},

    COMMAND:        {offset: 0x04, shift: 0, mask: 0xffff},
    STATUS:         {offset: 0x04, shift: 2, mask: 0xffff},

    REVISION_ID:    {offset: 0x08, shift: 0, mask: 0xff},
    PROG_IF:        {offset: 0x08, shift: 1, mask: 0xff},
    SUBCLASS:       {offset: 0x08, shift: 2, mask: 0xff},
    CLASS_CODE:     {offset: 0x08, shift: 3, mask: 0xff},

    CACHE_LINESIZE: {offset: 0x0c, shift: 0, mask: 0xff},
    LATENCY_TIMER:  {offset: 0x0c, shift: 1, mask: 0xff},
    HEADER_TYPE:    {offset: 0x0c, shift: 2, mask: 0xff},
    BIST:           {offset: 0x0c, shift: 3, mask: 0xff},
  };

  /**
   * Available PCI configuration space fields for general devices
   * (header type 0x00)
   */
  var generalFields = {
    BAR:       [{offset: 0x10, shift: 0, mask: 0xffffffff},
                {offset: 0x14, shift: 0, mask: 0xffffffff},
                {offset: 0x18, shift: 0, mask: 0xffffffff},
                {offset: 0x1c, shift: 0, mask: 0xffffffff},
                {offset: 0x20, shift: 0, mask: 0xffffffff},
                {offset: 0x24, shift: 0, mask: 0xffffffff}],

    SUBSYS_VENDOR:  {offset: 0x2c, shift: 0, mask: 0xffff},
    SUBSYS_ID:      {offset: 0x2c, shift: 2, mask: 0xffff},

    INTERRUPT_LINE: {offset: 0x3c, shift: 0, mask: 0xff},
    INTERRUPT_PIN:  {offset: 0x3c, shift: 1, mask: 0xff},
  };

  /**
   * Available PCI configuration space fields for bridge devices
   * (header type 0x01 or 0x02)
   */
  var bridgeFields = {
    PRIMARY_BUS:    {offset: 0x18, shift: 0, mask: 0xff},
    SECONDARY_BUS:  {offset: 0x18, shift: 1, mask: 0xff},
    SUBORDINATE:    {offset: 0x18, shift: 2, mask: 0xff},
  };

  function setPort(bus, slot, func, offset) {
    var addr = (bus << 16) | (slot << 11) | (func << 8) |
      (offset & 0xfc) | 0x80000000;
    address_port.write32(addr);
  }

  function readRaw32(bus, slot, func, offset) {
    if (offset % sizeof.UINT32 !== 0) {
      throw new Error('unaligned pci space 32 bit read');
    }

    setPort(bus, slot, func, offset);
    return data_port.read32();
  }

  function dwToFieldValue(value, field) {
    return ((value >>> (8 * sizeof.BYTE * field.shift)) &
        field.mask) >>> 0;
  }

  /**
   * Provides a way to read and write PCI Configuration space registers.
   * Uses internal cache to speed up reads of the same field. Address
   * includes bus, slot and func of a device.
   */
  function PciAccessor(address) {
    var bus = address.bus >>> 0,
      slot = address.slot >>> 0,
      func = address.func >>> 0;

    if (bus > 255) {
      throw new Error('invalid bus value (expected 0-255)');
    }

    if (slot > 31) {
      throw new Error('invalid slot value (expected 0-31)');
    }

    if (func > 7) {
      throw new Error('invalid func value (expected 0-7)');
    }

    var offsetCache = new Map();

    function writeRaw32(offset, value) {
      if (offset % sizeof.UINT32 !== 0) {
        throw new Error('unaligned pci space 32-bit write');
      }

      setPort(bus, slot, func, offset);
      return data_port.write32(value >>> 0);
    }

    function writeRaw16(offset, value) {
      if (offset % sizeof.UINT16 !== 0) {
        throw new Error('unaligned pci space 16-bit write');
      }

      setPort(bus, slot, func, offset);
      return data_port.write16((value & 0xffff) >>> 0);
    }

    function writeRaw8(offset, value) {
      setPort(bus, slot, func, offset);
      return data_port.write8((value & 0xff) >>> 0);
    }

    /**
     * Read PCI configuration space field
     */
    this.read = function __read(field) {
      var value;

      if (offsetCache.has(field.offset)) {
        value = offsetCache.get(field.offset);
      } else {
        value = readRaw32(bus, slot, func, field.offset);
        offsetCache.set(field.offset, value);
      }

      return dwToFieldValue(value, field);
    };

    /**
     * Write PCI configuration space field
     */
    this.write = function __write(field, value) {
      offsetCache.delete(field.offset);

      switch (field.mask) {
        case 0xffffffff: writeRaw32(field.offset, value); break;
        case 0xffff: writeRaw16(field.offset + field.shift, value); break;
        case 0xff: writeRaw8(field.offset + field.shift, value); break;
        default:
          throw new Error('invalid pci space field mask');
      }
    };

    /**
     * Set of methods to get available accessor fields
     */
    this.fields = function __fields() { return fields; }
    this.generalFields = function __generalFields() { return generalFields; }
    this.bridgeFields = function __bridgeFields() { return bridgeFields; }
  }

  return {
    /**
     * Returns PCI accessor object for provided address
     */
    get: function __get(address) {
      var key = JSON.stringify([address.bus, address.slot, address.func]);
      if (accessorCache.has(key)) {
        return accessorCache.get(key);
      }

      var value = new PciAccessor(address);
      accessorCache.set(key, value);
      return value;
    },
    /**
     * Check if PCI device at address exists
     */
    exists: function __exists(bus, slot, func) {
      var field = fields.VENDOR_ID;
      var value = readRaw32(bus, slot, func, field.offset);
      var vendor_id = dwToFieldValue(value, field);
      return 0xffff !== vendor_id;
    },
  };
})(address_port, data_port);

/**
 * Find ACPI PCI device bus, slot and function
 */
function locateAcpiDevice(dev) {
  if (!dev.isDevice()) {
    return null;
  }

  var addr = dev.address();
  var slotId = ((addr >>> 16) & 0xffff) >>> 0;
  var funcId = (addr & 0xffff) >>> 0;

  if (dev.isRootBridge()) {
    var busId = dev.getRootBridgeBusNumber();

    return {
      bus: busId,
      slot: slotId,
      func: funcId,
    };
  }

  var parentDev = dev.parent();
  if (null === parentDev) {
    return null;
  }

  if (!parentDev.isDevice()) {
    return null;
  }

  if (parentDev.isRootBridge()) {
    var busId = parentDev.getRootBridgeBusNumber();

    return {
      bus: busId,
      slot: slotId,
      func: funcId,
    };
  }

  var parentLocation = locateAcpiDevice(parentDev);
  if (null === parentLocation) {
    return null;
  }

  var pciParent = pciAccessorFactory.get({
    bus: parentLocation.bus,
    slot: parentLocation.slot,
    func: parentLocation.func,
  });

  var header = pciParent.read(pciParent.fields().HEADER_TYPE);

  // Mask multifunction bit
  var headerType = (header & 0x7f) >>> 0;
  if (0x01 !== headerType && 0x02 !== headerType) {
    return null;
  }

  var bridgeBus = pciParent.read(pciParent.bridgeFields().SECONDARY_BUS);

  return {
    bus: bridgeBus,
    slot: slotId,
    func: funcId,
  };
}

/**
 * Provides enumeration services for the whole PCI configuration space
 */
var pciSpace = (function(pciAccessorFactory) {
  function checkDevice(bus, slot, func, fn) {
    var addr = {bus: bus, slot:slot, func: func};
    var pciAccessor = pciAccessorFactory.get(addr);
    var vendorId = pciAccessor.read(pciAccessor.fields().VENDOR_ID);

    if (0xffff === vendorId) {
      return;
    }

    fn(addr, pciAccessor);
  }

  function checkDeviceFunctions(bus, slot, fn) {
    var func = 0;
    var pciAccessor = pciAccessorFactory.get({bus: bus, slot:slot, func: func});
    var headerType = pciAccessor.read(pciAccessor.fields().HEADER_TYPE);
    var isMultifunc = (headerType & 0x80) >>> 0;
    var funcCount = isMultifunc ? 8 : 1;

    for (func = 0; func < funcCount; ++func) {
      checkDevice(bus, slot, func, fn);
    }
  }

  return {
    eachDevice: function(fn) {
      var func = 0;

      for (var bus = 0; bus < 255; ++bus) {
        for (var slot = 0; slot < 32; ++slot) {

          if (!pciAccessorFactory.exists(bus, slot, func)) {
            continue;
          }

          checkDeviceFunctions(bus, slot, fn);
        }
      }
    },
  };
})(pciAccessorFactory);

/**
 * Service for converting PCI data codes to readable names
 */
var codeNameResolver = (function() {
  var classCodes = [
    'Unclassified',
    'Mass Storage Controller',
    'Network Controller',
    'Display Controller',
    'Multimedia Controller',
    'Memory Controller',
    'Bridge Device',
    'Simple Communication Controller',
    'Base System Peripheral',
    'Input Device',
    'Docking Station',
    'Processor',
    'Serial Bus Controller',
    'Wireless Controller',
    'Intelligent I/O Controller',
    'Satellite Communication Controller',
    'Encryption/Decryption Controller',
    'Data Acquisition and Signal Processing Controller',
  ];

  return {
    /**
     * Get name for provided PCI device class code
     */
    classCodeToName: function(code) {
      if ('undefined' === typeof classCodes[code]) {
        return classCodes[0];
      }

      return classCodes[code];
    },
  };
})();

/**
 * Represents PCI device of any type
 */
function PciDevice(address, pciAccessor) {
  var vendorId = pciAccessor.read(pciAccessor.fields().VENDOR_ID);
  var deviceId = pciAccessor.read(pciAccessor.fields().DEVICE_ID);
  var header = pciAccessor.read(pciAccessor.fields().HEADER_TYPE);
  var isBridge = false;

  var headerType = (header & 0x7f) >>> 0;
  if (0x01 === headerType || 0x02 === headerType) {
    isBridge = true;
  }

  var that = {
    acpiDevice: null,
  };

  var irqVector = null;

  /**
   * Attach ACPI PCI device handle to current PCI device
   */
  this.attachAcpiDevice = function __attachAcpiDevice(acpiDevice) {
    if (null !== that.acpiDevice) {
      return;
    }

    that.acpiDevice = acpiDevice;
  };

  /**
   * Get 16bit vendor ID of current device
   */
  this.vendorId = function __vendorId() { return vendorId; };

  /**
   * Get 16bit device ID of current device
   */
  this.deviceId = function __deviceId() { return deviceId; };

  /**
   * Check if current device is a PCI-to-PCI or PCI-to-CardBus
   * bridge
   */
  this.isBridge = function __isBridge() { return isBridge; };

  /**
   * Get PCI device address (bus, slot and function)
   */
  this.address = function __address() { return address; };

  /**
   * Get bridge secondary bus number (bus number of current bridge)
   */
  this.getSecondaryBus = function __getSecondaryBus() {
    if (!isBridge) {
      throw new Error('device is not a bridge');
    }

    return pciAccessor.read(pciAccessor.bridgeFields().SECONDARY_BUS);
  };

  this.setCommandFlag = function __setCommandFlag(flag) {
    var value = pciAccessor.read(pciAccessor.fields().COMMAND);
    value |= (1 << flag) >>> 0;
    pciAccessor.write(pciAccessor.fields().COMMAND, value);
  };

  /**
   * Get current device IRQ vector
   */
  this.getIRQVector = function __getIRQVector(vector) {
    return irqVector;
  };

  /**
   * Set current device IRQ vector. May be called only once
   */
  this.setIRQVector = function __setIRQVector(vector) {
    if (null !== irqVector) {
      throw new Error('IRQ vector already set');
    }

    irqVector = vector >>> 0;
  };

  /**
   * Get interrupt pin of current device
   */
  this.interruptPin = function __interruptPin() {
    if (isBridge) {
      throw new Error('device is a bridge');
    }

    return pciAccessor.read(pciAccessor.generalFields().INTERRUPT_PIN);
  };

  /**
   * Get the class data of current device (class code, subclass,
   * class name)
   */
  this.classData = function __classData() {
    var classCode = pciAccessor.read(pciAccessor.fields().CLASS_CODE);
    var subclass = pciAccessor.read(pciAccessor.fields().SUBCLASS);
    var className = codeNameResolver.classCodeToName(classCode);

    return {
      classCode: classCode,
      className: className,
      subclass: subclass,
    };
  };

  this.subsystemData = function __subsystemData() {
    if (isBridge) {
      throw new Error('device is a bridge');
    }

    return {
      subsystemId: pciAccessor.read(pciAccessor.generalFields().SUBSYS_ID),
      subsystemVendor: pciAccessor.read(pciAccessor.generalFields().SUBSYS_VENDOR),
    };
  };

  /**
   * Read PCI base address register (BAR) and return resource type,
   * offset, size and object. Returns null is BAR is not valid
   */
  this.getBAR = function __getBAR(index) {
    if (isBridge) {
      throw new Error('device is a bridge');
    }

    var indexValue = index >>> 0;
    if (indexValue > 5) {
      throw new Error('invalid BAR register index (expected 0-5)');
    }

    var barFlag = {
      BAR_IO: 0x01,
      BAR_64: 0x04,
    };

    var barField = pciAccessor.generalFields().BAR[indexValue];
    var barAddr = pciAccessor.read(barField);
    if (!barAddr) {
      return null;
    }

    pciAccessor.write(barField, 0xffffffff);
    var barSize = pciAccessor.read(barField);

    // Restore original value
    pciAccessor.write(barField, barAddr >>> 0);

    if (!barSize) {
      return null;
    }

    var base = 0;
    var size = 0;
    var barType = null;
    var obj = null;

    if (barAddr & barFlag.BAR_64) {
      // TODO: 64bit bar support
      barType = 'mem64';

    } else if (barAddr & barFlag.BAR_IO) {
      // TODO: verify io base & size
      base = ((barAddr & ~0x3) & 0xffff) >>> 0;
      size = ((~(barSize & ~0x3) + 1) & 0xffff) >>> 0;
      barType = 'io';
      if (0 === size) {
        return null;
      }

      obj = io.subrange(base, base + size - 1);
    } else {
      base = (barAddr & 0xfffffff0) >>> 0;
      size = (((~(barSize & 0xfffffff0) >>> 0) + 1) & 0xffffffff) >>> 0;

      if (0 === size) {
        return null;
      }

      barType = 'mem32';
      obj = memrange.block(base, size);
    }

    if (null === barType || null === obj) {
      return null;
    }

    return {
      type: barType,
      base: base,
      size: size,
      resource: obj,
    };
  };
}

/**
 * PCI configuration space command register flags
 */
PciDevice.commandFlags = {
  IOSpace: 0,
  MemorySpace: 1,
  BusMaster: 2,
  SpecialCycles: 3,
  MemoryWriteInvalidate: 4,
  VGAPaletteSnoop: 5,
  ParityError: 6,
  SERR: 8,
  BackToBack: 9,
  InterruptDisable: 10,
};

/**
 * Manages PCI devices
 */
var pciManager = (function() {
  var devicesMap = new Map();

  function addressHash(address) {
    return JSON.stringify([address.bus, address.slot, address.func]);
  }

  function findDevice(address) {
    var key = addressHash(address);

    if (!devicesMap.has(key)) {
      return null;
    }

    return devicesMap.get(key);
  }

  return {
    /**
     * Add new PCI device using its address (bus, slot and function) and
     * PCI configuration space accessor
     */
    addDevice: function(address, pciAccessor) {
      var key = addressHash(address);

      if (devicesMap.has(key)) {
        throw new Error('device on the same address already exists' +
          JSON.stringify(address));
      }

      devicesMap.set(key, new PciDevice(address, pciAccessor));
    },
    /**
     * Search for an existing device by its address
     */
    findDevice: findDevice,
    /**
     * Iterates over all devices
     */
    each: function(fn) {
      devicesMap.forEach(function(pciDevice) {
        fn(pciDevice);
      });
    },
  };
})();

// Enumerate configuration space and create PCI devices
pciSpace.eachDevice(function(address, pciAccessor) {
  pciManager.addDevice(address, pciAccessor);
});

// Collect bus ACPI device handles with their bus numbers
var acpiDevicesBuses = [];
acpiDevices.forEach(function(acpiDevice) {
  var address = locateAcpiDevice(acpiDevice);

  if (acpiDevice.isRootBridge()) {
    var busId = acpiDevice.getRootBridgeBusNumber();
    acpiDevicesBuses[busId] = acpiDevice;
  }

  // Check if unable to locate ACPI device on PCI bus
  if (null === address) {
    return;
  }

  var dev = pciManager.findDevice(address);

  // Check if unable to find device described in ACPI tables
  if (null === dev) {
    return;
  }

  dev.attachAcpiDevice(acpiDevice);

  if (dev.isBridge()) {
    var busId = dev.getSecondaryBus();
    acpiDevicesBuses[busId] = acpiDevice;
  }
});

// Extract IRQ routing information
var busRouting = [];
acpiDevicesBuses.forEach(function(acpiDevice, bus) {
  if ('undefined' === typeof acpiDevice) {
    return;
  }

  var routes = acpiDevice.getIrqRoutingTable();
  if (!Array.isArray(routes)) {
    return;
  }

  busRouting[bus] = routes;
});

// Set IRQs
pciManager.each(function(pciDevice) {
  var address = pciDevice.address();

  // Skip bridges for now
  if (pciDevice.isBridge()) {
    return;
  }

  if ('undefined' === typeof busRouting[address.bus]) {
    // No ACPI routing for this current device bridge
    return;
  }

  var routing = busRouting[address.bus];
  var devicePin = pciDevice.interruptPin();
  var deviceIRQ = null;

  // Check if this device does not use an IRQ pin
  if (0 === devicePin) {
    return;
  }

  routing.forEach(function(route) {
    if (address.slot !== route.deviceId) {
      return;
    }

    // Plus 1 because routing data returns 0-base pin
    // numbers (0-A, 1-B, 2-C, 3-D)
    // PCI configuration space returns pins in format
    // (0-don't use, 1-A, 2-B, 3-C, 4-D)
    if (devicePin !== route.pin + 1) {
      return;
    }

    deviceIRQ = route.irq;
  });

  if (null !== deviceIRQ) {
    pciDevice.setIRQVector(deviceIRQ);
  }
});

// Start drivers
pciManager.each(function(pciDevice) {
  var vendorId = pciDevice.vendorId();
  var deviceId = pciDevice.deviceId();
  var driverData = pciDrivers.findDevice(vendorId, deviceId);

  if (null === driverData || 'undefined' === typeof driverData.driver ||
     !driverData.enabled) {
    return;
  }

  var irqVector = pciDevice.getIRQVector();
  var irqObject = null;
  if (null !== irqVector) {
    irqObject = irqRange.irq(irqVector);
  }

  var argsBars = [];
  for (var i = 0; i < 6; ++i) {
    var bar = pciDevice.getBAR(i);
    var barData = null;

    if (null !== bar) {
      barData = {
        type: bar.type,
        resource: bar.resource,
      };
    }

    argsBars.push(barData);
  }

  if (driverData.busMaster) {
    pciDevice.setCommandFlag(PciDevice.commandFlags.BusMaster);
    pciDevice.setCommandFlag(PciDevice.commandFlags.MemorySpace);
  }

  var driverArgs = {
    pci: {
      bars: argsBars,
      irq: irqObject,
      classData: pciDevice.classData(),
      subsystemData: pciDevice.subsystemData(),
    },
    allocator: allocator,
  };

  require('driver/' + driverData.driver)(driverArgs);

  // Debug
  // isolate.log(JSON.stringify(driverData), JSON.stringify(argsBars));

  // vfs.getInitrdRoot()({
  //   action: 'spawn',
  //   path: '/driver/' + driverData.driver,
  //   data: driverArgs,
  //   env: {}
  // }).then(function() {}, function(err) {
  //   isolate.log(err);
  // });
});

// Print PCI devices debug info
pciManager.each(function(pciDevice) {
  var address = pciDevice.address();
  var vector = pciDevice.getIRQVector();
  var classData = pciDevice.classData();

  var devicePin = 0;
  if (!pciDevice.isBridge()) {
    devicePin = pciDevice.interruptPin();
  }

  var pins = ['dont use', 'A', 'B', 'C', 'D'];

  var info = address.bus.toString(16) + ':' + address.slot.toString(16) + '.' + address.func + ' ' +
    pciDevice.vendorId().toString(16) + ':' + pciDevice.deviceId().toString(16) + ' ' +
    classData.className + ' IRQ: ' + vector + ' PIN: ' + pins[devicePin];
  isolate.log(info);
});

function listPciDevices() {
  var results = [];

  pciManager.each(function(pciDevice) {
    var address = pciDevice.address();
    var vector = pciDevice.getIRQVector();
    var classData = pciDevice.classData();

    var devicePin = 0;
    if (!pciDevice.isBridge()) {
      devicePin = pciDevice.interruptPin();
    }

    var pins = [null, 'A', 'B', 'C', 'D'];

    results.push({
      bus: address.bus,
      slot: address.slot,
      func: address.func,
      vendorId: pciDevice.vendorId(),
      deviceId: pciDevice.deviceId(),
      className: classData.className,
      irq: vector,
      pin: pins[devicePin],
    });
  });

  return results;
}

// Expose lspci function to applications
vfs.setKernelValue('lspci', listPciDevices);

module.exports = {
  /*
   * List PCI devices
   */
  lspci: listPciDevices,
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using DTcms.DBUtility;
using DTcms.Common;

namespace DTcms.DAL
{
    /// <summary>
    /// 数据访问类:支付方式
    /// </summary>
    public partial class payment
    {
        private string databaseprefix; //数据库表名前缀
        public payment(string _databaseprefix)
        {
            databaseprefix = _databaseprefix;
        }

        #region 基本方法============================
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from " + databaseprefix + "payment");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)};
            parameters[0].Value = id;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Model.payment model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into " + databaseprefix + "payment(");
            strSql.Append("title,img_url,remark,type,poundage_type,poundage_amount,sort_id,is_mobile,is_lock,api_path)");
            strSql.Append(" values (");
            strSql.Append("@title,@img_url,@remark,@type,@poundage_type,@poundage_amount,@sort_id,@is_mobile,@is_lock,@api_path)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@title", SqlDbType.NVarChar,100),
					new SqlParameter("@img_url", SqlDbType.NVarChar,255),
					new SqlParameter("@remark", SqlDbType.NVarChar,500),
					new SqlParameter("@type", SqlDbType.TinyInt,1),
					new SqlParameter("@poundage_type", SqlDbType.TinyInt,1),
					new SqlParameter("@poundage_amount", SqlDbType.Decimal,5),
					new SqlParameter("@sort_id", SqlDbType.Int,4),
					new SqlParameter("@is_mobile", SqlDbType.TinyInt,1),
					new SqlParameter("@is_lock", SqlDbType.TinyInt,1),
					new SqlParameter("@api_path", SqlDbType.NVarChar,100)};
            parameters[0].Value = model.title;
            parameters[1].Value = model.img_url;
            parameters[2].Value = model.remark;
            parameters[3].Value = model.type;
            parameters[4].Value = model.poundage_type;
            parameters[5].Value = model.poundage_amount;
            parameters[6].Value = model.sort_id;
            parameters[7].Value = model.is_mobile;
            parameters[8].Value = model.is_lock;
            parameters[9].Value = model.api_path;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.payment model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + databaseprefix + "payment set ");
            strSql.Append("title=@title,");
            strSql.Append("img_url=@img_url,");
            strSql.Append("remark=@remark,");
            strSql.Append("type=@type,");
            strSql.Append("poundage_type=@poundage_type,");
            strSql.Append("poundage_amount=@poundage_amount,");
            strSql.Append("sort_id=@sort_id,");
            strSql.Append("is_mobile=@is_mobile,");
            strSql.Append("is_lock=@is_lock,");
            strSql.Append("api_path=@api_path");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@title", SqlDbType.NVarChar,100),
					new SqlParameter("@img_url", SqlDbType.NVarChar,255),
					new SqlParameter("@remark", SqlDbType.NVarChar,500),
					new SqlParameter("@type", SqlDbType.TinyInt,1),
					new SqlParameter("@poundage_type", SqlDbType.TinyInt,1),
					new SqlParameter("@poundage_amount", SqlDbType.Decimal,5),
					new SqlParameter("@sort_id", SqlDbType.Int,4),
					new SqlParameter("@is_mobile", SqlDbType.TinyInt,1),
					new SqlParameter("@is_lock", SqlDbType.TinyInt,1),
					new SqlParameter("@api_path", SqlDbType.NVarChar,100),
					new SqlParameter("@id", SqlDbType.Int,4)};
            parameters[0].Value = model.title;
            parameters[1].Value = model.img_url;
            parameters[2].Value = model.remark;
            parameters[3].Value = model.type;
            parameters[4].Value = model.poundage_type;
            parameters[5].Value = model.poundage_amount;
            parameters[6].Value = model.sort_id;
            parameters[7].Value = model.is_mobile;
            parameters[8].Value = model.is_lock;
            parameters[9].Value = model.api_path;
            parameters[10].Value = model.id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from " + databaseprefix + "payment ");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)};
            parameters[0].Value = id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.payment GetModel(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 1 id,title,img_url,remark,type,poundage_type,poundage_amount,sort_id,is_mobile,is_lock,api_path");
            strSql.Append(" from " + databaseprefix + "payment");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)};
            parameters[0].Value = id;

            Model.payment model = new Model.payment();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select id,title,img_url,remark,type,poundage_type,poundage_amount,sort_id,is_mobile,is_lock,api_path ");
            strSql.Append(" FROM " + databaseprefix + "payment ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by sort_id asc,id desc");
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" id,title,img_url,remark,type,poundage_type,poundage_amount,sort_id,is_mobile,is_lock,api_path ");
            strSql.Append(" FROM " + databaseprefix + "payment ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }
        #endregion

        #region 扩展方法============================
        /// <summary>
        /// 返回标题名称
        /// </summary>
        public string GetTitle(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 1 title from " + databaseprefix + "payment");
            strSql.Append(" where id=" + id);
            string title = Convert.ToString(DbHelperSQL.GetSingle(strSql.ToString()));
            if (string.IsNullOrEmpty(title))
            {
                return "-";
            }
            return title;
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public void UpdateField(int id, string strValue)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + databaseprefix + "payment set " + strValue);
            strSql.Append(" where id=" + id);
            DbHelperSQL.ExecuteSql(strSql.ToString());
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.payment DataRowToModel(DataRow row)
        {
            Model.payment model = new Model.payment();
            if (row != null)
            {
                if (row["id"] != null && row["id"].ToString() != "")
                {
                    model.id = int.Parse(row["id"].ToString());
                }
                if (row["title"] != null)
                {
                    model.title = row["title"].ToString();
                }
                if (row["img_url"] != null)
                {
                    model.img_url = row["img_url"].ToString();
                }
                if (row["remark"] != null)
                {
                    model.remark = row["remark"].ToString();
                }
                if (row["type"] != null && row["type"].ToString() != "")
                {
                    model.type = int.Parse(row["type"].ToString());
                }
                if (row["poundage_type"] != null && row["poundage_type"].ToString() != "")
                {
                    model.poundage_type = int.Parse(row["poundage_type"].ToString());
                }
                if (row["poundage_amount"] != null && row["poundage_amount"].ToString() != "")
                {
                    model.poundage_amount = decimal.Parse(row["poundage_amount"].ToString());
                }
                if (row["sort_id"] != null && row["sort_id"].ToString() != "")
                {
                    model.sort_id = int.Parse(row["sort_id"].ToString());
                }
                if (row["is_mobile"] != null && row["is_mobile"].ToString() != "")
                {
                    model.is_mobile = int.Parse(row["is_mobile"].ToString());
                }
                if (row["is_lock"] != null && row["is_lock"].ToString() != "")
                {
                    model.is_lock = int.Parse(row["is_lock"].ToString());
                }
                if (row["api_path"] != null)
                {
                    model.api_path = row["api_path"].ToString();
                }
            }
            return model;
        }
        #endregion
    }
}


text:
using J2N.Text;
using Lucene.Net.QueryParsers.Flexible.Core.Parser;
using System.Text;

namespace Lucene.Net.QueryParsers.Flexible.Core.Nodes
{

    /// <summary>
    /// A <see cref="FuzzyQueryNode"/> represents a element that contains
    /// field/text/similarity tuple
    /// </summary>
    public class FuzzyQueryNode : FieldQueryNode
    {
        private float similarity;

        private int prefixLength;

        /// <summary>
        ///
        /// </summary>
        /// <param name="field">Name of the field query will use.</param>
        /// <param name="term">Term token to use for building term for the query</param>
        /// <param name="minSimilarity">similarity value</param>
        /// <param name="begin">position in the query string</param>
        /// <param name="end">position in the query string</param>
         // LUCENENET specific overload for string term
        public FuzzyQueryNode(string field, string term,
            float minSimilarity, int begin, int end)
            : this(field, term.AsCharSequence(), minSimilarity, begin, end)
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="field">Name of the field query will use.</param>
        /// <param name="term">Term token to use for building term for the query</param>
        /// <param name="minSimilarity">similarity value</param>
        /// <param name="begin">position in the query string</param>
        /// <param name="end">position in the query string</param>
         // LUCENENET specific overload for StringBuilder term
        public FuzzyQueryNode(string field, StringBuilder term,
            float minSimilarity, int begin, int end)
            : this(field, term.AsCharSequence(), minSimilarity, begin, end)
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="field">Name of the field query will use.</param>
        /// <param name="term">Term token to use for building term for the query</param>
        /// <param name="minSimilarity">similarity value</param>
        /// <param name="begin">position in the query string</param>
        /// <param name="end">position in the query string</param>
        public FuzzyQueryNode(string field, ICharSequence term,
            float minSimilarity, int begin, int end)
            : base(field, term, begin, end)
        {
            this.similarity = minSimilarity;
            IsLeaf = true;
        }

        public virtual int PrefixLength
        {
            get => this.prefixLength;
            set => this.prefixLength = value;
        }

        public override string ToQueryString(IEscapeQuerySyntax escaper)
        {
            if (IsDefaultField(this.m_field))
            {
                return GetTermEscaped(escaper) + "~" + this.similarity;
            }
            else
            {
                return this.m_field + ":" + GetTermEscaped(escaper) + "~" + this.similarity;
            }
        }

        public override string ToString()
        {
            return "<fuzzy field='" + this.m_field + "' similarity='" + this.similarity
                + "' term='" + this.m_text + "'/>";
        }

        /// <summary>
        /// Gets or Sets the similarity
        /// </summary>
        public virtual float Similarity
        {
            get => this.similarity;
            set => this.similarity = value;
        }

        public override IQueryNode CloneTree()
        {
            FuzzyQueryNode clone = (FuzzyQueryNode)base.CloneTree();

            clone.similarity = this.similarity;

            return clone;
        }
    }
}


text:
from chat.tests.common import *

from chat.models import Message
from chat.utils import datetime_to_timestamp, timestamp_to_datetime

def create_message(message_content, timestamp, username, channel, message_type):
    """
    Creates a message with the given text, datetime,
    username, channel and with typing set to True.
    """
    return Message.objects.create(
        message_content=message_content,
        datetime_start=timestamp_to_datetime(timestamp),
        username=username,
        typing=True,
        channel=channel,
        message_type=message_type
    )


text:
<h:html xmlns="http://www.w3.org/2002/xforms"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:ev="http://www.w3.org/2001/xml-events"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:jr="http://openrosa.org/javarosa">
{% load template_tags %}
<h:head>
<h:title>
  {{survey.name}} - {{ allocation.allocation_ea.name }}
</h:title>
  <model>
  <instance>
   <survey id="alloc-{{ allocation.pk }}" >
     <meta>
       <instanceID />
       <instanceName />
     </meta>
	 <type>S</type>
    <household>
        <houseNumber />
		{% if not survey.has_sampling %}
			<physicalAddress />
		{% endif %}
		<householdMember>
            <surname />
            <firstName />
            <sex />
            <age />
            <isHead>0</isHead>
        </householdMember>
    </household>
	{% for batch in survey_batches %}

	   		{% for question in batch.survey_questions %}
	           {% if question in loop_starters %}
	   			  <q{{question.loop_boundary.0}}q{{question.loop_boundary.1}}>
	           {% endif %}
					<q{{ question.pk }} />
	   			{% if question in loop_enders %}
	   			  </q{{question.loop_boundary.0}}q{{question.loop_boundary.1}}>
	           {% endif %}
			{% endfor %}

	{% endfor %}
   </survey>
  </instance>

  <bind nodeset="/survey/meta/instanceID" type="string"
           readonly="true()" calculate="concat('uuid:',uuid())" />
  <bind nodeset="/survey/meta/instanceName" type="string"
           readonly="true()" calculate="concat(/survey/household/houseNumber, ' ', /survey/household/householdMember/surname, '_', /survey/household/householdMember/firstName)" />
  <bind nodeset="/survey/household/houseNumber" type="{%if survey.has_sampling %}select1{% else %}int{% endif %}"  required="true()" />
  <bind nodeset="/survey/household/householdMember/surname" type="string"  required="true()" />
  <bind nodeset="/survey/household/householdMember/firstName" type="string"  required="true()"  />
{% if not survey.has_sampling %}
  <bind nodeset="/survey/household/householdMember/physicalAddress" type="string"  required="true()"  />
{% endif %}
  <bind nodeset="/survey/household/householdMember/sex" type="select1"  required="true()" />
  <bind nodeset="/survey/household/householdMember/age" type="int" required="true()" constraint=". >= 0 and . <= 150 "/>
  <bind nodeset="/survey/household/householdMember/isHead" type="select1" required="true()" />

	{% for batch in survey_batches  %}
		{% for question in batch.survey_questions %}
		{% get_question_path question loop_boundaries as question_path %}
		{% is_relevant_odk question interviewer registered_households loop_boundaries as relevance_context %}
	        {% if question in loop_starters %}
			<bind nodeset="/survey/b{{batch.pk}}/q{{question.loop_boundary.0}}q{{question.loop_boundary.1}}" relevant="{{ relevance_context }}" />
			{% endif %}
			<bind nodeset="{{ question_path }}"
				type="{% if question.answer_type == answer_types.numericalanswer %}int{% elif question.answer_type == answer_types.multichoiceanswer %}select1{% elif question.answer_type == answer_types.multiselectanswer %}select{% elif question.answer_type == answer_types.dateanswer %}date{% elif question.answer_type == answer_types.audioanswer or answer_type == answer_types.imageanswer or answer_type == answer_types.videoanswer %}binary{% elif question.answer_type == answer_types.geopointanswer %}geopoint{% else %}string{% endif %}"
				required="true()"
				relevant="{{ relevance_context }}"/>

		{% endfor %}
	{% endfor %}

  </model>
</h:head>
<h:body>
    <group>
        Household details

		{% if survey.has_sampling %}
			<select1 ref="/survey/household/houseNumber">
		         Select Household
		         {% for r_household in registered_households %}
				    <item>
						HH-{{r_household.house_number}}{% if r_household.head_desc %}-{{r_household.head_desc}}{% endif %}
	               		<value>{{r_household.house_number}}</value>
		            </item>
		         {% endfor %}
		    </select1>
		{% else %}
       <input ref="/survey/household/houseNumber">
			Enter household number
		</input>
		<input ref="/survey/household/physicalAddress">
			Enter the Physical Address
			<hint>Skip if already assigned for this household</hint>
		</input>
		{% endif %}
    <group>
        Household Member Details
			<select1 ref="/survey/household/householdMember/isHead">
				Is this the main respondent of this household?
                <hint>Skip if already assigned for this household</hint>
				<item>
					 Yes
					<value>1</value>
				</item>
				<item>
					 No
					<value>0</value>
				</item>
			</select1>
		<input ref="/survey/household/householdMember/surname">
						Enter Surname
					</input>
		<input ref="/survey/household/householdMember/firstName">
						Enter Firstname
					</input>
        	<select1 ref="/survey/household/householdMember/sex">
				Enter sex
				<item>
					 Male
					<value>1</value>
				</item>
				<item>
					 Female
					<value>0</value>
				</item>
			</select1>
        <input ref="/survey/household/householdMember/age" >
						Enter the Age
					</input>
		</group>
    </group>
	{% for batch in survey_batches %}
		<group>
			{{ batch.name }}
			<hint>{{ batch.description }}</hint>
			{% for question in batch.survey_questions %}
				{% get_question_path question loop_boundaries as question_path %}
				{% if question in loop_starters %}
				<group>
					{{question.text}}
			     	<repeat nodeset="/survey/b{{batch.pk}}/q{{question.loop_boundary.0}}q{{question.loop_boundary.1}}">
			    {% endif %}
				{% get_odk_mem_question question as member_question %}
				{% if question.answer_type == answer_types.multichoiceanswer %}
					<select1 ref="{{ question_path }}">
						{{member_question}}
						{% for option in question.options.all %}
						<item>
							{{ option.text }}
							<value>{{ option.order }}</value>
						</item>
						{% endfor %}
					</select1>
				{% elif question.answer_type == answer_types.multiselectanswer %}
					<select ref="{{ question_path }}">
						{{member_question}}
						{% for option in question.options.all %}
						<item>
							{{ option.text }}
							<value>{{ option.text|trim }}</value>
						</item>
						{% endfor %}
					</select>
				{% elif question.answer_type == answer_types.imageanswer %}
					<upload ref="{{ question_path }}"   appearance="annotate" mediatype="image/*">
						{{member_question}}
					</upload>
				{% elif question.answer_type == answer_types.audioanswer %}
					<upload ref="{{ question_path }}"   mediatype="audio/*">
						{{member_question}}
					</upload>
				{% elif question.answer_type == answer_types.videoanswer %}
					<upload ref="{{ question_path }}" mediatype="video/*">
						{{member_question}}
					</upload>
                {% elif question.answer_type == answer_types.dateanswer %}
				<input ref="{{ question_path }}" appearance="no-calendar">
					{{member_question}}
				</input>
				{% else %}
				<input ref="{{ question_path }}">
					{{member_question}}
				</input>
				{% endif %}
				{% if question in loop_enders %}
				 </repeat>
				</group>
				{% endif %}
			{% endfor %}
		</group>
	{% endfor %}

</h:body>
</h:html>


text:
SELECT
  pivot.PatientID,
  pivot.BodyPartExamined,
  pivot.SeriesInstanceUID,
  pivot.SliceThickness,
  pivot.SeriesNumber,
  pivot.SeriesDescription,
  pivot.StudyInstanceUID,
  pivot.StudyDescription,
  pivot.StudyDate,
  pivot.SOPInstanceUID,
  pivot.Modality,
  pivot.SOPClassUID,
  pivot.collection_id,
  Internal_structure,
  Sphericity,
  Calcification,
  Lobular_Pattern,
  Spiculation,
  Margin,
  Texture,
  Subtlety_score,
  Malignancy,
  SUVbw,
  Volume,
  Diameter,
  Surface_area_of_mesh, Total_Lesion_Glycolysis,
  Standardized_Added_Metabolic_Activity,
  Percent_Within_First_Quarter_of_Intensity_Range,
  Percent_Within_Third_Quarter_of_Intensity_Range,
  Percent_Within_Fourth_Quarter_of_Intensity_Range,
  Percent_Within_Second_Quarter_of_Intensity_Range,
  Standardized_Added_Metabolic_Activity_Background,
  Glycolysis_Within_First_Quarter_of_Intensity_Range,
  Glycolysis_Within_Third_Quarter_of_Intensity_Range,
  Glycolysis_Within_Fourth_Quarter_of_Intensity_Range,
  Glycolysis_Within_Second_Quarter_of_Intensity_Range,
  pivot.AnatomicRegionSequence,
  SegmentedPropertyCategoryCodeSequence,
  SegmentedPropertyTypeCodeSequence,
  pivot.FrameOfReferenceUID,
  SegmentNumber,
  SegmentAlgorithmType,
  pivot.crdc_study_uuid,
  pivot.crdc_series_uuid,
  pivot.crdc_instance_uuid,
  Program,
  pivot.tcia_tumorLocation,
  pivot.source_DOI,
  gcs_url,
  pivot.tcia_species
FROM `PROJECT.DATASET.dicom_derived_all` pivot
JOIN `PROJECT.DATASET.dicom_all` dicom_all
ON pivot.SOPInstanceUID = dicom_all.SOPInstanceUID


text:
<?php
   session_start();
   if(isset($_SESSION['id_usuario'])) header('Location: ./user.php');
?>

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>Project Fest</title>
   <meta content="width=device-width, initial-scale=1.0" name="viewport">
   <meta content="" name="keywords">
   <meta content="" name="description">

   <link href="favicon.ico" rel="shortcut icon">

   <link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,700,700i" rel="stylesheet">
   <link href="public/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
   <link href="public/lib/font-awesome/css/font-awesome.min.css" rel="stylesheet">

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

         <video autoplay="true" loop="true" muted>
	 <source src="public/vid/bg.mp4">
	 <source src="public/vid/bg.m4v">
	 <source src="public/vid/bg.webm">
	 </video>

               <audio hidden="true" src="public/vid/song.mp3" controls id="audio" autoplay></audio>

Bienvenido a Project Fest

Registrate y obtén acceso a todas las fiestas del momento

               Iniciar Sesión

   <?php include(__DIR__ . '/public/views/header.php') ?>

INGRESAR

Iniciar Sesión

               <form role="login" name="login" action="" method="post" id="formlg">

  Usuario y/o contraseña incorrectos

                     <input type="text" name="dato" placeholder="Nombre de usuario o correo" class="form-control" required autofocus/>

                     <input type="password" name="password" placeholder="Contraseña" required class="form-control"/>

                     <input type="submit" name="iniciar" class="btn-get-started btn-lg botonlg" value="INGRESAR">

               </form>

Registrar Nueva Cuenta

               <form role="registro" name="registro" action="" method="post" id="formReg">

El correo y/o usuario ingresado ya existe

Por favor ingresa todos los datos

                     <input type="text" name="usuario" placeholder="Nombre de usuario" class="form-control" required autofocus/>

                     <input type="password" name="password" placeholder="Contraseña" required class="form-control"/>

                     <input type="text" name="nombre" placeholder="Nombre completo" class="form-control" required autofocus/>

                     <input type="email" name="correo" placeholder="Correo electrónico" class="form-control" required autofocus/>

                     <button type="submit" name="registrar" class="btn-get-started btn-lg botonReg">REGISTRARSE</button>

               </form>

   <?php include(__DIR__ . '/public/views/footer.html') ?>


text:
def get_num_days():
	days_in_year = 365
	days_in_leap_year = 366
	num_years = 100
	num_leap_years = num_years / 4
	non_leap_year_days = (num_years - num_leap_years) * days_in_year
	leap_year_days = num_leap_years * days_in_leap_year
	total_days = non_leap_year_days + leap_year_days

	return total_days

def build_day_list(total_num_days):
	day_list = []

	for i in range(0, total_num_days):
		if i % 7 == 5:
			day_list.append('Sun')
		else:
			day_list.append('x')

	return day_list

def get_sundays(day_list):
	sundays = 0

	for year in range(0, 100):
		for month in range(0, 12):
			if day_list[0] == 'Sun':
				sundays += 1
			if month == 1 and (year + 1) % 4 == 0:
				day_list = day_list[29:]
			elif month == 1:
				day_list = day_list[28:]
			elif month == 3 or month == 5 or month == 8 or month == 10:
				day_list = day_list[30:]
			else:
				day_list = day_list[31:]

	return sundays

total_num_days = get_num_days()
day_list = build_day_list(total_num_days)
num_sundays = get_sundays(day_list)
print "Total number of Sundays falling on the first of the month in the 20th century:", num_sundays


text:
//----------------------------------------------------------------------------
// ptr/common.hpp
//
// Classes and helper functions that are needed by smart and specialized
// pointers.
//
// Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)
//----------------------------------------------------------------------------
#ifndef ECUDA_PTR_COMMON_HPP
#define ECUDA_PTR_COMMON_HPP

#include "../global.hpp"

namespace ecuda {

/// \cond DEVELOPER_DOCUMENTATION
namespace detail {

// this is hacky structure that takes any pointer (const or not)
// and casts it to void* so it can be used by the deleter dispose() method
// and other places that call cudaFree
template<typename T> struct void_cast;
template<typename T> struct void_cast<const T*> { __HOST__ __DEVICE__ inline void* operator()( const T* ptr ) { return reinterpret_cast<void*>( const_cast<T*>(ptr) ); } };
template<typename T> struct void_cast           { __HOST__ __DEVICE__ inline void* operator()( T ptr        ) { return reinterpret_cast<void*>(ptr); } };

} // namespace detail
/// \endcond

///
/// \brief The default destruction policy used by smart pointers to device memory.
///
/// The CUDA API function cudaFree() is used to deallocate memory.
///
template<typename T>
struct default_device_delete {

	///
	/// \brief Constructs an ecuda::default_device_delete object.
	///
	__HOST__ __DEVICE__ default_device_delete() ECUDA__NOEXCEPT {}

	///
	/// \brief Constructs an ecuda::default_device_delete object from another one.
	///
	/// This constructor will only participate in overload resolution
	/// if U* is implicitly convertible to T*.
	///
	template<typename U> __HOST__ __DEVICE__ default_device_delete( const default_device_delete<U>& src ) ECUDA__NOEXCEPT {}

	///
	/// \brief Calls cudaFree() on a pointer.
	/// \param ptr an object or array to delete
	///
	__HOST__ __DEVICE__ inline void operator()( T* ptr ) const {
		#ifdef __CUDA_ARCH__
		//ptr = NULL;
		#else
		#ifndef __CUDACC__
		delete [] reinterpret_cast<char*>(ptr); // hacky as hell but this should be valid for most test cases
		#else
		if( ptr ) cudaFree( detail::void_cast<T*>()(ptr) );
		//if( ptr ) cudaFree(ptr);
		#endif // __CUDACC__
		#endif
	}

};

///
/// \brief The default destruction policy used by smart pointers to page-locked host memory.
///
/// The CUDA API function cudaFreeHost() is used to deallocate memory.
///
template<typename T>
struct default_host_delete {
	__HOST__ __DEVICE__ ECUDA__CONSTEXPR default_host_delete() ECUDA__NOEXCEPT {}
	template<typename U> __HOST__ __DEVICE__ default_host_delete( const default_host_delete<U>& src ) ECUDA__NOEXCEPT {}
	__HOST__ __DEVICE__ inline void operator()( T* ptr ) const {
		#ifdef __CUDA_ARCH__
		#else
		#ifndef __CUDACC__
		delete [] reinterpret_cast<char*>(ptr);
		#else
		if( ptr ) cudaFreeHost( detail::void_cast<T*>()(ptr) );
		#endif
		#endif
	}
};

} // namespace ecuda

#endif


text:
/**
 * @since 2019-04-23 05:04
 * @author vivaxy
 */

abstract class AnimalOfAbstractClasses {
  abstract eat(): void;
  abstract makeSound(): void;
  move(): void {
      console.log("roaming the earth...");
  }
}

// Non-abstract class 'DogOfAbstractClasses' does not implement inherited abstract member 'eat' from class 'AnimalOfAbstractClasses'.
class DogOfAbstractClasses extends AnimalOfAbstractClasses {
  makeSound() {
    console.log('bark');
  }
}

const dogOfAbstractClasses = new DogOfAbstractClasses();
dogOfAbstractClasses.move(); // ok
dogOfAbstractClasses.makeSound(); // ok

const animalOfAbstractClasses = new AnimalOfAbstractClasses(); // Cannot create an instance of an abstract class.


text:
require_relative '../game'
require_relative 'game_board'
require_relative 'database_manager_impl'
require_relative 'victory_conditions'

# Choose victory condition based on game options
def get_victory_condition(game_options)
	if game_options['otto_and_toot']
		Proc.new{ |b| VictoryConditions.otto_and_toot(b) }
	else
		Proc.new{ |b| VictoryConditions.connect4(b) }
	end
end

options = {}
options['player_names'] = ["Bob", "Frank"]
options['current_turn'] = 1
options['otto_and_toot'] = true
options['board'] = GameBoard.new
options['board'][1,2] = 1
a = Game.new(options, &get_victory_condition(options))
db_manager = DatabaseManagerImpl.new
b = db_manager.save_game(a)
if b == 16
	puts "yay"
end

db_manager.save_result({"Player1" => "bob", "Player2" => "frank", "Winner" => 1, "GameType" => 1})
db_manager.save_result({"Player1" => "bob", "Player2" => "frank", "Winner" => 1, "GameType" => 1})
db_manager.save_result({"Player1" => "bob", "Player2" => "cindy", "Winner" => 2, "GameType" => 1})
db_manager.save_result({"Player1" => "bob", "Player2" => "cindy", "Winner" => 0, "GameType" => 1})
db_manager.save_result({"Player1" => "bob", "Player2" => "frank", "Winner" => 1, "GameType" => 2})
db_manager.save_result({"Player1" => "bob", "Player2" => "frank", "Winner" => 1, "GameType" => 2})
db_manager.save_result({"Player1" => "bob", "Player2" => "cindy", "Winner" => 2, "GameType" => 2})
db_manager.save_result({"Player1" => "bob", "Player2" => "cindy", "Winner" => 0, "GameType" => 2})
c = db_manager.leaderboards(1)
puts c.length
c.each{ |d|
	puts d["Player"]
	puts d["Wins"]
	puts d["Losses"]
	puts d["Ties"]
}
c = db_manager.leaderboards(2)
puts c.length
c.each{ |d|
	puts d["Player"]
	puts d["Wins"]
	puts d["Losses"]
	puts d["Ties"]
}
puts db_manager.saved_game_ids


text:
const gulp = require('gulp');

// const concat = require('gulp-concat');
// const rename = require('gulp-rename');
// const uglify = require('gulp-uglify');

// const jsfiles = 'assets/vendor/mdl/scripts/**/*.js';

const child = require('child_process');
const gutil = require('gulp-util');

const browserSync = require('browser-sync').create();

const siteRoot = '_site';

// gulp.task('scripts', function () {
//   return gulp.src(jsfiles)
//   .pipe(concat('index.js'))
//   .pipe(gulp.dest('assets/js'))
//   .pipe(rename('index.min.js'))
//   .pipe(uglify())
//   .pipe(gulp.dest('assets/js'))
// });

gulp.task('jekyll', function () {
  const jekyll = child.spawn('jekyll', ['build', '--watch', 'incremental', '--drafts']);

  const jekyllLogger = function (buffer) {
    buffer.toString()
    .split(/\n/)
    .forEach(function (message) {
      gutil.log('Jekyll: ' + message);
    });
  };

  jekyll.stdout.on('data', jekyllLogger);
  jekyll.stderr.on('data', jekyllLogger);
});

gulp.task('serve', function () {
  browserSync.init({
    files: [siteRoot + '/**'],
    port: 3000,
    server: {
      baseDir: siteRoot
    }
  });
  // gulp.watch(jsfiles, ['scripts']);
});

gulp.task('default', ['jekyll', 'serve']);


text:
#include <iostream>
#include <stdlib.h>
#include <dali/public-api/dali-core.h>
#include <dali-test-suite-utils.h>

void utc_dali_angle_axis_startup(void)
{
  test_return_value = TET_UNDEF;
}

void utc_dali_angle_axis_cleanup(void)
{
  test_return_value = TET_PASS;
}

int UtcDaliAngleAxisNew01(void)
{
  TestApplication application;

  AngleAxis a;
  DALI_TEST_EQUALS(float(a.angle), 0.0f, 0.001f, TEST_LOCATION);
  DALI_TEST_EQUALS(a.axis, Vector3(0.0f, 0.0f, 0.0f), 0.001f, TEST_LOCATION);
  END_TEST;
}

int UtcDaliAngleAxisNew02(void)
{
  TestApplication application;

  Degree d(75.0f);
  AngleAxis a(d, Vector3::XAXIS);

  DALI_TEST_EQUALS(a.angle, Radian(d), 0.001f, TEST_LOCATION);
  DALI_TEST_EQUALS(a.axis, Vector3::XAXIS, 0.001f, TEST_LOCATION);
  END_TEST;
}

int UtcDaliAngleAxisNew03(void)
{
  TestApplication application;

  Radian r(Math::PI_2);
  AngleAxis a(r, Vector3::ZAXIS);

  // AngleAxis stores its angle as a degree, so should only do degree comparison.
  DALI_TEST_EQUALS(a.angle, Radian(Math::PI_2), 0.001f, TEST_LOCATION);
  DALI_TEST_EQUALS(a.axis, Vector3::ZAXIS, 0.001f, TEST_LOCATION);
  END_TEST;
}

int UtcDaliAngleAxisAssign(void)
{
  TestApplication application;

  Radian r(Math::PI_2);
  AngleAxis a(r, Vector3::ZAXIS);

  AngleAxis b = a;

  // AngleAxis stores its angle as a degree, so should only do degree comparison.
  DALI_TEST_EQUALS(b.angle, Radian(Math::PI_2), 0.001f, TEST_LOCATION);
  DALI_TEST_EQUALS(b.axis, Vector3::ZAXIS, 0.001f, TEST_LOCATION);
  END_TEST;
}

int UtcDaliAngleAxisCopy(void)
{
  TestApplication application;

  Radian r(Math::PI_2);
  AngleAxis a(r, Vector3::ZAXIS);
  AngleAxis b(a);

  // AngleAxis stores its angle as a degree, so should only do degree comparison.
  DALI_TEST_EQUALS(b.angle, Radian(Math::PI_2), 0.001f, TEST_LOCATION);
  DALI_TEST_EQUALS(b.axis, Vector3::ZAXIS, 0.001f, TEST_LOCATION);
  END_TEST;
}

int UtcDaliAngleAxisEqual(void)
{
  TestApplication application;

  Radian r(Math::PI_2);
  AngleAxis a(r, Vector3::ZAXIS);
  AngleAxis b(a);

  tet_result((a == b) ? TET_PASS : TET_FAIL);

  b.axis = Vector3::YAXIS;
  tet_result(!(a == b) ? TET_PASS : TET_FAIL);
  END_TEST;
}


text:
<?php

/** @Assertions(2) */
function testArrayMerge() {
    $options = array('foo' => 1);
    $options = array_merge($options, array(
        'foo' => 'bar',
        'enabled' => true,
    ));

    /** @type string */ $options['foo'];
    /** @type boolean */ $options['enabled'];
};

/** @Assertions(4) */
function testArrayMergeWhenNumericKeys() {
    $tupel = array_merge(array('a', 1), array(3.4, true));

    /** @type string */ $tupel[0];
    /** @type integer */ $tupel[1];
    /** @type double */ $tupel[2];
    /** @type boolean */ $tupel[3];
}

/** @Assertions(2) */
function testArrayReplace() {
    $options = array_replace(array('foo' => 1), array('foo' => 'bar', 'enabled' => true));
    /** @type string */ $options['foo'];
    /** @type boolean */ $options['enabled'];
};

/** @Assertions(4) */
function testArrayReplaceWhenNumericKeys() {
    $tupel = array_replace(array('a', 1), array(3.4, true));

    /** @type double */ $tupel[0];
    /** @type boolean */ $tupel[1];

    // The following two could be discussed. Theoretically, we could know that
    // we know all defined items, and then automatically assign the None, or
    // Unknown type when items for which we know for sure that they do not exist
    // are accessed.
    /** @type string|integer|double|boolean */ $tupel[2];
    /** @type string|integer|double|boolean */ $tupel[3];
}

/** @Assertions(5) */
function testArrayMergeRecursive() {
    $ar1 = array("color" => array("favorite" => "red"), 5);
    $ar2 = array(10.4545, "color" => array("favorite" => true, 43.432));
    $result = array_merge_recursive($ar1, $ar2);

    // Resulting Array
    // ['color' => ['favorite' => ['red', true], 43.432], 5, 10.4545]

    /** @type string */ $result['color']['favorite'][0];
    /** @type boolean */ $result['color']['favorite'][1];
    /** @type double */ $result['color'][0];
    /** @type integer */ $result[0];
    /** @type double */ $result[1];
};

/** @Assertions(4) */
function testArrayReplaceRecursive() {
    $base = array('citrus' => array("orange") , 'berries' => array("blackberry", 434), 'others' => true );
    $replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
    $replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

    $basket = array_replace_recursive($base, $replacements, $replacements2);

    /** @type string */ $basket['citrus'][0];
    /** @type string */ $basket['berries'][0];
    /** @type integer */ $basket['berries'][1];
    /** @type string */ $basket['others'];
}


text:
#ifndef CONTACTDATA_H
#define CONTACTDATA_H

#include <QMetaType>
#include <QString>
#include <QStringList>

class ContactData
{
public:
    ContactData() {}
    ContactData(const ContactData&);

    QString name;
    QString firstname;
    QString lastname;
    QString nickname;
    QString phone;
    QStringList contexts;
    QStringList subtypes;
};

Q_DECLARE_METATYPE(ContactData)

QString displayPhoneType(const ContactData & contact);

#endif // CONTACTDATA_H


text:
#pragma once
#include "library/type_context.h"
namespace lean {
/** \brief Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
    meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
    local constants and metavariables). The result is the updated environment and an expression of the form

          (c.{l_1 ... l_n} a_1 ... a_m)

    where l_i's and a_j's are the collected dependencies.

    If is_meta is none, then function also computes whether the new definition should be tagged as trusted or not.

    The updated environment is an extension of ctx.env() */
pair<environment, expr> mk_aux_definition(environment const & env, metavar_context const & mctx, local_context const & lctx,
                                          name const & c, expr const & type, expr const & value,
                                          optional<bool> const & is_meta = optional<bool>());
/** \brief Similar to mk_aux_definition, but the type of value is inferred using ctx. */
pair<environment, expr> mk_aux_definition(environment const & env, metavar_context const & mctx, local_context const & lctx,
                                          name const & c, expr const & value,
                                          optional<bool> const & is_meta = optional<bool>());
/** \brief Similar to mk_aux_definition, but creates a lemma */
pair<environment, expr> mk_aux_lemma(environment const & env, metavar_context const & mctx, local_context const & lctx,
                                     name const & c, expr const & type, expr const & value);

pair<environment, expr> abstract_nested_proofs(environment const & env, metavar_context const & mctx, local_context const & lctx, name const & base_name, expr const & e);
pair<environment, expr> abstract_nested_proofs(environment const & env, name const & base_name, expr const & e);
}


text:
import jangopath
import os

def handle():
   time = raw_input("Enter time(HH:MM:SS) : ")
   time = time.split(":")
   hour = int(time[0])
   minute = int(time[1])
   second = int(time[2])
   hour = hour*3600
   minute = minute*60
   total = hour + minute + second
   path = jangopath.MODULE_PATH + "/timer_helper.py"
   os.system("python " + path + " " + str(total) + " & " )

handle()


text:
<?php

namespace Eva\EvaOAuth\User;

use Eva\EvaOAuth\Token\AccessTokenInterface;

/**
 * Interface UserProviderInterface
 * @package Eva\EvaOAuth\User
 */
interface UserProviderInterface
{
    /**
     * @param AccessTokenInterface $token
     * @return UserInterface
     */
    public function getUser(AccessTokenInterface $token);
}


text:
package org.wikimark;

import java.io.Closeable;
import java.io.IOException;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.stream.Collectors.toList;

import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.store.*;

/**
 *
 * @author Martín Straus
 */
public class Index implements Closeable {

    @FunctionalInterface
    private static interface IndexAction {

        void execute(IndexWriter writer) throws IOException;
    }

    private final Directory directory;
    private final Analyzer analyzer;

    public Index(Set<Page> pages) throws IOException {
        directory = new RAMDirectory();
        analyzer = new StandardAnalyzer();
        indexAllPages(pages);
    }

    public void indexAllPages(final Set<Page> pages) throws IOException {
        withNewWriter((writer) -> pages.forEach((page) -> {
            try {
                writer.addDocument(page.asLuceneDocument());
            } catch (IOException ex) {
                Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
            }
        }));
    }

    public void index(final Page page) {
        withNewWriter((w) -> w.addDocument(page.asLuceneDocument()));
    }

    private void withNewWriter(IndexAction action) {
        try (IndexWriter iwriter = newIndexWriter()) {
            action.execute(iwriter);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    private IndexWriter newIndexWriter() throws IOException {
        return new IndexWriter(directory, new IndexWriterConfig(analyzer));
    }

    public List<Document> search(final String queryText, final int maxResults) throws IOException, ParseException {
        try (DirectoryReader ireader = DirectoryReader.open(directory)) {
            final IndexSearcher searcher = new IndexSearcher(ireader);
            return search(searcher, queryText, maxResults)
                .stream()
                .map((scoreDoc) -> documentForScore(searcher, scoreDoc))
                .collect(toList());
        }
    }

    private Document documentForScore(IndexSearcher searcher, ScoreDoc scoreDoc) {
        try {
            return searcher.doc(scoreDoc.doc);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    private List<ScoreDoc> search(IndexSearcher searcher, String queryText, int maxResults) throws IOException, ParseException {
        return asList(searcher.search(queryFromText(queryText), maxResults).scoreDocs);
    }

    private Query queryFromText(String queryText) throws ParseException {
        return new MultiFieldQueryParser(
            new String[]{"name", "author", "title", "keywords", "content"},
            analyzer
        ).parse(queryText);
    }

    @Override
    public void close() throws IOException {
        directory.close();
    }

    public List<Document> latest(int maxResults) throws IOException {
        try (DirectoryReader ireader = DirectoryReader.open(directory)) {
            final IndexSearcher searcher = new IndexSearcher(ireader);
            return collectDocuments(
                searcher,
                searcher.search(
                    new MatchAllDocsQuery(),
                    maxResults,
                    new Sort(SortField.FIELD_SCORE, new SortField("creationDate", SortField.Type.DOUBLE, true))
                )
            );
        }
    }

    private List<Document> collectDocuments(final IndexSearcher searcher, final TopFieldDocs foundDocs) {
        return asList(foundDocs.scoreDocs)
            .stream()
            .map((scoreDoc) -> documentForScore(searcher, scoreDoc))
            .collect(toList());
    }

}


text:
package com.jakewharton.rxbinding.widget;

import android.app.Instrumentation;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.widget.SeekBar;
import com.jakewharton.rxbinding.RecordingObserver;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
import static com.google.common.truth.Truth.assertThat;
import static com.jakewharton.rxbinding.MotionEventUtil.motionEventAtPosition;

@RunWith(AndroidJUnit4.class)
public final class RxSeekBarTest {
  @Rule public final ActivityTestRule<RxSeekBarTestActivity> activityRule =
      new ActivityTestRule<>(RxSeekBarTestActivity.class);

  private final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

  private SeekBar seekBar;

  @Before public void setUp() {
    seekBar = activityRule.getActivity().seekBar;
  }

  @Test public void changes() {
    RecordingObserver<Integer> o = new RecordingObserver<>();
    Subscription subscription = RxSeekBar.changes(seekBar) //
        .subscribeOn(AndroidSchedulers.mainThread()) //
        .subscribe(o);
    assertThat(o.takeNext()).isEqualTo(0);

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(100);

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 0, 50));
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(0);

    subscription.unsubscribe();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }

  @Test public void changeEvents() {
    RecordingObserver<SeekBarChangeEvent> o = new RecordingObserver<>();
    Subscription subscription = RxSeekBar.changeEvents(seekBar) //
        .subscribeOn(AndroidSchedulers.mainThread()) //
        .subscribe(o);
    assertThat(o.takeNext()).isEqualTo(SeekBarProgressChangeEvent.create(seekBar, 0, false));

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(SeekBarStartChangeEvent.create(seekBar));

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(SeekBarProgressChangeEvent.create(seekBar, 100, true));

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_UP, 100, 50));
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(SeekBarStopChangeEvent.create(seekBar));

    instrumentation.runOnMainSync(new Runnable() {
      @Override public void run() {
        seekBar.setProgress(0);
      }
    });
    instrumentation.waitForIdleSync();
    assertThat(o.takeNext()).isEqualTo(SeekBarProgressChangeEvent.create(seekBar, 0, false));

    subscription.unsubscribe();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }
}


text:
package com.in28minutes.mockito;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class ListTest {

	private List<String> list;

	@Before
	public void before() {
		this.list = mock(List.class);
	}

	@Test
	public void letsMockListSize() {
		when(list.size()).thenReturn(10);
		assertEquals(10, list.size());
	}

	@Test
	public void letsMockListSizeWithMultipleReturnValues() {
		when(list.size()).thenReturn(10).thenReturn(20);
		assertEquals(10, list.size()); // First Call
		assertEquals(20, list.size()); // Second Call
	}

	@Test
	public void letsMockListGet() {
		when(list.get(0)).thenReturn("in28Minutes");
		assertEquals("in28Minutes", list.get(0));
		assertNull(list.get(1));
	}

	@Test(expected = RuntimeException.class)
	public void letsMockListGetToThrowException() {
		when(list.get(Mockito.anyInt())).thenThrow(new RuntimeException("Something went wrong"));
		list.get(0);
	}

	@Test
	public void letsMockListGetWithAny() {
		Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes");
		// If you are using argument matchers, all arguments
		// have to be provided by matchers.
		assertEquals("in28Minutes", list.get(0));
		assertEquals("in28Minutes", list.get(1));
	}

	@Test
	public void bddAliases_UsingGivenWillReturn() {
		// given
		given(list.get(Mockito.anyInt())).willReturn("in28Minutes");

		// then
		assertThat("in28Minutes", is(list.get(0)));
		assertThat("in28Minutes", is(list.get(0)));
	}
}


text:
<?php

require __DIR__ . "/../vendor/autoload.php";

// The output will be:
//
// I will live forever!!!
// I will live forever!!!
// I will live forever!!!
// ...
// I will live forever!!!
// I will live forever!!!
// Maybe not... :-(

$startedAt = time();
GracefulDeath::around(function() {
    echo "I will live forever!!!\n";
    // Let's pretend to do something useful :-)
    usleep(50000);
    // Avoid to print the error in order to have clean output, don't try this at home :-)
    error_reporting(E_ALL ^ E_ERROR);
    // Creating an instance of an unknown class will cause a fatal error
    new UnknownClass();
})
->reanimationPolicy(function($status, $attempts, $output) use($startedAt) {
    return (time() - $startedAt) < 5;
})
->afterViolentDeath("Maybe not... :-(\n")
->run();


text:
static inline NSString *NSStringCCHashFunction(unsigned char *(function)(const void *data, CC_LONG len, unsigned char *md), CC_LONG digestLength, NSString *string)
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[digestLength];

    function(data.bytes, (CC_LONG)data.length, digest);

    NSMutableString *output = [NSMutableString stringWithCapacity:digestLength * 2];

    for (int i = 0; i < digestLength; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }

    return output;
}

@implementation NSString (Hashes)

- (NSString *)md5
{
    return NSStringCCHashFunction(CC_MD5, CC_MD5_DIGEST_LENGTH, self);
}

- (NSString *)sha1
{
    return NSStringCCHashFunction(CC_SHA1, CC_SHA1_DIGEST_LENGTH, self);
}

- (NSString *)sha224
{
    return NSStringCCHashFunction(CC_SHA224, CC_SHA224_DIGEST_LENGTH, self);
}

- (NSString *)sha256
{
    return NSStringCCHashFunction(CC_SHA256, CC_SHA256_DIGEST_LENGTH, self);
}

- (NSString *)sha384
{
    return NSStringCCHashFunction(CC_SHA384, CC_SHA384_DIGEST_LENGTH, self);
}

- (NSString *)sha512
{
    return NSStringCCHashFunction(CC_SHA512, CC_SHA512_DIGEST_LENGTH, self);
}

@end


text:
<Dialog Name="Clip" HelpFile="Clip.html">
	<DialogComponent type="DialogFile">
		<Name>inputFile</Name>
		<Description>Enter the name of the input file to be clipped here</Description>
		<LabelText>Input Vector File:</LabelText>
		<DialogMode>Open File</DialogMode>
		<Filter>Vector Files (*.shp), SHP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
        <DialogComponent type="DialogFile">
		<Name>clipFile</Name>
		<Description>Enter the name of the input clip file here</Description>
		<LabelText>Input Clip Vector File:</LabelText>
		<DialogMode>Open File</DialogMode>
		<Filter>Vector Files (*.shp), SHP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
        <DialogComponent type="DialogFile">
		<Name>outputFile</Name>
		<Description>Enter the name of the output file here</Description>
		<LabelText>Output Vector File:</LabelText>
		<DialogMode>Save File</DialogMode>
		<Filter>Vector Files (*.shp), SHP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
</Dialog>


text:
namespace llvm {

class Pass;

/// Pass to mark all loops with llvm metadata to disable unrolling.
Pass *createSetNoUnrollPass();

}  // namespace llvm

#endif  // IREE_COMPILER_DIALECT_HAL_TARGET_CUDA_PASS_H_


text: global.order.push("k");


text:
package org.apache.carbondata.core.util;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.datastore.page.EncodedTablePage;
import org.apache.carbondata.core.datastore.page.encoding.ColumnPageEncoderMeta;
import org.apache.carbondata.core.datastore.page.encoding.EncodedColumnPage;
import org.apache.carbondata.core.datastore.page.key.TablePageKey;
import org.apache.carbondata.core.datastore.page.statistics.PrimitivePageStatsCollector;
import org.apache.carbondata.core.metadata.ValueEncoderMeta;
import org.apache.carbondata.core.metadata.index.BlockIndexInfo;
import org.apache.carbondata.format.BlockIndex;
import org.apache.carbondata.format.BlockletIndex;
import org.apache.carbondata.format.BlockletInfo;
import org.apache.carbondata.format.BlockletInfo3;
import org.apache.carbondata.format.BlockletMinMaxIndex;
import org.apache.carbondata.format.ColumnSchema;
import org.apache.carbondata.format.DataChunk;
import org.apache.carbondata.format.DataChunk2;
import org.apache.carbondata.format.DataType;
import org.apache.carbondata.format.Encoding;
import org.apache.carbondata.format.FileFooter3;
import org.apache.carbondata.format.IndexHeader;
import org.apache.carbondata.format.SegmentInfo;

import mockit.Mock;
import mockit.MockUp;
import org.junit.BeforeClass;
import org.junit.Test;

import static junit.framework.TestCase.assertEquals;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.convertFileFooterVersion3;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockIndexInfo;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockletIndex;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getIndexHeader;

public class CarbonMetadataUtilTest {
  static List<ByteBuffer> byteBufferList;
  static byte[] byteArr;
  static List<ColumnSchema> columnSchemas;
  static List<BlockletInfo> blockletInfoList;
  static List<ColumnSchema> columnSchemaList;
  static Long[] objMaxArr;
  static Long[] objMinArr;
  static int[] objDecimal;

  @BeforeClass public static void setUp() {
    objMaxArr = new Long[6];
    objMaxArr[0] = new Long("111111");
    objMaxArr[1] = new Long("121111");
    objMaxArr[2] = new Long("131111");
    objMaxArr[3] = new Long("141111");
    objMaxArr[4] = new Long("151111");
    objMaxArr[5] = new Long("161111");

    objMinArr = new Long[6];
    objMinArr[0] = new Long("119");
    objMinArr[1] = new Long("121");
    objMinArr[2] = new Long("131");
    objMinArr[3] = new Long("141");
    objMinArr[4] = new Long("151");
    objMinArr[5] = new Long("161");

    objDecimal = new int[] { 0, 0, 0, 0, 0, 0 };

    columnSchemaList = new ArrayList<>();
    List<Encoding> encodingList = new ArrayList<>();
    encodingList.add(Encoding.BIT_PACKED);
    encodingList.add(Encoding.DELTA);
    encodingList.add(Encoding.INVERTED_INDEX);
    encodingList.add(Encoding.DIRECT_DICTIONARY);

    byteArr = "412111".getBytes();
    byte[] byteArr1 = "321".getBytes();
    byte[] byteArr2 = "356".getBytes();

    byteBufferList = new ArrayList<>();
    ByteBuffer bb = ByteBuffer.allocate(byteArr.length);
    bb.put(byteArr);
    ByteBuffer bb1 = ByteBuffer.allocate(byteArr1.length);
    bb1.put(byteArr1);
    ByteBuffer bb2 = ByteBuffer.allocate(byteArr2.length);
    bb2.put(byteArr2);
    byteBufferList.add(bb);
    byteBufferList.add(bb1);
    byteBufferList.add(bb2);

    DataChunk dataChunk = new DataChunk();
    dataChunk.setEncoders(encodingList);
    dataChunk.setEncoder_meta(byteBufferList);

    List<DataChunk> dataChunkList = new ArrayList<>();
    dataChunkList.add(dataChunk);
    dataChunkList.add(dataChunk);

    BlockletInfo blockletInfo = new BlockletInfo();
    blockletInfo.setColumn_data_chunks(dataChunkList);
    blockletInfoList = new ArrayList<>();
    blockletInfoList.add(blockletInfo);
    blockletInfoList.add(blockletInfo);

    ValueEncoderMeta meta = CarbonTestUtil.createValueEncoderMeta();
    meta.setDecimal(5);
    meta.setMinValue(objMinArr);
    meta.setMaxValue(objMaxArr);
    meta.setType(ColumnPageEncoderMeta.DOUBLE_MEASURE);

    List<Encoding> encoders = new ArrayList<>();
    encoders.add(Encoding.INVERTED_INDEX);
    encoders.add(Encoding.BIT_PACKED);
    encoders.add(Encoding.DELTA);
    encoders.add(Encoding.DICTIONARY);
    encoders.add(Encoding.DIRECT_DICTIONARY);
    encoders.add(Encoding.RLE);

    ColumnSchema columnSchema = new ColumnSchema(DataType.INT, "column", "3", true, encoders, true);
    ColumnSchema columnSchema1 =
        new ColumnSchema(DataType.ARRAY, "column", "3", true, encoders, true);
    ColumnSchema columnSchema2 =
        new ColumnSchema(DataType.DECIMAL, "column", "3", true, encoders, true);
    ColumnSchema columnSchema3 =
        new ColumnSchema(DataType.DOUBLE, "column", "3", true, encoders, true);
    ColumnSchema columnSchema4 =
        new ColumnSchema(DataType.LONG, "column", "3", true, encoders, true);
    ColumnSchema columnSchema5 =
        new ColumnSchema(DataType.SHORT, "column", "3", true, encoders, true);
    ColumnSchema columnSchema6 =
        new ColumnSchema(DataType.STRUCT, "column", "3", true, encoders, true);
    ColumnSchema columnSchema7 =
        new ColumnSchema(DataType.STRING, "column", "3", true, encoders, true);
    columnSchemas = new ArrayList<>();
    columnSchemas.add(columnSchema);
    columnSchemas.add(columnSchema1);
    columnSchemas.add(columnSchema2);
    columnSchemas.add(columnSchema3);
    columnSchemas.add(columnSchema4);
    columnSchemas.add(columnSchema5);
    columnSchemas.add(columnSchema6);
    columnSchemas.add(columnSchema7);
  }

  @Test public void testGetIndexHeader() {
    int[] columnCardinality = { 1, 2, 3, 4 };
    SegmentInfo segmentInfo = new SegmentInfo();
    segmentInfo.setNum_cols(0);
    segmentInfo.setColumn_cardinalities(CarbonUtil.convertToIntegerList(columnCardinality));
    IndexHeader indexHeader = new IndexHeader();
    indexHeader.setVersion(3);
    indexHeader.setSegment_info(segmentInfo);
    indexHeader.setTable_columns(columnSchemaList);
    indexHeader.setBucket_id(0);
    IndexHeader indexheaderResult = getIndexHeader(columnCardinality, columnSchemaList, 0);
    assertEquals(indexHeader, indexheaderResult);
  }

  @Test public void testConvertFileFooter() throws Exception {
    int[] cardinality = { 1, 2, 3, 4, 5 };

    org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema =
        new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
    org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema1 =
        new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
    List<org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema>
        columnSchemaList = new ArrayList<>();
    columnSchemaList.add(colSchema);
    columnSchemaList.add(colSchema1);

    SegmentProperties segmentProperties = new SegmentProperties(columnSchemaList, cardinality);

    final EncodedColumnPage measure = new EncodedColumnPage(new DataChunk2(), new byte[]{0,1},
        PrimitivePageStatsCollector.newInstance(
        org.apache.carbondata.core.metadata.datatype.DataType.BYTE, 0, 0));
    new MockUp<EncodedTablePage>() {
      @SuppressWarnings("unused") @Mock
      public EncodedColumnPage getMeasure(int measureIndex) {
        return measure;
      }
    };

    new MockUp<TablePageKey>() {
      @SuppressWarnings("unused") @Mock
      public byte[] serializeStartKey() {
        return new byte[]{1, 2};
      }

      @SuppressWarnings("unused") @Mock
      public byte[] serializeEndKey() {
        return new byte[]{1, 2};
      }
    };

    TablePageKey key = new TablePageKey(3, null, segmentProperties, false);
    EncodedTablePage encodedTablePage = EncodedTablePage.newInstance(3, new EncodedColumnPage[0], new EncodedColumnPage[0],
        key);

    List<EncodedTablePage> encodedTablePageList = new ArrayList<>();
    encodedTablePageList.add(encodedTablePage);

    BlockletInfo3 blockletInfoColumnar1 = new BlockletInfo3();

    List<BlockletInfo3> blockletInfoColumnarList = new ArrayList<>();
    blockletInfoColumnarList.add(blockletInfoColumnar1);

    byte[] byteMaxArr = "1".getBytes();
    byte[] byteMinArr = "2".getBytes();

    BlockletIndex index = getBlockletIndex(encodedTablePageList, segmentProperties.getMeasures());
    List<BlockletIndex> indexList = new ArrayList<>();
    indexList.add(index);

    BlockletMinMaxIndex blockletMinMaxIndex = new BlockletMinMaxIndex();
    blockletMinMaxIndex.addToMax_values(ByteBuffer.wrap(byteMaxArr));
    blockletMinMaxIndex.addToMin_values(ByteBuffer.wrap(byteMinArr));
    FileFooter3 footer = convertFileFooterVersion3(blockletInfoColumnarList,
        indexList,
        cardinality, 2);
    assertEquals(footer.getBlocklet_index_list(), indexList);

  }

  @Test public void testGetBlockIndexInfo() throws Exception {
    byte[] startKey = { 1, 2, 3, 4, 5 };
    byte[] endKey = { 9, 3, 5, 5, 5 };
    byte[] byteArr = { 1, 2, 3, 4, 5 };
    List<ByteBuffer> minList = new ArrayList<>();
    minList.add(ByteBuffer.wrap(byteArr));

    byte[] byteArr1 = { 9, 9, 8, 6, 7 };
    List<ByteBuffer> maxList = new ArrayList<>();
    maxList.add(ByteBuffer.wrap(byteArr1));

    org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex
        blockletMinMaxIndex =
        new org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex(minList,
            maxList);
    org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex
        blockletBTreeIndex =
        new org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex(startKey,
            endKey);
    org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex blockletIndex =
        new org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex(
            blockletBTreeIndex, blockletMinMaxIndex);

    BlockIndexInfo blockIndexInfo = new BlockIndexInfo(1, "file", 1, blockletIndex);

    List<BlockIndexInfo> blockIndexInfoList = new ArrayList<>();
    blockIndexInfoList.add(blockIndexInfo);
    List<BlockIndex> result = getBlockIndexInfo(blockIndexInfoList);
    String expected = "file";
    assertEquals(result.get(0).file_name, expected);
  }

}