text:
export default {
  primaryColor: '#39A7DE', // primary color of ant design
  navTheme: 'light', // theme for nav menu
  layout: 'sidemenu', // nav menu position: sidemenu or topmenu
  contentWidth: 'Fixed', // layout of content: Fluid or Fixed, only works when layout is topmenu
  fixedHeader: true, // sticky header
  fixSiderbar: true, // sticky siderbar
  autoHideHeader: false, //  auto hide header
  invertedMode: true,
  multiTab: false, // enable to have tab/route history stuff
  // vue-ls options
  storageOptions: {
    namespace: 'primate__', // key prefix
    name: 'ls', // name variable Vue.[ls] or this.[$ls],
    storage: 'local' // storage name session, local, memory
  }
}


text:
require File.expand_path("../login_banner", __FILE__)

module Fog
  module Compute
    class Ecloud
      class LoginBanners < Fog::Ecloud::Collection
        identity :href

        model Fog::Compute::Ecloud::LoginBanner

        def all
          data = service.get_login_banners(href).body
          load(data)
        end

        def get(uri)
          if data = service.get_login_banner(uri)
            new(data.body)
          end
        rescue ServiceError => e
          raise e unless e.status_code == 404
          nil
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package edu.sampleu.kim.api.location;

import edu.sampleu.admin.AdminTmplMthdAftNavBase;
import org.apache.commons.lang.RandomStringUtils;
import org.kuali.rice.testtools.common.JiraAwareFailable;
import org.kuali.rice.testtools.selenium.AutomatedFunctionalTestUtils;
import org.kuali.rice.testtools.selenium.WebDriverUtils;

/**
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public abstract class LocationPostCodeAftBase extends AdminTmplMthdAftNavBase {

    /**
     * ITUtil.PORTAL + "?channelTitle=Postal%20Code&channelUrl="
     * + WebDriverUtils.getBaseUrlString() + ITUtil.KNS_LOOKUP_METHOD + "org.kuali.rice.location.impl.postalcode.PostalCodeBo&docFormKey=88888888&returnLocation=" +
     * ITUtil.PORTAL_URL + ITUtil.HIDE_RETURN_LINK;
     */
    public static final String BOOKMARK_URL = AutomatedFunctionalTestUtils.PORTAL + "?channelTitle=Postal%20Code&channelUrl="
            + WebDriverUtils.getBaseUrlString() + AutomatedFunctionalTestUtils.KNS_LOOKUP_METHOD +
            "org.kuali.rice.location.impl.postalcode.PostalCodeBo&docFormKey=88888888&returnLocation=" +
            AutomatedFunctionalTestUtils.PORTAL_URL + AutomatedFunctionalTestUtils.HIDE_RETURN_LINK ;

    @Override
    protected String getBookmarkUrl() {
        return BOOKMARK_URL;
    }

    /**
     * {@inheritDoc}
     * Postal Code
     * @return
     */
    @Override
    protected String getLinkLocator() {
        return "Postal Code";
    }

    @Override
    protected void createNewEnterDetails() throws InterruptedException {
        waitAndTypeByName("document.documentHeader.documentDescription", getDescriptionUnique());
        jiraAwareTypeByName("document.newMaintainableObject.countryCode", "US");
        jiraAwareTypeByName("document.newMaintainableObject.code", uniqueString);
        jiraAwareTypeByName("document.newMaintainableObject.stateCode", "IN");
        jiraAwareTypeByName("document.newMaintainableObject.cityName", "name" + uniqueString);
    }

    public void testLocationPostCodeBookmark(JiraAwareFailable failable) throws Exception {
        testCreateNewCancel();
        passed();
    }

    public void testLocationPostCodeNav(JiraAwareFailable failable) throws Exception {
        testCreateNewCancelNav();
        passed();
    }
}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>describe-layers — AWS CLI 1.0.0 documentation</title>
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" />

    <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" />
    <link rel="up" title="opsworks" href="index.html" />
    <link rel="next" title="describe-load-based-auto-scaling" href="describe-load-based-auto-scaling.html" />
    <link rel="prev" title="describe-instances" href="describe-instances.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" />

        AWS CLI

Home

Documentation

Forum

GitHub

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

opsworks »

          ← describe-instances
          /

describe-load-based-auto-scaling →

Table Of Contents

describe-layers

Description

Synopsis

Options

Examples

Quick search

    <form class="form-search margin-top-1em" action="../../search.html" method="get">
        <input type="text" name="q" style="width: 105px" class="input-small search-query" />
        <button type="submit" class="btn btn-small">Search</button>
        <input type="hidden" name="check_keywords" value="yes" />
        <input type="hidden" name="area" value="default" />
    </form>

Feedback

Did you find this page useful? Do you have a suggestion? Give us feedback or
  send us a pull request on GitHub.

[ aws . opsworks ]

describe-layers¶

Description¶

Requests a description of one or more layers in a specified stack.

Synopsis¶

  describe-layers
--stack-id <value>
[--layer-ids <value>]

Options¶

<tt class="docutils literal">--stack-id</tt> (string)

The stack ID.

<tt class="docutils literal">--layer-ids</tt> (list)

An array of layer IDs that specify the layers to be described. If you omit this parameter, <tt class="docutils literal">describe-layers</tt>  returns a description of every layer in the specified stack.

Syntax:

"string" "string" ...

Examples¶

To describe a stack's layers

The following <tt class="docutils literal">describe-layers</tt> commmand describes the layers in a stack, whose ID is
<tt class="docutils literal">38ee91e2-abdc-4208-a107-0b7168b3cc7a</tt>:

aws opsworks describe-layers --stack-id 38ee91e2-abdc-4208-a107-0b7168b3cc7a

Output:

{
  "Layers": [
      {
          "StackId": "38ee91e2-abdc-4208-a107-0b7168b3cc7a",
          "Type": "db-master",
          "DefaultSecurityGroupNames": [
              "AWS-OpsWorks-DB-Master-Server"
          ],
          "Name": "MySQL",
          "Packages": [],
          "DefaultRecipes": {
              "Undeploy": [],
              "Setup": [
                  "opsworks_initial_setup",
                  "ssh_host_keys",
                  "ssh_users",
                  "mysql::client",
                  "dependencies",
                  "ebs",
                  "opsworks_ganglia::client",
                  "mysql::server",
                  "dependencies",
                  "deploy::mysql"
              ],
              "Configure": [
                  "opsworks_ganglia::configure-client",
                  "ssh_users",
                  "agent_version",
                  "deploy::mysql"
              ],
              "Shutdown": [
                  "opsworks_shutdown::default",
                  "mysql::stop"
              ],
              "Deploy": [
                  "deploy::default",
                  "deploy::mysql"
              ]
          },
          "CustomRecipes": {
              "Undeploy": [],
              "Setup": [],
              "Configure": [],
              "Shutdown": [],
              "Deploy": []
          },
          "EnableAutoHealing": false,
          "LayerId": "41a20847-d594-4325-8447-171821916b73",
          "Attributes": {
              "MysqlRootPasswordUbiquitous": "true",
              "RubygemsVersion": null,
              "RailsStack": null,
              "HaproxyHealthCheckMethod": null,
              "RubyVersion": null,
              "BundlerVersion": null,
              "HaproxyStatsPassword": null,
              "PassengerVersion": null,
              "MemcachedMemory": null,
              "EnableHaproxyStats": null,
              "ManageBundler": null,
              "NodejsVersion": null,
              "HaproxyHealthCheckUrl": null,
              "MysqlRootPassword": "*****FILTERED*****",
              "GangliaPassword": null,
              "GangliaUser": null,
              "HaproxyStatsUrl": null,
              "GangliaUrl": null,
              "HaproxyStatsUser": null
          },
          "Shortname": "db-master",
          "AutoAssignElasticIps": false,
          "CustomSecurityGroupIds": [],
          "CreatedAt": "2013-07-25T18:11:19+00:00",
          "VolumeConfigurations": [
              {
                  "MountPoint": "/vol/mysql",
                  "Size": 10,
                  "NumberOfDisks": 1
              }
          ]
      },
      {
          "StackId": "38ee91e2-abdc-4208-a107-0b7168b3cc7a",
          "Type": "custom",
          "DefaultSecurityGroupNames": [
              "AWS-OpsWorks-Custom-Server"
          ],
          "Name": "TomCustom",
          "Packages": [],
          "DefaultRecipes": {
              "Undeploy": [],
              "Setup": [
                  "opsworks_initial_setup",
                  "ssh_host_keys",
                  "ssh_users",
                  "mysql::client",
                  "dependencies",
                  "ebs",
                  "opsworks_ganglia::client"
              ],
              "Configure": [
                  "opsworks_ganglia::configure-client",
                  "ssh_users",
                  "agent_version"
              ],
              "Shutdown": [
                  "opsworks_shutdown::default"
              ],
              "Deploy": [
                  "deploy::default"
              ]
          },
          "CustomRecipes": {
              "Undeploy": [],
              "Setup": [
                  "tomcat::setup"
              ],
              "Configure": [
                  "tomcat::configure"
              ],
              "Shutdown": [],
              "Deploy": [
                  "tomcat::deploy"
              ]
          },
          "EnableAutoHealing": true,
          "LayerId": "e6cbcd29-d223-40fc-8243-2eb213377440",
          "Attributes": {
              "MysqlRootPasswordUbiquitous": null,
              "RubygemsVersion": null,
              "RailsStack": null,
              "HaproxyHealthCheckMethod": null,
              "RubyVersion": null,
              "BundlerVersion": null,
              "HaproxyStatsPassword": null,
              "PassengerVersion": null,
              "MemcachedMemory": null,
              "EnableHaproxyStats": null,
              "ManageBundler": null,
              "NodejsVersion": null,
              "HaproxyHealthCheckUrl": null,
              "MysqlRootPassword": null,
              "GangliaPassword": null,
              "GangliaUser": null,
              "HaproxyStatsUrl": null,
              "GangliaUrl": null,
              "HaproxyStatsUser": null
          },
          "Shortname": "tomcustom",
          "AutoAssignElasticIps": false,
          "CustomSecurityGroupIds": [],
          "CreatedAt": "2013-07-25T18:12:53+00:00",
          "VolumeConfigurations": []
      }
  ]
}

