text:
package org.apache.spark.sql.test

import java.io.{File, FilenameFilter}
import java.util.ServiceLoader

import scala.collection.mutable.ArrayBuffer

import org.apache.spark.sql.{DataFrame, SQLContext}
import org.apache.spark.util.Utils

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.datastore.impl.FileFactory
import org.apache.carbondata.core.util.CarbonProperties

/**
 * the sql executor of spark
 */
trait TestQueryExecutorRegister {
  def sql(sqlText: String): DataFrame

  def stop()

  def sqlContext: SQLContext
}

object TestQueryExecutor {

  private val LOGGER = LogServiceFactory.getLogService(this.getClass.getCanonicalName)

  val (projectPath, isIntegrationModule, localTarget) = {
    val path = new File(this.getClass.getResource("/").getPath)
      .getCanonicalPath.replaceAll("\\\\", "/")
    // Check whether it is integration module
    var isIntegrationModule = path.indexOf("/integration/") > -1
    // Get the local target folder path
    val targetPath = path.substring(0, path.lastIndexOf("/target/") + 7)
    // Get the relative project path
    val projectPathLocal = if (isIntegrationModule) {
      path.substring(0, path.indexOf("/integration/"))
    } else if (path.indexOf("/mv/") > -1) {
      path.substring(0, path.indexOf("/mv/"))
    } else if (path.indexOf("/secondary-index/") > -1) {
      isIntegrationModule = true
      path.substring(0, path.indexOf("/index/"))
    } else if (path.indexOf("/index/") > -1) {
      path.substring(0, path.indexOf("/index/"))
    } else if (path.indexOf("/tools/") > -1) {
      path.substring(0, path.indexOf("/tools/"))
    } else if (path.indexOf("/examples/") > -1) {
      path.substring(0, path.indexOf("/examples/"))
    } else {
      path
    }
    (projectPathLocal, isIntegrationModule, targetPath)
  }
  LOGGER.info(s"project path: $projectPath")
  val integrationPath = s"$projectPath/integration"
  val target = if (isIntegrationModule) {
    // If integration module , always point to spark/target location
    s"$integrationPath/spark/target"
  } else {
    // Otherwise point to respective target folder location
    localTarget
  }
  val location = s"$target/dbpath"
  val masterUrl = {
    val property = System.getProperty("spark.master.url")
    if (property == null) {
      "local[2]"
    } else {
      property
    }
  }
  val hdfsUrl = {
    val property = System.getProperty("hdfs.url")
    if (property == null) {
      "local"
    } else {
      LOGGER.info("HDFS PATH given : " + property)
      property
    }
  }

  val resourcesPath = if (hdfsUrl.startsWith("hdfs://")) {
    hdfsUrl
  } else {
    s"$integrationPath/spark/src/test/resources"
  }

  val warehouse = if (hdfsUrl.startsWith("hdfs://")) {
    val carbonFile = FileFactory.getCarbonFile(s"$hdfsUrl/warehouse")
    FileFactory.deleteAllCarbonFilesOfDir(carbonFile)
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.LOCK_TYPE,
      CarbonCommonConstants.CARBON_LOCK_TYPE_HDFS)
    s"$hdfsUrl/warehouse_" + System.nanoTime()
  } else {
    CarbonProperties.getInstance().addProperty(CarbonCommonConstants.LOCK_TYPE,
      CarbonCommonConstants.CARBON_LOCK_TYPE_LOCAL)
    s"$target/warehouse"
  }

  val storeLocation = warehouse

  val badStoreLocation = if (hdfsUrl.startsWith("hdfs://")) {
       s"$hdfsUrl/bad_store_" + System.nanoTime()
      } else {
        s"$target/bad_store"
      }
  val systemFolderPath = if (hdfsUrl.startsWith("hdfs://")) {
    s"$hdfsUrl/systemfolder" + System.nanoTime()
  } else {
    s"$target/systemfolder"
  }
  createDirectory(badStoreLocation)

  val hiveresultpath = if (hdfsUrl.startsWith("hdfs://")) {
    val p = s"$hdfsUrl/hiveresultpath"
    FileFactory.mkdirs(p)
    p
  } else {
    val p = s"$target/hiveresultpath"
    new File(p).mkdirs()
    p
  }

  LOGGER.info(s"""Store path taken $storeLocation""")
  LOGGER.info(s"""Warehouse path taken $warehouse""")
  LOGGER.info(s"""Resource path taken $resourcesPath""")

  lazy val modules = Seq(TestQueryExecutor.projectPath + "/common/target",
    TestQueryExecutor.projectPath + "/core/target",
    TestQueryExecutor.projectPath + "/hadoop/target",
    TestQueryExecutor.projectPath + "/processing/target",
    TestQueryExecutor.projectPath + "/integration/spark/target",
    TestQueryExecutor.projectPath + "/integration/spark/target/jars",
    TestQueryExecutor.projectPath + "/streaming/target",
    TestQueryExecutor.projectPath + "/sdk/sdk/target")

  lazy val jars = {
    val jarsLocal = new ArrayBuffer[String]()
    modules.foreach { path =>
      val files = new File(path).listFiles(new FilenameFilter {
        override def accept(dir: File, name: String) = {
          name.endsWith(".jar")
        }
      })
      files.foreach(jarsLocal += _.getAbsolutePath)
    }
    jarsLocal
  }

  lazy val INSTANCE = lookupQueryExecutor.newInstance().asInstanceOf[TestQueryExecutorRegister]
  CarbonProperties.getInstance()
    .addProperty(CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION, "FORCE")
    .addProperty(CarbonCommonConstants.CARBON_BADRECORDS_LOC, badStoreLocation)
    .addProperty(CarbonCommonConstants.CARBON_MAX_DRIVER_LRU_CACHE_SIZE, "1024")
    .addProperty(CarbonCommonConstants.CARBON_MAX_EXECUTOR_LRU_CACHE_SIZE, "1024")
    .addProperty(CarbonCommonConstants.CARBON_SYSTEM_FOLDER_LOCATION, systemFolderPath)
    .addProperty(CarbonCommonConstants.CARBON_MINMAX_ALLOWED_BYTE_COUNT, "40")

  private def lookupQueryExecutor: Class[_] = {
    ServiceLoader.load(classOf[TestQueryExecutorRegister], Utils.getContextOrSparkClassLoader)
      .iterator().next().getClass
  }

  private def createDirectory(badStoreLocation: String) = {
    FileFactory.mkdirs(badStoreLocation)
  }
}


text:
using TodoTemplate.Server.Api.Models.TodoItem;
using TodoTemplate.Shared.Dtos.TodoItem;

namespace TodoTemplate.Server.Api.Mappers;

