text:
<?php //-->

namespace Eden\Facebook;

use Eden\Curl\Base as Curl;
use Eden\Facebook\Graph\Base as GraphBase;

/**
 * Facebook Graph API
 *
 * @vendor Eden
 * @package Facebook
 * @author Ian Mark Muninio <ianmuninio@openovate.com>
 */
class Graph extends Base
{
    const INSTANCE = 0; // sets to multiton
    const GRAPH_URL = 'https://graph.facebook.com/';

    protected $token = null;

    /**
     * Preloads the token.
     *
     * @param string $token
     * @return void
     */
    public function __construct($token)
    {
        Argument::i()->test(1, 'string');

        $this->token = $token;
    }

    /**
     * Returns the facebook object.
     *
     * @param string $name name of the facebook object
     * @param scalar $args the constructor arguments
     * @return \Eden\Facebook\Graph\Base
     */
    public function __call($name, $args)
    {
        Argument::i()->test(1, 'string');

        return GraphBase::i($this->token)
                        ->__call($name, $args);
    }

    /**
     * Deletes an object based on id.
     *
     * @param string      $id         id of the object
     * @param string|null $connection [optional] the connection
     * @return array
     */
    public function delete($id, $connection = null)
    {
        Argument::i()
                ->test(1, 'string')
                ->test(2, 'string', 'null');

        $url = self::GRAPH_URL . '/' . $id;

        if ($connection) {
            $url .= '/' . $connection;
        }

        $url .= '?access_token=' . $this->token;

        return $this->getResponse($url, array(), Curl::DELETE);
    }

    /**
     * Returns specific fields of an object.
     *
     * @param string|int   $id     [optional]
     * @param string|array $fields
     * @return array
     */
    public function getFields($id = 'me', $fields = array())
    {
        Argument::i()
                ->test(1, 'string', 'int')
                ->test(2, 'string', 'array');

        // if fields is an array
        if (is_array($fields)) {
            //make it into a string
            $fields = implode(',', $fields);
        }

        // call it
        return $this->getObject($id, null, array('fields' => $fields));
    }

    /**
     * Returns the detail of any object.
     *
     * @param string|int  $id         [optional] (defaul: me) id of the object
     * @param string|null $connection [optional] the page name
     * @param array       $query      [optional] the query
     * @param bool        $auth       [optional] (default: true) required auth
     * @return array json object
     */
    public function getObject($id = 'me', $connection = null, array $query = array(), $auth = true)
    {
        Argument::i()
                ->test(1, 'string', 'int')
                ->test(2, 'string', 'null')
                ->test(3, 'array')
                ->test(4, 'bool');

        // if we have a connection
        if ($connection) {
            //prepend a slash
            $connection = '/' . $connection;
        }

        // for the url
        $url = self::GRAPH_URL . $id . $connection;

        // if this requires authentication
        if ($auth) {
            // add the token
            $query['access_token'] = $this->token;
        }

        // if we have a query
        if (!empty($query)) {
            //append it to the url
            $url .= '?' . http_build_query($query);
        }

        // call it
        $object = $this->getResponse($url, array());

        return $object;
    }

    /**
     * Search over all public objects in the social graph
     *
     * @param string
     * @param string
     * @param boolean
     * @return array
     **/
    public function search($query, $type, $auth = true)
    {
        Argument::i()
            ->test(1, 'string')
            ->test(2, 'string')
            ->test(3, 'bool');

        // fix query
        $query = array(
            'q'     => $query,
            'type'  => $type);

        // fix url, append the search word
        $url = self::GRAPH_URL.'/search';

        // if this requires authentication
        if ($auth) {
            // add the token
            $query['access_token'] = $this->token;
        }

        // if we have a query
        if (!empty($query)) {
            //append it to the url
            $url .= '?' . http_build_query($query);
        }

        // call it
        $object = $this->getResponse($url, array());

        return $object;
    }

    /**
     * Get response using curl.
     *
     * @param string $url     graph url
     * @param array  $post    post fields
     * @param string $request the request method
     * @return array
     */
    protected function getResponse($url, array $post = array(), $request = Curl::GET)
    {
        Argument::i()
                ->test(1, 'string')
                ->test(2, 'array')
                ->test(3, 'string');

        //send it off
        $curl = Curl::i()
                ->setUrl($url)
                ->setConnectTimeout(10)
                ->setFollowLocation(true)
                ->setTimeout(60)
                ->verifyPeer(false)
                ->setUserAgent(Auth::USER_AGENT)
                ->setHeaders('Expect');

        switch ($request) {
            case Curl::PUT:
                $curl->setCustomPut();
                break;
            case Curl::GET:
                $curl->setCustomGet();
                break;
            case Curl::DELETE:
                $curl->setCustomDelete();
                break;
            case Curl::POST:
                $curl->setPost(true)
                        ->setPostFields(http_build_query($post));
                break;
            default:
        }

        $response = $curl->getJsonResponse();

        return $response;
    }
}


text:
<link rel="import" href="chrome://resources/html/polymer.html">

<link rel="import" href="chrome://resources/cr_components/chromeos/smb_shares/add_smb_share_dialog.html">
<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/policy/cr_policy_pref_indicator.html">
<link rel="import" href="chrome://resources/html/action_link.html">
<link rel="import" href="chrome://resources/cr_elements/action_link_css.html">
<link rel="import" href="chrome://resources/html/assert.html">
<link rel="import" href="../localized_link/localized_link.html">
<link rel="import" href="../os_route.html">
<link rel="import" href="../../router.html">
<link rel="import" href="../../settings_shared_css.html">
<link rel="import" href="../../settings_vars_css.html">

<dom-module id="settings-smb-shares-page">
  <template>

         <settings-localized-link
             localized-string="$i18n{smbSharesLearnMoreLabel}"
             link-url="$i18n{smbSharesLearnMoreURL}">
         </settings-localized-link>

      <template is="dom-if" if="[[!prefs.network_file_shares.allowed.value]]"
          restamp>
        <cr-policy-pref-indicator
            pref="[[prefs.network_file_shares.allowed]]"
            icon-aria-label="$i18n{smbSharesTitle}">
        </cr-policy-pref-indicator>
      </template>
      <cr-button class="action-button" id="addShare"
          on-click="onAddShareTap_"
          disabled="[[!prefs.network_file_shares.allowed.value]]">
        $i18n{addSmbShare}
      </cr-button>

    <template is="dom-if" if="[[showAddSmbDialog_]]" restamp>
      <add-smb-share-dialog on-close="onAddSmbDialogClosed_"
          last-url="[[prefs.network_file_shares.most_recently_used_url.value]]"
          should-open-file-manager-after-mount>
      </add-smb-share-dialog>
    </template>
  </template>

</dom-module>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using NAudio.Vorbis;
using NAudio.Wave;
using Pulse.Core;

namespace Pulse.FS
{
    public sealed class ScdFileReader
    {
        private readonly Stream _input;

        public ScdFileReader(Stream input)
        {
            _input = Exceptions.CheckArgumentNull(input, "input");
        }

        public WaveStream[] Read()
        {
            SectionHeader sectionHeader = _input.ReadContent<SectionHeader>();
            SscfHeader sscfHeader = _input.ReadContent<SscfHeader>();

            BinaryReader br = new BinaryReader(_input);
            _input.SetPosition(sscfHeader.WavesOffset);
            int[] offsets = new int[sscfHeader.NumWaves];
            for (int i = 0; i < offsets.Length; i++)
                offsets[i] = br.ReadInt32();

            WaveStream[] result = new WaveStream[sscfHeader.NumWaves];
            for (int i = 0; i < offsets.Length; i++)
            {
                _input.SetPosition(offsets[i]);
                SscfWaveHeader waveHeader = _input.ReadContent<SscfWaveHeader>();
                if (waveHeader.Format == SscfWaveFormat.Vorbis)
                {
                    _input.SetPosition(waveHeader.DataOffset);
                    byte[] vorbisData = _input.EnsureRead(waveHeader.DataLength);
                    MemoryStream vorbisMs = new MemoryStream(vorbisData, 0, vorbisData.Length, false);
                    result[i] = new VorbisWaveReader(vorbisMs);
                    continue;
                }

                WaveFormat format = ReadWaveFormat(waveHeader);
                if (format == null)
                    continue;

                _input.SetPosition(waveHeader.DataOffset);
                byte[] data = _input.EnsureRead(waveHeader.DataLength);
                MemoryStream ms = new MemoryStream(data, 0, data.Length, false);
                result[i] = new RawSourceWaveStream(ms, format);
            }
            return result;
        }

        private WaveFormat ReadWaveFormat(SscfWaveHeader waveHeader)
        {
            switch (waveHeader.Format)
            {
                case SscfWaveFormat.Empty:
                    if (waveHeader.DataLength != 0)
                        throw new InvalidDataException();
                    return null;
                case SscfWaveFormat.Pcm:
                    return CreatePcmWaveFormat(waveHeader);
                case SscfWaveFormat.Vorbis:
                    //voice = new VorbisWave() {Parent = this, WaveHeader = waveHeader};
                    throw new NotSupportedException("Unsupported Wave Format: " + waveHeader.Format);
                case SscfWaveFormat.MsAdPcm:
                    return ReadMicrosoftAdPcmWaveFormat(waveHeader);
                case SscfWaveFormat.Atrac3:
                case SscfWaveFormat.Atrac3Too:
                case SscfWaveFormat.Xma:
                    throw new NotSupportedException("Unsupported Wave Format: " + waveHeader.Format);
                default:
                    throw new NotImplementedException("Unknown Wave Format: 0x" + ((int)waveHeader.Format).ToString("X"));
            }
        }

        private WaveFormat CreatePcmWaveFormat(SscfWaveHeader waveHeader)
        {
            const int bitsPerSample = 16;
            short channels = (short)waveHeader.NumChannels;
            short blockAlign = (short)(channels * 2);
            int sampleRate = waveHeader.SamplingRate;
            int averageBytesPerSecond = sampleRate * blockAlign;

            return WaveFormat.CreateCustomFormat(
                WaveFormatEncoding.Pcm,
                sampleRate,
                channels,
                averageBytesPerSecond,
                blockAlign,
                bitsPerSample);
        }