For more information, see Layers in the OpsWorks User Guide.

          ← describe-instances
          /

describe-load-based-auto-scaling →

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

opsworks »

    © Copyright 2013, Amazon Web Services. Created using Sphinx.


text:
/* Duplex stream for Tellstick (Duo)
*/

var Duplex = require("stream").Duplex
var inherits = require("util").inherits
var tellsock = require("tellsock")
var through2 = require("through2")

function Tellstick() {
    this._init()

    Duplex.call(this, { objectMode: true })
}

inherits(Tellstick, Duplex)

Tellstick.prototype._init = function() {
    this.events = new tellsock.TelldusEvents()
    this.client = new tellsock.TelldusClient()

    this.events.on("raw", this.push.bind(this))

    this.events.on("end", function() {
        console.log("Reconnecting")
        setTimeout(this._init.bind(this), 3000)
    }.bind(this))
}

Tellstick.prototype._read = function (size) {
}

// [ command, deviceId, arg1, ... ]
Tellstick.prototype._write = function (arr, enc, done) {
    this.client[arr.splice(0,1)].apply(this.client, arr)
    done()
}

Tellstick.dimmerEvents = function(source) {

    /* Events from selflearning remotes come in the form of house, unit, method
     * Map them to id, dimLevel events using the remotes.js config */

    var buttonMap = require("../config/remotes")

    return source.pipe(through2.obj(function(obj, enc, done) {
        var house = buttonMap[obj.house] || {}
        var tuple = house[obj.unit]
        if (tuple) {
            this.push({
                id: "light" + tuple[0],
                key: "dimLevel",
                value: (obj.method == 'turnoff') ? 0 : tuple[1],
                origin: [ "433mhz", obj.house, obj.unit ].join(":")
            })
        }
        done()
    }))
}

Tellstick.sensorEvents = function(source) {
    return source.pipe(through2.obj(function(obj, enc, done) {
        if (obj.temp || obj.humidity) {
            var ev = { id: "rf" + obj.id }
            if (obj.temp) ev.temperature = parseFloat(obj.temp);
            if (obj.humidity) ev.humidity = parseFloat(obj.humidity);
            this.push(ev)
        }
        done()
    }))
}

module.exports = Tellstick


text:
require 'minitest_helper'

describe Fog::Compute::XenServer::Models::Consoles do
  let(:consoles_class) { Fog::Compute::XenServer::Models::Consoles }

  it 'should be a collection of Consoles' do
    consoles_class.model.must_equal(Fog::Compute::XenServer::Models::Console)
  end
end


text:
#ifndef __MenuLayer_h__
#define __MenuLayer_h__

class MenuLayer : public CCLayer
{
	public :

		CREATE_FUNC ( MenuLayer );

	protected :

		virtual KDbool			init				( KDvoid );

		KDvoid					onButtonClick		( CCObject*	pSender );

		KDvoid					initMenuButton		( CCMenu* pMenu, const KDchar* name, KDint tag );
};

#endif	//__MenuLayer_h__


text:
package main //same package name as source file

import (
	"testing" //import go package for testing related functionality
)

func Benchmark_nthPrime1(b *testing.B) { // Form: Benchmark_functionName
	for i := 0; i < b.N; i++ {
		nthPrime1(10001)
	}
}

func Benchmark_nthPrime2(b *testing.B) { // Form: Benchmark_functionName
	for i := 0; i < b.N; i++ {
		nthPrime2(10001)
	}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DebugLogListener.cs" company="Catel development team">
//   Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

#if SL5

namespace Catel.Logging
{
    using System;
    using System.Windows.Browser;
    using System.Windows.Threading;

    public partial class DebugLogListener
    {
        private ScriptObject _console = null;
        private readonly Dispatcher _dispatcher = System.Windows.Deployment.Current.Dispatcher;

        /// <summary>
        /// Initializes the console for silverlight applications.
        /// </summary>
        /// <returns><c>true</c> if the console is available; otherwise <c>false</c>.</returns>
        private bool InitializeConsole()
        {
            try
            {
                if (_console == null && HtmlPage.IsEnabled)
                {
                    if (!_dispatcher.CheckAccess())
                    {
                        return false;
                    }

                    var window = HtmlPage.Window;
                    var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
                    if (isConsoleAvailable)
                    {
                        var createLogFunction = (bool)window.Eval("typeof(catellog) === 'undefined'");
                        if (createLogFunction)
                        {
                            // Load the logging function into global scope:
                            const string logFunction = @"function catellog(msg) { console.log(msg); }";
                            string code = string.Format(@"if(window.execScript) {{ window.execScript('{0}'); }} else {{ eval.call(null, '{0}'); }}", logFunction);
                            window.Eval(code);
                        }

                        _console = window.Eval("catellog") as ScriptObject;
                    }
                }
            }
            catch (Exception)
            {
            }

            return (_console != null);
        }

        /// <summary>
        /// Called when any message is written to the log.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="message">The message.</param>
        /// <param name="logEvent">The log event.</param>
        /// <param name="extraData">The extra data.</param>
        /// <param name="time">The time.</param>
        protected override void Write(ILog log, string message, LogEvent logEvent, object extraData, DateTime time)
        {
            string consoleMessage = FormatLogEvent(log, message, logEvent, extraData, time);

            if (InitializeConsole())
            {
                _dispatcher.BeginInvoke(() => _console.InvokeSelf(consoleMessage));
            }

            System.Diagnostics.Debug.WriteLine(consoleMessage);
        }
    }
}

#endif


text:
#include <openbabel/babelconfig.h>
#include <openbabel/op.h>
#include <openbabel/mol.h>
#include <openbabel/obconversion.h>
#include <openbabel/descriptor.h>
#include <openbabel/inchiformat.h>
#if defined(_MSC_VER) || defined(_LIBCPP_VERSION)
  #include <unordered_map>
#elif (__GNUC__ == 4 && __GNUC_MINOR__ >= 1 && !defined(__APPLE_CC__))
  #include <tr1/unordered_map>
#else
  #ifdef USE_BOOST
    #include <boost/tr1/unordered_map.hpp>
  #else
    #define NO_UNORDERED_MAP
    #include <map>
  #endif
#endif

using namespace std;
#ifndef NO_UNORDERED_MAP
  #ifdef _LIBCPP_VERSION
    using std::unordered_map;
  #else
    using std::tr1::unordered_map;
  #endif
#endif
namespace OpenBabel
{

class OpUnique : public OBOp
{
public:
  OpUnique(const char* ID) : OBOp(ID, false){
    OBConversion::RegisterOptionParam("unique", NULL, 1, OBConversion::GENOPTIONS);}

  const char* Description(){ return
    "[param] remove duplicates by descriptor;default inchi\n"
    "param is a descriptor or property, or a truncation spec for InChI\n"
    "(making the comparison less detailed, see below).\n"
    "An OpenBabel warning message is output for each duplicate.\n"
    "Examples: --unique   --unique cansmi   --unique /nostereo\n\n"

    "The duplicates can be output instead by making the first character\n"
    "in the parameter ~  e.g. --unique ~cansmi   --unique ~\n\n"

    "/formula  formula only\n"
    "/connect  formula and connectivity only\n"
    "/nostereo ignore E/Z and sp3 stereochemistry\n"
    "/nosp3    ignore sp3 stereochemistry\n"
    "/noEZ     ignore E/Z steroeochemistry\n"
    "/nochg    ignore charge and protonation\n"
    "/noiso    ignore isotopes\n\n"
; }

  virtual bool WorksWith(OBBase* pOb)const{ return dynamic_cast<OBMol*>(pOb)!=NULL; }
  virtual bool Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion* pConv);

private:

  bool _reportDup;
  std::string _trunc;
  OBDescriptor* _pDesc;
  unsigned _ndups;
  bool _inv;

#ifdef NO_UNORDERED_MAP
  typedef map<std::string, std::string> UMap;
#else
  typedef unordered_map<std::string, std::string> UMap;
#endif

  //key is descriptor text(usually inchi) value is molecule title
  UMap _inchimap;
};

/////////////////////////////////////////////////////////////////
OpUnique theOpUnique("unique"); //Global instance

/////////////////////////////////////////////////////////////////
bool OpUnique::Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion* pConv)
{
  OBMol* pmol = dynamic_cast<OBMol*>(pOb);
  if(!pmol)
    return false;

  if(pConv->IsFirstInput())
  {
    _ndups=0;
    string descID("inchi"); // the default
    _trunc.clear();
    _inv = OptionText[0]=='~';   //has the parameter a leading ~ ?
    if(_inv)
      clog << "The output has the duplicate structures" << endl;

    if(OptionText[0+_inv]=='/')  //is parameter is /x?
      _trunc = OptionText+_inv;
    else if(OptionText[0+_inv]!='\0') // not empty?
      descID = OptionText+_inv;

    _pDesc = OBDescriptor::FindType(descID.c_str());
    if(!_pDesc)
    {
      obErrorLog.ThrowError(__FUNCTION__,
              "Cannot find descriptor " + descID, obError, onceOnly);
      return false;
    }
    _pDesc->Init();
    _inchimap.clear();

    _reportDup = !_inv; //do not report duplicates when they are the output
  }

  if(!_pDesc)
    return false;
  std::string s;
  _pDesc->GetStringValue(pmol, s);

  if(!_trunc.empty())
    InChIFormat::EditInchi(s, _trunc);
  std::pair<UMap::iterator, bool> result = _inchimap.insert(make_pair(s, pmol->GetTitle()));
  bool ret = true;
  if(!s.empty() && !result.second)
  {
    // InChI is already present in set
    ++_ndups;
    if(_reportDup)
      clog << "Removed " << pmol->GetTitle() << " - a duplicate of " << result.first->second
         << " (#" << _ndups << ")" << endl;
    //delete pOb;
    ret = false; //filtered out
  }
  if(_inv)
    ret = !ret;
  if(!ret)
    delete pOb;
  return ret;
}

}//namespace
/*
Usage: --unique param
During conversion, this option eliminates molecules that are identical by some criterion.
With current babel interface it needs to be last on the command line. With nbabel
it can be anywhere.
If param is missing the criterion is the InChI.
If param starts with / the criterion is a truncated InChI string, see below.
Otherwise param is taken as a descriptor or property ID and the criterion is
its string value. Descriptors which couldbe useful here are cansmi, cansmiNS
(ignores stereo) and possibly title.

OpUnique works by attempting to insert the string value of the descriptor for
each molecule to an internal std::unordered_map. If the string has been seen
previously, the molecule is deleted and OpUnique::Do() returns false, which
causes the molecule not to be output.

InChI trucation values. param can be a concatination of these e.g. /nochg/noiso
/formula  formula only
/connect formula and connectivity only
/nostereo ignore E/Z and sp3 stereochemistry
/nosp3    ignore sp3 stereochemistry
/noEZ     ignore E/Z steroeochemistry
/nochg    ignore charge and protonation
/noiso    ignore isotopes

*/