public class TodoItemMapperConfiguration : Profile
{
    public TodoItemMapperConfiguration()
    {
        CreateMap<TodoItem, TodoItemDto>().ReverseMap();
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation Tiger
- (id) initWithName:(NSString *)name
{
    self = [super initWithName:name];
    self->_voices = [NSMutableArray arrayWithObjects:@"Oar", @"Krrr", nil];
    return self;
}

- (void) doSomethingMoveable
{
    self->_moveable = YES; //truy xuất biến thành phần
    NSLog(@"%d", _moveable); //Nếu hàm truy xuất biến trong cùng một đối tượng

}
@end


text:
Zaboravljena lozinka

        <?php
        if ($status == 1):
            echo '

Poslali smo link za povratak lozinke na Vaš email

';
        endif;
        ?>
        <form role="form" action="<?php echo site_url(); ?>/home/attemtRecovery" method="post">

                E-mail
                <input name="email" type="email" class="form-control" id="email" placeholder="email@email.com" required/>
                <?php
                if ($status == -1):
                    echo '
E-mail ne postoji u bazi
';
                endif;
                if ($status == 1):
                    echo '
Poslali smo link za povratak lozinke na Vaš email
';
                endif;
                ?>

            <button type="submit" class="btn btn-lg btn-primary">Povrati lozinku</button>
        </form>

<img src="<?php echo base_url(); ?>img/sloth.png" class="img-responsive center-block" >


text:
from tests import TestCase

class TestInstrumentedList(TestCase):
    def test_any_returns_true_if_member_has_attr_defined(self):
        category = self.Category()
        category.articles.append(self.Article())
        category.articles.append(self.Article(name=u'some name'))
        assert category.articles.any('name')

    def test_any_returns_false_if_no_member_has_attr_defined(self):
        category = self.Category()
        category.articles.append(self.Article())
        assert not category.articles.any('name')


text:
package com.android.gallery3d.data;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.mtp.MtpDevice;
import android.mtp.MtpObjectInfo;
import android.mtp.MtpStorageInfo;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * This class helps an application manage a list of connected MTP or PTP devices.
 * It listens for MTP devices being attached and removed from the USB host bus
 * and notifies the application when the MTP device list changes.
 */
public class MtpClient {

    private static final String TAG = "MtpClient";

    private static final String ACTION_USB_PERMISSION =
            "android.mtp.MtpClient.action.USB_PERMISSION";

    private final Context mContext;
    private final UsbManager mUsbManager;
    private final ArrayList<Listener> mListeners = new ArrayList<Listener>();
    // mDevices contains all MtpDevices that have been seen by our client,
    // so we can inform when the device has been detached.
    // mDevices is also used for synchronization in this class.
    private final HashMap<String, MtpDevice> mDevices = new HashMap<String, MtpDevice>();
    // List of MTP devices we should not try to open for which we are currently
    // asking for permission to open.
    private final ArrayList<String> mRequestPermissionDevices = new ArrayList<String>();
    // List of MTP devices we should not try to open.
    // We add devices to this list if the user canceled a permission request or we were
    // unable to open the device.
    private final ArrayList<String> mIgnoredDevices = new ArrayList<String>();

    private final PendingIntent mPermissionIntent;

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            String deviceName = usbDevice.getDeviceName();

            synchronized (mDevices) {
                MtpDevice mtpDevice = mDevices.get(deviceName);

                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    if (mtpDevice == null) {
                        mtpDevice = openDeviceLocked(usbDevice);
                    }
                    if (mtpDevice != null) {
                        for (Listener listener : mListeners) {
                            listener.deviceAdded(mtpDevice);
                        }
                    }
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    if (mtpDevice != null) {
                        mDevices.remove(deviceName);
                        mRequestPermissionDevices.remove(deviceName);
                        mIgnoredDevices.remove(deviceName);
                        for (Listener listener : mListeners) {
                            listener.deviceRemoved(mtpDevice);
                        }
                    }
                } else if (ACTION_USB_PERMISSION.equals(action)) {
                    mRequestPermissionDevices.remove(deviceName);
                    boolean permission = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
                            false);
                    Log.d(TAG, "ACTION_USB_PERMISSION: " + permission);
                    if (permission) {
                        if (mtpDevice == null) {
                            mtpDevice = openDeviceLocked(usbDevice);
                        }
                        if (mtpDevice != null) {
                            for (Listener listener : mListeners) {
                                listener.deviceAdded(mtpDevice);
                            }
                        }
                    } else {
                        // so we don't ask for permission again
                        mIgnoredDevices.add(deviceName);
                    }
                }
            }
        }
    };

    /**
     * An interface for being notified when MTP or PTP devices are attached
     * or removed.  In the current implementation, only PTP devices are supported.
     */
    public interface Listener {
        /**
         * Called when a new device has been added
         *
         * @param device the new device that was added
         */
        public void deviceAdded(MtpDevice device);

        /**
         * Called when a new device has been removed
         *
         * @param device the device that was removed
         */
        public void deviceRemoved(MtpDevice device);
    }

    /**
     * Tests to see if a {@link android.hardware.usb.UsbDevice}
     * supports the PTP protocol (typically used by digital cameras)
     *
     * @param device the device to test
     * @return true if the device is a PTP device.
     */
    static public boolean isCamera(UsbDevice device) {
        int count = device.getInterfaceCount();
        for (int i = 0; i < count; i++) {
            UsbInterface intf = device.getInterface(i);
            if (intf.getInterfaceClass() == UsbConstants.USB_CLASS_STILL_IMAGE &&
                    intf.getInterfaceSubclass() == 1 &&
                    intf.getInterfaceProtocol() == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * MtpClient constructor
     *
     * @param context the {@link android.content.Context} to use for the MtpClient
     */
    public MtpClient(Context context) {
        mContext = context;
        mUsbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        context.registerReceiver(mUsbReceiver, filter);
    }

    /**
     * Opens the {@link android.hardware.usb.UsbDevice} for an MTP or PTP
     * device and return an {@link android.mtp.MtpDevice} for it.
     *
     * @param usbDevice the device to open
     * @return an MtpDevice for the device.
     */
    private MtpDevice openDeviceLocked(UsbDevice usbDevice) {
        String deviceName = usbDevice.getDeviceName();

        // don't try to open devices that we have decided to ignore
        // or are currently asking permission for
        if (isCamera(usbDevice) && !mIgnoredDevices.contains(deviceName)
                && !mRequestPermissionDevices.contains(deviceName)) {
            if (!mUsbManager.hasPermission(usbDevice)) {
                mUsbManager.requestPermission(usbDevice, mPermissionIntent);
                mRequestPermissionDevices.add(deviceName);
            } else {
                UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);
                if (connection != null) {
                    MtpDevice mtpDevice = new MtpDevice(usbDevice);
                    if (mtpDevice.open(connection)) {
                        mDevices.put(usbDevice.getDeviceName(), mtpDevice);
                        return mtpDevice;
                    } else {
                        // so we don't try to open it again
                        mIgnoredDevices.add(deviceName);
                    }
                } else {
                    // so we don't try to open it again
                    mIgnoredDevices.add(deviceName);
                }
            }
        }
        return null;
    }

    /**
     * Closes all resources related to the MtpClient object
     */
    public void close() {
        mContext.unregisterReceiver(mUsbReceiver);
    }

    /**
     * Registers a {@link com.com.android.gallery3d.data.MtpClient.Listener} interface to receive
     * notifications when MTP or PTP devices are added or removed.
     *
     * @param listener the listener to register
     */
    public void addListener(Listener listener) {
        synchronized (mDevices) {
            if (!mListeners.contains(listener)) {
                mListeners.add(listener);
            }
        }
    }

    /**
     * Unregisters a {@link com.com.android.gallery3d.data.MtpClient.Listener} interface.
     *
     * @param listener the listener to unregister
     */
    public void removeListener(Listener listener) {
        synchronized (mDevices) {
            mListeners.remove(listener);
        }
    }

    /**
     * Retrieves an {@link android.mtp.MtpDevice} object for the USB device
     * with the given name.
     *
     * @param deviceName the name of the USB device
     * @return the MtpDevice, or null if it does not exist
     */
    public MtpDevice getDevice(String deviceName) {
        synchronized (mDevices) {
            return mDevices.get(deviceName);
        }
    }

    /**
     * Retrieves an {@link android.mtp.MtpDevice} object for the USB device
     * with the given ID.
     *
     * @param id the ID of the USB device
     * @return the MtpDevice, or null if it does not exist
     */
    public MtpDevice getDevice(int id) {
        synchronized (mDevices) {
            return mDevices.get(UsbDevice.getDeviceName(id));
        }
    }

    /**
     * Retrieves a list of all currently connected {@link android.mtp.MtpDevice}.
     *
     * @return the list of MtpDevices
     */
    public List<MtpDevice> getDeviceList() {
        synchronized (mDevices) {
            // Query the USB manager since devices might have attached
            // before we added our listener.
            for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
                if (mDevices.get(usbDevice.getDeviceName()) == null) {
                    openDeviceLocked(usbDevice);
                }
            }

            return new ArrayList<MtpDevice>(mDevices.values());
        }
    }

    /**
     * Retrieves a list of all {@link android.mtp.MtpStorageInfo}
     * for the MTP or PTP device with the given USB device name
     *
     * @param deviceName the name of the USB device
     * @return the list of MtpStorageInfo
     */
    public List<MtpStorageInfo> getStorageList(String deviceName) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return null;
        }
        int[] storageIds = device.getStorageIds();
        if (storageIds == null) {
            return null;
        }

        int length = storageIds.length;
        ArrayList<MtpStorageInfo> storageList = new ArrayList<MtpStorageInfo>(length);
        for (int i = 0; i < length; i++) {
            MtpStorageInfo info = device.getStorageInfo(storageIds[i]);
            if (info == null) {
                Log.w(TAG, "getStorageInfo failed");
            } else {
                storageList.add(info);
            }
        }
        return storageList;
    }

    /**
     * Retrieves the {@link android.mtp.MtpObjectInfo} for an object on
     * the MTP or PTP device with the given USB device name with the given
     * object handle
     *
     * @param deviceName the name of the USB device
     * @param objectHandle handle of the object to query
     * @return the MtpObjectInfo
     */
    public MtpObjectInfo getObjectInfo(String deviceName, int objectHandle) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return null;
        }
        return device.getObjectInfo(objectHandle);
    }

    /**
     * Deletes an object on the MTP or PTP device with the given USB device name.
     *
     * @param deviceName the name of the USB device
     * @param objectHandle handle of the object to delete
     * @return true if the deletion succeeds
     */
    public boolean deleteObject(String deviceName, int objectHandle) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return false;
        }
        return device.deleteObject(objectHandle);
    }

    /**
     * Retrieves a list of {@link android.mtp.MtpObjectInfo} for all objects
     * on the MTP or PTP device with the given USB device name and given storage ID
     * and/or object handle.
     * If the object handle is zero, then all objects in the root of the storage unit
     * will be returned. Otherwise, all immediate children of the object will be returned.
     * If the storage ID is also zero, then all objects on all storage units will be returned.
     *
     * @param deviceName the name of the USB device
     * @param storageId the ID of the storage unit to query, or zero for all
     * @param objectHandle the handle of the parent object to query, or zero for the storage root
     * @return the list of MtpObjectInfo
     */
    public List<MtpObjectInfo> getObjectList(String deviceName, int storageId, int objectHandle) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return null;
        }
        if (objectHandle == 0) {
            // all objects in root of storage
            objectHandle = 0xFFFFFFFF;
        }
        int[] handles = device.getObjectHandles(storageId, 0, objectHandle);
        if (handles == null) {
            return null;
        }

        int length = handles.length;
        ArrayList<MtpObjectInfo> objectList = new ArrayList<MtpObjectInfo>(length);
        for (int i = 0; i < length; i++) {
            MtpObjectInfo info = device.getObjectInfo(handles[i]);
            if (info == null) {
                Log.w(TAG, "getObjectInfo failed");
            } else {
                objectList.add(info);
            }
        }
        return objectList;
    }

    /**
     * Returns the data for an object as a byte array.
     *
     * @param deviceName the name of the USB device containing the object
     * @param objectHandle handle of the object to read
     * @param objectSize the size of the object (this should match
     *      {@link android.mtp.MtpObjectInfo#getCompressedSize}
     * @return the object's data, or null if reading fails
     */
    public byte[] getObject(String deviceName, int objectHandle, int objectSize) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return null;
        }
        return device.getObject(objectHandle, objectSize);
    }

    /**
     * Returns the thumbnail data for an object as a byte array.
     *
     * @param deviceName the name of the USB device containing the object
     * @param objectHandle handle of the object to read
     * @return the object's thumbnail, or null if reading fails
     */
    public byte[] getThumbnail(String deviceName, int objectHandle) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return null;
        }
        return device.getThumbnail(objectHandle);
    }

    /**
     * Copies the data for an object to a file in external storage.
     *
     * @param deviceName the name of the USB device containing the object
     * @param objectHandle handle of the object to read
     * @param destPath path to destination for the file transfer.
     *      This path should be in the external storage as defined by
     *      {@link android.os.Environment#getExternalStorageDirectory}
     * @return true if the file transfer succeeds
     */
    public boolean importFile(String deviceName, int objectHandle, String destPath) {
        MtpDevice device = getDevice(deviceName);
        if (device == null) {
            return false;
        }
        return device.importFile(objectHandle, destPath);
    }
}


text:
"""
Created on Jul 31, 2014

@author: ionut
"""
#Edit and save as settings.py
import logging

#General settings
LOG_LEVEL = logging.INFO
SECRET = "secret"

#Tornado settings
DEBUG = True
PORT = 9001
TEMPLATE_PATH = "templates"
STATIC_PATH = "static"

#Database settings
DB_URI = "mongodb://127.0.0.1/"
DB_NAME = "bbgps"


text:
require 'helpers'

require 'instance_accountant/cli'

module InstanceAccountant
end


text:
import U from './Upw';

import {dasherize}                   from './Str';
import {mapObject, valueize, valueizeObject}   from './Obj';
import {observeObject, makeObserver, observeObjectNow} from './Obs';
import keepAssigned                  from './Ass';

var {push} = Array.prototype;

var subAttrs = ['style', 'class', 'dataset'];
function isSubattr(a) { return subAttrs.contains(a); }

// Make observers for children, attributes, and subattributes.
// -----------------------------------------------------------
function makeChildrenObserver(e) {
  function add    (v)                   { e.appendChild(v); }
  function _delete(v, i, o, {oldValue}) { e.removeChild(oldValue); }
  function update (v, i, c, {oldValue}) {
    if (i !== 'length') { e.replaceChild(v, oldValue); }
  }
  return makeObserver({add, update, delete: _delete});
}