        private WaveFormat ReadMicrosoftAdPcmWaveFormat(SscfWaveHeader waveHeader)
        {
            BinaryReader br = new BinaryReader(_input);
            return WaveFormat.FromFormatChunk(br, waveHeader.FormatHeaderLength);
        }
    }
}


text:
# ember-axe

[![Build Status](https://travis-ci.org/trentmwillis/ember-axe.svg?branch=master)](https://travis-ci.org/trentmwillis/ember-axe)
[![NPM Version](https://badge.fury.io/js/ember-axe.svg)](http://badge.fury.io/js/ember-axe)

Ember Axe is a wrapper around [Deque Labs'](https://github.com/dequelabs)
[axe-core](https://github.com/dequelabs/axe-core) accessibility testing engine.
It automatically integrates into your testing environment by running during the
`afterRender` step in the [run loop](http://guides.emberjs.com/v1.10.0/understanding-ember/run-loop/)
during any acceptance tests.

If you're using Ember 1.13.0 or above, it also integrates into your development
workflow by running during a component's `didRender` phase in non-production
environments. This gives you instant feedback on if your component's are
accessible in any given state.

## Future Plans

Now that your components and acceptance tests can self-audit, the next step
going forward is to give helpful and meaningful feedback to developers. This
means easily highlighting areas with violations and giving suggestions on how to
fix and improve them. Additionally, work will be done to tackle Ember-specific
accessibility issues, such as identifying actions on inaccessible elements.

## Usage In Testing

Usage inside tests right now is super simple, just install the addon via:

```bash
ember install ember-axe
```

That's it! It will automatically begin running during _acceptance_ tests. It
also injects the `axe` object globally during development so you can run tests
while developing your application as well.

_Note:_ any tests run with Ember Axe will adjust the testing container to occupy
the entire screen. This is to simulate the actual application environment, as
browsers adjust styles at small sizes for accessibility reasons. It will reset
itself at the conclusion of testing though.

### Disable/Enable Tests

By default, the axe-core tests only run during acceptance tests. In order to
enable them for other tests, simply run the following at the beginning of your
testing module:

```javascript
axe.ember.turnAxeOn();
```

On the flip side, if you want to turn tests off, simply use:

```javascript
axe.ember.turnAxeOff();
```

### Options

You can pass specific options to be used during `a11yCheck` by setting them on a
global `testOptions` property:

```javascript
axe.ember.testOptions = {
  runOnly: {
    type: "tag",
    values: ["wcag2a"]
  }
};
```

You can see the available options in the [axe-core repo](https://github.com/dequelabs/axe-core/blob/master/doc/API.md#b-options-parameter).

_Note:_ the options will stay set, until set to something different.

## Usage In Development

Usage in development is restricted to applications using Ember 1.13 and up as it
relies on the `didRender` hook of a component's life-cycle (a feature only
available in versions of Ember with the Glimmer rendering engine).

That said, setup for development is as simple as it is for testing, simply
install the addon.

By default, Ember Axe will audit a component for accessibility each time it is
rendered. This ensures that the component is still accessible even after state
changes, and since the checks are scoped to a component's element, it means that
any state change propagated downwards is also caught.

### Component Hooks

Since development is not a uniform experience, Ember Axe provides several hooks
to help stay out of the way.

_Note:_ these are all `undefined` by default.

#### Defining a custom callback

If you feel the logging of violations is poor or you just want to see the entire
results of a component's audit, you can define a custom callback. The callback
receives the results of the `a11yCheck` audit that is scoped to the component's
element. Simply set it as `axeCallback` on the component in question:

```javascript
axeCallback(results) {
  // do stuff with results
}
```

#### Setting options for the audit

As with testing, if you need to set custom auditing options for a component, you
can do so easily. Simply set a value for the `axeOptions` property value:

```javascript
axeOptions: { /* a11yCheck options */ }
```

#### Turning the audit off

Lastly, if you really find the audits to be cramping development, you can turn
them off via a simple boolean switch:

```javascript
turnAuditOff: true
```


text:
package org.zalando.logbook.servlet;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;

import javax.servlet.DispatcherType;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;

final class RequestBuilders {

    static RequestBuilder async(final MvcResult result) {
        final RequestBuilder builder = asyncDispatch(result);

        return context -> {
            final MockHttpServletRequest request = builder.buildRequest(context);
            // this is missing in MockMvcRequestBuilders#asyncDispatch
            request.setDispatcherType(DispatcherType.ASYNC);
            return request;
        };
    }

}


text:
title: 'Brisbane Writers Festival: Friday Panel'
date: 2017-09-08 14:30:00
show_time: true
venue:
  name: Auditorium 1
  address:
  city:
  state:
  zip:
link: 'http://uplit.com.au/festival/brisbane-writers-festival-2017/program/pains-of-the-past'
---

How does the past impact the future? Find out how fiction can explore the impact of intergenerational trauma, and how writing about it may be cathartic.

With Nir Baram, Dr. Sandra Philips, Claire Coleman, and Min Jin Lee.


text:
package org.oep.dossiermgt.service.persistence;

import com.liferay.portal.kernel.dao.orm.BaseActionableDynamicQuery;
import com.liferay.portal.kernel.exception.SystemException;

import org.oep.dossiermgt.model.StatisticByAgency;
import org.oep.dossiermgt.service.StatisticByAgencyLocalServiceUtil;

/**
 * @author trungdk
 * @generated
 */
public abstract class StatisticByAgencyActionableDynamicQuery
	extends BaseActionableDynamicQuery {
	public StatisticByAgencyActionableDynamicQuery() throws SystemException {
		setBaseLocalService(StatisticByAgencyLocalServiceUtil.getService());
		setClass(StatisticByAgency.class);

		setClassLoader(org.oep.dossiermgt.service.ClpSerializer.class.getClassLoader());

		setPrimaryKeyPropertyName("statisticByAgencyId");
	}
}


text:
var countWords = function (inputWords) {
  return inputWords.reduce(function(acc, elt) {
    acc[elt] = acc[elt] + 1 || 1;
    return acc;
  }, {});
};

module.exports = countWords;


text:
namespace Amazon.Ssm;

public sealed class DescribeInstancePatchStatesResponse
{
}


text:
/**
 * Created by liudan on 15/7/14.
 */
var Util = require('./util');
var isObject = Util.isObject;
/**
 *
 * @param target  {object}  容器节点
 * @param obj  {object}
 *     - type: 'left', left向左,right向右,top向上,bottom向下
 *     - suffix: 'rem', 单位
 *     - speed: 10, 移动速度
 *     - start: 0, 起始位置
 *     - end: 100, 结束位置
 *     - pxToRem: 192  px转rem的换算值
 */

function Track(target, obj) {
    if (!target) {
        throw 'node is not defined';
    }

    this.node = null;
    this.target = target;
    this.type = obj.type || 'left';
    this.suffix = obj.suffix || 'px';
    this.speed = obj.speed || 10;
    this.start = obj.start || 0;
    this.end = obj.end || 0;
    this.pxToRem = obj.pxToRem || 1;

    this.className = obj.className || '';
    this.templateNode = obj.templateNode || 'div';
    this.template = obj.template || '';
    this.style = isObject(obj.style) ? obj.style : {};

    this.position = this.start;
    this.transformText = 'translate3d({num}, 0, 0)';

    this.state = true;

    this.init();
}

Track.prototype.init = function() {
    this.node = document.createElement(this.templateNode);

    this.node.classList.add(this.className);

    this.node.innerHTML = this.template;
    this.target.appendChild(this.node);

    if (this.type === 'left' || this.type === 'right') {
        this.transformText = 'translate3d({num}, 0, 0)';
    } else if (this.type === 'top' || this.type === 'bottom') {
        this.transformText = 'translate3d(0, {num}, 0)';
    } else {
        throw 'type is error';
    }

    if (this.type === 'top' || this.type === 'left') {
        this.speed = -this.speed;
        this.start = -this.start;
        this.end = -this.end;
        this.position = -this.position;
    }

    for (var key in this.style) {
        if (hasOwnProperty.call(this.style, key)) {
            this.node.style[key] = this.style[key];
        }
    }

    this.move();
};

Track.prototype.move = function() {
    this.node.style.webkitTransform = this.transformText.replace(/\{num\}/g, (this.position / this.pxToRem)+this.suffix);
};

//跑起来
Track.prototype.run = function() {
    if (!this.state) {
        return;
    }

    if (this.type === 'top' || this.type === 'left') {
        var value = Math.abs(this.position) - Math.abs(this.end);
    } else {
        value = this.position - this.end;
    }

    if (value < 0) {
        this.position += this.speed;
    } else {
        this.position = this.start;
    }

    this.move();
};

//开启
Track.prototype.go = function() {
    this.state = true;
};

//关闭
Track.prototype.stop = function() {
    this.state = false;
};

//删除
Track.prototype.delete = function() {
    this.node.parentNode.removeChild(this.node);

    for (var key in this) {
        if (hasOwnProperty.call(this, key)) {
            this[key] = null;
        }
    }
};

module.exports = Track;


text:
var QBerDispatcher = require('../dispatcher/QBerDispatcher');
var EventEmitter = require('events').EventEmitter;
var DataverseConstants = require('../constants/DataverseConstants');
var DatasetStore = require('./DatasetStore');
var assign = require('object-assign');

var CHANGE_EVENT = 'change';

var _files;
var _study;
var _modal_visible = true;

var DataverseStore = assign({}, EventEmitter.prototype, {

  getModalVisible: function(){
    return _modal_visible;
  },

  setModalVisible: function(visible_or_not){
    _modal_visible = visible_or_not;
  },

  getFiles: function() {
    return _files;
  },

  setFiles: function(files) {
    _files = files;
  },

  getStudy: function() {
    return _study;
  },

  setStudy: function(study) {
    _study = study;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});

// Register callback to handle all updates
QBerDispatcher.register(function(action) {

  switch(action.actionType) {
    case DataverseConstants.DV_UPDATE_FILES:
      DataverseStore.setFiles(action.file_list.files);
      DataverseStore.setStudy(action.file_list.study);
      DataverseStore.emitChange();
      break;
    case DataverseConstants.DV_CLOSE_BROWSER:
      DataverseStore.setModalVisible(false);
      DataverseStore.emitChange();
      break;
    case DataverseConstants.DV_SHOW_BROWSER:
      DataverseStore.setModalVisible(true);
      DataverseStore.emitChange();
      break;
    default:

      // no op
  }
});

module.exports = DataverseStore;


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

package kafka.api

import java.io.File
import java.util.Properties

import kafka.server.{ConfigEntityName, KafkaConfig, QuotaId}
import kafka.utils.JaasTestUtils
import org.apache.kafka.common.security.auth.SecurityProtocol
import org.apache.kafka.common.utils.Sanitizer
import org.junit.{After, Before}

class UserQuotaTest extends BaseQuotaTest with SaslSetup {

  override protected def securityProtocol = SecurityProtocol.SASL_SSL
  override protected lazy val trustStoreFile = Some(File.createTempFile("truststore", ".jks"))
  private val kafkaServerSaslMechanisms = Seq("GSSAPI")
  private val kafkaClientSaslMechanism = "GSSAPI"
  override protected val serverSaslProperties = Some(kafkaServerSaslProperties(kafkaServerSaslMechanisms, kafkaClientSaslMechanism))
  override protected val clientSaslProperties = Some(kafkaClientSaslProperties(kafkaClientSaslMechanism))

  override val userPrincipal = JaasTestUtils.KafkaClientPrincipalUnqualifiedName2
  override val producerQuotaId = QuotaId(Some(userPrincipal), None, None)
  override val consumerQuotaId = QuotaId(Some(userPrincipal), None, None)

  @Before
  override def setUp() {
    startSasl(jaasSections(kafkaServerSaslMechanisms, Some("GSSAPI"), KafkaSasl, JaasTestUtils.KafkaServerContextName))
    this.serverConfig.setProperty(KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString)
    this.serverConfig.setProperty(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString)
    super.setUp()
    val defaultProps = quotaProperties(defaultProducerQuota, defaultConsumerQuota, defaultRequestQuota)
    adminZkClient.changeUserOrUserClientIdConfig(ConfigEntityName.Default, defaultProps)
    waitForQuotaUpdate(defaultProducerQuota, defaultConsumerQuota, defaultRequestQuota)
  }

  @After
  override def tearDown(): Unit = {
    super.tearDown()
    closeSasl()
  }

  override def overrideQuotas(producerQuota: Long, consumerQuota: Long, requestQuota: Double) {
    val props = quotaProperties(producerQuota, consumerQuota, requestQuota)
    updateQuotaOverride(props)
  }

  override def removeQuotaOverrides() {
    val emptyProps = new Properties
    updateQuotaOverride(emptyProps)
    updateQuotaOverride(emptyProps)
  }

  private def updateQuotaOverride(properties: Properties) {
    adminZkClient.changeUserOrUserClientIdConfig(Sanitizer.sanitize(userPrincipal), properties)
  }
}


text:
/**
 *  win32sysinfo.c
 *
 *  File:     win32sysinfo.c
 *  Purpose:  Portprogram for supervision of disk and memory usage.
 *
 *  Synopsis: win32sysinfo
 *
 *  PURPOSE OF THIS PROGRAM
 *
 *  This program supervises the reports the memory status or disk status
 *  on request from the Erlang system
 *
 *
 *  SPAWNING FROM ERLANG
 *
 *  This program is started from Erlang as follows,
 *
 *       Port = open_port({spawn, 'memsup'}, [{packet,1}]) for UNIX
 *
 *  COMMUNICATION
 *
 *    WIN32
 *
 * get_disk_info 'd' (request info about all drives)
 *      The result is returned as one packet per logical drive with the
 *      following format:
 *      Drive Type AvailableBytes TotalBytes TotalBytesFree
 *      END
 *
 *      Example:
 *      A:\ DRIVE_REMOVABLE 0 0 0
 *      C:\ DRIVE_FIXED 10000000 20000000 10000000
 *      END

 * get_disk_info 'd'Driveroot (where Driveroot is a string like this "A:\\"
 *      (request info of specific drive)
 *      The result is returned with the same format as above except that
 *      Type will be DRIVE_NOT_EXIST if the drive does not exist.
 *
 * get_mem_info 'm' (request info about memory)
 *
 *      The result is returned as one packet with the following format
 *
 *
 *
 *
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <windows.h>
#include "winbase.h"

#define MEM_INFO 'm'
#define DISK_INFO 'd'
#define OK "o"

#define ERLIN_FD      0
#define ERLOUT_FD     1

typedef BOOL (WINAPI *tfpGetDiskFreeSpaceEx)(LPCTSTR, PULARGE_INTEGER,PULARGE_INTEGER,PULARGE_INTEGER);

static  tfpGetDiskFreeSpaceEx fpGetDiskFreeSpaceEx;

static void print_error(const char *msg);
static void
return_answer(char* value)
{
    int left, bytes, res;

    bytes = strlen(value); /* Skip trailing zero */

    res = write(1,(char*) &bytes,1);
    if (res != 1) {
	print_error("Error writing to pipe");
	exit(1);
    }

    left = bytes;

    while (left > 0)
    {
	res = write(1, value+bytes-left, left);
	if (res <= 0) {
	    print_error("Error writing to pipe");
	    exit(1);
	}
	left -= res;
    }
}

void output_drive_info(char* drive){
    ULARGE_INTEGER availbytes,totbytesfree,totbytes;
    OSVERSIONINFO osinfo;
    char answer[512];
    osinfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
    GetVersionEx(&osinfo);
    switch (GetDriveType(drive)) {
    case DRIVE_UNKNOWN:
	sprintf(answer,"%s DRIVE_UNKNOWN 0 0 0\n",drive);
	return_answer(answer);
	break;
    case DRIVE_NO_ROOT_DIR:
	sprintf(answer,"%s DRIVE_NO_ROOT_DIR 0 0 0\n",drive);
	return_answer(answer);
	break;
    case DRIVE_REMOVABLE:
	sprintf(answer,"%s DRIVE_REMOVABLE 0 0 0\n",drive);
	return_answer(answer);
	break;
    case DRIVE_FIXED:
	/*		if ((osinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) &&
			(LOWORD(osinfo.dwBuildNumber) <= 1000)) {
			sprintf(answer,"%s API_NOT_SUPPORTED 0 0 0\n",drive);
			return_answer(answer);
			}
			else
			*/
	    if (fpGetDiskFreeSpaceEx == NULL){
		sprintf(answer,"%s API_NOT_SUPPORTED 0 0 0\n",drive);
		return_answer(answer);
	    }
	    else
		if (fpGetDiskFreeSpaceEx(drive,&availbytes,&totbytes,&totbytesfree)){
		    sprintf(answer,"%s DRIVE_FIXED %I64u %I64u %I64u\n",drive,availbytes,totbytes,totbytesfree);
		    return_answer(answer);
		}
		else {
		    sprintf(answer,"%s API_ERROR 0 0 0\n",drive);
		    return_answer(answer);
		}
	break;
    case DRIVE_REMOTE:
	sprintf(answer,"%s DRIVE_REMOTE 0 0 0\n",drive);
	return_answer(answer);
	break;
    case DRIVE_CDROM:
	sprintf(answer,"%s DRIVE_CDROM 0 0 0\n",drive);
	return_answer(answer);
	break;
    case DRIVE_RAMDISK:
	sprintf(answer,"%s DRIVE_RAMDISK 0 0 0\n",drive);
	return_answer(answer);
	break;
    default:
	sprintf(answer,"%s DRIVE_NOT_EXIST 0 0 0\n",drive);
	return_answer(answer);
    } /* switch */
}

int load_if_possible() {
    HINSTANCE lh;
    if((lh = LoadLibrary("KERNEL32")) ==NULL)
	return 0;		/* error */
    if ((fpGetDiskFreeSpaceEx =
	 (tfpGetDiskFreeSpaceEx) GetProcAddress(lh,"GetDiskFreeSpaceExA")) ==NULL)
	return GetLastError(); /* error */
    return 1;
}

void get_disk_info_all(){
    DWORD dwNumBytesForDriveStrings;
    char DriveStrings[255];
    char* dp = DriveStrings;

    dwNumBytesForDriveStrings = GetLogicalDriveStrings(254,dp);
    if (dwNumBytesForDriveStrings != 0) {
	/* GetLogicalDriveStringsIs supported on this platform */
	while (*dp != 0) {
	    output_drive_info(dp);
	    dp = strchr(dp,0) +1;
	}
    }
    else {
	/* GetLogicalDriveStrings is not supported (some old W95) */
	DWORD dwDriveMask = GetLogicalDrives();
	int nDriveNum;
	char drivename[]="A:\\";
	/*printf("DriveName95 DriveType BytesAvail BytesTotal BytesTotalFree\n");*/
	for (nDriveNum = 0; dwDriveMask != 0;nDriveNum++) {
	    if (dwDriveMask & 1) {
		drivename[0]='A'+ nDriveNum;
		output_drive_info(drivename);
	    }
	    dwDriveMask = dwDriveMask >> 1;
	}
    }
}

void get_avail_mem_ext() {
    char answer[512];
    MEMORYSTATUSEX ms;
    ms.dwLength=sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&ms);
    sprintf(answer,"%d %I64d %I64d %I64d %I64d %I64d %I64d\n",
	    ms.dwMemoryLoad,
	    ms.ullTotalPhys,
	    ms.ullAvailPhys,
	    ms.ullTotalPageFile,
	    ms.ullAvailPageFile,
	    ms.ullTotalVirtual,
	    ms.ullAvailVirtual
	    );
    return_answer(answer);
    /*
	DWORD     dwLength;
	DWORD     dwMemoryLoad;
	DWORDLONG ullTotalPhys;
	DWORDLONG ullAvailPhys;
	DWORDLONG ullTotalPageFile;
	DWORDLONG ullAvailPageFile;
	DWORDLONG ullTotalVirtual;
	DWORDLONG ullAvailVirtual;
    */
}

static void
message_loop()
{
    char cmdLen;
    char cmd[512];
    int res;

    /* Startup ACK. */
    return_answer(OK);
    while (1)
    {
	/*
	 *  Wait for command from Erlang
	 */
	if ((res = read(0, &cmdLen, 1)) < 0) {
	    print_error("Error reading from Erlang");
	    return;
	}

	if (res != 1){	/* Exactly one byte read ? */
	    print_error("Erlang has closed");
	    return;
	}
	if ((res = read(0, &cmd, cmdLen)) == cmdLen){
	    if (cmdLen == 1) {
		switch (cmd[0]) {
		case MEM_INFO:
		    get_avail_mem_ext();
		    return_answer(OK);
		    break;
		case DISK_INFO:
		    get_disk_info_all();
		    return_answer(OK);
		    break;
		default:	/* ignore all other messages */
		    break;
		} /* switch */
	    }
	    else
		if ((res > 0) && (cmd[0]==DISK_INFO)) {
		    cmd[cmdLen] = 0;
		    output_drive_info(&cmd[1]);
		    return_answer("OK");
		    return;
		}
		else
		    return_answer("xEND");
	}
	else if (res == 0) {
	    print_error("Erlang has closed");
	    return;
	}
	else {
	    print_error("Error reading from Erlang");
	    return;
	}
    }
}

int main(int argc, char ** argv){

    _setmode(0, _O_BINARY);
    _setmode(1, _O_BINARY);
    load_if_possible();
    message_loop();
    return 0;
}
static void
print_error(const char *msg) {
  /* try to use one write only */
  fprintf(stderr, "[os_mon] win32 supervisor port (win32sysinfo): %s\r\n", msg);
  fflush(stderr);
}


text:
package org.apache.qpid.proton.codec.transport;

import java.util.AbstractList;
import java.util.List;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.transport.DeliveryState;
import org.apache.qpid.proton.amqp.transport.Disposition;
import org.apache.qpid.proton.amqp.transport.Role;
import org.apache.qpid.proton.codec.AbstractDescribedType;
import org.apache.qpid.proton.codec.DecodeException;
import org.apache.qpid.proton.codec.Decoder;
import org.apache.qpid.proton.codec.DescribedTypeConstructor;
import org.apache.qpid.proton.codec.EncoderImpl;

public final class DispositionType extends AbstractDescribedType<Disposition,List> implements DescribedTypeConstructor<Disposition>
{
    private static final Object[] DESCRIPTORS =
    {
        UnsignedLong.valueOf(0x0000000000000015L), Symbol.valueOf("amqp:disposition:list"),
    };

    private static final UnsignedLong DESCRIPTOR = UnsignedLong.valueOf(0x0000000000000015L);

    private DispositionType(EncoderImpl encoder)
    {
        super(encoder);
    }

    public UnsignedLong getDescriptor()
    {
        return DESCRIPTOR;
    }

    @Override
    protected List wrap(Disposition val)
    {
        return new DispositionWrapper(val);
    }

    private static final class DispositionWrapper extends AbstractList
    {

        private Disposition _disposition;

        public DispositionWrapper(Disposition disposition)
        {
            _disposition = disposition;
        }

        public Object get(final int index)
        {

            switch(index)
            {
                case 0:
                    return _disposition.getRole().getValue();
                case 1:
                    return _disposition.getFirst();
                case 2:
                    return _disposition.getLast();
                case 3:
                    return _disposition.getSettled();
                case 4:
                    return _disposition.getState();
                case 5:
                    return _disposition.getBatchable();
            }

            throw new IllegalStateException("Unknown index " + index);

        }

        public int size()
        {
            return _disposition.getBatchable()
                      ? 6
                      : _disposition.getState() != null
                      ? 5
                      : _disposition.getSettled()
                      ? 4
                      : _disposition.getLast() != null
                      ? 3
                      : 2;

        }
    }

        public Disposition newInstance(Object described)
        {
            List l = (List) described;

            Disposition o = new Disposition();

            if(l.isEmpty())
            {
                throw new DecodeException("The first field cannot be omitted");
            }

            switch(6 - l.size())
            {

                case 0:
                    Boolean batchable = (Boolean) l.get(5);
                    o.setBatchable(batchable == null ? false : batchable);
                case 1:
                    o.setState( (DeliveryState) l.get( 4 ) );
                case 2:
                    Boolean settled = (Boolean) l.get(3);
                    o.setSettled(settled == null ? false : settled);
                case 3:
                    o.setLast( (UnsignedInteger) l.get( 2 ) );
                case 4:
                    o.setFirst( (UnsignedInteger) l.get( 1 ) );
                case 5:
                    o.setRole( Boolean.TRUE.equals(l.get( 0 )) ? Role.RECEIVER : Role.SENDER );
            }

            return o;
        }

        public Class<Disposition> getTypeClass()
        {
            return Disposition.class;
        }

    public static void register(Decoder decoder, EncoderImpl encoder)
    {
        DispositionType type = new DispositionType(encoder);
        for(Object descriptor : DESCRIPTORS)
        {
            decoder.register(descriptor, type);
        }
        encoder.register(type);
    }

}


text:
package govet

import (
	"reflect"
	"testing"
)

var wantVetResult = []string{
	`../../engine/config.go:204: struct field FilesNum repeats json tag "content" also at ../../engine/config.go:203`,
	`../../engine/config.go:205: struct field Quality repeats json tag "content" also at ../../engine/config.go:203`,
	`../../engine/reporter.go:128: call of strategy.Percentage copies lock value: engine.Summaries`,
	`../../engine/strategy_copycheck.go:69: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_countcode.go:51: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_cyclo.go:76: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_deadcode.go:66: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_dependgraph.go:38: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_depth.go:74: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_importpackages.go:38: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_interfacer.go:66: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_lint.go:64: return copies lock value: engine.Summaries`,
	`../../engine/strategy_lint.go:67: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_simplecode.go:61: return copies lock value: engine.Summaries`,
	`../../engine/strategy_simplecode.go:64: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_spellcheck.go:64: Percentage passes lock by value: engine.Summaries`,
	`../../engine/strategy_unittest.go:94: Percentage passes lock by value: engine.Summaries`,
}

func Test_GoVet(t *testing.T) {
	res, err := GoVet([]string{"../../engine"})
	if err != nil {
		t.Error("go vet failed.")
	} else {
		if !reflect.DeepEqual(res, wantVetResult) {
			t.Errorf("want %v, but got %v", wantVetResult, res)
		}
	}
}


text:
namespace x0d {

class WebdavModule : public Module {
 public:
  explicit WebdavModule(Daemon* d);

  // main handler
  bool webdav(Context* cx, Params& args);

 private:
  bool webdav_mkcol(Context* cx);
  bool webdav_get(Context* cx);
  bool webdav_put(Context* cx, Params& args);
  bool todo(Context* cx);
};

} // namespace x0d


text:
package chapter_3_StacksAndQueues;

import java.util.Stack;

/** 3.6 sort a stack in ascending order (biggest items on top) */
/** you can use additional stacks but not other data structure like array */
public class SortStack {

	public static Stack<Integer> sort(Stack<Integer> stack) {

		if (stack.isEmpty()) {
			return stack;
		}

		Stack<Integer> buf = new Stack<Integer>();
		buf.push(stack.pop());
		while (!stack.isEmpty()) {
			int temp = stack.pop();
			while (!buf.isEmpty() && buf.peek() > temp) {
				stack.push(buf.pop());
			}
			buf.push(temp);
		}

		return buf;

		// if we must change the original stack, we have to push everything back
		//while (!buf.isEmpty()) {
		//	stack.push(buf.pop());
		//}
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();

		stack.push(3);
		stack.push(4);
		stack.push(1);
		stack.push(2);
		stack.push(5);
		System.out.println(stack.toString());

		stack = SortStack.sort(stack);
		System.out.println(stack.toString());
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 6(6): 562 (1908)

#### Original name
Dothichiza exigua Sacc.

### Remarks
null


text:
tesseract
=========

![](https://badge.imagelayers.io/vimagick/tesseract:latest.svg)

[Tesseract][1] is an Open Source OCR engine, available under the Apache 2.0
license. It can be used directly, or (for programmers) using an API. It
supports a wide variety of languages.

Tesseract doesn't have a built-in GUI, but there are several available from the
3rdParty page.

Quick Start
-----------

```
$ alias tesseract='docker run --rm -v `pwd`:/work -w /work vimagick/tesseract'
$ tesseract myscan.png out
$ cat out.txt
```

[1]: https://github.com/tesseract-ocr/tesseract


text:
package org.culturegraph.mf.stream.converter;

import org.culturegraph.mf.framework.DefaultObjectPipe;
import org.culturegraph.mf.framework.StreamReceiver;
import org.culturegraph.mf.framework.annotations.Description;
import org.culturegraph.mf.framework.annotations.Out;

/**
 * Outputs a record containing the input object as literal.
 *
 * @param <T> input object type
 * @author Christoph Böhme
 */
@Description("Outputs a record containing the input object as literal")
@Out(StreamReceiver.class)
public final class ObjectToLiteral<T> extends
		DefaultObjectPipe<T, StreamReceiver> {

	public static final String DEFAULT_LITERAL_NAME = "obj";

	private String literalName = DEFAULT_LITERAL_NAME;

	public void setLiteralName(final String literalName) {
		this.literalName = literalName;
	}

	public String getLiteralName() {
		return literalName;
	}

	@Override
	public void process(final T obj) {
		assert obj!=null;
		assert !isClosed();
		getReceiver().startRecord("");
		getReceiver().literal(literalName, obj.toString());
		getReceiver().endRecord();
	}

}


text:
/*!
	PhoenixCore Config File.
*/
#ifndef __PHOENIXCORE_CONFIG_H__
#define __PHOENIXCORE_CONFIG_H__

// Version Name/Number/Release.
#define PHOENIXCORE_VERSION "PhoenixCore 0.3 Raven"
#define PHEONIXCORE_VERSION_NUMBER "0.3"
#define PHEONIXCORE_VERSION_NAME "Raven"

// OpenGL Include
#include "glew/GL/glew.h"
#include <GL/glfw.h>

//! Define this to use the default GLFW Window Manager, or set to 0 to not compile the GLFW window manager.
/*!
	\note If this is 0, the system will not have a window manager, your custom window manager must be Instance()'d before calling RenderSystem();
*/
#define PH_USE_GLFW 1

#endif //__PHOENIXCORE_CONFIG_H__


text:
package org.apache.etch.compiler;

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

/**
 * LogHandler which accumulates messages in a list.
 */
public class ListLogHandler extends AbstractLogHandler
{
	/** list of accumulated messages */
	public List<Message> msgs = new ArrayList<Message>();

	@Override
	protected void log( Message message )
	{
		msgs.add( message );
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_home"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/exercise_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:gravity="center_vertical|center_horizontal"
        android:text="exercise_name"
        android:textColor="#FFFFFF" />

    <TextView
        android:id="@+id/question"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center_vertical|center_horizontal"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:text="question"
        android:textColor="#FFFFFF"
        android:textSize="15sp" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <RadioButton
            android:id="@+id/rb_answer1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:button="@drawable/selector_right_answer"
            android:paddingLeft="50dp"
            android:text="Answer1"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

        <RadioButton
            android:id="@+id/rb_answer2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:button="@drawable/selector_right_answer"
            android:paddingLeft="50dp"
            android:text="Answer2"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

        <RadioButton
            android:id="@+id/rb_answer3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:button="@drawable/selector_right_answer"
            android:paddingLeft="50dp"
            android:text="Answer3"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

        <RadioButton
            android:id="@+id/rb_answer4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:button="@drawable/selector_right_answer"
            android:paddingLeft="50dp"
            android:text="Answer4"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />
    </RadioGroup>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/bt_previous_step"
                android:layout_width="wrap_content"
                android:layout_height="70dp"
                android:layout_marginTop="10dp"
                android:background="@android:color/transparent"
                android:src="@drawable/selector_bt_step" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="70dp"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_marginTop="-70dp"
                android:gravity="center_horizontal|center_vertical"
                android:src="@drawable/previous" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/bt_save"
                android:layout_width="wrap_content"
                android:layout_height="70dp"
                android:layout_marginTop="10dp"
                android:background="@android:color/transparent"
                android:src="@drawable/selector_bt_step" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="70dp"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_marginTop="-70dp"
                android:gravity="center_horizontal|center_vertical"
                android:src="@drawable/confirm" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
package com.humorusz.practice.frameAnimtor;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.view.SurfaceHolder;

import com.humorousz.commonutils.log.Logger;
import com.humorousz.uiutils.helper.UIUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by zhangzhiquan on 2017/8/2.
 */

public class Actor extends BaseActor implements SurfaceHolder.Callback {
    private static final String TAG = "Actor";
    private WeakReference<Context> mContext;
    private BlockingQueue<Bitmap> mQueue;
    private SurfaceHolder mHoler;
    private int totalCount;
    public Actor(Context context) {
        super(context);
        mContext = new WeakReference<Context>(context);
        mQueue = new ArrayBlockingQueue<>(10);
        mHoler = this.getHolder();
        mHoler.addCallback(this);
        setZOrderOnTop(true);
        this.setFocusable(true);
        this.setFocusableInTouchMode(true);
        getHolder().setFormat(PixelFormat.TRANSPARENT);
        initTotalCount();
        startDecode();
    }

    private void initTotalCount(){
        try {
            if(mContext.get() != null){
                totalCount = mContext.get().getResources().getAssets().list("f2").length;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startDecode(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    decodeBitmap();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        DrawThread thread = new DrawThread();
        thread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//        rect=new Rect(0,0,width,height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if(mQueue != null){
           while(!mQueue.isEmpty()){
               mQueue.poll().recycle();
           }
        }
    }

    private Bitmap getImage() throws InterruptedException {
        return mQueue.take();
    }

    private Bitmap getImageFromAssetsFile(int id){
        if(mContext.get() == null)
            return null;
        Bitmap image = null;
        AssetManager am = mContext.get().getResources().getAssets();
        try {
            InputStream is = am.open("f2/"+id+".png");
            image = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    private void decodeBitmap() throws InterruptedException {
        for(int i = 0;i<totalCount;i++){
            mQueue.put(getImageFromAssetsFile(i+1));
            Logger.d(TAG,"decode "+i);
        }
    }

    private class DrawThread extends Thread{
        @Override
        public void run() {
            super.run();
            while(true){
                try {
                    Bitmap bitmap = getImage();
                    Canvas canvasstart = mHoler.lockCanvas();
                    if (bitmap == null || canvasstart == null )
                        break;
                    doDraw(canvasstart, bitmap);
                    mHoler.unlockCanvasAndPost(canvasstart);
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doDraw(Canvas canvas,Bitmap bitmap){
//			*important*背景透明
        if(canvas == null)
            return;
        int left = UIUtils.getScreenWidth()/2 - bitmap.getWidth()/2;
        int top = UIUtils.getScreenHeight()/2 - bitmap.getHeight()/2;
        Paint paint = new Paint();//实例化画笔
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setColor(0xffffffff);
        paint.setAntiAlias(true);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        canvas.save();
        canvas.drawBitmap(bitmap,new Rect(0,0,bitmap.getWidth(),bitmap.getHeight())
                ,new Rect(left,top,left+bitmap.getWidth(),top+bitmap.getHeight()),paint);
        canvas.restore();
        bitmap.recycle();
    }

}


text:
import _ from "lodash";
import React from "react";
import ReactDOM from "react-dom";
import ReactSuperSelect from "../src/react-super-select";
import testData from "./super-selects/support/test-data.js";
import TestPageExampleOptionTemplate from "./super-selects/support/test-page-example-option-template";

const mockAjaxPerPage = 10;
let lastPage = 0;

class RSSTestPageApp extends React.Component{
  constructor(props) {
    super(props);

    _.bindAll(this, [
      "_renderPropsLinks",
      "_renderProps"
    ]);

    this._groupBy = 'size';

  }

  render() {
    return (

Basic Example

          <ReactSuperSelect placeholder="Make a Selection" searchable={true} searchPlaceholder="search" dataSource={testData} onChange={this.handlerExample} />

Custom Template Example

          <ReactSuperSelect groupBy={this._groupBy} placeholder="Make a Selection" customClassName="your-custom-wrapper-class" tags={true} initialValue={[testData[0], testData[4]]} searchable={true} searchPlaceholder="search" onChange={this.handlerExample} customOptionTemplateFunction={this._customMarkupMapper} dataSource={testData} />

Ajax Example

          <ReactSuperSelect placeholder="Make a Selection" tags={true} searchable={true} searchPlaceholder="filter" onChange={this.handlerExample} ajaxDataFetch={this._simulatedAjaxFetch} pageDataFetch={this._simulatedPageFetch} hasMorePages={this._hasMorePages} />

    );
  }

  handlerExample(newValue) {
    console.info(newValue);
  }

  _customMarkupMapper(item) {
    return(
    <TestPageExampleOptionTemplate key={item.id} option={item} />);
  }

  _simulatedAjaxFetch() {
    const data = _.take(testData, mockAjaxPerPage);
    // simulate a 2.5 second ajax fetch for collection data
    return {
      then: function(callback) {
        setTimeout(function() {
          callback(data);
        }, 2500);
      }
    };
  }

  _simulatedPageFetch(collection) {
    lastPage = lastPage + 1;
    const sliceLocation = lastPage * mockAjaxPerPage;

    let data;

    if (sliceLocation < testData.length) {
      data = [];

      for (var i = sliceLocation; i < (sliceLocation + mockAjaxPerPage); i++) {
        if (testData[i]) {
          data.push(testData[i]);
        }
      }
    } else {
      data = testData;
    }

    return {
      then: function(callback) {
        setTimeout(function() {
          callback(collection.concat(data));
        }, 1500);
      }
    };
  }

  _hasMorePages(collection) {
    return collection.length < testData.length;
  }
}

ReactDOM.render(<RSSTestPageApp />, document.getElementById('test_page_app'));


text:
---
title: Explicit values for generated properties | Microsoft Docs
author: rowanmiller
ms.author: divega
ms.date: 10/27/2016
ms.assetid: 3f1993c2-cdf5-425b-bac2-a2665a20322b
ms.technology: entity-framework-core
uid: core/saving/explicit-values-generated-properties
---
#生成属性的显式值
# Explicit values for generated properties

生成属性是指当实体添加和/或更新时,其值(EF或数据库)生成的属性。更多信息见[Generated Properties](../modeling/generated-properties.html)。

A generated property is a property whose value is generated (either by EF or the database) when the entity is added and/or updated. See [Generated Properties](../modeling/generated-properties.html) for more information.

有些情况下,您希望为生成属性设置显式值,而不是一个生成值。

There may be situations where you want to set an explicit value for a generated property, rather than having one generated.

> [!TIP]
> 你可以在GitHub上查看本文的[示例代码](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Saving/Saving/ExplicitValuesGenerateProperties/)。

> You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Saving/Saving/ExplicitValuesGenerateProperties/) on GitHub.

## The model

本文中使用的模型包含一个`Employee`实体。

The model used in this article contains a single `Employee` entity.
````csharp
		public class Employee
		{
			public int EmployeeId { get; set; }
			public string Name { get; set; }
			public DateTime EmploymentStarted { get; set; }
			public int Salary { get; set; }
			public DateTime? LastPayRaise { get; set; }
		}
````

## Saving an explicit value during add

在数据插入一个新实体时,`Employee.EmploymentStarted`属性通过配置,将得到生成值(使用默认值)。

The `Employee.EmploymentStarted` property is configured to have values generated by the database for new entities (using a default value).

```csharp
	modelBuilder.Entity<Employee>()
    .Property(b => b.EmploymentStarted)
    .HasDefaultValueSql("CONVERT(date, GETDATE())");
```

下面的代码将两个雇员插入数据库。

The following code inserts two employees into the database.

*第一个,没有值分配给`Employee.EmploymentStarted`属性,所以它仍然设置为CLR默认值给`DateTime`。

* For the first, no value is assigned to `Employee.EmploymentStarted` property, so it remains set to the CLR default value for `DateTime`.

*第一个,我们设置了一个显示值`1-Jan-2000`。

* For the second, we have set an explicit value of `1-Jan-2000`.

```csharp
using (var db = new EmployeeContext())
{
    db.Employees.Add(new Employee { Name = "John Doe" });
    db.Employees.Add(new Employee { Name = "Jane Doe", EmploymentStarted = new DateTime(2000, 1, 1) });
    db.SaveChanges();

    foreach (var employee in db.Employees)
    {
        Console.WriteLine(employee.EmployeeId + ": " + employee.Name + ", " + employee.EmploymentStarted);
    }
}
```
数据库输出显示,第一个雇员为生成值,第二个为显示值。
Output shows that the database generated a value for the first employee and our explicit value was used for the second.

````
1: John Doe, 1/26/2017 12:00:00 AM
2: Jane Doe, 1/1/2000 12:00:00 AM
````

### Explicit values into SQL Server IDENTITY columns

按照约定,`Employee.EmployeeId`属性是存储生成`IDENTITY`列。

By convention the `Employee.EmployeeId` property is a store generated `IDENTITY` column.

对于大多数情况,上面显示的方法将适用于主键属性。然而,在SQL Server`IDENTITY` 列中可以插入显式值,在调用`SaveChanges()`之前你需要手动启用`IDENTITY_INSERT`。

For most situations, the approach shown above will work for key properties. However, to insert explicit values into a SQL Server `IDENTITY` column, you need to manually enable `IDENTITY_INSERT` before calling `SaveChanges()`.

> [!NOTE]
>  SQL Server提供程序上,我们的待办事项上有一个[feature request](https://github.com/aspnet/EntityFramework/issues/703)去做这种自动。

> We have a [feature request](https://github.com/aspnet/EntityFramework/issues/703) on our backlog to do this automatically within the SQL Server provider.

```csharp
using (var db = new EmployeeContext())
{
    db.Employees.Add(new Employee { EmployeeId = 100, Name = "John Doe" });
    db.Employees.Add(new Employee { EmployeeId = 101, Name = "Jane Doe" });

    db.Database.OpenConnection();
    try
    {
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employees ON");
        db.SaveChanges();
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employees OFF");
    }
    finally
    {
        db.Database.CloseConnection();
    }

    foreach (var employee in db.Employees)
    {
        Console.WriteLine(employee.EmployeeId + ": " + employee.Name);
    }
}
```
输出显示所提供的ids保存到数据库中了。

Output shows that the supplied ids were saved to the database.

````
100: John Doe
101: Jane Doe
````
## 在更新时,设置一个显示值

## Setting an explicit value during update

在数据库更新时,`Employee.LastPayRaise`属性配置有值生成。

The `Employee.LastPayRaise` property is configured to have values generated by the database during updates.

<!--[!code-csharp[Main](../../../samples/core/Saving/Saving/ExplicitValuesGenerateProperties/EmployeeContext.cs#LastPayRaise)]-->
```csharp
modelBuilder.Entity<Employee>()
    .Property(b => b.LastPayRaise)
    .ValueGeneratedOnAddOrUpdate();

modelBuilder.Entity<Employee>()
    .Property(b => b.LastPayRaise)
    .Metadata.IsReadOnlyAfterSave = false;
```

> [!NOTE]

> 默认情况下,EF Core将抛出以下异常,如果你试图保存一个显式值的属性被配置为在更新过程中生成。为了避免这种情况,你需要降低元数据API的级别,并设置`IsReadOnlyAfterSave`标志(如上所示)。

> By default, EF Core will throw the following exception if you try to save an explicit value for a property that is configured to be generated during update. To avoid this, you need to drop down to the lower level metadata API and set the `IsReadOnlyAfterSave` flag (as shown above).
>
> `System.InvalidOperationException The property 'LastPayRaise' on entity type 'Employee' is defined to be read-only after it has been saved, but its value has been modified or marked as modified.`

还可以在数据库的触发器在`UPDATE`操作期间为`LastPayRaise`生成值。

There is also a trigger in the database to generate values for the `LastPayRaise` column during `UPDATE` operations.

<!--[!code-sql[Main](../../../samples/core/Saving/Saving/ExplicitValuesGenerateProperties/employee_UPDATE.sql)]-->
```sql
CREATE TRIGGER [dbo].[Employees_UPDATE] ON [dbo].[Employees]
	AFTER UPDATE
AS
BEGIN
	SET NOCOUNT ON;

	IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

	IF UPDATE(Salary) AND NOT Update(LastPayRaise)
	BEGIN
		DECLARE @Id INT
		DECLARE @OldSalary INT
		DECLARE @NewSalary INT

		SELECT @Id = INSERTED.EmployeeId, @NewSalary = Salary
		FROM INSERTED

		SELECT @OldSalary = Salary
		FROM deleted

		IF @NewSalary > @OldSalary
		BEGIN
			UPDATE dbo.Employees
			SET LastPayRaise = CONVERT(date, GETDATE())
			WHERE EmployeeId = @Id
		END
	END
END
```
下面的代码增加了数据库中两名员工的工资。

The following code increases the salary of two employees in the database.

* 对于第一个,没有值被分配给`Employee.LastPayRaise`属性,所以它仍然设置为null。

* For the first, no value is assigned to `Employee.LastPayRaise` property, so it remains set to null.

* 对于第二个,我们给设设置了一个星期前的显示值(回溯加薪)。

* For the second, we have set an explicit value of one week ago (back dating the pay raise).

<!--[!code-csharp[Main](../../../samples/core/Saving/Saving/ExplicitValuesGenerateProperties/Sample.cs#LastPayRaise)]-->
```csharp
using (var db = new EmployeeContext())
{
    var john = db.Employees.Single(e => e.Name == "John Doe");
    john.Salary = 200;

    var jane = db.Employees.Single(e => e.Name == "Jane Doe");
    jane.Salary = 200;
    jane.LastPayRaise = DateTime.Today.AddDays(-7);

    db.SaveChanges();

    foreach (var employee in db.Employees)
    {
        Console.WriteLine(employee.EmployeeId + ": " + employee.Name + ", " + employee.LastPayRaise);
    }
}
```
数据库输出显示第一个雇员为生成值,第二个为显式值。

Output shows that the database generated a value for the first employee and our explicit value was used for the second.

````
1: John Doe, 1/26/2017 12:00:00 AM
2: Jane Doe, 1/19/2017 12:00:00 AM
````


text:
package ru.job4j.market;

public class Application {

    public int id;
    public String book;
    public String t;
    public String action;
    public int price;
    public int volume;

    public Application(int id, String book, String t, String action, int price, int volume) {
        this.id = id;
        this.book = book;
        this.t = t;
        this.action = action;
        this.price = price;
        this.volume = volume;
    }

    @Override
    public int hashCode() {
        int result = price != 0 ? price : 0;
        result = 31 * result + id;
        return result;
    }
}


text:
Plugin.define "Spree-Commerce" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-11-22
version "0.1"
description "Spree Commerce is an open source e-commerce solution"
website "http://spreecommerce.com/"

# Google results as at 2011-11-22 #
# 34 for inurl:"products?utf8=" inurl:keywords

# Dorks #
dorks [
'inurl:"products?utf8=" inurl:keywords'
]

# Matches #
matches [

# utf8 input box
{ :text=>'
<input name="utf8" type="hidden" value="✓" />
' },

]

end


text:
package dispatch_test

import (
	"fmt"
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"

	dp "github.com/markus-wa/godispatch"
)

type AB interface {
	foo() string
}

type A struct {
	val int
}

func (a A) foo() string {
	return strconv.Itoa(a.val)
}

type B struct {
	val string
}

func (b B) foo() string {
	return b.val
}

type result struct {
	strVal  string
	intVal  int
	f32Val  float32
	f64Val  float64
	abVal   AB
	aVal    A
	bPtrVal *B
}

func registerHandlers(t *testing.T, d *dp.Dispatcher) *result {
	t.Helper()

	res := &result{}

	// string handler
	d.RegisterHandler(func(s string) {
		res.strVal = s
		t.Log("Handled string", res.strVal)
	})
	// int handler
	d.RegisterHandler(func(i int) {
		res.intVal = i
		t.Log("Handled int", res.intVal)
	})
	// float32 handler
	d.RegisterHandler(func(f float32) {
		res.f32Val = f
		t.Log("Handled float32", res.f32Val)
	})
	// float64 handler
	d.RegisterHandler(func(f float64) {
		res.f64Val = f
		t.Log("Handled float64", res.f64Val)
	})
	// interface handler
	d.RegisterHandler(func(ab AB) {
		res.abVal = ab
		t.Log("Handled AB", res.abVal)
	})
	// struct handler
	d.RegisterHandler(func(a A) {
		res.aVal = a
		t.Log("Handled A", res.aVal)
	})
	// pointer handler (no reflect.Type.Elem() call)
	d.RegisterHandler(func(bPtr *B) {
		res.bPtrVal = bPtr
		t.Log("Handled *B", res.bPtrVal)
	})

	return res
}

func TestString(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := "test"
	d.Dispatch(val)

	assert.Equal(t, result{strVal: val}, *res)
}

func TestInt(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := 13
	d.Dispatch(val)

	assert.Equal(t, result{intVal: val}, *res)
}

func TestFloat32(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := float32(1.23)
	d.Dispatch(val)

	assert.Equal(t, result{f32Val: val}, *res)
}

// Should only be handled by float64 handler, not float32
func TestFloat64(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := 9.87
	d.Dispatch(val)

	assert.Equal(t, result{f64Val: val}, *res)
}

func TestStructA(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := A{val: 17}
	d.Dispatch(val)

	assert.Equal(t, result{abVal: val, aVal: val}, *res)
}

// Tests if the handler cache is cleared after registering an interface handler
func TestStructB(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}

	val := B{val: "bVal"}
	// Make Dispatcher initialize the cache
	d.Dispatch(val)

	res := registerHandlers(t, &d)

	d.Dispatch(val)

	assert.Equal(t, result{abVal: val}, *res)
}

// Should work with pointers just as well
func TestStructPointer(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	val := &B{val: "bPtrVal"}
	d.Dispatch(val)

	assert.Equal(t, result{abVal: val, bPtrVal: val}, *res)
}

// Tests queue functionality
func TestQueues(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	res := registerHandlers(t, &d)

	q := make(chan interface{})

	d.AddQueues(q)

	strVal := "txt"
	q <- strVal

	d.SyncAllQueues()

	exp := result{strVal: strVal}
	assert.Equal(t, exp, *res)

	err := d.RemoveQueues(q)
	assert.NoError(t, err)

	select {
	case q <- 10:
		// Nobody should be receiving on this channel after removal
		t.Error("Data sent to channel and still received after RemoveQueues()")
	default:
		// nop
	}

	d.AddQueues(q)

	f32Val := float32(0.5)
	q <- f32Val

	d.SyncAllQueues()

	exp.f32Val = f32Val
	assert.Equal(t, exp, *res)
}

// Tests how handlers behave if added dynamically by other handlers
func TestAddHandlerInHandler(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	h1 := 0
	h2 := 0
	h3 := 0

	d.RegisterHandler(func(i int) {
		t.Log("Handled", i, "in h1")
		if h1 == 0 {
			d.RegisterHandler(func(i2 int) {
				t.Log("Handled", i2, "in h2")
				if h2 == 0 {
					d.RegisterHandler(func(i3 int) {
						t.Log("Handled", i3, "in h3")
						h3++
					})
				}
				h2++
			})
		}
		h1++
	})

	d.Dispatch(1)
	d.Dispatch(2)
	d.Dispatch(3)

	// h2 & h3 should only be increased by new dispatches, not the one which registered it
	if h1 != 3 || h2 != 2 || h3 != 1 {
		t.Errorf("Handler call counts should be h1=3, h2=2 & h3=1 but are h1=%d, h2=%d, h3=%d", h1, h2, h3)
	}
}

// Tests if unregistering handlers works
func TestUnregisterHandler(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}

	iInt := 0

	d.RegisterHandler(func(int) {
		iInt++
	})

	iRemovedInt := 0
	id := d.RegisterHandler(func(int) {
		iRemovedInt++
	})

	d.Dispatch(1)

	d.UnregisterHandler(id)

	d.Dispatch(1)

	if iInt != 2 {
		t.Error("The handler that wasn't removed wasn't triggered after removal")
	}

	if iRemovedInt != 1 {
		t.Error("The removed handler was triggered after removal")
	}

	iInterface := 0

	d.RegisterHandler(func(AB) {
		iInterface++
	})

	iRemovedInterface := 0
	id = d.RegisterHandler(func(AB) {
		iRemovedInterface++
	})

	d.Dispatch(A{})

	d.UnregisterHandler(id)

	d.Dispatch(A{})

	if iInterface != 2 {
		t.Error("The interface handler that wasn't removed wasn't triggered after removal")
	}

	if iRemovedInterface != 1 {
		t.Error("The removed interface handler was triggered after removal")
	}
}

// Tests what happens for illegal arguments
func TestIllegalArguments(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}

	err := d.RemoveQueues(make(chan interface{}))
	if err == nil {
		t.Error("RemoveQueues() returned no error for non-registered queue")
	}

	err = d.SyncQueues(make(chan interface{}))

	if err == nil {
		t.Error("SyncQueues() returned no error for non-registered queue")
	}

	func() {
		defer func() {
			e := recover()
			if e == nil {
				t.Error("RegisterHandler() didn't panic for wrong handler type")
			}
		}()
		d.RegisterHandler(5)
	}()

	func() {
		defer func() {
			e := recover()
			if e == nil {
				t.Error("RegisterHandler() didn't panic for wrong input parameter count")
			}
		}()
		d.RegisterHandler(func() {})
	}()
}

func TestConsumerCodePanic(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	d.RegisterHandler(func(a *A) {
		t.Log(a.val)
	})

	var err interface{}

	func() {
		defer func() {
			err = recover()
		}()

		var a *A
		d.Dispatch(a)
	}()

	switch ccp := err.(type) {
	case dp.ConsumerCodePanic:
		if ccp.String() != "runtime error: invalid memory address or nil pointer dereference" {
			t.Error("ConsumerCodePanic.String() is not \"runtime error: invalid memory address or nil pointer dereference\"")
		}

		if fmt.Sprint(ccp.Value()) != "runtime error: invalid memory address or nil pointer dereference" {
			t.Error("ConsumerCodePanic.Value() is not \"runtime error: invalid memory address or nil pointer dereference\"")
		}
	default:
		t.Error("recovered type != ConsumerCodePanic")
	}
}

// Just a compile test for the README example
func TestExample(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	// Register a handler for string (not *string!)
	// We get the string Type by calling Elem() on reflect.Type *string)
	// This is faster than doing reflect.TypeOf("")
	d.RegisterHandler(func(s string) {
		t.Log("Handled string", s)
	})
	d.RegisterHandler(func(obj interface{}) {
		t.Log("Handled object", obj)
	})

	d.Dispatch("Hello")
	// Prints (in this order - as the object handler was registered after the string handler)
	// "Handled string Hello"
	// "Handled object Hello"
	d.Dispatch(123)
	// Prints "Handled object 123"
}

type Event struct {
	reference int
	message   string
}

type TriggerEvent struct{}

// Just a compile test for the README example
func TestQueueExample(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}
	// If you wanted to handle pointers of the Event just remove .Elem(),
	// use *Event for the type assertion and send pointers
	d.RegisterHandler(func(e Event) {
		t.Log("Handled Event", e)
		// Handle event
	})
	d.RegisterHandler(func(te TriggerEvent) {
		// Do stuff when we receive a 'TriggerEvent'
	})

	// Buffered to improve performance by avoiding locking
	q := make(chan interface{}, 5)
	q2 := make(chan interface{}, 5)
	q3 := make(chan interface{}, 5)

	// Add queues to dispatcher
	d.AddQueues(q, q2, q3)

	// Send some events
	for i := 0; i < 10; i++ {
		q <- Event{i, "abc"}
		q <- TriggerEvent{}
		q2 <- Event{i, "def"}
		q3 <- Event{i, "geh"}
		// Events that are not in the same queue will be handled concurrently
		d.SyncQueues(q)
		// Do stuff that requires events in q (but not q2 & q3) to be handled
	}

	d.SyncAllQueues()
	// Do stuff that requires events of q, q2 & q3 to be handled

	// Maybe send some more events . . .
	q <- TriggerEvent{}

	// Remove queues q & q2
	d.RemoveQueues(q, q2)

	q3 <- Event{}

	// Also remove q3
	d.RemoveAllQueues()
}

// Tests queue functionality
func TestPanicHandler(t *testing.T) {
	t.Parallel()

	var recovered interface{}

	d := dp.NewDispatcherWithConfig(dp.Config{
		PanicHandler: func(v interface{}) {
			recovered = v
		},
	})

	d.RegisterHandler(func(string) {
		panic("test")
	})

	q := make(chan interface{}, 2)

	d.AddQueues(q)
	q <- "txt"

	d.SyncAllQueues()

	if recovered.(dp.ConsumerCodePanic).Value() != "test" {
		t.Error("panic value not recovered")
	}
}

func TestUnregisterAllHandlers(t *testing.T) {
	t.Parallel()

	d := dp.Dispatcher{}

	count := 0
	count2 := 0

	d.RegisterHandler(func(string) {
		count++
		d.UnregisterAllHandlers()
		d.RegisterHandler(func(string) {
			count2++
		})
	})

	q := make(chan interface{}, 2)

	d.AddQueues(q)
	q <- "one"
	q <- "two"
	q <- "three"

	assert.Equal(t, 1, count)
	assert.Equal(t, 2, count2)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using FluentNHibernate.Diagnostics;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Engine;
using NHibernate.Event;
using NHibernate.Event.Default;
using NHibernate.Persister.Entity;
using Orchard.Data.Conventions;
using Orchard.Environment.ShellBuilders.Models;
using Orchard.Logging;
using Configuration = NHibernate.Cfg.Configuration;

namespace Orchard.Data.Providers {
    [Serializable]
    public abstract class AbstractDataServicesProvider : IDataServicesProvider {

        public abstract IPersistenceConfigurer GetPersistenceConfigurer(bool createDatabase);

        protected AbstractDataServicesProvider() {
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public Configuration BuildConfiguration(SessionFactoryParameters parameters) {
            var database = GetPersistenceConfigurer(parameters.CreateDatabase);
            var persistenceModel = CreatePersistenceModel(parameters.RecordDescriptors.ToList());

            var config = Fluently.Configure();

            foreach (var c in parameters.Configurers.OfType<ISessionConfigurationEventsWithParameters>()) {
                c.Parameters = parameters;
            }

            parameters.Configurers.Invoke(c => c.Created(config, persistenceModel), Logger);

            config = config.Database(database)
                           .Mappings(m => m.AutoMappings.Add(persistenceModel))
                           .ExposeConfiguration(cfg => {
                               cfg
                                    .SetProperty(NHibernate.Cfg.Environment.FormatSql, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, Hbm2DDLKeyWords.None.ToString())
                                    .SetProperty(NHibernate.Cfg.Environment.PropertyBytecodeProvider, "lcg")
                                    .SetProperty(NHibernate.Cfg.Environment.PropertyUseReflectionOptimizer, Boolean.TrueString)
                                    .SetProperty(NHibernate.Cfg.Environment.QueryStartupChecking, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.ShowSql, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.StatementFetchSize, "100")
                                    .SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.UseSqlComments, Boolean.FalseString)
                                    .SetProperty(NHibernate.Cfg.Environment.WrapResultSets, Boolean.TrueString)
                                    .SetProperty(NHibernate.Cfg.Environment.BatchSize, "256")
                                    ;

                               cfg.EventListeners.LoadEventListeners = new ILoadEventListener[] { new OrchardLoadEventListener() };
                               cfg.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[0];
                               cfg.EventListeners.PreLoadEventListeners = new IPreLoadEventListener[0];

                               // don't enable PrepareSql by default as it breaks on SqlCe
                               // this can be done per driver by overriding AlterConfiguration
                               AlterConfiguration(cfg);

                               parameters.Configurers.Invoke(c => c.Building(cfg), Logger);

                           })
                           ;

            parameters.Configurers.Invoke(c => c.Prepared(config), Logger);

            return config.BuildConfiguration();
        }

        protected virtual void AlterConfiguration(Configuration config) {

        }

        public static AutoPersistenceModel CreatePersistenceModel(ICollection<RecordBlueprint> recordDescriptors) {
            if(recordDescriptors == null) {
                throw new ArgumentNullException("recordDescriptors");
            }

            return AutoMap.Source(new TypeSource(recordDescriptors))
                // Ensure that namespaces of types are never auto-imported, so that
                // identical type names from different namespaces can be mapped without ambiguity
                .Conventions.Setup(x => x.Add(AutoImport.Never()))
                .Conventions.Add(new RecordTableNameConvention(recordDescriptors))
                .Conventions.Add(new CacheConventions(recordDescriptors))
                .Conventions.Add(new UtcDateTimeConvention())
                .Alterations(alt => {
                    foreach (var recordAssembly in recordDescriptors.Select(x => x.Type.Assembly).Distinct()) {
                        alt.Add(new AutoMappingOverrideAlteration(recordAssembly));
                    }
                    alt.AddFromAssemblyOf<DataModule>();
                   // alt.Add(new ContentItemAlteration(recordDescriptors));
                })
                .Conventions.AddFromAssemblyOf<DataModule>();
        }

        [Serializable]
        class TypeSource : ITypeSource {
            private readonly IEnumerable<RecordBlueprint> _recordDescriptors;

            public TypeSource(IEnumerable<RecordBlueprint> recordDescriptors) { _recordDescriptors = recordDescriptors; }

            public IEnumerable<Type> GetTypes() { return _recordDescriptors.Select(descriptor => descriptor.Type); }

            public void LogSource(IDiagnosticLogger logger) {
                throw new NotImplementedException();
            }

            public string GetIdentifier() {
                throw new NotImplementedException();
            }
        }

        [Serializable]
        class OrchardLoadEventListener : DefaultLoadEventListener, ILoadEventListener {

            public new void OnLoad(LoadEvent @event, LoadType loadType) {
                var source = (ISessionImplementor)@event.Session;
                IEntityPersister entityPersister;
                if (@event.InstanceToLoad != null) {
                    entityPersister = source.GetEntityPersister(null, @event.InstanceToLoad);
                    @event.EntityClassName = @event.InstanceToLoad.GetType().FullName;
                } else
                    entityPersister = source.Factory.GetEntityPersister(@event.EntityClassName);
                if (entityPersister == null)
                    throw new HibernateException("Unable to locate persister: " + @event.EntityClassName);

                //a hack to handle unused ContentPartRecord proxies on ContentItemRecord or ContentItemVersionRecord.
                //I don't know why it actually works, or how to do it right

                //if (!entityPersister.IdentifierType.IsComponentType)
                //{
                //    Type returnedClass = entityPersister.IdentifierType.ReturnedClass;
                //    if (returnedClass != null && !returnedClass.IsInstanceOfType(@event.EntityId))
                //        throw new TypeMismatchException(string.Concat(new object[4]
                //    {
                //      (object) "Provided id of the wrong type. Expected: ",
                //      (object) returnedClass,
                //      (object) ", got ",
                //      (object) @event.EntityId.GetType()
                //    }));
                //}

                var keyToLoad = new EntityKey(@event.EntityId, entityPersister, source.EntityMode);

                if (loadType.IsNakedEntityReturned) {
                    @event.Result = Load(@event, entityPersister, keyToLoad, loadType);
                } else if (@event.LockMode == LockMode.None) {
                    @event.Result = ProxyOrLoad(@event, entityPersister, keyToLoad, loadType);
                } else {
                    @event.Result = LockAndLoad(@event, entityPersister, keyToLoad, loadType, source);
                }
            }
        }
    }
}


text:
package com.daimabaike;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Test implements Runnable{

    public static void main(String[] args) {

    	Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

    	cfg.setDefaultEncoding("UTF-8");

    	try {
			cfg.setDirectoryForTemplateLoading(new File("E:\\git\\spring-study\\test\\main\\resources"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
//    	cfg.sett
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("study", "hw");
    	map.put("a", "v1");
    	map.put("upcase", new UpperCaseTransform());
    	StringWriter sw = new StringWriter();
    	try {
			Template template = cfg.getTemplate("test.ftl");

			template.process(map, sw);

			System.out.println(sw.getBuffer().toString());

		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}

    }

	@Override
	public void run() {
		System.out.println(System.nanoTime());
	}

}


text:
SEQAN_DEFINE_TEST(test_bam_io_bam_header_class)
{
    using namespace seqan;

    // Nothing interesting, just instantiating.

    BamHeader header;
}

SEQAN_DEFINE_TEST(test_bam_io_bam_header_typedefs)
{
    using namespace seqan;

    typedef BamIOContext<>::TLengthStore TLengthStore SEQAN_UNUSED_TYPEDEF;
}

SEQAN_DEFINE_TEST(test_bam_io_bam_header_record_class)
{
    using namespace seqan;

    BamHeaderRecord record;
}

SEQAN_DEFINE_TEST(test_bam_io_bam_header_record_typedefs)
{
    using namespace seqan;

    typedef BamHeaderRecord::TTagName  TTagName  SEQAN_UNUSED_TYPEDEF;
    typedef BamHeaderRecord::TTagValue TTagValue SEQAN_UNUSED_TYPEDEF;
    typedef BamHeaderRecord::TTag      TTag      SEQAN_UNUSED_TYPEDEF;
    typedef BamHeaderRecord::TTags     TTags     SEQAN_UNUSED_TYPEDEF;
}

SEQAN_DEFINE_TEST(test_bam_io_bam_header_record_find_tag_key)
{
    using namespace seqan;

    typedef BamHeaderRecord::TTag      TTag;

    BamHeaderRecord record;
    appendValue(record.tags, TTag("SN", "aa"));
    appendValue(record.tags, TTag("BC", "bb"));
    appendValue(record.tags, TTag("ZX", "cc"));

    unsigned idx = 0;

    SEQAN_ASSERT(findTagKey(idx, "BC", record));
    SEQAN_ASSERT_EQ(idx, 1u);
    SEQAN_ASSERT(findTagKey(idx, "ZX", record));
    SEQAN_ASSERT_EQ(idx, 2u);
    SEQAN_ASSERT(findTagKey(idx, "SN", record));
    SEQAN_ASSERT_EQ(idx, 0u);
}

SEQAN_DEFINE_TEST(test_bam_io_bam_header_record_get_tag_value)
{
    using namespace seqan;

    typedef BamHeaderRecord::TTag      TTag;

    BamHeaderRecord record;
    appendValue(record.tags, TTag("SN", "aa"));
    appendValue(record.tags, TTag("BC", "bb"));
    appendValue(record.tags, TTag("ZX", "cc"));

    CharString res;
    SEQAN_ASSERT(getTagValue(res, "BC", record));
    SEQAN_ASSERT_EQ(res, CharString("bb"));
    clear(res);
    SEQAN_ASSERT(getTagValue(res, 1, record));
    SEQAN_ASSERT_EQ(res, CharString("bb"));

    clear(res);
    SEQAN_ASSERT(getTagValue(res, "ZX", record));
    SEQAN_ASSERT_EQ(res, CharString("cc"));
    clear(res);
    SEQAN_ASSERT(getTagValue(res, 2, record));
    SEQAN_ASSERT_EQ(res, CharString("cc"));

    clear(res);
    SEQAN_ASSERT(getTagValue(res, "SN", record));
    SEQAN_ASSERT_EQ(res, CharString("aa"));
    clear(res);
    SEQAN_ASSERT(getTagValue(res, 0, record));
    SEQAN_ASSERT_EQ(res, CharString("aa"));
}

#endif  // TESTS_BAM_IO_TEST_BAM_HEADER_RECORD_H_


text:
<!--
   Copyright 2011-2015 Blue River Interactive

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<plugin>
<name>MuraCache</name>
<package>MuraCache</package>
<directoryFormat>packageOnly</directoryFormat>
<version>0.1.0</version>
<loadPriority>1</loadPriority>
<provider>Blue River</provider>
<providerURL>http://blueriver.com</providerURL>
<category>Application</category>
<settings>
    <setting>
        <name>instanceName</name>
        <label>Instance name (optional)</label>
        <hint>If provided, cache will be have {InstanceName}- added to the start of its name</hint>
        <type>text</type>
        <required>false</required>
        <validation>regex</validation>
        <regex>^[a-zA-Z0-9]+$</regex>
        <message>Please enter only letters and numbers</message>
        <defaultValue></defaultValue>
        <optionList></optionList>
        <optionLabelList></optionLabelList>
    </setting>
</settings>
<eventHandlers>
	<eventHandler event="onApplicationLoad" component="lib.eventHandler" persist="false"/>
</eventHandlers>
<displayobjects location="global"/>
</plugin>


text:
import Reflux from 'reflux';
import AuthCookie from '../helpers/AuthCookie';
import {User} from '../data/Api';

const Actions = Reflux.createActions([
    'login',
    'create',
    'logout'
]);

let UserStore = Reflux.createStore({
    init() {
        this.listenToMany(Actions);
        this.isLoggedIn = AuthCookie.readCookie();
        this.errors = null;
        this._trigger();
    },
    login(email, password) {
        this.errors = null;
        User.login(email, password).then(() => {
            this.isLoggedIn = true;
            this._trigger();
        }, response => {
            this.errors = response.errors;
            this._trigger();
        });
    },
    create(userData) {
        this.errors = null;
        User.create(userData).then(() => {
            this.isLoggedIn = true;
            this._trigger();
        }, response => {
            this.errors = response.errors;
            this._trigger();
        })
    },
    logout() {
        this.errors = null;
        User.logout().then(() => {
            this.isLoggedIn = false;
            this._trigger();
        }, response => {
            console.log(response);
        })
    },
    _trigger() {
        this.trigger({isLoggedIn: this.isLoggedIn, errors: this.errors});
    }
});

export default {
    UserActions: Actions,
    UserStore: UserStore
}


text:
#pragma once

#include <lk/compiler.h>
#include <sys/types.h>
#include <kernel/mp.h>

__BEGIN_CDECLS

/* send inter processor interrupt, if supported */
status_t arch_mp_send_ipi(mp_cpu_mask_t target, mp_ipi_t ipi);

void arch_mp_init_percpu(void);

__END_CDECLS


text:
@interface ARNImageStoreCache : NSObject

+ (void)clear;

+ (void)setThumbnailCacheLimit:(NSUInteger)cacheLimit;
+ (void)setImageCacheLimit:(NSUInteger)cacheLimit;

+ (void)addThumbnailImageWithImage:(UIImage *)image imageURL:(NSURL *)imageURL;
+ (void)addImageWithImage:(UIImage *)image imageURL:(NSURL *)imageURL;

+ (UIImage *)cacheThumbnailImageWIthURL:(NSURL *)imageURL;
+ (UIImage *)cacheImageWIthURL:(NSURL *)imageURL;

@end