text:
package de.kaiserpfalzedv.paladinsinn.commons.api.paging;

import java.io.Serializable;
import java.util.List;

/**
 * A data page.
 *
 * @author klenkes {@literal <rlichti@kaiserpfalz-edv.de>}
 * @version 1.0.0
 * @since 2017-03-17
 */
public interface Page<T extends Serializable> extends Serializable {
    /**
     * @return The data content of the page retrieved.
     */
    List<T> getData();

    /**
     * @return The default page size requested. The {@link #getCurrentPageSize()} can vary from this value, since the
     * last page can be smaller than the other ones.
     */
    long getPageSize();

    /**
     * @return The current page number of this data set.
     */
    long getCurrentPageNumber();

    /**
     * @return The current page size of this data set. The page size can be smaller than the requested page size on the
     * last page.
     */
    long getCurrentPageSize();

    /**
     * @return The total number of pages of the requested data set.
     */
    long getTotalPages();

    /**
     * @return The total number of elements on all pages of the requested data set.
     */
    long getTotalElements();

    /**
     * @return The current request definition.
     */
    PageRequest getCurrentRequest();

    /**
     * @return The {@link PageRequest} to retrieve the first page of the data set.
     */
    PageRequest getFirstPageRequest();

    /**
     * Retrieves a {@link PageRequest} for the previous page. If the current page is the first page, then a request
     * information set for the same page again is returned.
     *
     * @return The request information to retrieve the previous page of the data set.
     */
    PageRequest getPreviousPageRequest();

    /**
     * Retrieves a {@link PageRequest} for the next page. If the current page is the last page, then a request
     * information set for the same page again is returned.
     *
     * @return The request information to retrieve the next page of the data set.
     */
    PageRequest getNextPageRequest();

    /**
     * @return The {@link PageRequest} to retrieve the last page of the data set.
     */
    PageRequest getLastPageRequest();
}


text:
alert-message: ', http://getbootstrap.com, and http://c3js.org/'
categories: [Charts]
layout: page
title: Donut Charts
resource: true
url-js-extra: ['//cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js', '//cdnjs.cloudflare.com/ajax/libs/d3/3.5.0/d3.min.js']
---

Donut Chart - Utilization

    {% include widgets/charts/donut-utilization.html id="utilizationDonutChart" %}

Donut Chart - Relationship to a Whole

    {% include widgets/charts/donut-whole-relationship.html id1="donut-chart-no-legend" id2="donut-chart-right-legend" id3="donut-chart-bottom-legend" %}

Donut Chart - Small

    {% include widgets/charts/donut-mini.html id="smallDonutChart" %}


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <Button
        android:id="@+id/client_certificate_spinner_button"
        style="?android:attr/spinnerStyle"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/client_certificate_spinner_empty"
        android:freezesText="true" />

    <ImageButton
        android:id="@+id/client_certificate_spinner_delete"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="@drawable/selectable_item_background"
        android:contentDescription="@string/client_certificate_spinner_delete"
        android:padding="8dp"
        android:src="?attr/iconActionCancel" />

</merge>


text:
package seaclouds.utils.toscamodel.impl;

import seaclouds.utils.toscamodel.INamedEntity;
import seaclouds.utils.toscamodel.INodeType;
import seaclouds.utils.toscamodel.IProperty;
import seaclouds.utils.toscamodel.IType;

import java.util.Collections;
import java.util.Map;

/**
 * Created by pq on 20/04/2015.
 */
public class NamedNodeType extends  NodeType implements INamedEntity {
    private String name;
    public boolean hidden = false;

    @Override
    public String toString() {
        return name();
    }

    public NamedNodeType(String name, NodeType unnamedNodeType) {
        super((NodeType)unnamedNodeType.baseType, unnamedNodeType.description,unnamedNodeType.declaredProperties ,unnamedNodeType.attributes);
        this.name = name;
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public INodeType addProperty(String propName, IType propType, Object defaultValue) {
        if(propName == null)
            return new NodeType(this,description,Collections.emptyMap(),Collections.emptyMap());
        return new NodeType(this,description, Collections.singletonMap(propName,new Property(propType, defaultValue)),Collections.emptyMap());
    }

    @Override
    public INodeType changeDescription(String newDescription) {
        return new NodeType((NodeType)baseType,newDescription,declaredProperties,attributes);
    }

    public void rename(String newEntityName) {
        name = newEntityName;
    }
}


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

namespace Prolog.Code
{
    /// <summary>
    /// Represents a list of the form [Head|Tail].
    /// </summary>
    /// <remarks>The head of a <see cref="CodeList"/> can contain an arbitrary number of elements.</remarks>
    [Serializable]
    public sealed class CodeList : CodeTerm, IEquatable<CodeList>, IImmuttable
    {
        #region Fields

        public new const string ElementName = "CodeList";

        private CodeTermList m_head;
        private CodeTerm m_tail;

        #endregion

        #region Constructors

        public CodeList()
        {
            m_head = new CodeTermList(new List<CodeTerm>());
            m_tail = new CodeCompoundTerm(CodeFunctor.NilFunctor);
        }

        public CodeList(IEnumerable<CodeTerm> head, CodeTerm tail)
        {
            if (head == null)
            {
                throw new ArgumentNullException("head");
            }
            if (tail == null)
            {
                throw new ArgumentNullException("tail");
            }

            if (tail.IsCodeList)
            {
                List<CodeTerm> headTerms = new List<CodeTerm>(head);
                headTerms.AddRange(tail.AsCodeList.Head);

                m_head = new CodeTermList(headTerms);
                m_tail = tail.AsCodeList.Tail;
            }
            else
            {
                m_head = new CodeTermList(new List<CodeTerm>(head));
                m_tail = tail;
            }
        }

        public new static CodeList Create(XElement xCodeList)
        {
            return new CodeList(
                CodeTermList.Create(xCodeList.Element(CodeTermList.ElementName)),
                CodeTerm.Create(xCodeList.Element(CodeTerm.ElementName)));
        }

        #endregion

        #region Public Properties

        public CodeTermList Head
        {
            get { return m_head; }
        }

        public CodeTerm Tail
        {
            get { return m_tail; }
        }

        public override bool IsCodeList
        {
            get { return true; }
        }

        #endregion

        #region Public Methods

        public override bool Equals(object obj)
        {
            if (obj == null) return false;

            CodeList rhs = obj as CodeList;
            if (rhs == null) return false;

            return Head == rhs.Head
                   && Tail == rhs.Tail;
        }

        public override int GetHashCode()
        {
            return Head.GetHashCode()
                   ^ Tail.GetHashCode();
        }

        public static bool operator ==(CodeList lhs, CodeList rhs)
        {
            if (object.ReferenceEquals(lhs, rhs)) return true;

            if (object.ReferenceEquals(lhs, null) || object.ReferenceEquals(rhs, null)) return false;

            return lhs.Equals(rhs);
        }

        public static bool operator !=(CodeList lhs, CodeList rhs)
        {
            return !(lhs == rhs);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("[");

            string prefix = null;
            foreach (CodeTerm codeTerm in Head)
            {
                sb.Append(prefix); prefix = ",";
                sb.Append(codeTerm.ToString());
            }

            if (Tail.IsCodeCompoundTerm
                && Tail.AsCodeCompoundTerm.Functor == CodeFunctor.NilFunctor)
            {
                // no action required.
            }
            else
            {
                sb.Append("|");
                sb.Append(Tail.ToString());
            }

            sb.Append("]");

            return sb.ToString();
        }

        public override XElement ToXElement()
        {
            return ToXElementBase(
                new XElement(ElementName,
                    Head.ToXElement(),
                    Tail.ToXElement()));
        }

        #endregion

        #region IEquatable<CodeList> Members