function makeAttrsObserver(e) {
  function add(v, k)     { e.setAttribute(k, valueize(v)); }
  function _delete(v, k) { e.removeAttribute(k); }
  return makeObserver({add, update: add, delete: _delete});
}

function makeStyleObserver(s) {
  function add(v, k)     { elt.style[k] = v; }
  function _delete(v, k) { result.style[name] = ""; }
  return makeObserver({add, update: add, delete: _delete});
}

function makeDatasetObserver(e) {
  function add(v, k)     { e.dataset[k] = v; }
  function _delete(v, k) { delete e.dataset[k]; }
  return makeObserver({add, change: add, delete: _delete});
}

function makeClassObserver(e) {
  function add(v, k)     { e.classList.toggle(dasherize(k), v); }
  function _delete(v, k) { e.classList.remove(dasherize(k)); }
  return makeObserver({add, change: add, delete: _delete});
}

function _keepRendered(tagName, params) {

  // Handle changes to parameters.
  // -----------------------------
  function makeParamsObserver() {

    // Observe and unobserve the children.
    function _observeChildren  (v) { observeObjectNow(v, childrenObserver); }
    function _unobserveChildren(v) { unobserveObject (v, childrenObserver); }

    function _observeAttrs(v) {
      observeObjectNow(v, attrsObserver);
      subAttrs.forEach(a => observeObjectNow(v[a], subAttrObservers[a]));
    }
    function _unobserveAttrs(v) {
      unobserveObject(v, AttributesObserver);
      subAttr.forEach(a => unobserveObject(v[a], subAttrObservers[a]));
    }

    // When we get a new parameter, set up observers.
    function add(v, i) {
      switch (i) {
      case 'children':
        _observeChildren(v);
        break;
      case 'attrs':    _observeAttrs   (v); break;
      }
    }

    // When parameters change, tear down and resetup observers.
    function update(v, i, params, {oldValue}) {
      switch (i) {
      case 'children': _unobserveChildren(oldValue); _observeChildren(v); break;
      case 'attrs':    _unobserveAttrs   (oldValue); _observeAttrs   (v); break;
      }
    }

    return makeObserver({add, update});
  }

  var result = document.createElement(tagName);

  var subAttrObservers = {
    class:   makeClassObserver(result),
    dataset: makeDatasetObserver(result),
    style:   makeStyleObserver(result)
  };
  var attrsObserver = makeAttrsObserver(result);
  var childrenObserver = makeChildrenObserver(result);
  var paramsObserver = makeParamsObserver();

  //mapObject(params, (v, k) => upward(v, vv => params[k] = vv));
  params = valueizeObject(params);
  params.attrs = keepAssigned(params.attrs, {style: {}, class: {}, dataset: {}}, push);
  params.children = params.children || [];
  observeObjectNow(params, paramsObserver);

  return result;
}

export default function(tagName, children = [], attrs = {}) {
  return _keepRendered(tagName, {attrs, children});
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild.Logging;

namespace Microsoft.CodeAnalysis.MSBuild
{
    /// <summary>
    /// Provides information about a project that has been loaded from disk and
    /// built with MSBuild. If the project is multi-targeting, this represents
    /// the information from a single target framework.
    /// </summary>
    internal sealed class ProjectFileInfo
    {
        public bool IsEmpty { get; }

        /// <summary>
        /// The language of this project.
        /// </summary>
        public string Language { get; }

        /// <summary>
        /// The path to the project file for this project.
        /// </summary>
        public string FilePath { get; }

        /// <summary>
        /// The path to the output file this project generates.
        /// </summary>
        public string OutputFilePath { get; }

        /// <summary>
        /// The path to the reference assembly output file this project generates.
        /// </summary>
        public string OutputRefFilePath { get; }

        /// <summary>
        /// The default namespace of the project ("" if not defined, which means global namespace),
        /// or null if it is unknown or not applicable.
        /// </summary>
        /// <remarks>
        /// This only has meaning in C# and is explicitly set to null in VB.
        /// </remarks>>
        public string DefaultNamespace { get; }

        /// <summary>
        /// The target framework of this project.
        /// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.)
        /// </summary>
        public string TargetFramework { get; }

        /// <summary>
        /// The command line args used to compile the project.
        /// </summary>
        public ImmutableArray<string> CommandLineArgs { get; }

        /// <summary>
        /// The source documents.
        /// </summary>
        public ImmutableArray<DocumentFileInfo> Documents { get; }

        /// <summary>
        /// The additional documents.
        /// </summary>
        public ImmutableArray<DocumentFileInfo> AdditionalDocuments { get; }

        /// <summary>
        /// References to other projects.
        /// </summary>
        public ImmutableArray<ProjectFileReference> ProjectReferences { get; }

        /// <summary>
        /// The error message produced when a failure occurred attempting to get the info.
        /// If a failure occurred some or all of the information may be inaccurate or incomplete.
        /// </summary>
        public DiagnosticLog Log { get; }

        public override string ToString()
            => string.IsNullOrWhiteSpace(TargetFramework)
                ? FilePath
                : $"{FilePath} ({TargetFramework})";

        private ProjectFileInfo(
            bool isEmpty,
            string language,
            string filePath,
            string outputFilePath,
            string outputRefFilePath,
            string defaultNamespace,
            string targetFramework,
            ImmutableArray<string> commandLineArgs,
            ImmutableArray<DocumentFileInfo> documents,
            ImmutableArray<DocumentFileInfo> additionalDocuments,
            ImmutableArray<ProjectFileReference> projectReferences,
            DiagnosticLog log)
        {
            Debug.Assert(filePath != null);

            this.IsEmpty = isEmpty;
            this.Language = language;
            this.FilePath = filePath;
            this.OutputFilePath = outputFilePath;
            this.OutputRefFilePath = outputRefFilePath;
            this.DefaultNamespace = defaultNamespace;
            this.TargetFramework = targetFramework;
            this.CommandLineArgs = commandLineArgs;
            this.Documents = documents;
            this.AdditionalDocuments = additionalDocuments;
            this.ProjectReferences = projectReferences;
            this.Log = log;
        }

        public static ProjectFileInfo Create(
            string language,
            string filePath,
            string outputFilePath,
            string outputRefFilePath,
            string defaultNamespace,
            string targetFramework,
            ImmutableArray<string> commandLineArgs,
            ImmutableArray<DocumentFileInfo> documents,
            ImmutableArray<DocumentFileInfo> additionalDocuments,
            ImmutableArray<ProjectFileReference> projectReferences,
            DiagnosticLog log)
            => new ProjectFileInfo(
                isEmpty: false,
                language,
                filePath,
                outputFilePath,
                outputRefFilePath,
                defaultNamespace,
                targetFramework,
                commandLineArgs,
                documents,
                additionalDocuments,
                projectReferences,
                log);

        public static ProjectFileInfo CreateEmpty(string language, string filePath, DiagnosticLog log)
            => new ProjectFileInfo(
                isEmpty: true,
                language,
                filePath,
                outputFilePath: null,
                outputRefFilePath: null,
                defaultNamespace: null,
                targetFramework: null,
                commandLineArgs: ImmutableArray<string>.Empty,
                documents: ImmutableArray<DocumentFileInfo>.Empty,
                additionalDocuments: ImmutableArray<DocumentFileInfo>.Empty,
                projectReferences: ImmutableArray<ProjectFileReference>.Empty,
                log);
    }
}


text:
using System;
using System.Data;
using System.Data.Common;
using DocaLabs.NHibernateStorage;
using DocaLabs.Storage.Core;
using DocaLabs.Storage.Core.Partitioning;
using Machine.Specifications;
using Moq;
using NHibernate;
using It = Machine.Specifications.It;

namespace DocaLabs.Storage.Integration.Tests._Repositories._NHibernate._Partitioned
{
    [Subject(typeof(PartitionedRepositorySession))]
    class wehen_newing_repository_session_with_null_session_factory
    {
        static Exception actual_exception;

        Because of =
            () => actual_exception = Catch.Exception(() => new PartitionedRepositorySession(null, new Mock<IPartitionProxy>().Object));

        It should_throw_argument_null_exception =
            () => actual_exception.ShouldBeOfType<ArgumentNullException>();

        It should_report_session_factory_argument =
            () => ((ArgumentNullException)actual_exception).ParamName.ShouldEqual("sessionFactory");
    }

    [Subject(typeof(PartitionedRepositorySession))]
    class wehen_newing_repository_session_with_null_database_connection
    {
        static Exception actual_exception;

        Because of =
            () => actual_exception = Catch.Exception(() => new PartitionedRepositorySession(new Mock<ISessionFactory>().Object, null));

        It should_throw_argument_null_exception =
            () => actual_exception.ShouldBeOfType<ArgumentNullException>();

        It should_report_patition_proxy_argument =
            () => ((ArgumentNullException)actual_exception).ParamName.ShouldEqual("partitionProxy");
    }

    [Subject(typeof(PartitionedRepositorySession))]
    class when_disposing_repository_session_without_openning_connection
    {
        static Mock<ISessionFactory> session_factory;
        static Mock<IPartitionProxy> partition_proxy;
        static PartitionedRepositorySession repository_session;

        Establish context = () =>
        {
            session_factory = new Mock<ISessionFactory>();
            partition_proxy = new Mock<IPartitionProxy>();
            repository_session = new PartitionedRepositorySession(session_factory.Object, partition_proxy.Object);
        };

        Because of =
            () => repository_session.Dispose();

        It should_not_dispose_session_factory =
            () => session_factory.Verify(x => x.Dispose(), Times.Never());

        It should_not_ask_partition_proxy_for_new_connection =
            () => partition_proxy.Verify(x => x.GetConnection(), Times.Never());
    }

    [Subject(typeof(PartitionedRepositorySession))]
    class when_getting_nhibernate_session_and_then_disposing_repository_session
    {
        static Mock<ISessionFactory> session_factory;
        static Mock<IPartitionProxy> partition_proxy;
        static Mock<IDatabaseConnection> database_connection;
        static Mock<DbConnection> db_connection;
        static Mock<ISession> mock_session;
        static ISession returned_session;
        static PartitionedRepositorySession repository_session;

        Establish context = () =>
        {
            mock_session = new Mock<ISession>();

            session_factory = new Mock<ISessionFactory>();
            session_factory.Setup(x => x.OpenSession(Moq.It.IsAny<DbConnection>())).Returns(mock_session.Object);

            db_connection = new Mock<DbConnection> { CallBase = true };
            db_connection.Setup(x => x.State).Returns(ConnectionState.Closed);

            database_connection = new Mock<IDatabaseConnection>();
            database_connection.Setup(x => x.Connection).Returns(db_connection.Object);

            partition_proxy = new Mock<IPartitionProxy>();
            partition_proxy.Setup(x => x.GetConnection()).Returns(database_connection.Object);

            repository_session = new PartitionedRepositorySession(session_factory.Object, partition_proxy.Object);
        };

        Because of = () =>
        {
            returned_session = repository_session.NHibernateSession;
            repository_session.Dispose();
        };

        It should_return_expected_nhibernate_session =
            () => returned_session.ShouldBeTheSameAs(mock_session.Object);

        It should_not_dispose_session_factory =
            () => session_factory.Verify(x => x.Dispose(), Times.Never());

        It should_open_underlying_db_connection =
            () => db_connection.Verify(x => x.Open(), Times.Once());

        It should_dispose_underlying_database_connection =
            () => database_connection.Verify(x => x.Dispose(), Times.AtLeastOnce());

        It should_dispose_nhibernate_session =
            () => mock_session.Verify(x => x.Dispose(), Times.AtLeastOnce());
    }

    [Subject(typeof(PartitionedRepositorySession))]
    class when_during_getting_nhibernate_session_and_an_excpetion_is_thrown_from_oppening_the_session
    {
        static Mock<ISessionFactory> session_factory;
        static Mock<IPartitionProxy> partition_proxy;
        static Mock<IDatabaseConnection> database_connection;
        static Mock<DbConnection> db_connection;
        static Exception actual_exception;
        static PartitionedRepositorySession repository_session;

        Establish context = () =>
        {
            session_factory = new Mock<ISessionFactory>();
            session_factory.Setup(x => x.OpenSession(Moq.It.IsAny<DbConnection>())).Throws<MarkerException>();

            db_connection = new Mock<DbConnection> { CallBase = true };
            db_connection.Setup(x => x.State).Returns(ConnectionState.Closed);

            database_connection = new Mock<IDatabaseConnection>();
            database_connection.Setup(x => x.Connection).Returns(db_connection.Object);

            partition_proxy = new Mock<IPartitionProxy>();
            partition_proxy.Setup(x => x.GetConnection()).Returns(database_connection.Object);

            repository_session = new PartitionedRepositorySession(session_factory.Object, partition_proxy.Object);
        };

        Because of =
            () => actual_exception = Catch.Exception(() => { var s = repository_session.NHibernateSession; s.ShouldNotBeNull(); });

        It should_throw_expected_exception =
            () => actual_exception.ShouldBeOfType<MarkerException>();

        It should_not_dispose_session_factory =
            () => session_factory.Verify(x => x.Dispose(), Times.Never());

        It should_open_underlying_db_connection =
            () => db_connection.Verify(x => x.Open(), Times.Once());

        It should_dispose_database_connection =
            () => database_connection.Verify(x => x.Dispose(), Times.AtLeastOnce());

        class MarkerException : Exception
        {
        }
    }
}


text:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import {
  Msg,
  Button,
} from 'react-weui';
import Clipboard from '../../components/Clipboard';
import {
  goBackAndEdit,
} from '../../redux/actions/participate';

class Success extends React.Component {
  get successContent() {
    return (
      <Msg
        type="success"
        title="完成"
        description="点击右上角的分享网页并发送给好友"
      />
    );
  }

  get controlButtons() {
    return (

        <Clipboard
          type="button"
          btnId="shareBtn"
          value={window.location.href}
        >
          点击复制链接, 然后发送给好友
        </Clipboard>
        <Button
          type="default"
          onClick={() => { this.props.dispatch(goBackAndEdit()); }}
        >返回修改</Button>

    );
  }

  render() {
    return (

        {this.successContent}
        {this.controlButtons}

    );
  }
}

Success.propTypes = {
  dispatch: PropTypes.func,
};

export default connect()(Success);


text:
//
//  GMSPlacePhotoMetadata.h
//  Google Places API for iOS
//
//  Copyright 2016 Google Inc.
//
//  Usage of this SDK is subject to the Google Maps/Google Earth APIs Terms of
//  Service: https://developers.google.com/maps/terms
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

/**
 * The metadata corresponding to a single photo associated with a place.
 */
@interface GMSPlacePhotoMetadata : NSObject

/**
 * The data provider attribution string for this photo.
 *
 * These are provided as a NSAttributedString, which may contain hyperlinks to the website of each
 * provider.
 *
 * In general, these must be shown to the user if data from this GMSPlacePhotoMetadata is shown, as
 * described in the Places API Terms of Service.
 */
@property(nonatomic, readonly, copy, nullable) NSAttributedString *attributions;

/**
 * The maximum pixel size in which this photo is available.
 */
@property(nonatomic, readonly, assign) CGSize maxSize;

@end

NS_ASSUME_NONNULL_END


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, The University of Chicago -
*  Argonne National Laboratory, Emory University, SemanticBits LLC,
*  and Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
/**
 *
 */
package gov.nih.nci.cagrid.portal.domain;

import gov.nih.nci.cagrid.portal.domain.metadata.common.PointOfContact;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

/**
 * @author Joshua Phillips
 *
 */
@Entity
@Table(name = "persons")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "seq_persons") })
public class Person extends AbstractDomainObject {

	private String firstName;

	private String lastName;

	private String emailAddress;

	private String phoneNumber;

	private List<Address> addresses = new ArrayList<Address>();

	private List<PointOfContact> pointOfContacts = new ArrayList<PointOfContact>();

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(
			name = "person_addresses",
			joinColumns = @JoinColumn(name = "person_id"),
			inverseJoinColumns = @JoinColumn(name = "address_id"),
			uniqueConstraints =	@UniqueConstraint(columnNames =
				{"person_id", "address_id" })
	)
	public List<Address> getAddresses() {
		return addresses;
	}

	public void setAddresses(List<Address> addresses) {
		this.addresses = addresses;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@OneToMany(mappedBy = "person")
	public List<PointOfContact> getPointOfContacts() {
		return pointOfContacts;
	}

	public void setPointOfContacts(List<PointOfContact> pointOfContacts) {
		this.pointOfContacts = pointOfContacts;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="../schema/schema.rnc" type="application/relax-ng-compact-syntax"?>
<root xmlns="http://www.example.com">
  <child y="a">text</child>
  <child/>
  <!-- asdf -->
</root>


text:
package com.angkorteam.fintech.pages.role;

import java.util.List;

import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import com.angkorteam.fintech.widget.WebMarkupContainer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.angkorteam.fintech.Page;
import com.angkorteam.fintech.Session;
import com.angkorteam.fintech.dto.Function;
import com.angkorteam.fintech.dto.builder.RoleBuilder;
import com.angkorteam.fintech.helper.RoleHelper;
import com.angkorteam.fintech.layout.Size;
import com.angkorteam.fintech.pages.SystemDashboardPage;
import com.angkorteam.fintech.widget.TextFeedbackPanel;
import com.angkorteam.fintech.widget.WebMarkupBlock;
import com.angkorteam.framework.models.PageBreadcrumb;
import com.angkorteam.framework.wicket.markup.html.form.Button;
import com.angkorteam.framework.wicket.markup.html.form.Form;
import com.google.common.collect.Lists;
import io.github.openunirest.http.JsonNode;

/**
 * Created by socheatkhauv on 6/26/17.
 */
@AuthorizeInstantiation(Function.ALL_FUNCTION)
public class RoleCreatePage extends Page {

    protected Form<Void> form;
    protected Button saveButton;
    protected BookmarkablePageLink<Void> closeLink;

    protected WebMarkupBlock descriptionBlock;
    protected WebMarkupContainer descriptionIContainer;
    protected String descriptionValue;
    protected TextField<String> descriptionField;
    protected TextFeedbackPanel descriptionFeedback;

    protected WebMarkupBlock nameBlock;
    protected WebMarkupContainer nameIContainer;
    protected String nameValue;
    protected TextField<String> nameField;
    protected TextFeedbackPanel nameFeedback;

    @Override
    public IModel<List<PageBreadcrumb>> buildPageBreadcrumb() {
        List<PageBreadcrumb> BREADCRUMB = Lists.newArrayList();
        {
            PageBreadcrumb breadcrumb = new PageBreadcrumb();
            breadcrumb.setLabel("Admin");
            BREADCRUMB.add(breadcrumb);
        }
        {
            PageBreadcrumb breadcrumb = new PageBreadcrumb();
            breadcrumb.setLabel("System");
            breadcrumb.setPage(SystemDashboardPage.class);
            BREADCRUMB.add(breadcrumb);
        }
        {
            PageBreadcrumb breadcrumb = new PageBreadcrumb();
            breadcrumb.setLabel("Role");
            breadcrumb.setPage(RoleBrowsePage.class);
            BREADCRUMB.add(breadcrumb);
        }
        {
            PageBreadcrumb breadcrumb = new PageBreadcrumb();
            breadcrumb.setLabel("Role Create");
            BREADCRUMB.add(breadcrumb);
        }
        return Model.ofList(BREADCRUMB);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initComponent() {
        this.form = new Form<>("form");
        add(this.form);

        this.saveButton = new Button("saveButton");
        this.saveButton.setOnSubmit(this::saveButtonSubmit);
        this.form.add(this.saveButton);

        this.closeLink = new BookmarkablePageLink<>("closeLink", RoleBrowsePage.class);
        this.form.add(this.closeLink);

        initDescriptionBlock();

        initNameBlock();
    }

    protected void initNameBlock() {
        this.nameBlock = new WebMarkupBlock("nameBlock", Size.Twelve_12);
        this.form.add(this.nameBlock);
        this.nameIContainer = new WebMarkupContainer("nameIContainer");
        this.nameBlock.add(this.nameIContainer);
        this.nameField = new TextField<>("nameField", new PropertyModel<>(this, "nameValue"));
        this.nameField.setRequired(true);
        this.nameIContainer.add(this.nameField);
        this.nameFeedback = new TextFeedbackPanel("nameFeedback", this.nameField);
        this.nameIContainer.add(this.nameFeedback);
    }

    protected void initDescriptionBlock() {
        this.descriptionBlock = new WebMarkupBlock("descriptionBlock", Size.Twelve_12);
        this.form.add(this.descriptionBlock);
        this.descriptionIContainer = new WebMarkupContainer("descriptionIContainer");
        this.descriptionBlock.add(this.descriptionIContainer);
        this.descriptionField = new TextField<>("descriptionField", new PropertyModel<>(this, "descriptionValue"));
        this.descriptionField.setRequired(true);
        this.descriptionIContainer.add(this.descriptionField);
        this.descriptionFeedback = new TextFeedbackPanel("descriptionFeedback", this.descriptionField);
        this.descriptionIContainer.add(this.descriptionFeedback);
    }

    @Override
    protected void configureMetaData() {
    }

    protected void saveButtonSubmit(Button button) {
        RoleBuilder builder = new RoleBuilder();
        builder.withName(this.nameValue);
        builder.withDescription(this.descriptionValue);

        JsonNode node = RoleHelper.create((Session) getSession(), builder.build());

        if (reportError(node)) {
            return;
        }
        setResponsePage(RoleBrowsePage.class);
    }

}


text:
package org.kasource.validation.reflection.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.kasource.validation.reflection.ExtendsClass;

public class IterableExtendsClassValidator extends AbstractExtendsClassValidator implements ConstraintValidator<ExtendsClass, Iterable<? extends Object>> {

    @Override
    public void initialize(ExtendsClass annotation) {
      super.initialize(annotation);
    }

    @Override
    public boolean isValid(Iterable<? extends Object> value, ConstraintValidatorContext context) {
        return isValidItarable(value);
    }

}


text:
namespace be::gfx::tex::detail {
namespace {

///////////////////////////////////////////////////////////////////////////////
void stbi_deleter(void* ptr, std::size_t size) noexcept {
   stbi_image_free(ptr);
}

///////////////////////////////////////////////////////////////////////////////
std::size_t get_stbi_texture_file_info(int w, int h, int components, int bpc, TextureFileInfo& info, std::error_code& ec) noexcept {
   std::size_t texture_size = 0;

   info.dim = ivec3(w, h, 1);
   info.faces = 1;
   info.layers = 1;
   info.levels = 1;
   info.tex_class = TextureClass::planar;

   if (bpc == 8) {
      switch (components) {
         case 1: info.format = ImageFormat(1, 1, BlockPacking::s_8, 1, field_types(FieldType::unorm, 1), swizzles_rrr(), Colorspace::unknown, false); break;
         case 2: info.format = ImageFormat(2, 1, BlockPacking::s_8_8, 2, field_types(FieldType::unorm, 2), swizzles(Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_one), Colorspace::unknown, false); break;
         case 3: info.format = ImageFormat(3, 1, BlockPacking::s_8_8_8, 3, field_types(FieldType::unorm, 3), swizzles_rgb(), Colorspace::unknown, false); break;
         case 4: info.format = ImageFormat(4, 1, BlockPacking::s_8_8_8_8, 4, field_types(FieldType::unorm, 4), swizzles_rgba(), Colorspace::unknown, false); break;
         default:
            ec = make_error_code(TextureFileError::unsupported);
            break;
      }
   } else if (bpc == 16) {
      switch (components) {
         case 1: info.format = ImageFormat(2, 1, BlockPacking::s_16, 1, field_types(FieldType::unorm, 1), swizzles_rrr(), Colorspace::unknown, false); break;
         case 2: info.format = ImageFormat(4, 1, BlockPacking::s_16_16, 2, field_types(FieldType::unorm, 2), swizzles(Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_one), Colorspace::unknown, false); break;
         case 3: info.format = ImageFormat(6, 1, BlockPacking::s_16_16_16, 3, field_types(FieldType::unorm, 3), swizzles_rgb(), Colorspace::unknown, false); break;
         case 4: info.format = ImageFormat(8, 1, BlockPacking::s_16_16_16_16, 4, field_types(FieldType::unorm, 4), swizzles_rgba(), Colorspace::unknown, false); break;
         default:
            ec = make_error_code(TextureFileError::unsupported);
            break;
      }
   } else if (bpc == 32) {
      switch (components) {
         case 1: info.format = ImageFormat(4, 1, BlockPacking::s_32, 1, field_types(FieldType::sfloat, 1), swizzles_rrr(), Colorspace::linear_other, false); break;
         case 2: info.format = ImageFormat(8, 1, BlockPacking::s_32_32, 2, field_types(FieldType::sfloat, 2), swizzles(Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_zero, Swizzle::field_one), Colorspace::linear_other, false); break;
         case 3: info.format = ImageFormat(12, 1, BlockPacking::s_32_32_32, 3, field_types(FieldType::sfloat, 3), swizzles_rgb(), Colorspace::linear_other, false); break;
         case 4: info.format = ImageFormat(16, 1, BlockPacking::s_32_32_32_32, 4, field_types(FieldType::sfloat, 4), swizzles_rgba(), Colorspace::linear_other, false); break;
         default:
            ec = make_error_code(TextureFileError::unsupported);
            break;
      }
   } else {
      ec = make_error_code(TextureFileError::unsupported);
   }

   if (!ec) {
      if (glm::any(glm::lessThanEqual(info.dim, ivec3()))) {
         ec = make_error_code(TextureFileError::unsupported);
      } else if (glm::any(glm::greaterThan(info.dim, ivec3(TextureStorage::max_dim)))) {
         ec = make_error_code(TextureFileError::unsupported);
      } else {
         std::error_code ec2;
         texture_size = calculate_required_texture_storage(info.layers, info.faces, info.levels, info.dim,
                                                           info.format.block_dim(), info.format.block_size(), ec2,
                                                           TextureAlignment(0, 0, 0, 0, 0));
         if (texture_size == 0 || ec2) {
            ec = make_error_code(TextureFileError::unsupported);
         }
      }
   }

   return texture_size;
}

} // be::gfx::tex::detail::()

///////////////////////////////////////////////////////////////////////////////
std::pair<TextureFileInfo, std::size_t> read_stbi_info(const Buf<const UC>& buf, TextureFileFormat format, be_stbi_info_func info_func, std::error_code& ec) noexcept {
   std::pair<TextureFileInfo, std::size_t> result;
   result.first.file_format = format;
   result.second = 0;

   if (buf.size() > std::numeric_limits<int>::max()) {
      ec = make_error_code(TextureFileError::unsupported);
   } else {
      int w, h, components, bpc;
      if (0 == info_func(buf.get(), (int)buf.size(), &w, &h, &components, &bpc)) {
         ec = make_error_code(TextureFileError::unsupported);
      } else {
         result.second = get_stbi_texture_file_info(w, h, components, bpc, result.first, ec);
      }
   }
   return result;
}

///////////////////////////////////////////////////////////////////////////////
Texture read_stbi_texture(const Buf<const UC>& buf, const TextureFileInfo& info, std::size_t texture_size, be_stbi_load_func load_func, std::error_code& ec) noexcept {
   Texture tex;

   if (buf.size() > std::numeric_limits<int>::max()) {
      ec = make_error_code(TextureFileError::unsupported);
   } else {
      int w, h, components, bpc;
      auto stbi_image_data = load_func(buf.get(), (int)buf.size(), &w, &h, &components, &bpc);
      if (stbi_image_data) {
         Buf<UC> data((UC*)stbi_image_data, texture_size, stbi_deleter);

         if (!ec) {
            tex.storage = std::make_unique<TextureStorage>(info.layers, info.faces, info.levels, info.dim, info.format.block_dim(), info.format.block_size(), std::move(data), TextureAlignment(0, 0, 0, 0, 0));
            tex.view = tex::TextureView(info.format, info.tex_class, *tex.storage, 0, info.layers, 0, info.faces, 0, info.levels);
         }
      } else {
         ec = make_error_code(TextureFileError::unsupported);
      }
   }

   return tex;
}

///////////////////////////////////////////////////////////////////////////////
Image read_stbi_image(const Buf<const UC>& buf, const TextureFileInfo& info, std::size_t texture_size, be_stbi_load_func load_func, std::error_code& ec) noexcept {
   Image img;

   if (buf.size() > std::numeric_limits<int>::max()) {
      ec = make_error_code(TextureFileError::unsupported);
   } else {
      int w, h, components, bpc;
      auto stbi_image_data = load_func(buf.get(), (int)buf.size(), &w, &h, &components, &bpc);
      if (stbi_image_data) {
         Buf<UC> data((UC*)stbi_image_data, texture_size, stbi_deleter);

         if (!ec) {
            img.storage = std::make_unique<TextureStorage>(info.layers, info.faces, info.levels, info.dim, info.format.block_dim(), info.format.block_size(), std::move(data), TextureAlignment(0, 0, 0, 0, 0));
            img.view = tex::ImageView(info.format, *img.storage, 0, 0, 0);
         }
      } else {
         ec = make_error_code(TextureFileError::unsupported);
      }
   }

   return img;
}

} // be::gfx::tex::detail


text:
#ifndef TEE_UTIL_H_
#define TEE_UTIL_H_

#include "apr_pools.h"
#include "apr_tables.h"
#include "apr_file_io.h"

/*
 * Replaces char in all the string. Works in place
 */
void tee_replace(char *str, const char *from, char to);

apr_off_t tee_get_file_pos(apr_file_t *file);

APR_DECLARE(apr_table_t *) tee_table_clone(apr_pool_t *p, const apr_table_t *t);

const char *tee_get_error_string(apr_status_t status, apr_pool_t *p);

pid_t gettid(void);

#endif /* TEE_UTIL_H_ */


text:
package com.intellij.dvcs;

import com.intellij.dvcs.ui.DvcsBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.NonFocusableCheckBox;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.*;
import java.util.List;

public abstract class DvcsCommitAdditionalComponent implements RefreshableOnComponent {

  private static final Logger log = Logger.getInstance(DvcsCommitAdditionalComponent.class);

  protected final JPanel myPanel;
  protected final JCheckBox myAmend;
  @NotNull private final String myPreviousMessage;
  @Nullable private String myAmendedMessage;
  @NotNull protected final CheckinProjectPanel myCheckinPanel;
  @Nullable  private  Map<VirtualFile, String> myMessagesForRoots;

  public DvcsCommitAdditionalComponent(@NotNull final Project project, @NotNull CheckinProjectPanel panel) {
    myCheckinPanel = panel;
    myPanel = new JPanel(new GridBagLayout());
    final Insets insets = JBUI.insets(2);
    // add amend checkbox
    GridBagConstraints c = new GridBagConstraints();
    //todo change to MigLayout
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    c.anchor = GridBagConstraints.CENTER;
    c.insets = insets;
    c.weightx = 1;
    c.fill = GridBagConstraints.HORIZONTAL;

    myAmend = new NonFocusableCheckBox(DvcsBundle.message("commit.amend"));
    myAmend.setMnemonic('m');
    myAmend.setToolTipText(DvcsBundle.message("commit.amend.tooltip"));
    myPreviousMessage = myCheckinPanel.getCommitMessage();

    myAmend.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        if (myAmend.isSelected()) {
            if (myPreviousMessage.equals(myCheckinPanel.getCommitMessage())) { // if user has already typed something, don't revert it
              if (myMessagesForRoots == null) {
                loadMessagesInModalTask(project);      //load all commit messages for all repositories
              }
              String message = constructAmendedMessage();
              if (!StringUtil.isEmptyOrSpaces(message)) {
                myAmendedMessage = message;
                substituteCommitMessage(myAmendedMessage);
              }
            }
        }
        else {
          // there was the amended message, but user has changed it => not reverting
          if (myCheckinPanel.getCommitMessage().equals(myAmendedMessage)) {
            myCheckinPanel.setCommitMessage(myPreviousMessage);
          }
        }
      }
    });
    myPanel.add(myAmend, c);
  }

  private String constructAmendedMessage() {
    Set<VirtualFile> selectedRoots = getVcsRoots(getSelectedFilePaths());        // get only selected files
    LinkedHashSet<String> messages = ContainerUtil.newLinkedHashSet();
    if (myMessagesForRoots != null) {
      for (VirtualFile root : selectedRoots) {
        String message = myMessagesForRoots.get(root);
        if (message != null) {
          messages.add(message);
        }
      }
    }
    return DvcsUtil.joinMessagesOrNull(messages);
  }

  public JComponent getComponent() {
    return myPanel;
  }

  public void refresh() {
    myAmend.setSelected(false);
  }

  private void loadMessagesInModalTask(@NotNull Project project) {
    try {
      myMessagesForRoots =
        ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<Map<VirtualFile,String>, VcsException>() {
          @Override
          public Map<VirtualFile, String> compute() throws VcsException {
            return getLastCommitMessages();
          }
        }, "Reading commit message...", false, project);
    }
    catch (VcsException e) {
      Messages.showErrorDialog(getComponent(), "Couldn't load commit message of the commit to amend.\n" + e.getMessage(),
                               "Commit Message not Loaded");
      log.info(e);
    }
  }