        public override bool Equals(CodeTerm other)
        {
            return Equals(other as CodeList);
        }

        public bool Equals(CodeList other)
        {
            if (object.ReferenceEquals(other, null)) return false;

            return Head == other.Head
                   && Tail == other.Tail;
        }

        #endregion
    }
}


text:
package org.jbpm.persistence.map.impl;

import static org.jbpm.persistence.util.PersistenceUtil.*;
import static org.kie.api.runtime.EnvironmentName.ENTITY_MANAGER_FACTORY;
import static org.kie.api.runtime.EnvironmentName.USE_PESSIMISTIC_LOCKING;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;

import javax.persistence.EntityManagerFactory;

import org.drools.persistence.jta.JtaTransactionManager;
import org.jbpm.persistence.util.PersistenceUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.kie.api.KieBase;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.kie.internal.persistence.jpa.JPAKnowledgeService;
import org.kie.internal.runtime.StatefulKnowledgeSession;

@RunWith(Parameterized.class)
public class JpaBasedPersistenceTest extends MapPersistenceTest {

    private HashMap<String, Object> context;
    private EntityManagerFactory emf;
    private JtaTransactionManager txm;
    private boolean useTransactions = false;

    public JpaBasedPersistenceTest(boolean locking) {
       this.useLocking = locking;
    }

    @Parameters
    public static Collection<Object[]> persistence() {
        Object[][] data = new Object[][] { { false }, { true } };
        return Arrays.asList(data);
    };

    @Before
    public void setUp() throws Exception {
        context = PersistenceUtil.setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
        emf = (EntityManagerFactory) context.get(ENTITY_MANAGER_FACTORY);

        if( useTransactions() ) {
            useTransactions = true;
            Environment env = createEnvironment(context);
            Object tm = env.get( EnvironmentName.TRANSACTION_MANAGER );
            this.txm = new JtaTransactionManager( env.get( EnvironmentName.TRANSACTION ),
                env.get( EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY ),
                tm );
        }
    }

    @After
    public void tearDown() throws Exception {
       cleanUp(context);
    }

    @Override
    protected StatefulKnowledgeSession createSession(KieBase kbase) {
        Environment env = createEnvironment(context);
        if( this.useLocking ) {
            env.set(USE_PESSIMISTIC_LOCKING, true);
        }
        return JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env);
    }

    @Override
    protected StatefulKnowledgeSession disposeAndReloadSession(StatefulKnowledgeSession ksession, long ksessionId,
                                                               KieBase kbase) {
        ksession.dispose();
        return JPAKnowledgeService.loadStatefulKnowledgeSession( ksessionId, kbase, null, createEnvironment(context) );
    }

    @Override
    protected int getProcessInstancesCount() {
        boolean txOwner = false;
        if( useTransactions ) {
            txOwner = txm.begin();
        }
        int size =  emf.createEntityManager().createQuery( "FROM ProcessInstanceInfo" ).getResultList().size();
        if( useTransactions ) {
            txm.commit(txOwner);
        }
        return size;
    }

    @Override
    protected int getKnowledgeSessionsCount() {
        boolean transactionOwner = false;
        if( useTransactions ) {
            transactionOwner = txm.begin();
        }
        int size = emf.createEntityManager().createQuery( "FROM SessionInfo" ).getResultList().size();
        if( useTransactions ) {
            txm.commit(transactionOwner);
        }
        return size;
    }

}


text:
<?php

abstract class yTest_ListChanges extends yTest_Changes {
    abstract protected function getElementDesc();

    /**
     * Description methods
     */

    public function add($id) {
        $this->addChange(new ChangeListAdd($this, $id));
        return $this;
    }

    public function remove($id) {
        $this->addChange(new ChangeListRemove($this, $id));
        return $this;
    }

    /**
     * Helpers
     */

    protected function getChangeById($id) {
        foreach ($this->changes as $change) {
            if ( $change->getId() == $id ) {
                return $change;
            }
        }
        return null;
    }

    public function assertChanges($test, & $initialData, & $finalData, $msg = null) {
        foreach ($this->getElementsList($initialData, $finalData) as $elementId) {
            if ( in_array($elementId, $this->ignoredElements) ) {
                continue;
            }
            if ( $this->getChangeById($elementId) === null ) {
                if ( $this->getElement($initialData, $elementId) === null ) {
                    $test->fail(($msg !== null ? $msg."\n" : '').'Unexpected addition of '.$this->getElementDesc().' '.$elementId);
                }
                if ( $this->getElement($finalData, $elementId) === null ) {
                    $test->fail(($msg !== null ? $msg."\n" : '').'Unexpected removal of '.$this->getElementDesc().' '.$elementId);
                }
            }
        }

        foreach ($this->changes as $change) {
            if (YTEST_DEBUG_CHANGE_ASSERTIONS) {
                echo "assert ".$change."\n";
            }
            $change->assertChange($test,
                $this->getElement($initialData, $change->getId()),
                $this->getElement($finalData, $change->getId()),
                $this->getElementDesc(),
                $msg
                                 );
        }
    }

    protected function getElementsList($initialData, $finalData) {
        return array_merge($initialData, $finalData);
    }

    protected function getElement($data, $id) {
        return in_array($id, $data) ? $id : null;
    }
}

class ChangeListDescription extends yTest_ChangeDescription {
    protected $elementId;

    public function __construct($container, $elementId) {
        parent::__construct($container);
        $this->elementId = $elementId;
    }

    public function getId() {
        return $this->elementId;
    }

    public function __toString() {
        return parent::__toString().' elementId='.$this->elementId;
    }

    // Top stack
    public function add() {
        $this->container->addChange($this);
        $args = func_get_args();
        return call_user_func_array(array($this->container, 'add'), $args);
    }

    public function remove() {
        $this->container->addChange($this);
        $args = func_get_args();
        return call_user_func_array(array($this->container, 'remove'), $args);
    }
}

class ChangeListAdd extends ChangeListDescription {
    public function assertChange($test, $initialElement, $finalElement, $elementDesc, $msg = null) {
        if ( $initialElement !== null ) {
            $test->fail(($msg !== null ? $msg."\n" : '').'Expecting addition of '.$elementDesc.' '.$this->elementId.' but it was already present initially');
        }
        if ( $finalElement === null ) {
            $test->fail(($msg !== null ? $msg."\n" : '').'Expected addition of '.$elementDesc.' '.$this->elementId.' did not happen');
        }
    }
}

class ChangeListRemove extends ChangeListDescription {
    public function assertChange($test, $initialElement, $finalElement, $elementDesc, $msg = null) {
        if ( $initialElement === null ) {
            $test->fail(($msg !== null ? $msg."\n" : '').'Expecting removal of '.$elementDesc.' '.$this->elementId.' but it was not present initially');
        }
        if ( $finalElement !== null ) {
            $test->fail(($msg !== null ? $msg."\n" : '').'Expected removal of '.$elementDesc.' '.$this->elementId.' did not happen');
        }
    }
}


text:
"use strict";
describe("movement-store module", function() {
  beforeEach(module("tichu-movement-store", "tichu-tournament-store"));

  describe("TichuMovementStore", function() {
    var store, tournamentStore;

    beforeEach(inject(function (TichuMovementStore, TichuTournamentStore) {
      store = TichuMovementStore;
      tournamentStore = TichuTournamentStore;
    }));

    describe("getOrCreateMovement", function() {
      it("creates a new movement with a pair and tournament from the tournament store", function() {
        expect(store.hasMovement("12345", 5)).toBe(false);
        var movement = store.getOrCreateMovement("12345", 5);
        expect(store.hasMovement("12345", 5)).toBe(true);
        expect(movement.tournamentId).toBe(tournamentStore.getOrCreateTournamentHeader("12345"));
        expect(movement.pair).toBe(tournamentStore.getOrCreateTournamentPair("12345", 5));
      });

      it("stores the movement and returns it on subsequent calls", function() {
        var movement = store.getOrCreateMovement("9999", 9);
        expect(store.getOrCreateMovement("9999", 9)).toBe(movement);
      });

      it("returns different objects for different IDs", function() {
        var movementA = store.getOrCreateMovement("54321", 5);
        var movementB = store.getOrCreateMovement("12345", 5);
        expect(movementB).not.toBe(movementA);
      });

      it("returns different objects for different pair numbers", function() {
        var movementA = store.getOrCreateMovement("54321", 8);
        var movementB = store.getOrCreateMovement("54321", 9);
        expect(movementB).not.toBe(movementA);
      });
    });

    describe("getOrCreateHand", function() {
      it("creates a new hand with the hand number and pairs given", function() {
        var hand = store.getOrCreateHand("12345", 1, 2, 3);
        expect(hand.northSouthPair).toBe(1);
        expect(hand.eastWestPair).toBe(2);
        expect(hand.handNo).toBe(3);
      });

      it("stores the movement and returns it on subsequent calls", function() {
        var hand = store.getOrCreateHand("9999", 8, 9, 5);
        expect(store.getOrCreateHand("9999", 8, 9, 5)).toBe(hand);
      });

      it("returns different objects for different IDs", function() {
        var handA = store.getOrCreateHand("696969", 6, 9, 6);
        var handB = store.getOrCreateHand("969696", 6, 9, 6);
        expect(handB).not.toBe(handA);
      });

      it("returns different objects for different north-south pair numbers", function() {
        var handA = store.getOrCreateHand("696969", 5, 9, 6);
        var handB = store.getOrCreateHand("696969", 6, 9, 6);
        expect(handB).not.toBe(handA);
      });

      it("returns different objects for different east-west pair numbers", function() {
        var handA = store.getOrCreateHand("696969", 6, 8, 6);
        var handB = store.getOrCreateHand("696969", 6, 9, 6);
        expect(handB).not.toBe(handA);
      });

      it("returns different objects for different board numbers", function() {
        var handA = store.getOrCreateHand("696969", 6, 9, 5);
        var handB = store.getOrCreateHand("696969", 6, 9, 6);
        expect(handB).not.toBe(handA);
      });
    });
  });
});