  private void substituteCommitMessage(@NotNull String newMessage) {
    if (!StringUtil.equalsIgnoreWhitespaces(myPreviousMessage, newMessage)) {
      VcsConfiguration.getInstance(myCheckinPanel.getProject()).saveCommitMessage(myPreviousMessage);
      myCheckinPanel.setCommitMessage(newMessage);
    }
  }

  @Nullable
  private Map<VirtualFile, String> getLastCommitMessages() throws VcsException {
    Map<VirtualFile, String> messagesForRoots = new HashMap<VirtualFile, String>();
    Collection<VirtualFile> roots = myCheckinPanel.getRoots(); //all committed vcs roots, not only selected
    final Ref<VcsException> exception = Ref.create();
    for (VirtualFile root : roots) {
      String message = getLastCommitMessage(root);
      messagesForRoots.put(root, message);
    }
    if (!exception.isNull()) {
      throw exception.get();
    }
    return messagesForRoots;
  }

  @NotNull
  private List<FilePath> getSelectedFilePaths() {
    return ContainerUtil.map(myCheckinPanel.getFiles(), new Function<File, FilePath>() {
      @Override
      public FilePath fun(File file) {
        return VcsUtil.getFilePath(file);
      }
    });
  }

  @NotNull
  protected abstract Set<VirtualFile> getVcsRoots(@NotNull Collection<FilePath> files);

  @Nullable
  protected abstract String getLastCommitMessage(@NotNull VirtualFile repo) throws VcsException;

  public boolean isAmend() {
    return myAmend.isSelected();
  }
}


text:
package org.hildan.livedoc.springmvc.readers.messages;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.hildan.livedoc.core.annotations.messages.StompCommand;
import org.hildan.livedoc.core.model.doc.async.AsyncMessageDoc;
import org.hildan.livedoc.core.readers.javadoc.JavadocHelper;
import org.hildan.livedoc.core.scanners.types.references.TypeReferenceProvider;
import org.hildan.livedoc.springmvc.readers.mappings.PathUtils;
import org.hildan.livedoc.springmvc.readers.payload.SpringReturnTypeReader;
import org.hildan.livedoc.springmvc.utils.ClasspathUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;

class TriggeredMessagesReader {

    static List<AsyncMessageDoc> buildTriggeredMessagesDocs(Method method,
            TypeReferenceProvider typeReferenceProvider) {
        List<AsyncMessageDoc> docs = new ArrayList<>();
        if (ClasspathUtils.isSendToOnClasspath() && method.isAnnotationPresent(SendTo.class)) {
            SendTo sendTo = method.getAnnotation(SendTo.class);
            docs.add(readSendToAnnotation(method, sendTo, typeReferenceProvider));
        }
        if (ClasspathUtils.isSendToUserOnClasspath() && method.isAnnotationPresent(SendToUser.class)) {
            SendToUser sendToUser = method.getAnnotation(SendToUser.class);
            docs.add(readSendToUserAnnotation(method, sendToUser, typeReferenceProvider));
        }
        return docs;
    }

    private static AsyncMessageDoc readSendToAnnotation(Method method, SendTo annotation,
            TypeReferenceProvider typeReferenceProvider) {
        return createTriggeredMessageDoc(method, typeReferenceProvider, Arrays.asList(annotation.value()));
    }

    private static AsyncMessageDoc readSendToUserAnnotation(Method method, SendToUser annotation,
            TypeReferenceProvider typeReferenceProvider) {
        List<String> destinations = Arrays.asList(annotation.value());
        // in reality, /user/{username} is prepended, but the broker will get rid of the username, and the actual path
        // that clients need to subscribe to is effectively only prepended with /user
        List<String> fullDestinations = PathUtils.joinAll(Collections.singletonList("/user"), destinations);
        return createTriggeredMessageDoc(method, typeReferenceProvider, fullDestinations);
    }

    @NotNull
    private static AsyncMessageDoc createTriggeredMessageDoc(Method method, TypeReferenceProvider typeReferenceProvider,
            List<String> destinations) {
        /*
        The current method does not define this message; it merely triggers it. This is why a lot of information is
        unavailable here: name, headers, destination variables, etc.
         */
        AsyncMessageDoc doc = new AsyncMessageDoc();
        doc.setCommand(StompCommand.SUBSCRIBE);
        doc.setDescription(JavadocHelper.getReturnDescription(method).orElse(null));
        doc.setDestinations(destinations);
        doc.setPayloadType(typeReferenceProvider.getReference(SpringReturnTypeReader.getActualReturnType(method)));
        return doc;
    }
}


text:
#include "db_config.h"

#include "db_int.h"

/*
 * fopen --
 *
 * PUBLIC: #ifndef HAVE_FOPEN
 * PUBLIC: FILE *fopen __P((const char *, const char *));
 * PUBLIC: #endif
 */
FILE *
fopen(filename, mode)
	const char *filename, *mode;
{
	IFile *pIFile;
	IFileMgr *pIFileMgr;
	OpenFileMode flags;
	int f_exists, ret, update_flag;

	/*
	 * Note: files are created with read/write privilege.
	 *
	 * Upon successful completion, fopen() returns a pointer to the
	 * object controlling the stream.  Otherwise, NULL is returned,
	 * and errno is set to indicate the error.
	 */
	DB_ASSERT(NULL, filename != NULL && mode != NULL);

	FILE_MANAGER_CREATE(NULL, pIFileMgr, ret);
	if (ret != 0) {
		__os_set_errno(ret);
		return (NULL);
	}

	/*
	 * The argument mode points to a string beginning with one of the
	 * following sequences:
	 * r or rb
	 *	Open file for reading.
	 * w or wb
	 *	Truncate to zero length or create file for writing.
	 * a or ab
	 *	Append; open or create file for writing at end-of-file.
	 * r+ or rb+ or r+b
	 *	Open file for update (reading and writing).
	 * w+ or wb+ or w+b
	 *	Truncate to zero length or create file for update.
	 * a+ or ab+ or a+b
	 *	Append; open or create file for update, writing at end-of-file.
	 */
	flags = 0;
	update_flag = strchr(mode, '+') ? 1 : 0;
	switch (*mode) {
	case 'a':			/* append mode */
		flags = _OFM_APPEND | _OFM_CREATE;
		break;
	case 'r':			/* read mode */
		flags = update_flag ? _OFM_READWRITE : _OFM_READ;
		break;
	case 'w':			/* write mode */
		flags = _OFM_READWRITE | _OFM_CREATE;
		break;
	}

	f_exists = IFILEMGR_Test(pIFileMgr, filename) == SUCCESS ? 1 : 0;
	if (f_exists)
		LF_CLR(_OFM_CREATE);		/* Clear _OFM_CREATE. */
	else
		LF_CLR(~_OFM_CREATE);		/* Leave only _OFM_CREATE. */

	if ((pIFile = IFILEMGR_OpenFile(
	    pIFileMgr, filename, (OpenFileMode)flags)) == NULL) {
		FILE_MANAGER_ERR(NULL,
		    pIFileMgr, filename, "IFILEMGR_OpenFile", ret);
		__os_set_errno(ret);
	}

	IFILEMGR_Release(pIFileMgr);
	return (pIFile);
}


text:
=head1 TITLE

Less line noise - let's get rid of @%

=head1 VERSION

  Maintainer: Karl Glazebrook <kgb@pha.jhu.edu>
  Date: 15 Aug 2000
  Last Modified: 28 Aug 2000
  Mailing List: perl6-language@perl.org
  Number: 109
  Version: 2
  Status: Withdrawn

=head1 ABSTRACT

This RFC proposes that C<$x>, C<@x>, and C<%x> be ditched and
replaced with C<$x> for everything.

I withdrew it on 28th August as I figured I had lost the
argument!

=head1 DESCRIPTION

Back in the days of yore, Larry had a dream of a simple
typeless language. Variables were 'things', they could
hold numbers or strings, and manipulated without much
caring. The only important distinctions were whether they
were lists of things or hashes of things for which was
introduced the compact notation of C<@> and C<%>. Perl4 was
the anti-object-oriented language in an age when there
were Real Computers and Bill Gates was still trying to
flog BASIC.

Those days are gone. Perl 5 introduced the idea of Objects
and now any variable can be one of ten million possible
types all of very different behaviours.

Also in modern programming, lists are not longer simple
lists, neither are hashes, we have multidimensional arrays,
FIFO stacks, LIFO stacks, semi-infinite lists, etc. Basically there
are innumerable ways of containing things and they are usually
represented by objects.

I argue in this Brave New World the distinction between C<$x>, C<@x>
and C<%x> are no longer useful and should be abolished. We might want
to use all kinds of array objects, why should @x be special? Rather
since there are infinitely many kinds of variable let's take the perl6
opportunity to make things simple and just use C<$x> for everything.