text:
:mod:`foolbox.devutils`
=======================

.. automodule:: foolbox.devutils
   :members:
   :undoc-members:


text:
package com.almasb.event;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
 */
public class GameApp extends Application {

    private EventBus eventBus;

    private AudioPlayer audioPlayer;

    @Override
    public void start(Stage stage) throws Exception {
        eventBus = ServiceLocator.INSTANCE.getService(EventBus.class);
        audioPlayer = ServiceLocator.INSTANCE.getService(AudioPlayer.class);

        Scene scene = new Scene(new VBox(), 600, 600);
        scene.setOnMouseClicked(event -> {
            eventBus.fireEvent(new GameEvent(GameEvent.PLAYER_DIED));
        });

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        ServiceLocator.INSTANCE.registerService(EventBus.class, EventBusProvider.class);
        ServiceLocator.INSTANCE.registerService(AudioPlayer.class, MockAudioPlayer.class);

        launch(args);
    }
}


text:
from conans.errors import ConanException
from conans.model.settings import Settings
import os

class CMake(object):

    def __init__(self, settings):
        assert isinstance(settings, Settings)
        self._settings = settings

    @staticmethod
    def options_cmd_line(options, option_upper=True, value_upper=True):
        result = []
        for option, value in options.values.as_list():
            if value is not None:
                option = option.upper() if option_upper else option
                value = value.upper() if value_upper else value
                result.append("-D%s=%s" % (option, value))
        return ' '.join(result)

    @property
    def generator(self):
        if (not self._settings.compiler or
                not self._settings.compiler.version or
                not self._settings.arch):
            raise ConanException("You must specify compiler, compiler.version and arch in "
                                 "your settings to use a CMake generator")

        operating_system = str(self._settings.os) if self._settings.os else None
        compiler = str(self._settings.compiler) if self._settings.compiler else None
        arch = str(self._settings.arch) if self._settings.arch else None

        if "CONAN_CMAKE_GENERATOR" in os.environ:
            return os.environ["CONAN_CMAKE_GENERATOR"]

        if compiler == "Visual Studio":
            _visuals = {'8': '8 2005',
                        '9': '9 2008',
                        '10': '10 2010',
                        '11': '11 2012',
                        '12': '12 2013',
                        '14': '14 2015'}
            str_ver = str(self._settings.compiler.version)
            base = "Visual Studio %s" % _visuals.get(str_ver, "UnknownVersion %s" % str_ver)
            if arch == "x86_64":
                return base + " Win64"
            elif "arm" in str(arch):
                return base + " ARM"
            else:
                return base

        if operating_system == "Windows":
            if compiler == "gcc":
                return "MinGW Makefiles"
            if compiler in ["clang", "apple-clang"]:
                return "MinGW Makefiles"
        if operating_system == "Linux":
            if compiler in ["gcc", "clang", "apple-clang"]:
                return "Unix Makefiles"
        if operating_system == "Macos":
            if compiler in ["gcc", "clang", "apple-clang"]:
                return "Unix Makefiles"

        if compiler in ["arm-none-eabi-gcc", "avr-gcc"]:
            return "Unix Makefiles"

        raise ConanException("Unknown cmake generator for these settings")

    @property
    def is_multi_configuration(self):
        """ some IDEs are multi-configuration, as Visual. Makefiles or Ninja are single-conf
        """
        if "Visual" in str(self._settings.compiler):
            return True
        # TODO: complete logic
        return False

    @property
    def command_line(self):
        return '-G "%s" %s %s %s -Wno-dev' % (self.generator, self.build_type,
                                              self.runtime, self.flags)

    @property
    def build_type(self):
        try:
            build_type = self._settings.build_type
        except ConanException:
            return ""
        if build_type and not self.is_multi_configuration:
            return "-DCMAKE_BUILD_TYPE=%s" % build_type
        return ""

    @property
    def build_config(self):
        """ cmake --build tool have a --config option for Multi-configuration IDEs
        """
        try:
            build_type = self._settings.build_type
        except ConanException:
            return ""
        if build_type and self.is_multi_configuration:
            return "--config %s" % build_type
        return ""

    @property
    def flags(self):
        op_system = str(self._settings.os) if self._settings.os else None
        arch = str(self._settings.arch) if self._settings.arch else None
        comp = str(self._settings.compiler) if self._settings.compiler else None
        comp_version = self._settings.compiler.version

        flags = []
        if op_system == "Windows":
            if comp == "clang":
                flags.append("-DCMAKE_C_COMPILER=clang")
                flags.append("-DCMAKE_CXX_COMPILER=clang++")
        if comp:
            flags.append('-DCONAN_COMPILER="%s"' % comp)
        if comp_version:
            flags.append('-DCONAN_COMPILER_VERSION="%s"' % comp_version)
        if arch == "x86":
            if op_system == "Linux":
                flags.extend(["-DCONAN_CXX_FLAGS=-m32",
                              "-DCONAN_SHARED_LINKER_FLAGS=-m32",
                              "-DCONAN_C_FLAGS=-m32"])
            elif op_system == "Macos":
                flags.append("-DCMAKE_OSX_ARCHITECTURES=i386")

        try:
            libcxx = self._settings.compiler.libcxx
            flags.append('-DCONAN_LIBCXX="%s"' % libcxx)
        except:
            pass
        return " ".join(flags)

    @property
    def runtime(self):
        try:
            runtime = self._settings.compiler.runtime
        except ConanException:
            return ""
        if runtime:
            return "-DCONAN_LINK_RUNTIME=/%s" % runtime
        return ""


text:
package moe.tristan.easyfxml.samples.form.user.view;

import org.springframework.stereotype.Component;

import moe.tristan.easyfxml.FxUiManager;
import moe.tristan.easyfxml.api.FxmlComponent;
import moe.tristan.easyfxml.samples.form.user.view.userform.UserFormComponent;

@Component
public class UserFormUiManager extends FxUiManager {

    private final UserFormComponent userFormComponent;

    public UserFormUiManager(UserFormComponent userFormComponent) {
        this.userFormComponent = userFormComponent;
    }

    @Override
    protected String title() {
        return "User sign up form";
    }

    @Override
    protected FxmlComponent mainComponent() {
        return userFormComponent;
    }

}


text:
<html><head>
<meta name="description" content="java-applet for learning "/>
<meta name="author" content="annemarie.govindraj">
<meta name="keywords" content="interactive">
</head>
<body>
<applet code="trywritemathsymbols.class" width="100%" height="100%">
<param name="step" value="6">
</applet></body>
</html>


text:
{{ 'log.LOGTITLE' | translate }}

         <tabset>
            <tab heading="货币变动查询">
               <legend>
                  <form role="form" name="log.searchForm" ng-submit="log.search(1)" novalidate="" class="form-validate form-inline">
                     <select name="server" ng-model="log.search.selectedServer" ng-options="item as item.name for item in log.servers" class="form-control">
                        <option value="">选择服务器</option>
                     </select>
                     <select name="currencyType" ng-model="log.search.currencyType" ng-options="item.value as item.name for item in log.currencyType" class="form-control">
                        <option value="">选择货币类型</option>
                     </select>
                     <input id="input-username" name="username" ng-model="log.search.username" placeholder="输入账号" class="form-control" />
                     <input id="input-userid" name="userid" type="number" ng-model="log.search.userid" placeholder="输入玩家ID" class="form-control" />
                     <select name="searchTime" ng-model="log.search.selectedSearchTime" ng-options="item.value as item.name for item in log.searchTime" class="form-control">
                        <option value="">选择查询时间</option>
                     </select>
                     <button type="submit" ng-disabled="log.searching" class="btn btn-primary btn-s">查询</button>
                  </form>

               </legend>

                        账号
                        账号ID
                        {{ log.search.lastCurrencyTypeNmae }}变动值
                        {{ log.search.lastCurrencyTypeNmae }}当前值
                        途径类型
                        操作时间

                        {{ item.username }}
                        {{ item.user_id }}
                        {{ item.change }}
                        {{ item.current }}
                        {{ item.type }}
                        {{ item.time }}

            </tab>
            <tab heading="物品变动查询">
               <legend>
                  <form role="form" name="log.searchForm" ng-submit="log.search(2)" novalidate="" class="form-validate form-inline">
                     <select name="server" ng-model="log.search.selectedServer" ng-options="item as item.name for item in log.servers" class="form-control">
                        <option value="">请选择服务器</option>
                     </select>
                     <input id="input-username" name="username" ng-model="log.search.username" placeholder="输入账号" class="form-control" />
                     <input id="input-userid" name="userid" type="number" ng-model="log.search.userid" placeholder="输入玩家ID" class="form-control" />
                     <input id="input-itemid" name="itemid" type="number" ng-model="log.search.itemid" placeholder="输入道具模板ID" class="form-control" />
                     <select name="searchTime" ng-model="log.search.selectedSearchTime" ng-options="item.value as item.name for item in log.searchTime" class="form-control">
                        <option value="">请选择查询时间</option>
                     </select>
                     <button type="submit" ng-disabled="log.searching" class="btn btn-primary btn-s">查询</button>
                  </form>

               </legend>

                        账号
                        账号ID
                        物品ID
                        变动值
                        当前值
                        途径类型
                        操作时间

                        {{ item.username }}
                        {{ item.user_id }}
                        {{ item.itemid }}
                        {{ item.change }}
                        {{ item.current }}
                        {{ item.type }}
                        {{ item.time }}

            </tab>
            <tab heading="充值记录查询">
               <legend>
                  <form role="form" name="log.searchForm" ng-submit="log.search(3)" novalidate="" class="form-validate form-inline">
                     <select name="server" ng-model="log.search.selectedServer" ng-options="item as item.name for item in log.servers" class="form-control">
                        <option value="">请选择服务器</option>
                     </select>
                     <input id="input-username" name="username" ng-model="log.search.username" placeholder="输入账号" class="form-control" />
                     <input id="input-userid" name="userid" type="number" ng-model="log.search.userid" placeholder="输入玩家ID" class="form-control" />
                     <select name="searchTime" ng-model="log.search.selectedSearchTime" ng-options="item.value as item.name for item in log.searchTime" class="form-control">
                        <option value="">请选择查询时间</option>
                     </select>
                     <button type="submit" ng-disabled="log.searching" class="btn btn-primary btn-s">查询</button>
                  </form>

               </legend>

                        账号
                        账号ID
                        充值金额
                        总充值金额
                        操作时间

                           {{ item.username }}
                           {{ item.user_id }}
                           {{ item.recharge }}
                           {{ item.totalrecharge }}
                           {{ item.time }}

            </tab>
            <tab heading="高级查询">
               <legend>
                  <form role="form" name="log.searchForm" ng-submit="log.search(4)" novalidate="" class="form-validate form-inline">
                     <select name="server" ng-model="log.search.selectedServer" ng-options="item as item.name for item in log.servers" class="form-control">
                        <option value="">请选择服务器</option>
                     </select>
                     <input id="input-query" name="query" ng-model="log.search.query" placeholder="输入查询语句,例如: username:huidu001 and cmd:getitem" style="width:30%" class="form-control" />
                     <select name="searchTime" ng-model="log.search.selectedSearchTime" ng-options="item.value as item.name for item in log.searchTime" class="form-control">
                        <option value="">请选择查询时间</option>
                     </select>
                     <button type="submit" ng-disabled="log.searching" class="btn btn-primary btn-s">查询</button>
                  </form>

               </legend>

            </tab>
         </tabset>


text:
'use strict';

var _ = require('lodash');
var Promise = require('bluebird');
var Resolver = require('./resolver');

/**
 * Module interface.
 */

module.exports = sync;

/**
 * Synchronize given schemas with database. If it exists, it calls `postBuild` afterwards
 *
 * @param {[Schemas]} schemas
 * @return {Promise}
 */

function sync(schemas) {
  var resolver = new Resolver(schemas);
  // Reduce force sequential execution.
  return Promise.resolve(Promise.reduce(resolver.resolve(), syncSchema.bind(this), []))
  .tap(function () {
    var knex = this.knex;
    return Promise.map(schemas || [], function(schema) {
      return (schema.postBuild || _.noop)(knex);
    });
  }.bind(this));
}

/**
 * Synchronize given schema with database.
 *
 * @param {[Schema]} result - reduce accumulator
 * @param {Schema} schema
 * @return {Promise}
 */

function syncSchema(result, schema) {
  var knex = this.knex;
  return knex.schema.hasTable(schema.tableName)
  .then(function (exists) {
    if (exists) return result;
    return knex.schema.createTable(schema.tableName, defineSchemaTable(schema))
    .then(function () {
      return result.concat([schema]);
    });
  });
}

/**
 * Define default properties on the given schema.
 *
 * @param {Schema} schema
 * @return {Function}
 */

function defineSchemaTable(schema) {
  return function (table) {
    table.timestamps();
    (schema.build || _.noop)(table);
  };
}


text:
from django.http import HttpResponse
from django.utils.translation import gettext as _
import md5, time, random

def djangouser_auth(username, password):
    """
    Check username and password against
    django.contrib.auth.models.User
    """
    from django.contrib.auth.models import User
    try:
        user = User.objects.get(username=username)
        if user.check_password(password):
            return True
        else:
            return False
    except User.DoesNotExist:
        return False

class NoAuthentication(object):
    """
    No authentication: Permit every request.
    """
    def is_authenticated(self, request):
        return True

    def challenge_headers(self):
        return {}

class HttpBasicAuthentication(object):
    """
    HTTP/1.0 basic authentication.
    """
    def __init__(self, authfunc=djangouser_auth, realm=_('Restricted Access')):
        """
        authfunc:
            A user-defined function which takes a username and
            password as its first and second arguments respectively
            and returns True if the user is authenticated
        realm:
            An identifier for the authority that is requesting
            authorization
        """
        self.realm = realm
        self.authfunc = authfunc

    def challenge_headers(self):
        """
        Returns the http headers that ask for appropriate
        authorization.
        """
        return {'WWW-Authenticate' : 'Basic realm="%s"' % self.realm}

    def is_authenticated(self, request):
        """
        Checks whether a request comes from an authorized user.
        """
        if not request.META.has_key('HTTP_AUTHORIZATION'):
            return False
        (authmeth, auth) = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        if authmeth.lower() != 'basic':
            return False
        auth = auth.strip().decode('base64')
        username, password = auth.split(':', 1)
        return self.authfunc(username=username, password=password)

def digest_password(realm, username, password):
    """
    Construct the appropriate hashcode needed for HTTP digest
    """
    return md5.md5("%s:%s:%s" % (username, realm, password)).hexdigest()

class HttpDigestAuthentication(object):
    """
    HTTP/1.1 digest authentication (RFC 2617).
    Uses code from the Python Paste Project (MIT Licence).
    """
    def __init__(self, authfunc, realm=_('Restricted Access')):
        """
        authfunc:
            A user-defined function which takes a username and
            a realm as its first and second arguments respectively
            and returns the combined md5 hash of username,
            authentication realm and password.
        realm:
            An identifier for the authority that is requesting
            authorization
        """
        self.realm = realm
        self.authfunc = authfunc
        self.nonce    = {} # prevention of replay attacks

    def get_auth_dict(self, auth_string):
        """
        Splits WWW-Authenticate and HTTP_AUTHORIZATION strings
        into a dictionaries, e.g.
        {
            nonce  : "951abe58eddbb49c1ed77a3a5fb5fc2e"',
            opaque : "34de40e4f2e4f4eda2a3952fd2abab16"',
            realm  : "realm1"',
            qop    : "auth"'
        }
        """
        amap = {}
        for itm in auth_string.split(", "):
            (k, v) = [s.strip() for s in itm.split("=", 1)]
            amap[k] = v.replace('"', '')
        return amap

    def get_auth_response(self, http_method, fullpath, username, nonce, realm, qop, cnonce, nc):
        """
        Returns the server-computed digest response key.

        http_method:
            The request method, e.g. GET
        username:
            The user to be authenticated
        fullpath:
            The absolute URI to be accessed by the user
        nonce:
            A server-specified data string which should be
            uniquely generated each time a 401 response is made
        realm:
            A string to be displayed to users so they know which
            username and password to use
        qop:
            Indicates the "quality of protection" values supported
            by the server.  The value "auth" indicates authentication.
        cnonce:
            An opaque quoted string value provided by the client
            and used by both client and server to avoid chosen
            plaintext attacks, to provide mutual authentication,
            and to provide some message integrity protection.
        nc:
            Hexadecimal request counter
        """
        ha1 = self.authfunc(realm, username)
        ha2 = md5.md5('%s:%s' % (http_method, fullpath)).hexdigest()
        if qop:
            chk = "%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2)
        else:
            chk = "%s:%s:%s" % (ha1, nonce, ha2)
        computed_response = md5.md5(chk).hexdigest()
        return computed_response

    def challenge_headers(self, stale=''):
        """
        Returns the http headers that ask for appropriate
        authorization.
        """
        nonce  = md5.md5(
            "%s:%s" % (time.time(), random.random())).hexdigest()
        opaque = md5.md5(
            "%s:%s" % (time.time(), random.random())).hexdigest()
        self.nonce[nonce] = None
        parts = {'realm': self.realm, 'qop': 'auth',
                 'nonce': nonce, 'opaque': opaque }
        if stale:
            parts['stale'] = 'true'
        head = ", ".join(['%s="%s"' % (k, v) for (k, v) in parts.items()])
        return {'WWW-Authenticate':'Digest %s' % head}

    def is_authenticated(self, request):
        """
        Checks whether a request comes from an authorized user.
        """

        # Make sure the request is a valid HttpDigest request
        if not request.META.has_key('HTTP_AUTHORIZATION'):
            return False
        fullpath = request.META['SCRIPT_NAME'] + request.META['PATH_INFO']
        (authmeth, auth) = request.META['HTTP_AUTHORIZATION'].split(" ", 1)
        if authmeth.lower() != 'digest':
            return False

        # Extract auth parameters from request
        amap = self.get_auth_dict(auth)
        try:
            username = amap['username']
            authpath = amap['uri']
            nonce    = amap['nonce']
            realm    = amap['realm']
            response = amap['response']
            assert authpath.split("?", 1)[0] in fullpath
            assert realm == self.realm
            qop      = amap.get('qop', '')
            cnonce   = amap.get('cnonce', '')
            nc       = amap.get('nc', '00000000')
            if qop:
                assert 'auth' == qop
                assert nonce and nc
        except:
            return False

        # Compute response key
        computed_response = self.get_auth_response(request.method, fullpath, username, nonce, realm, qop, cnonce, nc)

        # Compare server-side key with key from client
        # Prevent replay attacks
        if not computed_response or computed_response != response:
            if nonce in self.nonce:
                del self.nonce[nonce]
            return False
        pnc = self.nonce.get(nonce,'00000000')
        if nc <= pnc:
            if nonce in self.nonce:
                del self.nonce[nonce]
            return False # stale = True
        self.nonce[nonce] = nc
        return True