A RFC by Andy Wardley proposes `Highlander Variable Types' (`there can
only be one'). This addresses the same fundamental issues, but retains
C<@x> and C<%x> in the interests of backwards compatibility.

My proposal goes further: there should be NO  C<@x> and C<%x>, only
C<$x>.  This would make for a simplification of the language with
extreme prejudice.

=head1 PROPOSAL:

All variables should be C<$x>. They should behave appropriately
according to their object types and methods. ARRAY objects
and HASH objects would provide methods (inline, optimised
of course) to make $x[42] and $x{Fred} do the right thing.
See the pdl-porters RFC on 'default methods' for elegant
ways to do this.

The only distinction left would be between things which are
variables (prefixed by C<$>) and not-variables (subroutines and
keywords).

=head1 IMPLEMENTATION DETAILS

Considerable I expect. :)

Overloading should happen everywhere.

  print $x

Ought to use string overloading and be able to print an array or hash
depending on type.

Similarly accesses such as C<$x[42]> or C<$x{Fred}> should function via
overloaded C<[]> and C<{}> operators.

  $y = $x + 1

Ought to be able to execute appropriate code whether $x is a scalar, a
Perl array or a PDL array.

=head1 REFERENCES

PDL RFC on 'Default Methods' - PDL RFCs coming Real Soon Now

RFC 9: Highlander Variable Types


text:
// +build wireinject

package main

import (
	"context"

	"github.com/google/knative-gcp/pkg/broker/config/volume"
	"github.com/google/knative-gcp/pkg/broker/handler"
	"github.com/google/knative-gcp/pkg/metrics"
	"github.com/google/knative-gcp/pkg/utils/clients"
	"github.com/google/wire"
)

// InitializeSyncPool initializes the retry sync pool. Uses the given projectID to initialize the
// retry pool's pubsub client and uses targetsVolumeOpts to initialize the targets volume watcher.
func InitializeSyncPool(
	ctx context.Context,
	projectID clients.ProjectID,
	podName metrics.PodName,
	containerName metrics.ContainerName,
	targetsVolumeOpts []volume.Option,
	opts ...handler.Option) (*handler.RetryPool, error) {
	// Implementation generated by wire. Providers for required RetryPool dependencies should be
	// added here.
	panic(wire.Build(handler.ProviderSet, volume.NewTargetsFromFile, metrics.NewDeliveryReporter))
}


text: from .client import SamsaraClient  # noqa