text:
package org.apache.ignite.internal.processors.cache.persistence.pagemem;

import java.util.function.BiConsumer;
import org.apache.ignite.internal.pagemem.FullPageId;
import org.apache.ignite.internal.util.GridLongList;

/**
 * Interface for storing correspondence of page ID in a cache group to long value (address in offheap segment).

 * Map support versioning of entries. Outdated entry (entry having version lower than requested),
 * is not provided in case of get, outdated return value is provided instead.

 *
 * This mapping is not thread safe. Operations should be protected by outside locking.

 */
public interface LoadedPagesMap {
    /**
     * Gets value associated with the given key.
     *
     * @param grpId Cache Group ID. First part of the key.
     * @param pageId Page ID. Second part of the key.
     * @param reqVer Requested entry version, counter associated with value.
     * @param absent return if provided page is not presented in map.
     * @param outdated return if provided {@code reqVer} version is greater than value in map (was used for put).
     * @return A value associated with the given key.
     */
    public long get(int grpId, long pageId, int reqVer, long absent, long outdated);

    /**
     * Associates the given key with the given value.
     *
     * @param grpId Cache Group ID. First part of the key.
     * @param pageId Page ID. Second part of the key.
     * @param val Value to set.
     * @param ver Version/counter associated with value, can be used to check if value is outdated.
     */
    public void put(int grpId, long pageId, long val, int ver);

    /**
     * Refresh outdated value. Sets provided version to value associated with cache and page.
     * Method should be called only for key present and only if version was outdated.
     * Method may be called in case {@link #get(int, long, int, long, long)} returned {@code outdated} return value.
     *
     * @param grpId First part of the key. Cache Group ID.
     * @param pageId Second part of the key. Page ID.
     * @param ver Partition tag.
     * @return A value associated with the given key.
     * @throws IllegalArgumentException if method is called for absent key or key with fresh version.
     */
    public long refresh(int grpId, long pageId, int ver);

    /**
     * Removes key-value association for the given key.
     * @param grpId First part of the key. Cache Group ID.
     * @param pageId Second part of the key. Page ID.
     * @return {@code True} if value was actually found and removed.
     */
    public boolean remove(int grpId, long pageId);

    /**
     * @return Maximum number of entries in the map. This maximum can not be always reached.
     */
    public int capacity();

    /**
     * @return Current number of entries in the map.
     */
    public int size();

    /**
     * Find nearest presented value from specified position to the right.
     *
     * @param idxStart Index to start searching from. Bounded with {@link #capacity()}.
     * @return Closest value to the index and it's partition tag or  {@code null} value that will
     * be returned if no values present.
     */
    public ReplaceCandidate getNearestAt(int idxStart);

    /**
     * Removes entities matching provided predicate at specified mapping range.
     *
     * @param startIdxToClear Index to clear value at, inclusive. Bounded with {@link #capacity()}.
     * @param endIdxToClear Index to clear value at, inclusive. Bounded with {@link #capacity()}.
     * @param keyPred Test predicate for (cache group ID, page ID).
     * @return List with removed values, value is not added to list for empty cell or if key is not matching to
     * predicate.
     */
    public GridLongList removeIf(int startIdxToClear, int endIdxToClear, KeyPredicate keyPred);

    /**
     * Removes entities matching provided predicate.
     *
     * @param keyPred Test predicate for (cache group ID, page ID).
     * @return List with removed values, value is not added to list for empty cell or if key is not matching to
     * predicate.
     */
    default GridLongList removeIf(KeyPredicate keyPred) {
        return removeIf(0, capacity(), keyPred);
    }

    /**
     * Scans all the elements in this table.
     *
     * @param act Visitor/action to be applied to each not empty cell.
     */
    public void forEach(BiConsumer<FullPageId, Long> act);

    /**
     * Interface describing a predicate for Key (cache group ID, page ID). Usage of this predicate prevents odd object
     * creation.
     */
    @FunctionalInterface public interface KeyPredicate {
        /**
         * Predicate body.
         *
         * @param grpId Cache group ID.
         * @param pageId Page ID.
         */
        boolean test(int grpId, long pageId);
    }
}


text:
//---------------------------------------------------------------------
// <copyright file="ClientPropertyAnnotation.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Client.Metadata
{
    #region Namespaces.

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq.Expressions;
    using System.Reflection;
    using Microsoft.OData.Edm;
    using c = Microsoft.OData.Client;

    #endregion Namespaces.

    ///
    /// Represents an EDM property for client types and caches methods for the propertyInfo.
    ///
    [DebuggerDisplay("{PropertyName}")]
    internal sealed class ClientPropertyAnnotation
    {
        /// Back reference to the EdmProperty this annotation is part of.
        internal readonly IEdmProperty EdmProperty;

        /// property name for debugging
        internal readonly string PropertyName;

        /// Exact property type; possibly nullable but not necessarily so.
        internal readonly Type NullablePropertyType;

        /// type of the property
        internal readonly Type PropertyType;

        /// what is the dictionary value type
        internal readonly Type DictionaryValueType;

        /// what type was this property declared on?
        internal readonly Type DeclaringClrType;

        ///
        /// Is this a known primitive/reference type or an entity/complex/collection type?
        ///
        internal readonly bool IsKnownType;

        /// property getter
        private readonly Func<Object, Object> propertyGetter;

        /// property setter
        private readonly Action<Object, Object> propertySetter;

        /// "set_Item" method supporting IDictionary properties
        private readonly Action<Object, String, Object> dictionarySetter;

        /// "Add" method supporting ICollection<> properties
        private readonly Action<Object, Object> collectionAdd;

        /// "Remove" method supporting ICollection<> properties
        private readonly Func<Object, Object, Boolean> collectionRemove;

        /// "Contains" method supporting ICollection<> properties
        private readonly Func<Object, Object, Boolean> collectionContains;

        /// "Clear" method supporting ICollection<> properties
        private readonly Action<Object> collectionClear;

        /// ICollection<> generic type
        private readonly Type collectionGenericType;

        /// cached value for IsPrimitiveOrEnumOrComplexCollection property
        private bool? isPrimitiveOrEnumOrComplexCollection;

        /// cached value of IsGeographyOrGeometry property
        private bool? isSpatialType;

        /// The other property in this type that holds the MIME type for this one
        private ClientPropertyAnnotation mimeTypeProperty;

        ///
        /// constructor
        ///
        /// <param name="edmProperty">Back reference to the EdmProperty this annotation is part of.</param>
        /// <param name="propertyInfo">propertyInfo instance.</param>
        /// <param name="model">The client model.</param>
        internal ClientPropertyAnnotation(IEdmProperty edmProperty, PropertyInfo propertyInfo, ClientEdmModel model)
        {
            Debug.Assert(edmProperty != null, "edmProperty != null");
            Debug.Assert(propertyInfo != null, "null propertyInfo");

            // Property should always have DeclaringType
            Debug.Assert(propertyInfo.DeclaringType != null, "Property without a declaring type");

            this.EdmProperty = edmProperty;
            this.PropertyName = ClientTypeUtil.GetServerDefinedName(propertyInfo);
            this.NullablePropertyType = propertyInfo.PropertyType;
            this.PropertyType = Nullable.GetUnderlyingType(this.NullablePropertyType) ?? this.NullablePropertyType;
            this.DeclaringClrType = propertyInfo.DeclaringType;

            MethodInfo propertyGetMethod = propertyInfo.GetGetMethod();
            MethodInfo propertySetMethod = propertyInfo.GetSetMethod();

            ParameterExpression instance = Expression.Parameter(typeof(Object), "instance");
            ParameterExpression value = Expression.Parameter(typeof(Object), "value");

            // instance => (Object)(((T)instance).get_PropertyName());  <-- we need to box the value back to object to return
            this.propertyGetter = propertyGetMethod == null ? null : (Func<object, object>)Expression.Lambda(
                Expression.Convert(
                    Expression.Call(
                        Expression.Convert(instance, this.DeclaringClrType),
                        propertyGetMethod),
                    typeof(Object)),
                instance).Compile();

            // (instance, value) => ((T)instance).set_PropertyName((T1)value);
            this.propertySetter = propertySetMethod == null ? null : (Action<object, object>)Expression.Lambda(
                Expression.Call(
                    Expression.Convert(instance, this.DeclaringClrType),
                    propertySetMethod,
                    Expression.Convert(value, this.NullablePropertyType)),
                instance,
                value).Compile();

            this.Model = model;

            this.IsKnownType = PrimitiveType.IsKnownType(this.PropertyType);

            // non primitive types: dictionary/collections
            if (!this.IsKnownType)
            {
                var setMethodInfo = ClientTypeUtil.GetMethodForGenericType(this.PropertyType, typeof(IDictionary<,>), "set_Item", out this.DictionaryValueType);

                if (setMethodInfo != null)
                {
                    ParameterExpression propertyNameParam = Expression.Parameter(typeof(String), "propertyName");

                    // (instance, propertyName, value) => ((IDictionary<string, DictionaryValueType>)instance)[propertyName] = (DictionaryValueType)value;
                    this.dictionarySetter = (Action<Object, String, Object>)Expression.Lambda(
                        Expression.Call(
                            Expression.Convert(instance, typeof(IDictionary<,>).MakeGenericType(typeof(String), this.DictionaryValueType)),
                            setMethodInfo,
                            propertyNameParam,
                            Expression.Convert(value, this.DictionaryValueType)),
                        instance,
                        propertyNameParam,
                        value).Compile();
                }
                else
                {
                    var containsMethod = ClientTypeUtil.GetMethodForGenericType(this.PropertyType, typeof(ICollection<>), "Contains", out this.collectionGenericType);
                    var addMethod = ClientTypeUtil.GetAddToCollectionMethod(this.PropertyType, out this.collectionGenericType);
                    var removeMethod = ClientTypeUtil.GetMethodForGenericType(this.PropertyType, typeof(ICollection<>), "Remove", out this.collectionGenericType);
                    var clearMethod = ClientTypeUtil.GetMethodForGenericType(this.PropertyType, typeof(ICollection<>), "Clear", out this.collectionGenericType);

                    // (instance, value) => ((PropertyType)instance).Contains((CollectionType)value);  returns boolean
                    this.collectionContains = containsMethod == null ? null : (Func<Object, Object, Boolean>)Expression.Lambda(
                        Expression.Call(
                            Expression.Convert(instance, this.PropertyType),
                            containsMethod,
                            Expression.Convert(value, this.collectionGenericType)),
                        instance,
                        value).Compile();

                    // (instance, value) => ((PropertyType)instance).Add((CollectionType)value);
                    this.collectionAdd = addMethod == null ? null : (Action<Object, Object>)Expression.Lambda(
                        Expression.Call(
                            Expression.Convert(instance, this.PropertyType),
                            addMethod,
                            Expression.Convert(value, this.collectionGenericType)),
                        instance,
                        value).Compile();

                    // (instance, value) => ((PropertyType)instance).Remove((CollectionType)value);  returns boolean
                    this.collectionRemove = removeMethod == null ? null : (Func<Object, Object, Boolean>)Expression.Lambda(
                        Expression.Call(
                            Expression.Convert(instance, this.PropertyType),
                            removeMethod,
                            Expression.Convert(value, this.collectionGenericType)),
                        instance,
                        value).Compile();

                    // (instance) => ((PropertyType)instance).Clear();
                    this.collectionClear = clearMethod == null ? null : (Action<Object>)Expression.Lambda(
                        Expression.Call(
                             Expression.Convert(instance, this.PropertyType),
                             clearMethod),
                        instance).Compile();
                }
            }

            Debug.Assert(this.collectionGenericType == null || this.DictionaryValueType == null, "collectionGenericType and DictionaryItemType mutually exclusive. (They both can be null though).");
        }

        ///
        /// Gets the client model.
        ///
        internal ClientEdmModel Model { get; private set; }

        /// The other property in this type that holds the MIME type for this one
        internal ClientPropertyAnnotation MimeTypeProperty
        {
            get { return this.mimeTypeProperty; }
            set { this.mimeTypeProperty = value; }
        }

        /// what is the nested collection element
        internal Type EntityCollectionItemType
        {
            get { return this.IsEntityCollection ? this.collectionGenericType : null; }
        }

        /// Is this property a collection of entities?
        internal bool IsEntityCollection
        {
            get { return this.collectionGenericType != null && !this.IsPrimitiveOrEnumOrComplexCollection; }
        }

        /// Type of items in the primitive or complex collection.
        internal Type PrimitiveOrComplexCollectionItemType
        {
            get
            {
                if (this.IsPrimitiveOrEnumOrComplexCollection)
                {
                    return this.collectionGenericType;
                }

                return null;
            }
        }

        /// Returns if this property is enum type.
        internal bool IsEnumType
        {
            get { return this.PropertyType.IsEnum(); }
        }

        /// Is this property a collection of primitive or enum or complex types?
        internal bool IsPrimitiveOrEnumOrComplexCollection
        {
            get
            {
                if (!this.isPrimitiveOrEnumOrComplexCollection.HasValue)
                {
                    if (this.collectionGenericType == null)
                    {
                        this.isPrimitiveOrEnumOrComplexCollection = false;
                    }
                    else
                    {
                        bool collection = this.EdmProperty.PropertyKind == EdmPropertyKind.Structural && this.EdmProperty.Type.TypeKind() == EdmTypeKind.Collection;

                        this.isPrimitiveOrEnumOrComplexCollection = collection;
                    }
                }

                return this.isPrimitiveOrEnumOrComplexCollection.Value;
            }
        }

        /// Returns true if the type of property is a Geography or Geometry type, otherwise returns false.
        internal bool IsSpatialType
        {
            get
            {
                if (!this.isSpatialType.HasValue)
                {
                    if (typeof(Microsoft.Spatial.ISpatial).IsAssignableFrom(this.PropertyType))
                    {
                        this.isSpatialType = true;
                    }
                    else
                    {
                        this.isSpatialType = false;
                    }
                }

                return this.isSpatialType.Value;
            }
        }

        /// Is this property a dictionary?
        internal bool IsDictionary
        {
            get { return this.DictionaryValueType != null; }
        }

        /// Returns true if this property is a stream link property, otherwise false.
        internal bool IsStreamLinkProperty
        {
            get { return this.PropertyType == typeof(DataServiceStreamLink); }
        }

        ///
        /// get property value from an object
        ///
        /// <param name="instance">object to get the property value from</param>
        /// <returns>property value</returns>
        internal object GetValue(object instance)
        {
            Debug.Assert(null != instance, "null instance");
            Debug.Assert(null != this.propertyGetter, "null propertyGetter");
            return this.propertyGetter.Invoke(instance);
        }

        ///
        /// remove a item from the collection instance
        ///
        /// <param name="instance">collection</param>
        /// <param name="value">item to remove</param>
        internal void RemoveValue(object instance, object value)
        {
            Debug.Assert(null != instance, "null instance");
            Debug.Assert(null != this.collectionRemove, "missing removeMethod");

            Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance");
            Debug.Assert((null == value) || this.EntityCollectionItemType.IsAssignableFrom(value.GetType()) || this.PrimitiveOrComplexCollectionItemType.IsAssignableFrom(value.GetType()), "unexpected collection value to remove");
            this.collectionRemove.Invoke(instance, value);
        }

        ///
        /// set property value on an object
        ///
        /// <param name="instance">object to set the property value on</param>
        /// <param name="value">property value</param>
        /// <param name="propertyName">used for open type</param>
        /// <param name="allowAdd">allow add to a collection if available, else allow setting collection property</param>
        internal void SetValue(object instance, object value, string propertyName, bool allowAdd)
        {
            Debug.Assert(null != instance, "null instance");
            if (null != this.dictionarySetter)
            {
                {
                    Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected dictionary instance");
                    Debug.Assert((null == value) || this.DictionaryValueType.IsAssignableFrom(value.GetType()), "unexpected dictionary value to set");

                    // ((IDictionary<string, DictionaryValueType>)instance)[propertyName] = (DictionaryValueType)value;
                    this.dictionarySetter.Invoke(instance, propertyName, value);
                }
            }
            else if (allowAdd && (null != this.collectionAdd))
            {
                Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance");
                Debug.Assert(
                    (null == value) ||
                    (this.EntityCollectionItemType != null && this.EntityCollectionItemType.IsAssignableFrom(value.GetType())) ||
                    (this.PrimitiveOrComplexCollectionItemType != null && this.PrimitiveOrComplexCollectionItemType.IsAssignableFrom(value.GetType())),
                    "unexpected collection value to add");

                if (!this.collectionContains.Invoke(instance, value))
                {
                    this.AddValueToBackingICollectionInstance(instance, value);
                }
            }
            else if (null != this.propertySetter)
            {
                // ((ElementType)instance).PropertyName = (PropertyType)value;
                this.propertySetter.Invoke(instance, value);
            }
            else
            {
                throw c.Error.InvalidOperation(c.Strings.ClientType_MissingProperty(value.GetType().ToString(), propertyName));
            }
        }

        ///
        /// Clears <paramref name="collectionInstance"/>.
        ///
        /// <param name="collectionInstance">ICollection instance that needs to be cleared.</param>
        internal void ClearBackingICollectionInstance(object collectionInstance)
        {
            Debug.Assert(this.IsEntityCollection || this.IsPrimitiveOrEnumOrComplexCollection, "this.IsEntityCollection or this.IsPrimitiveOrComplexCollection has to be true otherwise it is not a collection");
            Debug.Assert(this.collectionClear != null, "For collections the clearMethod must not be null");

            this.collectionClear.Invoke(collectionInstance);
        }

        ///
        /// Adds value to a collection.
        ///
        /// <param name="collectionInstance">ICollection Instance to add <paramref name="value"/> to.</param>
        /// <param name="value">Value to be added to <paramref name="collectionInstance" />.</param>
        internal void AddValueToBackingICollectionInstance(object collectionInstance, object value)
        {
            Debug.Assert(this.IsEntityCollection || this.IsPrimitiveOrEnumOrComplexCollection, "this.IsEntityCollection or this.IsPrimitiveOrComplexCollection has to be true otherwise it is not a collection");
            Debug.Assert(this.collectionAdd != null, "For collections the addMethod must not be null");

            this.collectionAdd.Invoke(collectionInstance, value);
        }
    }
}


text:
PKMultipartInputStream
######################

This NSInputStream subclass is suitable for building multipart/form-data HTTP requests bodies in MacOSX/iOS applications.

=====
Usage
=====

A very simple example is presented below::

    PKMultipartInputStream *body = [[PKMultipartInputStream alloc] init];
    [body addPartWithName:@"string" string:@"value"];
    [body addPartWithName:@"data" data:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"]]];
    [body addPartWithName:@"file" path:[[NSBundle mainBundle] pathForResource:@"video" ofType:@"mp4"]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://site.com/upload.php"]];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", [body boundary]] forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBodyStream:body];
    [request setHTTPMethod:@"POST"];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

An example iOS application is provided along with the class code, please refer to it.