text:
package org.apache.commons.cli;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class GnuParseTest extends TestCase
{
    private Options _options = null;
    private Parser _parser = null;

    public static Test suite() {
        return new TestSuite( GnuParseTest.class );
    }

    public GnuParseTest( String name )
    {
        super( name );
    }

    public void setUp()
    {
        _options = new Options()
            .addOption("a",
                       "enable-a",
                       false,
                       "turn [a] on or off")
            .addOption("b",
                       "bfile",
                       true,
                       "set the value of [b]")
            .addOption("c",
                       "copt",
                       false,
                       "turn [c] on or off");

        _parser = new GnuParser( );
    }

    public void tearDown()
    {

    }

    public void testSimpleShort()
    {
        String[] args = new String[] { "-a",
                                       "-b", "toast",
                                       "foo", "bar" };

        try
        {
            CommandLine cl = _parser.parse(_options, args);

            assertTrue( "Confirm -a is set", cl.hasOption("a") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") );
            assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2);
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testSimpleLong()
    {
        String[] args = new String[] { "--enable-a",
                                       "--bfile", "toast",
                                       "foo", "bar" };

        try
        {
            CommandLine cl = _parser.parse(_options, args);

            assertTrue( "Confirm -a is set", cl.hasOption("a") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") );
            assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2);
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testExtraOption()
    {
        String[] args = new String[] { "-a", "-d", "-b", "toast",
                                       "foo", "bar" };

        boolean caught = false;

        try
        {
            CommandLine cl = _parser.parse(_options, args);

            assertTrue( "Confirm -a is set", cl.hasOption("a") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "confirm arg of -b", cl.getOptionValue("b").equals("toast") );
            assertTrue( "Confirm size of extra args", cl.getArgList().size() == 3);
        }
        catch (UnrecognizedOptionException e)
        {
            caught = true;
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
        assertTrue( "Confirm UnrecognizedOptionException caught", caught );
    }

    public void testMissingArg()
    {

        String[] args = new String[] { "-b" };

        boolean caught = false;

        try
        {
            CommandLine cl = _parser.parse(_options, args);
        }
        catch (MissingArgumentException e)
        {
            caught = true;
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }

        assertTrue( "Confirm MissingArgumentException caught", caught );
    }

    public void testStop()
    {
        String[] args = new String[] { "-c",
                                       "foober",
                                       "-b",
                                       "toast" };

        try
        {
            CommandLine cl = _parser.parse(_options, args, true);
            assertTrue( "Confirm -c is set", cl.hasOption("c") );
            assertTrue( "Confirm  3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testMultiple()
    {
        String[] args = new String[] { "-c",
                                       "foobar",
                                       "-b",
                                       "toast" };

        try
        {
            CommandLine cl = _parser.parse(_options, args, true);
            assertTrue( "Confirm -c is set", cl.hasOption("c") );
            assertTrue( "Confirm  3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);

            cl = _parser.parse(_options, cl.getArgs() );

            assertTrue( "Confirm -c is not set", ! cl.hasOption("c") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") );
            assertTrue( "Confirm  1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
            assertTrue( "Confirm  value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") );
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testMultipleWithLong()
    {
        String[] args = new String[] { "--copt",
                                       "foobar",
                                       "--bfile", "toast" };

        try
        {
            CommandLine cl = _parser.parse(_options,args,
                                            true);
            assertTrue( "Confirm -c is set", cl.hasOption("c") );
            assertTrue( "Confirm  3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);

            cl = _parser.parse(_options, cl.getArgs() );

            assertTrue( "Confirm -c is not set", ! cl.hasOption("c") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") );
            assertTrue( "Confirm  1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
            assertTrue( "Confirm  value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") );
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testDoubleDash()
    {
        String[] args = new String[] { "--copt",
                                       "--",
                                       "-b", "toast" };

        try
        {
            CommandLine cl = _parser.parse(_options, args);

            assertTrue( "Confirm -c is set", cl.hasOption("c") );
            assertTrue( "Confirm -b is not set", ! cl.hasOption("b") );
            assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2);

        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }
    }

    public void testSingleDash()
    {
        String[] args = new String[] { "--copt",
                                       "-b", "-",
                                       "-a",
                                       "-" };

        try
        {
            CommandLine cl = _parser.parse(_options, args);

            assertTrue( "Confirm -a is set", cl.hasOption("a") );
            assertTrue( "Confirm -b is set", cl.hasOption("b") );
            assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("-") );
            assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
            assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") );
        }
        catch (ParseException e)
        {
            fail( e.toString() );
        }

    }
}


text: export default () => "FructoseComponent";


text:
@class NSMutableArray, NSString;

@interface GiftEntrance : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSString *desc; // @dynamic desc;
@property(retain, nonatomic) NSMutableArray *icons; // @dynamic icons;
@property(retain, nonatomic) NSString *summary; // @dynamic summary;
@property(retain, nonatomic) NSString *title; // @dynamic title;
@property(retain, nonatomic) NSString *url; // @dynamic url;

@end


text:
package org.reldb.rel.v0.storage.catalog;

import org.reldb.rel.v0.generator.SelectAttributes;
import org.reldb.rel.v0.storage.RelDatabase;
import org.reldb.rel.v0.storage.relvars.RelvarGlobal;
import org.reldb.rel.v0.storage.relvars.RelvarHeading;
import org.reldb.rel.v0.types.Heading;
import org.reldb.rel.v0.types.builtin.TypeCharacter;

public class RelvarSystemDependenciesMetadata extends RelvarSystemMetadata {
	public static final long serialVersionUID = 0;

	static Heading getNewHeading() {
		Heading heading = new Heading();
		heading.add("Object", TypeCharacter.getInstance());
		heading.add("Uses", TypeCharacter.getInstance());
		return heading;
	}

	static RelvarHeading getNewKeyDefinition() {
		SelectAttributes attributes = new SelectAttributes();
		attributes.add("Object");
		attributes.add("Uses");
		RelvarHeading keyDefinition = new RelvarHeading(getNewHeading());
		keyDefinition.addKey(attributes);
		return keyDefinition;
	}

	public RelvarSystemDependenciesMetadata(RelDatabase database, String name) {
		super(database, name, getNewKeyDefinition());
	}

	public RelvarGlobal getRelvar(String name, RelDatabase database) {
		return new RelvarSystemDependencies(name, database, this);
	}

}


text:
<?php
declare(strict_types = 1);

namespace Domain\Specification\Canonical;

use Domain\Entity\{
    Canonical as Entity,
    HttpResource\Identity,
};
use Innmind\Specification\{
    Comparator,
    Sign,
};

final class HttpResource implements Comparator, Specification
{
    use Composable;

    private string $value;

    public function __construct(Identity $value)
    {
        $this->value = $value->toString();
    }

    /**
     * {@inheritdoc}
     */
    public function property(): string
    {
        return 'resource';
    }

    /**
     * {@inheritdoc}
     */
    public function sign(): Sign
    {
        return Sign::equality();
    }

    /**
     * {@inheritdoc}
     */
    public function value()
    {
        return $this->value;
    }

    public function isSatisfiedBy(Entity $canonical): bool
    {
        return $canonical->resource()->toString() === $this->value;
    }
}


text:
@interface IntrinsicViewController : UIViewController

@end


text:
module GcloudStorage
  module Error
    class Configuration < StandardError; end
    class Argument < ArgumentError; end

    def self.missing_credentials
      raise Configuration.new("Missing credentials. Please configure using GcloudStorage.configure(&block).")
    end
  end
end


text:
{% from 'macros.html' import transaction, goal_bar with context %}
{% extends "layout.html" %}
{% block title %}{{goal.label}} in {{date.year}}{% endblock %}
{% block head %}

  <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='chartist.min.css')}}">
{% endblock %}

{% block page_header %}

    «

{{ goal.label }} in {{date.year}}

    {% if next_year %}
    »
    {% else %}

    {% endif %}

{% endblock %}

{% block page %}

      {{ goal_bar(goal) }}

        Target
        {{famount(goal.target)}}

        Saved
        {{famount(goal.saved)}}

        Used
        {{famount(goal.used)}}

        Remaining
        {{famount(goal.remaining)}}

  {% if categories %}
    {% include "_categories_bar.html" %}
  {% endif %}

    {% for tx in transactions %}
      {{ transaction(tx) }}
    {% endfor %}

  Clear filter

  {% include "_tx_options.html" %}
{% endblock %}


text:
'use strict';

import {localize} from 'vs/nls';
import {sequence} from 'vs/base/common/async';
import {illegalArgument} from 'vs/base/common/errors';
import {TPromise} from 'vs/base/common/winjs.base';
import {IModel, IPosition} from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry} from 'vs/editor/common/editorCommonExtensions';
import {IRenameResult, RenameRegistry} from 'vs/editor/common/modes';

export function rename(model: IModel, position: IPosition, newName: string): TPromise<IRenameResult> {

	const supports = RenameRegistry.ordered(model);
	const resource = model.getAssociatedResource();
	const rejects: string[] = [];
	let hasResult = false;

	const factory = supports.map(support => {
		return () => {
			if (!hasResult) {
				return support.rename(resource, position, newName).then(result => {
					if (!result) {
						// ignore
					} else if (!result.rejectReason) {
						hasResult = true;
						return result;
					} else {
						rejects.push(result.rejectReason);
					}
				});
			}
		};
	});

	return sequence(factory).then(values => {
		let result = values[0];
		if (rejects.length > 0) {
			return <IRenameResult>{
				currentName: undefined,
				edits: undefined,
				rejectReason: rejects.join('\n')
			};
		} else if (!result) {
			return <IRenameResult>{
				currentName: undefined,
				edits: undefined,
				rejectReason: localize('no result', "No result.")
			};
		} else {
			return result;
		}
	});
}

CommonEditorRegistry.registerDefaultLanguageCommand('_executeDocumentRenameProvider', function(model, position, args) {
	let {newName} = args;
	if (typeof newName !== 'string') {
		throw illegalArgument('newName');
	}
	return rename(model, position, newName);
});


text:
'use strict';

    var zrUtil = require('zrender/lib/core/util');
    var formatUtil = require('../util/format');
    var modelUtil = require('../util/model');
    var ComponentModel = require('./Component');

    var encodeHTML = formatUtil.encodeHTML;
    var addCommas = formatUtil.addCommas;

    var SeriesModel = ComponentModel.extend({

        type: 'series.__base__',

        /**
         * @readOnly
         */
        seriesIndex: 0,

        // coodinateSystem will be injected in the echarts/CoordinateSystem
        coordinateSystem: null,

        /**
         * @type {Object}
         * @protected
         */
        defaultOption: null,

        /**
         * Data provided for legend
         * @type {Function}
         */
        // PENDING
        legendDataProvider: null,

        init: function (option, parentModel, ecModel, extraOpt) {

            /**
             * @type {number}
             * @readOnly
             */
            this.seriesIndex = this.componentIndex;

            this.mergeDefaultAndTheme(option, ecModel);

            /**
             * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
             * @private
             */
            this._dataBeforeProcessed = this.getInitialData(option, ecModel);

            // If we reverse the order (make this._data firstly, and then make
            // this._dataBeforeProcessed by cloneShallow), cloneShallow will
            // cause this._data.graph.data !== this._data when using
            // module:echarts/data/Graph or module:echarts/data/Tree.
            // See module:echarts/data/helper/linkList
            this._data = this._dataBeforeProcessed.cloneShallow();
        },

        /**
         * Util for merge default and theme to option
         * @param  {Object} option
         * @param  {module:echarts/model/Global} ecModel
         */
        mergeDefaultAndTheme: function (option, ecModel) {
            zrUtil.merge(
                option,
                ecModel.getTheme().get(this.subType)
            );
            zrUtil.merge(option, this.getDefaultOption());

            // Default label emphasis `position` and `show`
            // FIXME Set label in mergeOption
            modelUtil.defaultEmphasis(option.label, modelUtil.LABEL_OPTIONS);

            this.fillDataTextStyle(option.data);
        },

        mergeOption: function (newSeriesOption, ecModel) {
            newSeriesOption = zrUtil.merge(this.option, newSeriesOption, true);
            this.fillDataTextStyle(newSeriesOption.data);

            var data = this.getInitialData(newSeriesOption, ecModel);
            // TODO Merge data?
            if (data) {
                this._data = data;
                this._dataBeforeProcessed = data.cloneShallow();
            }
        },

        fillDataTextStyle: function (data) {
            // Default data label emphasis `position` and `show`
            // FIXME Tree structure data ?
            // FIXME Performance ?
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i] && data[i].label) {
                        modelUtil.defaultEmphasis(data[i].label, modelUtil.LABEL_OPTIONS);
                    }
                }
            }
        },

        /**
         * Init a data structure from data related option in series
         * Must be overwritten
         */
        getInitialData: function () {},

        /**
         * @param {string} [dataType]
         * @return {module:echarts/data/List}
         */
        getData: function (dataType) {
            return dataType == null ? this._data : this._data.getLinkedData(dataType);
        },

        /**
         * @param {module:echarts/data/List} data
         */
        setData: function (data) {
            this._data = data;
        },

        /**
         * Get data before processed
         * @return {module:echarts/data/List}
         */
        getRawData: function () {
            return this._dataBeforeProcessed;
        },

        /**
         * Coord dimension to data dimension.
         *
         * By default the result is the same as dimensions of series data.
         * But in some series data dimensions are different from coord dimensions (i.e.
         * candlestick and boxplot). Override this method to handle those cases.
         *
         * Coord dimension to data dimension can be one-to-many
         *
         * @param {string} coordDim
         * @return {Array.<string>} dimensions on the axis.
         */
        coordDimToDataDim: function (coordDim) {
            return [coordDim];
        },

        /**
         * Convert data dimension to coord dimension.
         *
         * @param {string|number} dataDim
         * @return {string}
         */
        dataDimToCoordDim: function (dataDim) {
            return dataDim;
        },

        /**
         * Get base axis if has coordinate system and has axis.
         * By default use coordSys.getBaseAxis();
         * Can be overrided for some chart.
         * @return {type} description
         */
        getBaseAxis: function () {
            var coordSys = this.coordinateSystem;
            return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
        },

        // FIXME
        /**
         * Default tooltip formatter
         *
         * @param {number} dataIndex
         * @param {boolean} [multipleSeries=false]
         * @param {number} [dataType]
         */
        formatTooltip: function (dataIndex, multipleSeries, dataType) {
            var data = this._data;
            var value = this.getRawValue(dataIndex);
            var formattedValue = zrUtil.isArray(value)
                ? zrUtil.map(value, addCommas).join(', ') : addCommas(value);
            var name = data.getName(dataIndex);
            var color = data.getItemVisual(dataIndex, 'color');
            var colorEl = '';

            var seriesName = this.name;
            // FIXME
            if (seriesName === '\0-') {
                // Not show '-'
                seriesName = '';
            }
            return !multipleSeries
                ? ((seriesName && encodeHTML(seriesName) + '
') + colorEl
                    + (name
                        ? encodeHTML(name) + ' : ' + formattedValue
                        : formattedValue)
                  )
                : (colorEl + encodeHTML(this.name) + ' : ' + formattedValue);
        },

        restoreData: function () {
            this._data = this._dataBeforeProcessed.cloneShallow();
        },

        getAxisTooltipDataIndex: null
    });

    zrUtil.mixin(SeriesModel, modelUtil.dataFormatMixin);

    module.exports = SeriesModel;


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

<title>TableHandler</title>
<meta name="date" content="2016-11-09">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Class TableHandler

java.lang.Object

TableHandler

class TableHandler
extends java.lang.Object

A class to handle all table assignments for each Reservation class

Version:

1.3

Author:

Jonathan

See Also:

Reservation

Field Summary

Fields

Modifier and Type
Field and Description

private java.util.LinkedList<java.time.LocalDateTime>[]
TableArray

An array of 30 Linkedlists that hold LocalDateTimes, indicating on which day there
 exists a reservation

Constructor Summary

Constructors

Constructor and Description

TableHandler()

Constructor used in initialisation

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
assignTable(java.time.LocalDateTime arrivalDateTime,
           int session,
           int pax)

Assigns table on FUTURE dates, for current session, see CurrentSessionTableHandler

int[]
getArrayForCurrentSession(int session)

Method to get an array of 30 integers for CurrentSessionTableHandler

java.util.LinkedList<java.time.LocalDateTime>[]
getTableArray()

Simple get function to retrieve the array of linked lists

void
initialiseTableHandler(java.time.LocalDateTime tableLDT,
                      int tableID)

Used only for initialisation, when reading from TableBooking.txt,
 during initialiseTableBookings()

void
removeBooking(java.time.LocalDateTime arrivalDateTime,
             int session,
             int assignedTable)

Method to be called after Reservation is removed from ReservationHandler,
 as ReservationHandler does not handle table bookings.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

TableArray

private java.util.LinkedList<java.time.LocalDateTime>[] TableArray

An array of 30 Linkedlists that hold LocalDateTimes, indicating on which day there
 exists a reservation

Constructor Detail

TableHandler

public TableHandler()

Constructor used in initialisation

Method Detail

initialiseTableHandler

public void initialiseTableHandler(java.time.LocalDateTime tableLDT,
                                   int tableID)

Used only for initialisation, when reading from TableBooking.txt,
 during initialiseTableBookings()

Parameters:

tableLDT - LocalDateTime value for booking

tableID - Table number of booking

See Also:

ConsoleApplication

assignTable

public int assignTable(java.time.LocalDateTime arrivalDateTime,
                       int session,
                       int pax)

Assigns table on FUTURE dates, for current session, see CurrentSessionTableHandler

Parameters:

arrivalDateTime - Reservation LocalDateTime

session - Reservation session (based on arrivalDateTime

pax - Number of people in Reservation

Returns:

Table number assigned. If fails, return -1

getArrayForCurrentSession

public int[] getArrayForCurrentSession(int session)

Method to get an array of 30 integers for CurrentSessionTableHandler

Parameters:

session - 0 for AM session, 1 for PM session

Returns:

Array of 30 integers for constructor of CurrentSessionTableHandler

See Also:

CurrentSessionTableHandler

removeBooking

public void removeBooking(java.time.LocalDateTime arrivalDateTime,
                          int session,
                          int assignedTable)

Method to be called after Reservation is removed from ReservationHandler,
 as ReservationHandler does not handle table bookings.
 This method handles removal of table booking, is not aware of ReservationHandler

Parameters:

arrivalDateTime - LocalDateTime of removed Reservation

session - 0 is AM session, 1 is PM session

assignedTable - Table number assigned to removed Reservation

See Also:

ReservationHandler,
Reservation

getTableArray

public java.util.LinkedList<java.time.LocalDateTime>[] getTableArray()

Simple get function to retrieve the array of linked lists

Returns:

the class' array of linked lists

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method