text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="generator" content="Polymer Starter Kit" />
  <title>tmi-tree-basic</title>

  <link rel="stylesheet" href="../../styles/main.css">
  <script src="../../bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <script>
    window.Polymer = window.Polymer || {};
    window.Polymer.dom = 'shadow';
  </script>

  <link rel="import" href="../initApp.html">

  <!-- Step 1: import the element to test -->
  <link rel="import" href="../elements/elements.html">
<!--
  <link rel="import" href="../elements/tmi-tree/tmi-tree.html">
-->
<!--
  <script src="../../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <link rel="import" href="../../bower_components/polymer/polymer.html">
-->
  <script src="../../bower_components/web-component-tester/browser.js"></script>
  <script src="../../bower_components/test-fixture/test-fixture-mocha.js"></script>
  <link rel="import" href="../../bower_components/test-fixture/test-fixture.html">

  <!-- chrome.windows.getAll() data in window.testWins -->
  <!--
  <script src="/scripts/chrome.windows.test.data.js"></script>
  -->

</head>
<body>

  <test-fixture id="basic">
    <template>
      <tmi-tree id="fixture"></tmi-tree>
    </template>
  </test-fixture>
<!--
  <tmi-tree id="fixture"></tmi-tree>
-->

  <script>
    suite('tmi-tree', function() {

//      var el = document.querySelector('tmi-tree');
//      var el = document.querySelector('#fixture');
      setup(function() {
        el = fixture('basic');
      });

      test('Dummy test', function(done) {
        flush(function() {
          assert.equal(el.id, "fixture");
          done();
        });
      });

      test('Check initial menu state', function(done) {
        flush(function() {
          // Check first line
          var firstLine = el.$$('tmi-window').win.tabs[0].title;
          assert.equal(firstLine, "Title - 1001");
          var deepFirstLine = el.$$('tmi-window').$$('tmi-win-display').$$('span').innerText
          assert.equal(deepFirstLine, "Title - 1001");
          // Check default pointer
          assert.equal(el.getPointer().id, 'id-602');
          assert.equal(el.getVisibleEls().length, 17);
          done();
        });
      });

      test('TODO Check node API', function(done) {
        flush(function() {
          assert.equal(el.treeQuery('#id-601').id, 'id-601');
//          assert.equal(el.treeQuery('#id-901').win.tabs.length, 90);
          assert.equal(el.getNode('id-801').id, 'id-801');
          assert.equal(el.getFirstEl().id, 'id-10');
          done();
        });
      });

      test('TODO Check pointer API', function(done) {
        flush(function() {
          assert.equal(el.getPointer().id, 'id-602');
          el.setPointerId('id-3');
          assert.equal(el.getPointer().id, 'id-3');
          el.setPointer(el.getFirstEl())
          assert.equal(el.getPointer().id, 'id-10');
          el.setPointerToBottom();
          assert.equal(el.getPointer().id, 'id-12');
          el.setPointerToTop();
          assert.equal(el.getPointer().id, 'id-10');
          done();
        });
      });

      test('Check pointer movement', function(done) {
        flush(function() {
          el.hideAll();
          el.setPointerId('id-6');
          el.right();
          assert.equal(el.getPointer().id, 'id-602');
          el.down();
          el.up();
          assert.equal(el.getPointer().id, 'id-602');
          el.left();
          el.up();
          assert.equal(el.getPointer().id, 'id-5');
          el.up();
          el.up();
          el.up();
          //saved order was recovered
          assert.equal(el.getPointer().id, 'id-9');
          //wrap around
          el.up();
          el.up();
          el.up();
          el.up();
          el.up();
          assert.equal(el.getPointer().id, 'id-11');
          //check expanding
          el.right();
          flush(function() {
            el.down();
            assert.equal(el.getPointer().id, 'id-1112');
            //check goto top/bottom of tabs
            el.setPointerToTop();
            assert.equal(el.getPointer().id, 'id-1101');
            el.setPointerToBottom();
            assert.equal(el.getPointer().id, 'id-1190');
            el.left();
            el.up();
            assert.equal(el.getPointer().id, 'id-8');
            //check goto top/bottom of wins
            el.down();
            el.setPointerToTop();
            assert.equal(el.getPointer().id, 'id-10');
            el.setPointerToBottom();
            assert.equal(el.getPointer().id, 'id-12');
            done();
          });
        });
      });

      test('Test tmi-window', function(done) {
        flush(function() {
          el.hideAll();
          assert.equal(el.getVisibleEls().length, 12);
          var winNode = el.getNode('id-3');
          winNode.toggle();
          assert.equal(el.getVisibleEls().length, 22);
          done();
        });
      });

      test('Check search', function(done) {
        flush(function() {
          //match title
          el.searchstr='Title - 21';
          flush(function() {
            assert.equal(el.getVisibleEls().length, 11);
            assert.equal(el.getFirstEl().id, 'id-2');
            assert.equal(el.treeQuery('tmi-tab').id, 'id-210');
            //check pointer
            assert.equal(el.getPointer().id, 'id-210');
            //match URL
            el.searchstr='google.com/#q=111';
            flush(function() {
              assert.equal(el.getVisibleEls().length, 13);
              assert.equal(el.getFirstEl().id, 'id-1');
              assert.equal(el.treeQuery('tmi-tab').id, 'id-111');
              //match both
              el.searchstr='123';
              flush(function() {
                assert.equal(el.getVisibleEls().length, 13);
                //broaden search
                el.searchstr='12';
                flush(function() {
                  assert.equal(el.getVisibleEls().length, 115);
                  assert.equal(el.getPointer().id, 'id-1012');
                  //clear search
                  el.searchstr='';
                  flush(function() {
                    assert.equal(el.getVisibleEls().length, 12);
                    assert.equal(el.getFirstEl().id, 'id-10');
                    assert.equal(el.getPointer().id, 'id-6');
                    done();
                  });
                });
              });
            });
          });
        });
      });

      test('Check movement in search', function(done) {
        el.searchstr='123';
        flush(function() {
          assert.equal(el.getVisibleEls().length, 13);
          el.down();
          assert.equal(el.getPointer().id, 'id-12');
          el.right();
          assert.equal(el.getPointer().id, 'id-1234');
          done();
        });
      });

      test('Check select', function(done) {
        flush(function() {
          el.hideAll();
          el.selectId('id-3');
          assert.equal(el.getSelectedValues()[0], 'id-3');
          el.getNode('id-5').toggle();
          el.getNode('id-6').toggle();
          flush(function() {
            //select tabs
            el.selectId('id-501');
            el.selectId('id-603');
            assert.equal(el.getSelectedValues().length, 3);
            assert.equal(el.getSelectedValues()[0], 'id-3');
            assert.equal(el.getSelectedValues()[2], 'id-603');
            //unselect
            el.selectId('id-501');
            assert.equal(el.getSelectedValues().length, 2);
            assert.equal(el.getSelectedValues()[1], 'id-603');
            //clear selections
            el.clearSelected();
            assert.equal(el.getSelectedValues().length, 0);
            //pointer select
            el.setPointerId('id-5');
            el.selectPointer();
            el.setPointerId('id-602');
            el.selectPointer();
            flush(function() {
              assert.equal(el.getSelectedValues().length, 2);
              assert.equal(el.getSelectedValues()[0], 'id-5');
              assert.equal(el.getSelectedValues()[1], 'id-602');
              el.clearSelected();
              //selecToEnd (toggle each)
              el.setPointerId('id-602');
              el.selectId('id-604');
              el.selectToEnd()
              assert.equal(el.getSelectedValues().length, 3);
              assert.equal(el.getSelectedValues()[1], 'id-603');
              assert.equal(el.getSelectedValues()[2], 'id-605');
              // convert wins to tabs. maintain model order.
              el.selectId('id-3');
              var tabs = el.getSelectedTabs();
              assert.equal(tabs.length, 13);
              assert.equal(tabs[0].id, 301);
              assert.equal(tabs[9].id, 310);
              assert.equal(tabs[10].id, 602);
              assert.equal(tabs[12].id, 605);
              done();
            });
          });
        });
      });

      test('Cehck tabcount', function(done) {
        flush(function() {
          assert.equal(el.tabCount, 593);
          assert.equal(el.frozenCount, 3);
          done();
        });
      });

      // pin test changes stored order, affecting further tests.
      // fix or keep this test last.
      test('Check pin', function(done) {
        flush(function() {
          el.pin();
          flush(function() {
            assert.equal(el.getFirstEl().id, 'id-6');
            el.setPointerId('id-10')
            el.pin();
            flush(function() {
              assert.equal(el.getFirstEl().id, 'id-10');
//check pin in search
              done();
            });
          });
        });
      });

      test('dummy 2', function(done) {
        flush(function() {
          assert.equal(1, 1);
          done();
        });
      });

    });
  </script>

</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
@class NSSet;

@interface BITPLCrashMachExceptionPortSet : NSObject <NSFastEnumeration>
{
    NSSet *_state_set;
    struct plcrash_mach_exception_port_set _asyncSafeRepresentation;
}

@property(readonly, nonatomic) NSSet *set; // @synthesize set=_state_set;
@property(readonly, nonatomic) struct plcrash_mach_exception_port_set asyncSafeRepresentation; // @synthesize asyncSafeRepresentation=_asyncSafeRepresentation;
- (unsigned int)countByEnumeratingWithState:(CDStruct_11f37819 *)arg1 objects:(id *)arg2 count:(unsigned int)arg3;
- (void)dealloc;
- (id)initWithAsyncSafeRepresentation:(struct plcrash_mach_exception_port_set)arg1;
- (id)initWithSet:(id)arg1;

@end


text:
package org.apache.spark.streaming.event

import java.net.URI
import java.util.concurrent.atomic.AtomicLong

import scala.collection.JavaConversions
import scala.util.{Failure, Success, Try}

import org.apache.hadoop.fs.XAttr.NameSpace
import org.apache.hadoop.fs.{XAttr, GlobPattern}
import org.apache.hadoop.fs.permission._
import org.apache.hadoop.hdfs.DFSInotifyEventInputStream
import org.apache.hadoop.hdfs.client.HdfsAdmin
import org.apache.hadoop.hdfs.inotify.Event.CreateEvent.INodeType
import org.apache.hadoop.hdfs.inotify.Event.MetadataUpdateEvent.MetadataType
import org.apache.hadoop.hdfs.inotify.Event._
import org.apache.hadoop.hdfs.inotify.{Event => INotifyEvent}

import org.apache.spark.SparkException
import org.apache.spark.streaming.{StreamingContext, Time}

abstract class HDFSEvent(source: EventSource, index: Long, time: Time)
  extends Event(source, index, time) {

  def getEventType: EventType

  def toINotifyEvent: INotifyEvent

}

private[streaming] object HDFSEvent {
  def apply(
      source: EventSource,
      iNotifyEvent: INotifyEvent,
      index: Long,
      time: Time): HDFSEvent = iNotifyEvent match {
    case e: CloseEvent =>
      val t = e.getTimestamp
      HDFSCloseEvent(source, e.getPath, e.getFileSize, t, index, Time(t))

    case e: CreateEvent =>
      val t = e.getCtime
      val perms = e.getPerms
      HDFSCreateEvent(source, e.getiNodeType, e.getPath, t,
        e.getReplication, e.getOwnerName, e.getGroupName, HFsPermission(
          perms.getUserAction, perms.getGroupAction, perms.getOtherAction, perms.getStickyBit),
        e.getSymlinkTarget, e.getOverwrite, e.getDefaultBlockSize, index, Time(t))

    case e: MetadataUpdateEvent =>
      val at = e.getAtime
      val mt = e.getMtime
      val perms = e.getPerms
      HDFSMetadataUpdateEvent(source, e.getPath, e.getMetadataType, mt,
        at, e.getReplication, e.getOwnerName, e.getGroupName, HFsPermission(
          perms.getUserAction, perms.getGroupAction, perms.getOtherAction, perms.getStickyBit),
        JavaConversions.collectionAsScalaIterable(e.getAcls).map { aclEntry =>
          HAclEntry(aclEntry.getType, aclEntry.getName, aclEntry.getPermission, aclEntry.getScope)
        }.toList,
        JavaConversions.collectionAsScalaIterable(e.getxAttrs).map { xAttr =>
          HXAttr(xAttr.getNameSpace, xAttr.getName, xAttr.getValue)
        }.toList,
        e.isxAttrsRemoved, index, Time(at max mt)
      )

    case e: RenameEvent =>
      val t = e.getTimestamp
      HDFSRenameEvent(source, e.getSrcPath, e.getDstPath, t, index, Time(t))

    case e: AppendEvent =>
      HDFSAppendEvent(source, e.getPath, e.toNewBlock, index, time)

    case e: UnlinkEvent =>
      val t = e.getTimestamp
      HDFSUnlinkEvent(source, e.getPath, t, index, Time(t))
  }
}

case class HFsPermission(
    userAction: FsAction,
    groupAction: FsAction,
    otherAction: FsAction,
    stickyBit: Boolean) {
  def toFsPermission: FsPermission =
    new FsPermission(userAction, groupAction, otherAction, stickyBit)
}

case class HAclEntry(
    `type`: AclEntryType,
    name: String,
    permission: FsAction,
    scope: AclEntryScope
  ) {
  def toAclEntry: AclEntry = new AclEntry.Builder()
    .setType(`type`)
    .setName(name)
    .setPermission(permission)
    .setScope(scope)
    .build()
}

case class HXAttr(ns: NameSpace, name: String, value: Array[Byte]) {
  def toXAttr: XAttr = new XAttr.Builder()
    .setNameSpace(ns)
    .setName(name)
    .setValue(value)
    .build()
}

/** Sent when a file is closed after append or create. */
case class HDFSCloseEvent(
    source: EventSource,
    path: String,
    fileSize: Long,
    timestamp: Long,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.CLOSE

  override def toINotifyEvent: CloseEvent = {
    new CloseEvent(path, fileSize, timestamp)
  }

}

/** Sent when a new file is created (including overwrite). */
case class HDFSCreateEvent(
    source: EventSource,
    iNodeType: INodeType,
    path: String,
    ctime: Long,
    replication: Int,
    ownerName: String,
    groupName: String,
    perms: HFsPermission,
    symlinkTarget: String,
    overwrite: Boolean,
    defaultBlockSize: Long,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.CREATE

  override def toINotifyEvent: CreateEvent = {
    new CreateEvent.Builder()
      .iNodeType(iNodeType)
      .path(path)
      .ctime(ctime)
      .replication(replication)
      .ownerName(ownerName)
      .groupName(groupName)
      .perms(perms.toFsPermission)
      .symlinkTarget(symlinkTarget)
      .overwrite(overwrite)
      .defaultBlockSize(defaultBlockSize)
      .build()
  }

}

/**
 * Sent when there is an update to directory or file (none of the metadata
 * tracked here applies to symlinks) that is not associated with another
 * inotify event. The tracked metadata includes atime/mtime, replication,
 * owner/group, permissions, ACLs, and XAttributes. Fields not relevant to the
 * metadataType of the MetadataUpdateEvent will be null or will have their default
 * values.
 */
case class HDFSMetadataUpdateEvent(
    source: EventSource,
    path: String,
    metadataType: MetadataType,
    mtime: Long,
    atime: Long,
    replication: Int,
    ownerName: String,
    groupName: String,
    perms: HFsPermission,
    acls: List[HAclEntry],
    xAttrs: List[HXAttr],
    xAttrsRemoved: Boolean,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.METADATA

  override def toINotifyEvent: MetadataUpdateEvent = {
    new MetadataUpdateEvent.Builder()
      .path(path)
      .metadataType(metadataType)
      .mtime(mtime)
      .atime(atime)
      .replication(replication)
      .ownerName(ownerName)
      .groupName(groupName)
      .perms(perms.toFsPermission)
      .acls(JavaConversions.seqAsJavaList(acls.map(_.toAclEntry)))
      .xAttrs(JavaConversions.seqAsJavaList(xAttrs.map(_.toXAttr)))
      .xAttrsRemoved(xAttrsRemoved)
      .build()
  }

}

/** Sent when a file, directory, or symlink is renamed. */
case class HDFSRenameEvent(
    source: EventSource,
    srcPath: String,
    dstPath: String,
    timestamp: Long,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.RENAME

  override def toINotifyEvent: RenameEvent = {
    new RenameEvent.Builder()
      .srcPath(srcPath)
      .dstPath(dstPath)
      .timestamp(timestamp)
      .build()
  }

}

/** Sent when an existing file is opened for append. */
case class HDFSAppendEvent(
    source: EventSource,
    path: String,
    newBlock: Boolean,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.APPEND

  override def toINotifyEvent: AppendEvent = {
    new AppendEvent.Builder()
      .path(path)
      .newBlock(newBlock)
      .build()
  }

}

/** Sent when a file, directory, or symlink is deleted. */
case class HDFSUnlinkEvent(
    source: EventSource,
    path: String,
    timestamp: Long,
    override val index: Long,
    override val time: Time
  ) extends HDFSEvent(source, index, time) {

  override def getEventType: EventType = EventType.UNLINK

  override def toINotifyEvent: UnlinkEvent = {
    new UnlinkEvent.Builder()
      .path(path)
      .timestamp(timestamp)
      .build()
  }

}

class HDFSEventSource(
    @transient ssc: StreamingContext,
    hdfsURI: String,
    path: String,
    name: String
  ) extends EventSource(ssc, name) {

  private var stopped = false
  private val indexCounter = new AtomicLong(0L)
  private var lastReadTxid = 0L

  @transient private var inotifyEventStream: DFSInotifyEventInputStream = null
  @transient private var pathPattern: GlobPattern = null

  private def init(): Unit = {
    try {
      val hdfsAdmin = new HdfsAdmin(URI.create(hdfsURI), ssc.sparkContext.hadoopConfiguration)
      inotifyEventStream = hdfsAdmin.getInotifyEventStream(lastReadTxid)
      pathPattern = new GlobPattern(path)
    } catch {
      case e: Exception =>
        throw new SparkException(s"Could not initialize ${this.toString}", e)
    }
  }

  override def start(): Unit = synchronized {
    init()
    stopped = false
    new Thread(this.toString) {
      setDaemon(true)
      override def run() { loop() }
    }.start()
    logDebug(s"${this.toString} started")
  }

  private def paths(iNotifyEvent: INotifyEvent): Seq[String] = iNotifyEvent match {
    case e: CloseEvent => Seq(e.getPath)
    case e: CreateEvent => Seq(e.getPath)
    case e: MetadataUpdateEvent => Seq(e.getPath)
    case e: RenameEvent => Seq(e.getSrcPath, e.getDstPath)
    case e: AppendEvent => Seq(e.getPath)
    case e: UnlinkEvent => Seq(e.getPath)
  }

  private def loop(): Unit = {
    val clock = context.clock
    while (!stopped) {
      Try(inotifyEventStream.take()) match {
        case Success(eventBatch) =>
          lastReadTxid = eventBatch.getTxid
          val events = eventBatch.getEvents
            .filter(paths(_).exists(pathPattern.matches))
            .map(HDFSEvent(this, _, indexCounter.getAndIncrement(), Time(clock.getTimeMillis())))
          events.foreach(post)
          logDebug(s"${this.toString} emitted ${events.length} event(s)")

        case Failure(e) =>
          logWarning(s"${this.toString} encountered exception while retrieving" +
            s" the next batch of events in the stream", e)
      }
    }
    stop()
  }

  override def restart() = start()

  override def stop(): Unit = synchronized {
    if (!stopped) {
      stopped = true
      logDebug(s"${this.toString} stopped")
    }
  }

  override def toProduct: Product = (getClass.getSimpleName, name, hdfsURI, path)

  override def toDetailedString: String = {
    s"${getClass.getSimpleName}($name,$hdfsURI,$path)"
  }

}


text:
package com.squid.kraken.v4.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

/**
 * @author sergefantino
 *
 */
public class CustomerPK extends BasePK {

	private String customerId = null;

	/**
	 **/
	public CustomerPK customerId(String customerId) {
		this.customerId = customerId;
		return this;
	}

	@ApiModelProperty(example = "null", value = "")
	@JsonProperty("customerId")
	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}
}


text:
USE Bank
GO

CREATE TABLE Logs(
LogId INT IDENTITY NOT NULL,
AccountId INT NOT NULL,
OldSum DECIMAL(15,2) NOT NULL,
NewSum DECIMAL(15,2) NOT NULL
)
GO

CREATE OR ALTER TRIGGER tr_Accounts
ON Accounts
AFTER UPDATE
AS
BEGIN
	DECLARE @accountID INT = (
		SELECT Id FROM inserted
	)

	DECLARE @oldSum DECIMAL (15,2) = (
		SELECT Balance FROM deleted
	)

	DECLARE @newSum DECIMAL (15,2) = (
		SELECT Balance FROM inserted
	)

	INSERT INTO Logs VALUES
	(@accountID, @oldSum, @newSum)
END
GO

UPDATE Accounts
   SET Balance = 99.12
 WHERE Id = 1
GO

SELECT *
  FROM Logs
GO


text:
package org.catnut.processor;

import android.content.ContentValues;
import android.content.Context;
import android.provider.BaseColumns;
import org.catnut.core.CatnutProcessor;
import org.catnut.core.CatnutProvider;
import org.catnut.fragment.FavoriteFragment;
import org.catnut.metadata.Comment;
import org.catnut.metadata.Status;
import org.catnut.metadata.User;
import org.catnut.util.CatnutUtils;
import org.catnut.util.Constants;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 微博相关处理器
 *
 * @author longkai
 */
public class StatusProcessor {

	/**
	 * 判断是不是新浪在时间线中强奸的广告
	 *
	 * @param weibo json
	 * @return if it' s ad. or malformed data true or false
	 */
	public static final boolean fuckSina(JSONObject weibo) {
		if (weibo == null) {
			return true;
		}
		if (weibo.has(User.SINGLE)) {
			// 如果不是我关注的用户,那么基本上就是新浪的广告了,fuck
			JSONObject user = weibo.optJSONObject(User.SINGLE);
			if (user == null || !user.optBoolean(User.following)) {
				return true;
			}
		}
		// todo: 如果返回的微博是没有user这个字段,只有uid咋整呢?
		return false;
	}

	/**
	 * 持久化时间线
	 *
	 * @author longkai
	 */
	public static class TimelineProcessor implements CatnutProcessor<JSONObject> {

		private int type = Status.HOME;

		private boolean hasUser = true;

		public TimelineProcessor(boolean hasUser) {
			this.hasUser = hasUser;
		}

		public TimelineProcessor(int type, boolean hasUser) {
			this.type = type;
			this.hasUser = hasUser;
		}

		public void asyncProcess(Context context, JSONObject jsonObject) throws Exception {
			JSONArray jsonArray = jsonObject.optJSONArray(Status.MULTIPLE);
			ContentValues[] statuses = new ContentValues[jsonArray.length()];
			ContentValues[] users = null;
			if (hasUser) {
				users = new ContentValues[statuses.length];
			}
			User userMetadata = User.METADATA;
			Status statusMetadata = Status.METADATA;
			JSONObject json;
			ContentValues status;
			for (int i = 0; i < jsonArray.length(); i++) {
				json = jsonArray.optJSONObject(i);
				// 过滤一下不要的微博
				if (type == Status.HOME && fuckSina(json)) {
					continue;
				}
				// 一次持久化微博和作者信息
				status = statusMetadata.convert(json);
				status.put(Status.TYPE, type); // 标记为啥类型的微博
				statuses[i] = status;
				// 如果这条微博包含了原作者信息
				if (hasUser && json.has(User.SINGLE)) {
					users[i] = userMetadata.convert(json.optJSONObject(User.SINGLE));
				}
			}
			context.getContentResolver().bulkInsert(CatnutProvider.parse(Status.MULTIPLE), statuses);
			if (hasUser) {
				context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
			}
		}
	}

	/**
	 * 持久化评论时间线
	 *
	 * @author longkai
	 */
	public static class CommentTweetsProcessor implements CatnutProcessor<JSONObject> {

		/** 改评论指向的微博id */
		private long to;

		public CommentTweetsProcessor(long to) {
			this.to = to;
		}

		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			JSONArray array = data.optJSONArray(Status.COMMENTS);
			ContentValues[] comments = new ContentValues[array.length()];
			ContentValues[] users = new ContentValues[array.length()];
			ContentValues comment;
			JSONObject jsonUser;
			JSONObject jsonStatus;
			for (int i = 0; i < comments.length; i++) {
				// 解析微博
				jsonStatus = array.optJSONObject(i);
				comment = Status.METADATA.convert(jsonStatus);
				comment.put(Status.TYPE, Status.COMMENT); // 标记为评论微博
				comment.put(Status.TO_WHICH_TWEET, to);
				comments[i] = comment;
				// 解析评论作者
				jsonUser = jsonStatus.optJSONObject(User.SINGLE);
				users[i] = User.METADATA.convert(jsonUser);
			}
			// 持久化
			context.getContentResolver().bulkInsert(CatnutProvider.parse(Status.MULTIPLE), comments);
			context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
		}
	}

	/**
	 * 当前登录用户收到的评论
	 *
	 * @author longkai
	 */
	public static class Comments2MeProcessor implements CatnutProcessor<JSONObject> {
		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			JSONArray commentsArray = data.optJSONArray(Status.COMMENTS);
			ContentValues[] comments = new ContentValues[commentsArray.length()];
			ContentValues[] users = new ContentValues[comments.length];
			JSONObject json;
			for (int i = 0; i < comments.length; i++) {
				json = commentsArray.optJSONObject(i);
				comments[i] = Comment.METADATA.convert(json);
				users[i] = User.METADATA.convert(json.optJSONObject(User.SINGLE));
			}
			context.getContentResolver().bulkInsert(CatnutProvider.parse(Comment.MULTIPLE), comments);
			context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
		}
	}

	/**
	 * 处理单条评论
	 *
	 * @author longkai
	 */
	public static class CommentTweetProcessor implements CatnutProcessor<JSONObject> {

		private long id;

		public CommentTweetProcessor(long id) {
			this.id = id;
		}

		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			ContentValues comment = new ContentValues();
			comment = Status.METADATA.convert(data);
			comment.put(Status.TYPE, Status.COMMENT);
			comment.put(Status.TO_WHICH_TWEET, id);

			context.getContentResolver().insert(CatnutProvider.parse(Status.MULTIPLE), comment);
			String increment = CatnutUtils.increment(true, Status.TABLE, Status.comments_count, id);
			context.getContentResolver().update(CatnutProvider.parse(Status.MULTIPLE), null, increment, null);
		}
	}

	/**
	 * 收藏/取消收藏处理器
	 *
	 * @author longkai
	 */
	public static class FavoriteTweetProcessor implements CatnutProcessor<JSONObject> {

		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			JSONObject jsonObject = data.optJSONObject(Status.SINGLE);
			StringBuilder update = new StringBuilder("UPDATE ").append(Status.TABLE);
			update.append(" SET ").append(Status.favorited).append("=")
					.append(jsonObject.optBoolean(Status.favorited) ? "1" : "0")
					.append(" WHERE ").append(BaseColumns._ID).append("=").append(jsonObject.getLong(Constants.ID));
			context.getContentResolver().update(CatnutProvider.parse(Status.MULTIPLE), null, update.toString(), null);
			// 更新用户数据
			JSONObject user = jsonObject.optJSONObject(User.SINGLE);
			if (user != null) {
				String increment = CatnutUtils.increment(true, User.TABLE, User.favourites_count, user.getLong(Constants.ID));
				context.getContentResolver().update(CatnutProvider.parse(User.MULTIPLE), null, increment, null);
			}
		}
	}

	/**
	 * 持久化收藏列表
	 *
	 * @author longkai
	 */
	public static class FavoriteTweetsProcessor implements CatnutProcessor<JSONObject> {

		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			int delete = 0;
			JSONArray array = data.optJSONArray(Status.FAVORITES);
			ContentValues[] favorites = new ContentValues[array.length()];
			ContentValues[] users = new ContentValues[favorites.length];
			JSONObject json;
			for (int i = 0; i < favorites.length; i++) {
				// 解析微博,这里共用了变量名
				json = array.optJSONObject(i).optJSONObject(Status.SINGLE);
				if (json.optInt("deleted") == 1) {
					// 可能微博已经被删除了
					delete++;
					continue;
				}
				ContentValues values = Status.METADATA.convert(json);
				values.put(Status.favorited, 1);
				favorites[i] = values;
				// 解析用户
				users[i] = User.METADATA.convert(json.optJSONObject(User.SINGLE));
			}
			// persist
			context.getContentResolver().bulkInsert(CatnutProvider.parse(User.MULTIPLE), users);
			context.getContentResolver().bulkInsert(CatnutProvider.parse(Status.MULTIPLE), favorites);
			data.put(FavoriteFragment.TAG, delete);
		}
	}

	/**
	 * 普通的一条微博解析,需要提供一个微博类型
	 *
	 * @author longkai
	 */
	public static class SingleTweetProcessor implements CatnutProcessor<JSONObject> {

		// 微博类型
		private int type;

		public SingleTweetProcessor(int type) {
			this.type = type;
		}

		@Override
		public void asyncProcess(Context context, JSONObject data) throws Exception {
			ContentValues status = Status.METADATA.convert(data);
			status.put(Status.TYPE, type); // 添加类型
			ContentValues user = User.METADATA.convert(data.optJSONObject(User.SINGLE));
			context.getContentResolver().insert(CatnutProvider.parse(Status.MULTIPLE), status);
			context.getContentResolver().insert(CatnutProvider.parse(User.MULTIPLE), user);
			// 如果是转发微博的话,自增一下
			if (type == Status.RETWEET) {
				long id = data.optJSONObject(Status.retweeted_status).optLong(Constants.ID);
				String increment = CatnutUtils.increment(true, Status.TABLE, Status.reposts_count, id);
				context.getContentResolver().update(CatnutProvider.parse(Status.MULTIPLE), null, increment, null);
			}
		}
	}
}


text:
package com.amazonaws.services.machinelearning.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.machinelearning.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * DescribeDataSourcesRequest Marshaller
 */
public class DescribeDataSourcesRequestMarshaller
        implements
        Marshaller<Request<DescribeDataSourcesRequest>, DescribeDataSourcesRequest> {

    private final SdkJsonProtocolFactory protocolFactory;

    public DescribeDataSourcesRequestMarshaller(
            SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<DescribeDataSourcesRequest> marshall(
            DescribeDataSourcesRequest describeDataSourcesRequest) {

        if (describeDataSourcesRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<DescribeDataSourcesRequest> request = new DefaultRequest<DescribeDataSourcesRequest>(
                describeDataSourcesRequest, "AmazonMachineLearning");
        request.addHeader("X-Amz-Target",
                "AmazonML_20141212.DescribeDataSources");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = protocolFactory
                    .createGenerator();

            jsonGenerator.writeStartObject();

            if (describeDataSourcesRequest.getFilterVariable() != null) {
                jsonGenerator.writeFieldName("FilterVariable").writeValue(
                        describeDataSourcesRequest.getFilterVariable());
            }
            if (describeDataSourcesRequest.getEQ() != null) {
                jsonGenerator.writeFieldName("EQ").writeValue(
                        describeDataSourcesRequest.getEQ());
            }
            if (describeDataSourcesRequest.getGT() != null) {
                jsonGenerator.writeFieldName("GT").writeValue(
                        describeDataSourcesRequest.getGT());
            }
            if (describeDataSourcesRequest.getLT() != null) {
                jsonGenerator.writeFieldName("LT").writeValue(
                        describeDataSourcesRequest.getLT());
            }
            if (describeDataSourcesRequest.getGE() != null) {
                jsonGenerator.writeFieldName("GE").writeValue(
                        describeDataSourcesRequest.getGE());
            }
            if (describeDataSourcesRequest.getLE() != null) {
                jsonGenerator.writeFieldName("LE").writeValue(
                        describeDataSourcesRequest.getLE());
            }
            if (describeDataSourcesRequest.getNE() != null) {
                jsonGenerator.writeFieldName("NE").writeValue(
                        describeDataSourcesRequest.getNE());
            }
            if (describeDataSourcesRequest.getPrefix() != null) {
                jsonGenerator.writeFieldName("Prefix").writeValue(
                        describeDataSourcesRequest.getPrefix());
            }
            if (describeDataSourcesRequest.getSortOrder() != null) {
                jsonGenerator.writeFieldName("SortOrder").writeValue(
                        describeDataSourcesRequest.getSortOrder());
            }
            if (describeDataSourcesRequest.getNextToken() != null) {
                jsonGenerator.writeFieldName("NextToken").writeValue(
                        describeDataSourcesRequest.getNextToken());
            }
            if (describeDataSourcesRequest.getLimit() != null) {
                jsonGenerator.writeFieldName("Limit").writeValue(
                        describeDataSourcesRequest.getLimit());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
package spec

import com.outr.arango._
import com.outr.arango.monitored.{Materialized, MaterializedPart, MonitoredSupport, QueryInfo, Reference}
import com.outr.arango.query.AQLInterpolator
import org.scalatest.Assertion
import org.scalatest.concurrent.Eventually
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AsyncWordSpec
import profig.Profig
import reactify._

class MaterializedSpec extends AsyncWordSpec with Matchers with Eventually {
  "Materialized" should {
    val u1 = User("User 1", 21)
    val u2 = User("User 2", 31)
    val l1 = Location(u1._id, "San Jose", "California")
    val l2 = Location(u2._id, "Hollywood", "California")
    val l3 = Location(u2._id, "Santa Cruz", "California")

    val fu1Empty = FullUser(u1.name, u1.age, Nil, 0, FullUser.id(u1._id.value))
    val fu1Location = fu1Empty.copy(locations = List(l1), locationCount = 1)
    val fu2Empty = FullUser(u2.name, u2.age, Nil, 0, FullUser.id(u2._id.value))
    val fu2Location = fu2Empty.copy(locations = List(l2), locationCount = 1)
    val fu2Locations = fu2Empty.copy(locations = List(l2, l3), locationCount = 2)
    val fu2LocationsUpdated = fu2Locations.copy(age = 41)

    var updated: Var[List[Id[FullUser]]] = Var(Nil)
    var deleted: Var[List[Id[FullUser]]] = Var(Nil)

    @inline
    def verifyUpdatedAndClear(ids: Id[User]*): Assertion = try {
      updated() should be(ids.toList.map(id => Id[FullUser](id.value, database.fullUsers.name)))
    } finally {
      updated @= Nil
    }

    @inline
    def verifyDeletedAndClear(ids: Id[User]*): Assertion = try {
      deleted() should be(ids.toList.map(id => Id[FullUser](id.value, database.fullUsers.name)))
    } finally {
      deleted @= Nil
    }

    "initialize configuration" in {
      Profig.initConfiguration().map { _ =>
        succeed
      }
    }
    "initialize the database" in {
      database.init().map { _ =>
        database.materialized.updated.attach { id =>
          updated @= updated ::: List(id)
        }
        database.materialized.deleted.attach { id =>
          deleted @= deleted ::: List(id)
        }

        succeed
      }
    }
    "insert a user and verify it exists in materialized" in {
      database.users.insertOne(u1).flatMap { _ =>
        database.monitor.nextTick.flatMap { _ =>
          database.fullUsers.all.results.map { list =>
            list should be(List(fu1Empty))
            verifyUpdatedAndClear(u1._id)
            verifyDeletedAndClear()
          }
        }
      }
    }
    "insert a location and verify it was added to the materialized" in {
      val changedFuture = updated.future()
      for {
        _ <- database.locations.insertOne(l1)
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu1Location))
        verifyUpdatedAndClear(u1._id)
        verifyDeletedAndClear()
      }
    }
    "insert another user and verify it exists in materialized" in {
      database.users.insertOne(u2).flatMap { _ =>
        database.monitor.nextTick.flatMap { _ =>
          database.fullUsers.all.results.map { list =>
            list.map(_.name).sorted should be(List("User 1", "User 2"))
            verifyUpdatedAndClear(u2._id)
            verifyDeletedAndClear()
          }
        }
      }
    }
    "delete a location and verify it was deleted from the materialized" in {
      val changedFuture = updated.future()
      for {
        _ <- database.locations.deleteOne(l1._id)
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list.toSet should be(Set(fu1Empty, fu2Empty))
        verifyUpdatedAndClear(u1._id)
        verifyDeletedAndClear()
      }
    }
    "delete a user and verify it was deleted from materialized" in {
      val changedFuture = deleted.future()
      for {
        _ <- database.users.deleteOne(u1._id)
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu2Empty))
        verifyUpdatedAndClear()
        verifyDeletedAndClear(u1._id)
      }
    }
    "insert a location for user 2 and verify it was added to the materialized" in {
      val changedFuture = updated.future()
      for {
        _ <- database.locations.insertOne(l2)
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu2Location))
        verifyUpdatedAndClear(u2._id)
        verifyDeletedAndClear()
      }
    }
    "insert a second location for user 2 and verify it was added to the materialized" in {
      val changedFuture = updated.future()
      for {
        _ <- database.locations.insertOne(l3)
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu2Locations))
        verifyUpdatedAndClear(u2._id)
        verifyDeletedAndClear()
      }
    }
    "issue an update to all users and verify it applies" in {
      val changedFuture = updated.future()
      for {
        _ <- database.users.updateAll(FieldAndValue(User.age, 41))
        _ <- changedFuture
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu2LocationsUpdated))
        verifyUpdatedAndClear(u2._id)
        verifyDeletedAndClear()
      }
    }
    "truncate materialized and verify empty" in {
      for {
        _ <- database.fullUsers.truncate()
        list <- database.fullUsers.all.results
      } yield {
        list should be(Nil)
      }
    }
    "execution refreshAll to rebuild the materialized view" in {
      for {
        _ <- database.materialized.refreshAll()
        list <- database.fullUsers.all.results
      } yield {
        list should be(List(fu2LocationsUpdated))
      }
    }
    "cleanup" in {
      for {
        _ <- database.monitor.stop()
        _ <- database.drop()
      } yield {
        succeed
      }
    }
  }

  object database extends Graph("materializedSpec") with MonitoredSupport {
    val users: DocumentCollection[User] = vertex[User]
    val locations: DocumentCollection[Location] = vertex[Location]
    val fullUsers: DocumentCollection[FullUser] = vertex[FullUser]

    val materialized: Materialized[User, FullUser] = materialized(users -> fullUsers)
      .map(User.name -> FullUser.name)
      .map(User.age -> FullUser.age)
      .one2Many(locations, Location.userId, FullUser.locations)
      .withField(FullUser.locationCount) { info =>
        val collectionRef = NamedRef()
        aqlu"""
               FIRST(
                 FOR $collectionRef IN ${database.locations}
                 FILTER $collectionRef.${Location.userId} == ${info.baseRef}._id
                 COLLECT WITH COUNT INTO length
                 RETURN length
               )
            """
      }
      .build()
  }

  case class User(name: String, age: Int, _id: Id[User] = User.id()) extends Document[User]
  object User extends DocumentModel[User] {
    val name: Field[String] = field("name")
    val age: Field[Int] = field("age")

    override val collectionName: String = "users"
    override implicit val serialization: Serialization[User] = Serialization.auto[User]

    override def indexes: List[Index] = Nil
  }

  case class Location(userId: Id[User], city: String, state: String, _id: Id[Location] = Location.id()) extends Document[Location]
  object Location extends DocumentModel[Location] {
    val userId: Field[Id[User]] = field("userId")
    val city: Field[String] = field("city")
    val state: Field[String] = field("state")

    override val collectionName: String = "locations"
    override implicit val serialization: Serialization[Location] = Serialization.auto[Location]

    override def indexes: List[Index] = Nil
  }

  case class FullUser(name: String, age: Int, locations: List[Location], locationCount: Int, _id: Id[FullUser]) extends Document[FullUser]
  object FullUser extends DocumentModel[FullUser] {
    val name: Field[String] = field("name")
    val age: Field[Int] = field("age")
    val locations: Field[List[Location]] = field("locations")
    val locationCount: Field[Int] = field("locationCount")

    override val collectionName: String = "materializedUsers"
    override implicit val serialization: Serialization[FullUser] = Serialization.auto[FullUser]

    override def indexes: List[Index] = Nil
  }
}


text:
class Panel;
class PanelDragDelegate;

// Class for GTK handling of move-drag and resize-drag on a panel.
// Only one type of drag may be active at any time.
// Dragging only begins if the mouse is moved beyond the drag threshold.
// If mouse is released without exceeding the drag threshold, the mouse
// press and release is treated as a mouse click.
class PanelDragGtk {
 public:
  explicit PanelDragGtk(Panel* panel);
  ~PanelDragGtk();

  GtkWidget* widget() const { return drag_widget_; }

  // Sets up mouse and keyboard events processing while the mouse
  // is pressed on a window edge.
  // |event| is the mouse press event.
  // |cursor| is the cursor to display during the drag.
  // |edge| is the window edge from which to resize the panel.
  void InitialWindowEdgeMousePress(GdkEventButton* event, GdkCursor* cursor,
                                   GdkWindowEdge& edge);

  // Sets up mouse and keyboard events processing while the mouse is
  // pressed on the titlebar.
  // |event| is the mouse press event.
  // |titlebar_widget| should handle the mouse release event if the mouse
  // is released without exceeding the drag threshold (a mouse click).
  void InitialTitlebarMousePress(GdkEventButton* event,
                                 GtkWidget* titlebar_widget);

 private:
  friend class NativePanelTestingGtk;

  enum DragState {
    NOT_DRAGGING,
    DRAG_CAN_START,  // mouse pressed
    DRAG_IN_PROGRESS,  // mouse moved beyond drag threshold
    DRAG_ENDED_WAITING_FOR_MOUSE_RELEASE
  };

  // Callbacks for GTK mouse and key events.
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnMouseMoveEvent,
                       GdkEventMotion*);
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnButtonPressEvent,
                       GdkEventButton*);
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnButtonReleaseEvent,
                       GdkEventButton*);
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnKeyPressEvent,
                       GdkEventKey*);
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnKeyReleaseEvent,
                       GdkEventKey*);
  CHROMEGTK_CALLBACK_1(PanelDragGtk, gboolean, OnGrabBrokenEvent,
                       GdkEventGrabBroken*);

  // Utility to dcheck a bunch of state to ensure a clean slate.
  // Returns only if all the dchecks pass.
  void AssertCleanState();

  void GrabPointerAndKeyboard(GdkEventButton* event,
                              GdkCursor* cursor);
  void ReleasePointerAndKeyboardGrab();

  // Ends any drag that is currently in progress (if any).
  // Resets all drag state except for pointer and keyboard grabs.
  // The grabs are released when the mouse is released to prevent a
  // mouse release *after* the drag has ended (e.g. via ESC key) from
  // being treated as a mouse click.
  void EndDrag(bool canceled);

  // Weak pointer to the panel being dragged.
  Panel* panel_;

  // Invisible event box to receive mouse and key events.
  GtkWidget* drag_widget_;

  DragState drag_state_;

  // A copy of the initial button press event.
  GdkEvent* initial_mouse_down_;

  // Widget that should process the mouse click if mouse is released
  // without exceeding the drag threshold. May be NULL if no click
  // handling is necessary.
  GtkWidget* click_handler_;

  // Delegate for processing drag depends on actual type of drag.
  PanelDragDelegate* drag_delegate_;

  DISALLOW_COPY_AND_ASSIGN(PanelDragGtk);
};

#endif  // CHROME_BROWSER_UI_PANELS_PANEL_DRAG_GTK_H_


text:
import datetime

__author__ = 'wojtowpj'

from beer_api import Beer
from user_api import User
from auth import requires_auth, get_user
from db_helper import IdUrlField, generate_sorted_query
from flask.ext.restful import Resource, fields, reqparse, marshal, abort
from flask import request
from google.appengine.ext import db

class BeerReview(db.Model):
    beer = db.ReferenceProperty(Beer, required=True)
    user = db.ReferenceProperty(User, required=True)
    date_created = db.DateTimeProperty(auto_now_add=True)
    aroma = db.FloatProperty(required=True)
    appearance = db.FloatProperty(required=True)
    taste = db.FloatProperty(required=True)
    palate = db.FloatProperty(required=True)
    bottle_style = db.FloatProperty(required=True)
    overall = db.FloatProperty(required=True)
    comments = db.StringProperty()

class BeerReviewSummary(db.Model):
    beer = db.ReferenceProperty(Beer, required=True)
    count = db.IntegerProperty()
    aroma = db.FloatProperty(required=True)
    appearance = db.FloatProperty(required=True)
    taste = db.FloatProperty(required=True)
    palate = db.FloatProperty(required=True)
    bottle_style = db.FloatProperty(required=True)
    overall = db.FloatProperty(required=True)

beer_reference_fields = {
    'name': fields.String,
    'uri': IdUrlField('beer', absolute=True),
}

user_reference_fields = {
    'user_name': fields.String,
    'uri': IdUrlField('user', absolute=True),
}

beer_review_fields = {
    'user': fields.Nested(user_reference_fields),
    'beer': fields.Nested(beer_reference_fields),
    'date_created': fields.DateTime,
    'aroma': fields.Float,
    'appearance': fields.Float,
    'taste': fields.Float,
    'palate': fields.Float,
    'bottle_style': fields.Float,
    'overall': fields.Float,
    'comments': fields.String,
    'uri': IdUrlField('review', absolute=True)
}

beer_review_summary_fields = {
    'count': fields.Integer,
    'aroma': fields.Float,
    'appearance': fields.Float,
    'taste': fields.Float,
    'palate': fields.Float,
    'bottle_style': fields.Float,
    'overall': fields.Float,
    'beer': fields.Nested(beer_reference_fields),
}

post_parser = reqparse.RequestParser()
post_parser.add_argument('aroma', type=float, required=True, help='aroma is required')
post_parser.add_argument('appearance', type=float, required=True, help='appearance is required')
post_parser.add_argument('taste', type=float, required=True, help='taste is required')
post_parser.add_argument('palate', type=float, required=True, help='palate is required')
post_parser.add_argument('bottle_style', type=float, required=True, help='bottle_style is required')
post_parser.add_argument('comments', type=str)

class BeerReviewListApi(Resource):
    def __init__(self):
        self.getparse = reqparse.RequestParser()
        self.getparse.add_argument('type', type=str, location='args')

        super(BeerReviewListApi, self).__init__()

    @requires_auth
    def get(self):
        args = self.getparse.parse_args()
        if args.type == 'summary':
            summaries = []
            for s in generate_sorted_query(BeerReviewSummary):
                summaries.append(s)
            return {'beer_review_summaries': map(lambda s: marshal(s, beer_review_summary_fields), summaries)}
        else:
            review_list = []
            for r in generate_sorted_query(BeerReview):
                review_list.append(r)
            return {'beer_reviews': map(lambda r: marshal(r, beer_review_fields), review_list)}

    @requires_auth
    def post(self):
        args = post_parser.parse_args()
        if args.get('beer_id') is None:
            abort(400, message="beer_id is required")
        b = Beer.get_by_id(args.beer_id)

        return add_review(b, args)

class BeerReviewApi(Resource):
    @requires_auth
    def get(self, id):
        r = BeerReview.get_by_id(id)
        if not r:
            abort(404)
        return {"beer_review": marshal(r, beer_review_fields)}

class BeerReviewBeerApi(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('type', type=str, location='args')

        super(BeerReviewBeerApi, self).__init__()

    @requires_auth
    def get(self, id):
        review_list = []
        b = Beer.get_by_id(id)
        if not b:
            abort(404, message="Beer not found")
        args = self.reqparse.parse_args()
        if args.type == 'summary':
            summary = BeerReviewSummary.all().filter('beer', b).get()
            return {'beer_review_summary': marshal(summary, beer_review_summary_fields)}
        else:
            for r in generate_sorted_query(BeerReview).filter('beer', b):
                review_list.append(r)
            return {'beer_reviews': map(lambda r: marshal(r, beer_review_fields), review_list)}

    @requires_auth
    def post(self, id):
        args = post_parser.parse_args()
        b = Beer.get_by_id(id)

        return add_review(b, args)

class BeerReviewUserApi(Resource):
    def __init__(self):
        super(BeerReviewUserApi, self).__init__()

    @requires_auth
    def get(self, id):
        review_list = []
        u = User.get_by_id(id)
        if not u:
            abort(404, message="User not found")
        for r in generate_sorted_query(BeerReview).filter('user', u):
            review_list.append(r)

        return {'beer_reviews': map(lambda r: marshal(r, beer_review_fields), review_list)}

def moving_average(prev, current, count):
    return prev + (current - prev) / count

def add_review(beer, review_dict):
    def create_review_summary(beer_review):
        summary = BeerReviewSummary.all().filter('beer', beer_review.beer).get()
        if summary:
            summary.count += 1
            summary.aroma = moving_average(summary.aroma, beer_review.aroma, summary.count)
            summary.appearance = moving_average(summary.appearance, beer_review.appearance, summary.count)
            summary.taste = moving_average(summary.taste, beer_review.taste, summary.count)
            summary.palate = moving_average(summary.palate, beer_review.palate, summary.count)
            summary.bottle_style = moving_average(summary.bottle_style, beer_review.bottle_style, summary.count)
            summary.overall = moving_average(summary.overall, beer_review.overall, summary.count)
        else:
            summary = BeerReviewSummary(count=1,
                                        beer=beer_review.beer,
                                        aroma=beer_review.aroma,
                                        appearance=beer_review.appearance,
                                        taste=beer_review.taste,
                                        palate=beer_review.palate,
                                        bottle_style=beer_review.bottle_style,
                                        overall=beer_review.overall)

        summary.put()

    if beer is None:
        abort(404, message="Beer %s not found.")
    user = get_user()
    if user is None:
        abort(404, message="User is not found.")

    date_added = datetime.datetime.utcnow()
    r = BeerReview.all() \
        .filter('beer', beer) \
        .filter('user', user) \
        .filter('date_created >', date_added - datetime.timedelta(days=7)) \
        .get()

    if r:
        allowed_in = (r.date_created + datetime.timedelta(days=7) - date_added).total_seconds()
        abort(429, message="Only one review per user per beer per week allowed.", allowed_in=round(allowed_in))

    scores = [float(review_dict['aroma']), float(review_dict['appearance']), float(review_dict['taste']),
              float(review_dict['palate']),
              float(review_dict['bottle_style'])]
    overall = (sum(scores) / len(scores))
    r = BeerReview(beer=beer,
                   user=user,
                   aroma=review_dict['aroma'],
                   appearance=review_dict['appearance'],
                   taste=review_dict['taste'],
                   palate=review_dict['palate'],
                   bottle_style=review_dict['bottle_style'],
                   overall=overall,
                   comments=review_dict.get('comments'))

    r.put()
    create_review_summary(r)

    return {'beer_review': marshal(r, beer_review_fields)}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2010-2015, Google Inc.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:

     * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above
 copyright notice, this list of conditions and the following disclaimer
 in the documentation and/or other materials provided with the
 distribution.
     * Neither the name of Google Inc. nor the names of its
 contributors may be used to endorse or promote products derived from
 this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="8dip"
    android:layout_marginRight="8dip">

  <CheckBox
      android:id="@+id/user_dictionary_tool_entry_list_check"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center_vertical" />

  <TextView
      android:id="@+id/user_dictionary_tool_entry_list_reading"
      android:layout_width="0dip"
      android:layout_height="wrap_content"
      android:layout_gravity="center_vertical"
      android:layout_weight="2" />
  <TextView
      android:id="@+id/user_dictionary_tool_entry_list_word"
      android:layout_width="0dip"
      android:layout_height="wrap_content"
      android:layout_gravity="center_vertical"
      android:layout_weight="2" />
  <TextView
      android:id="@+id/user_dictionary_tool_entry_list_pos"
      android:layout_width="0dip"
      android:layout_height="wrap_content"
      android:layout_gravity="center_vertical"
      android:layout_weight="1" />
</LinearLayout>


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

// Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
// If it's not then please replace this with with your hosting url.

/*jshint esversion: 6 */

var fs = require("fs");

// `request` module is required for file upload.
// Use "npm install request" command to install.
var request = require("request");

// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const API_KEY = "XXXXXXXXXXXXX";

// Source PDF file to get information
const SourceFile = "./sample.pdf";

// Prepare URL for `Invoice Parser` API call
var query = `https://localhost/pdf/invoiceparser?inline=True`;
let reqOptions = {
    uri: query,
    headers: { "x-api-key": API_KEY },
    formData: {
        file: fs.createReadStream(SourceFile)
    }
};

// Send request
request.post(reqOptions, function (error, response, body) {
    if (error) {
        return console.error("Error: ", error);
    }

    // Parse JSON response
    let data = JSON.parse(body);
    if (data.error == false) {
         // Display extracted invoice fields
         for (var key in data.body) {
            console.log(`${key}: ${JSON.stringify(data.body[key])}`);
        }
    }
    else {
        // Service reported error
        console.log("Error: " + data.message);
    }
});


text:
import {h, render, Component, cloneElement} from 'preact';
import {addEvent, removeEvent} from './UXDom';
import UXEvent from './UXEvent';

class UXDrag extends Component {
  state = {
    transform: "translate(0px, 0px)"
  }

  handleDrag = (data) => {
    this.setState({
      transform: `translate(${data.dx}px, ${data.dy}px)`
    });
  }

  onDrag = (data) => {
    this.handleDrag(data);
    typeof this.props.onDrag == 'function' && this.props.onDrag(data);
  }

  render(props, state) {
    return (
      <UXEvent onDrag={this.onDrag}>
        {cloneElement(props.children[0], {
          style: {...state}
        })}
      </UXEvent>
    )
  }
}

export default UXDrag;


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<project name="${project.artifactId}" xmlns="http://maven.apache.org/DECORATION/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd">

<skin>
    <groupId>org.apache.maven.skins</groupId>
    <artifactId>maven-fluido-skin</artifactId>
    <version>1.5</version>
  </skin>

  <poweredBy>
        <logo name="Mr. Owl" href="http://www.ciwise.com" img="/img/logo.png"/>
  </poweredBy>

  <custom>
    <fluidoSkin>
      <copyrightClass>pull-right</copyrightClass>
      <gitHub>
        <projectId>ciwise/ciwise</projectId>
        <ribbonOrientation>right</ribbonOrientation>
        <ribbonColor>black</ribbonColor>
      </gitHub>
      <topBarEnabled>false</topBarEnabled>
      <sourceLineNumbersEnabled>true</sourceLineNumbersEnabled>
      <facebookLike/>
      <googlePlusOne/>
      <twitter>
        <user>dlwhitehurst</user>
        <showUser>true</showUser>
        <showFollowers>true</showFollowers>
      </twitter>
    </fluidoSkin>
  </custom>

  <body>
    <menu name="Documentation">
      <item name="Home" href="/index.html"/>
      <item name="Readme" href="README.html" />
    </menu>

    <menu name="Modules" ref="modules" inherit="none"/>
    <menu name="Reports" ref="reports" inherit="none"/>
    <menu name="Links" inherit="none" inheritAsRef="true">
      <item name="Company Site" href="http://www.ciwise.com/"/>
      <item name="Github Homepage" href="http://www.github.com/ciwise"/>
      <item name="LinkedIn Profile" href="https://www.linkedin.com/in/dlwhitehurst"/>
    </menu>
  </body>

</project>


text:
var debug = require('./lib/debug.js')('index');
var assign = require('lodash.assign');
var invariant = require('invariant');

var baseConfig = require('./lib/config.base.js');
var devConfig = require('./lib/config.dev.js');
var prodConfig = require('./lib/config.prod.js');
var removeKeys = require('./lib/removeKeys.js');

function toPrettyJSON(json) {
  return JSON.stringify(json, null, 2);
}

// Custom arguments that should be removed from the final config we export to
// webpack
var customArgs = [
  'in',
  'out',
  'cleanOnBuild',
  'isDev',
  'https',
  'port',
  'define',
];

function validateConfig(config) {
  invariant(config, 'Expected a configuration object.');
  if (!config || typeof config !== 'object') {
    debug('Non-object was passed as config');
    throw new TypeError('Expected a configuration object');
  }

  debug('Validating required config params');
  invariant(config.in || config.entry, 'Configuration object must have an `%s` property.', 'in');
  invariant(config.out || config.output, 'Configuration object must have an `%s` property.', 'out');
}

module.exports = function(config) {
  debug('Validating user defined config:', toPrettyJSON(config));
  validateConfig(config);
  debug('Config valid. Exporting based on NODE_ENV: ' + process.env.NODE_ENV);

  var finalConfig = assign(
    {},
    baseConfig(config),
    config.isDev === false ? prodConfig(config) : devConfig(config),
    removeKeys(config, customArgs)
  );

  debug('Exporting final config:', toPrettyJSON(finalConfig));
  return finalConfig;
};


text:
import assignConfig from './assignConfig';
import globElements from './globElements';
import optimize from './optimize';
import readElements from './readElements';

import { IScegContentData, IScegOption } from '../sceg';

/**
 * Create guide data from elements
 *
 * @param path Paths of element files that glob pattern
 * @param option Optional configure
 * @return guide data object
 */
export default function get (path: string, option: IScegOption = {}): Promise<IScegContentData> {
	const config = assignConfig(option, path);
	return globElements(config)
		.then(readElements(config))
		.then(optimize());
}


text:
local env=env
local tester={}
function tester.do_test(target)
    if target=="" then target=nil end
    if not target or taget=="ALL" then
        local list,keys={},{}
        for k,v in pairs(env) do
            if type(v)=="table" then
                if type(v.tester)=="function" then
                    list[k]=v.tester
                    table.insert(keys,k)
                end
              --if type(v.C)=="table" then end
            end
        end
        table.sort(keys)
        if #keys==0 then return print("No available modules.") end
        if not target then print("Available modules:") end
        for i,k in ipairs(keys) do
            if not target then
                print(string.format("%3s %s",i,k))
            else
                print("Start running unit test on '"..k.."'' module...")
                pcall(list[k],env[k])
            end
        end
    else
        assert(type(env[target])=="table","CLI-00001: No such module["..target.."]!")
        assert(type(env[target].tester)=="function","CLI-00002: Module['..target..'] does not have the tester function!")
        print("Start running unit test on '"..target.." module ...")
        pcall(env[target].tester,env[target])
    end
end

env.set_command(nil,"tester","#Invoke unit test on existing modules",tester.do_test,false,2)
return tester


text:
/**
 *
 * @param $ {object} jQuery object
 * @param params {object} other parameters
 * @returns {{className: string}}
 * @constructor
 * @memberof svl
 */
function OverlayMessageBox ($, params) {
    var self = { 'className' : 'OverlayMessageBox' },
        properties = { 'visibility' : 'visible' };

    function init() {
        if ("ui" in svl && svl.ui && svl.ui.overlayMessage) {
          setMessage('Walk');
        }

    }

    /**
     * Set the message in the overlay box
     * @param mode
     * @param message
     * @returns {*}
     */
    function setMessage (mode, message) {
        var instructions = svl.misc.getLabelInstructions(),
            labelColors = svl.misc.getLabelColors();

        if ((mode in instructions) && (mode in labelColors) && "ui" in svl) {
            // Set the box color.
            var modeColor = labelColors[mode];
            var backgroundColor = svl.util.color.changeAlphaRGBA(modeColor.fillStyle, 0.85);
            backgroundColor = svl.util.color.changeDarknessRGBA(backgroundColor, 0.35);

            svl.ui.overlayMessage.box.css({
                'background' : backgroundColor
            });
            svl.ui.overlayMessage.message.css({
                'color' : instructions[mode].textColor
            });

            // Set the instructional message.
            if (message) {
                // Manually set a message.
                svl.ui.overlayMessage.message.html(message);
            } else {
                // Otherwise use the pre set message
                svl.ui.overlayMessage.message.html('<strong>' + instructions[mode].instructionalText + '</strong>');
            }
            return this;
        } else {
            return false;
        }
    }

    /**
     * Set the visibility to visible or hidden.
     * @param val
     * @returns {setVisibility}
     */
    function setVisibility (val) {
        if (val === 'visible' || val === 'hidden') {
            properties.visibility = val;
        }
        return this;
    }

    self.setMessage = setMessage;
    self.setVisibility = setVisibility;

    init();

    return self;
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataBoxEdge.Models
{
    public partial class UserAccessRight : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("userId");
            writer.WriteStringValue(UserId);
            writer.WritePropertyName("accessType");
            writer.WriteStringValue(AccessType.ToString());
            writer.WriteEndObject();
        }

        internal static UserAccessRight DeserializeUserAccessRight(JsonElement element)
        {
            ResourceIdentifier userId = default;
            ShareAccessType accessType = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("userId"))
                {
                    userId = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("accessType"))
                {
                    accessType = new ShareAccessType(property.Value.GetString());
                    continue;
                }
            }
            return new UserAccessRight(userId, accessType);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.CloudFormation.Model
{
    ///
    /// <para>The output for ValidateTemplate action.</para>
    ///
    public class ValidateTemplateResult
    {

        private List<TemplateParameter> parameters = new List<TemplateParameter>();
        private string description;
        private List<string> capabilities = new List<string>();
        private string capabilitiesReason;

        ///
        /// A list of <c>TemplateParameter</c> structures.
        ///
        ///
        public List<TemplateParameter> Parameters
        {
            get { return this.parameters; }
            set { this.parameters = value; }
        }
        ///
        /// Adds elements to the Parameters collection
        ///
        /// <param name="parameters">The values to add to the Parameters collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithParameters(params TemplateParameter[] parameters)
        {
            foreach (TemplateParameter element in parameters)
            {
                this.parameters.Add(element);
            }

            return this;
        }

        ///
        /// Adds elements to the Parameters collection
        ///
        /// <param name="parameters">The values to add to the Parameters collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithParameters(IEnumerable<TemplateParameter> parameters)
        {
            foreach (TemplateParameter element in parameters)
            {
                this.parameters.Add(element);
            }

            return this;
        }

        // Check to see if Parameters property is set
        internal bool IsSetParameters()
        {
            return this.parameters.Count > 0;
        }

        ///
        /// The description found within the template.
        ///
        ///
        public string Description
        {
            get { return this.description; }
            set { this.description = value; }
        }

        ///
        /// Sets the Description property
        ///
        /// <param name="description">The value to set for the Description property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithDescription(string description)
        {
            this.description = description;
            return this;
        }

        // Check to see if Description property is set
        internal bool IsSetDescription()
        {
            return this.description != null;
        }

        ///
        /// The capabitilites found within the template. Currently, CAPABILITY_IAM is the only capability detected. If your template contains IAM
        /// resources, you must specify the CAPABILITY_IAM value for this parameter when you use the CreateStack or UpdateStack actions
        /// with your template; otherwise, those actions return an InsufficientCapabilities error.
        ///
        ///
        public List<string> Capabilities
        {
            get { return this.capabilities; }
            set { this.capabilities = value; }
        }
        ///
        /// Adds elements to the Capabilities collection
        ///
        /// <param name="capabilities">The values to add to the Capabilities collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithCapabilities(params string[] capabilities)
        {
            foreach (string element in capabilities)
            {
                this.capabilities.Add(element);
            }

            return this;
        }

        ///
        /// Adds elements to the Capabilities collection
        ///
        /// <param name="capabilities">The values to add to the Capabilities collection </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithCapabilities(IEnumerable<string> capabilities)
        {
            foreach (string element in capabilities)
            {
                this.capabilities.Add(element);
            }

            return this;
        }

        // Check to see if Capabilities property is set
        internal bool IsSetCapabilities()
        {
            return this.capabilities.Count > 0;
        }

        ///
        /// The capabilities reason found within the template.
        ///
        ///
        public string CapabilitiesReason
        {
            get { return this.capabilitiesReason; }
            set { this.capabilitiesReason = value; }
        }

        ///
        /// Sets the CapabilitiesReason property
        ///
        /// <param name="capabilitiesReason">The value to set for the CapabilitiesReason property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public ValidateTemplateResult WithCapabilitiesReason(string capabilitiesReason)
        {
            this.capabilitiesReason = capabilitiesReason;
            return this;
        }

        // Check to see if CapabilitiesReason property is set
        internal bool IsSetCapabilitiesReason()
        {
            return this.capabilitiesReason != null;
        }
    }
}


text:
<?php

namespace Bootstrap\Api\Providers;

use Hubzero\Error\Handler;
use Hubzero\Error\Renderer\Plain;
use Hubzero\Error\Renderer\Api;
use Hubzero\Base\ServiceProvider;

/**
 * Error handler service provider
 */
class ErrorServiceProvider extends ServiceProvider
{
	/**
	 * Register the service provider.
	 *
	 * @return  void
	 */
	public function register()
	{
		$this->app['error'] = function($app)
		{
			$logger = new \Monolog\Logger('cms');

			// Log to php's `error_log()`
			$loghandler = new \Monolog\Handler\ErrorLogHandler();

			// Alternatively, if you need to a specified file
			//$loghandler = new \Monolog\Handler\StreamHandler($app['config']->get('log_path') . '/error.php', 'error', true);

			$logger->pushHandler($loghandler);

			$handler = new Handler(
				new Plain($app['config']->get('debug')),
				$logger
			);

			return $handler;
		};
	}

	/**
	 * Register the exception handler.
	 *
	 * @return  void
	 */
	public function startHandling()
	{
		// Set the error_reporting
		switch ($this->app['config']->get('error_reporting'))
		{
			case 'default':
			case '-1':
				break;

			case 'none':
			case '0':
				error_reporting(0);
				break;

			case 'simple':
				error_reporting(E_ERROR | E_WARNING | E_PARSE);
				ini_set('display_errors', 1);
				break;

			case 'maximum':
				error_reporting(E_ALL);
				ini_set('display_errors', 1);
				break;

			case 'development':
				error_reporting(-1);
				ini_set('display_errors', 1);
				break;

			default:
				error_reporting($this->app['config']->get('error_reporting'));
				ini_set('display_errors', 1);
				break;
		}

		$this->app['error']->register($this->app['client']->name);
	}

	/**
	 * Register the exception handler.
	 *
	 * @return  void
	 */
	public function boot()
	{
		if (!$this->app->runningInConsole())
		{
			$this->app['error']->setRenderer(new Api(
				$this->app['response'],
				$this->app['config']->get('debug')
			));
		}
	}
}


text:
<!doctype html>

    <title>Origin for site with document.domain set to a parent domain</title>

Enable JavaScript and reload


text:
<?php
use yii\helpers\Html;

$this->title = 'Order Cancelled';

echo Html::tag('h1', $this->title);
echo Html::tag('div', 'The order has been cancelled');

echo Html::a('Start another order', ['/order/form'], ['class' => 'btn btn-primary']);


text:
from oslo_config import cfg

from ironic.common.i18n import _

opts = [
    cfg.IntOpt('client_timeout',
               default=60,
               help=_('Timeout (in seconds) for iLO operations')),
    cfg.PortOpt('client_port',
                default=443,
                help=_('Port to be used for iLO operations')),
    cfg.StrOpt('swift_ilo_container',
               default='ironic_ilo_container',
               help=_('The Swift iLO container to store data.')),
    cfg.IntOpt('swift_object_expiry_timeout',
               default=900,
               help=_('Amount of time in seconds for Swift objects to '
                      'auto-expire.')),
    cfg.BoolOpt('use_web_server_for_images',
                default=False,
                help=_('Set this to True to use http web server to host '
                       'floppy images and generated boot ISO. This '
                       'requires http_root and http_url to be configured '
                       'in the [deploy] section of the config file. If this '
                       'is set to False, then Ironic will use Swift '
                       'to host the floppy images and generated '
                       'boot_iso.')),
    cfg.IntOpt('clean_priority_reset_ilo',
               default=0,
               help=_('Priority for reset_ilo clean step.')),
    cfg.IntOpt('clean_priority_reset_bios_to_default',
               default=10,
               help=_('Priority for reset_bios_to_default clean step.')),
    cfg.IntOpt('clean_priority_reset_secure_boot_keys_to_default',
               default=20,
               help=_('Priority for reset_secure_boot_keys clean step. This '
                      'step will reset the secure boot keys to manufacturing '
                      'defaults.')),
    cfg.IntOpt('clean_priority_clear_secure_boot_keys',
               default=0,
               help=_('Priority for clear_secure_boot_keys clean step. This '
                      'step is not enabled by default. It can be enabled to '
                      'clear all secure boot keys enrolled with iLO.')),
    cfg.IntOpt('clean_priority_reset_ilo_credential',
               default=30,
               help=_('Priority for reset_ilo_credential clean step. This '
                      'step requires "ilo_change_password" parameter to be '
                      'updated in nodes\'s driver_info with the new '
                      'password.')),
    cfg.IntOpt('power_wait',
               default=2,
               help=_('Amount of time in seconds to wait in between power '
                      'operations')),
    cfg.IntOpt('oob_erase_devices_job_status_interval',
               min=10,
               default=300,
               help=_('Interval (in seconds) between periodic erase-devices '
                      'status checks to determine whether the asynchronous '
                      'out-of-band erase-devices was successfully finished or '
                      'not. On an average, a 300GB HDD with default pattern '
                      '"overwrite" would take approximately 9 hours and '
                      '300GB SSD with default pattern "block" would take '
                      'approx. 30 seconds to complete sanitize disk erase.')),
    cfg.StrOpt('ca_file',
               deprecated_for_removal=True,
               deprecated_reason=_('Its being replaced by new configuration '
                                   'parameter "verify_ca".'),
               help=_('CA certificate file to validate iLO.')),
    cfg.StrOpt('verify_ca',
               default='True',
               help=_('CA certificate to validate iLO. This can be either '
                      'a Boolean value, a path to a CA_BUNDLE file or '
                      'directory with certificates of trusted CAs. If set '
                      'to True the driver will verify the host certificates; '
                      'if False the driver will ignore verifying the SSL '
                      'certificate. If it\'s a path the driver will use the '
                      'specified certificate or one of the certificates in '
                      'the directory. Defaults to True.')),
    cfg.StrOpt('default_boot_mode',
               default='auto',
               choices=[('auto', _('based on boot mode settings on the '
                                   'system')),
                        ('bios', _('BIOS boot mode')),
                        ('uefi', _('UEFI boot mode'))],
               help=_('Default boot mode to be used in provisioning when '
                      '"boot_mode" capability is not provided in the '
                      '"properties/capabilities" of the node. The default is '
                      '"auto" for backward compatibility. When "auto" is '
                      'specified, default boot mode will be selected based '
                      'on boot mode settings on the system.')),
    cfg.IntOpt('file_permission',
               default=0o644,
               help=_('File permission for swift-less image hosting with the '
                      'octal permission representation of file access '
                      'permissions. This setting defaults to ``644``, '
                      'or as the octal number ``0o644`` in Python. '
                      'This setting must be set to the octal number '
                      'representation, meaning starting with ``0o``.')),
    cfg.StrOpt('kernel_append_params',
               default='nofb nomodeset vga=normal',
               mutable=True,
               help=_('Additional kernel parameters to pass down to the '
                      'instance kernel. These parameters can be consumed by '
                      'the kernel or by the applications by reading '
                      '/proc/cmdline. Mind severe cmdline size limit! Can be '
                      'overridden by `instance_info/kernel_append_params` '
                      'property.')),
    cfg.StrOpt('cert_path',
               default='/var/lib/ironic/ilo/',
               help=_('On the ironic-conductor node, directory where ilo '
                      'driver stores the CSR and the cert.')),

]

def register_opts(conf):
    conf.register_opts(opts, group='ilo')


text:
Awesome Pulseaudio Widget
=========================

Awesome Pulseaudio Widget (APW) is a little widget for
[Awesome WM](http://awesome.naquadah.org/), using the awful progressbar widget,
to display default's sink volume and control Pulseaudio.

It's compatible with Awesome 3.5.

First time I'm using Lua. So it might be a little bit quirky.

Get it
------

```sh
cd $XDG_CONFIG_HOME/awesome/
git clone https://github.com/mokasin/apw.git
```

Use it
------

Just put these line to the appropriate places in
*$XDG_CONFIG_HOME/awesome/rc.lua*.

```lua
-- Load the widget.
local APW = require("apw/widget")

-- Example: Add to wibox. Here to the right. Do it the way you like it.
right_layout:add(APW)

-- Configure the hotkeys.
awful.key({ }, "XF86AudioRaiseVolume",  APW.Up),
awful.key({ }, "XF86AudioLowerVolume",  APW.Down),
awful.key({ }, "XF86AudioMute",         APW.ToggleMute),

```

Customize it
------------

### Theme

*Important:* `beautiful.init` must be called before you `require` apw for
theming to work.

Just add these variables to your Beautiful theme.lua file and set them
to whatever colors or gradients you wish:

```lua
--{{{ APW
theme.apw_fg_color = {type = 'linear', from = {0, 0}, to={40,0},
	stops={{0, "#CC8888"}, {.4, "#88CC88"}, {.8, "#8888CC"}}}
theme.apw_bg_color = "#333333"
theme.apw_mute_fg_color = "#CC9393"
theme.apw_mute_bg_color = "#663333"
--}}}

```

### Directly edit widget.lua

You also can customize some properties by editing the configuration variables
directly in `widget.lua` (i.e. add a margin).
It is advisable to customize the source file in an own branch. This makes it
easy to update to a new version of APW via rebasing.

Mixer
----

Right-clicking the widget launches a mixer.  By default this is `pavucontrol`,
but you can set a different command by calling SetMixer() on your APW object:

```lua
local APW = require("apw/widget")
APW:SetMixer("mixer_command -whatever")
```

### Tip
You could update the widget periodically if you'd like. In case, the volume is
changed from somewhere else.

```lua
APWTimer = timer({ timeout = 0.5 }) -- set update interval in s
APWTimer:connect_signal("timeout", APW.Update)
APWTimer:start()
```

Contributing
------------
Just fork it and file a pull request. I'll look into it.


text:
import threading
import requests
import queue
import sys
import re
import os

requests.packages.urllib3.disable_warnings()

def ip2num(ip):
    ip = [int(x) for x in ip.split('.')]
    return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]

def num2ip(num):
    return '%s.%s.%s.%s' % ((num & 0xff000000) >> 24, (num & 0x00ff0000) >> 16, (num & 0x0000ff00) >> 8, num & 0x000000ff)

def ip_range(start, end):
    return [num2ip(num) for num in range(ip2num(start), ip2num(end) + 1) if num & 0xff]

def bThread(ip_list):
    thread_list = []
    queue_list = queue.Queue()
    for host in ip_list:
        queue_list.put(host)

    for x in range(0, int(SETTHREAD)):
        thread_list.append(tThread(queue_list))

    for t in thread_list:
        t.start()
    for t in thread_list:
        t.join()

class tThread(threading.Thread):
    def __init__(self, queue_list):
        threading.Thread.__init__(self)
        self.queue_list = queue_list

    def run(self):
        while not self.queue_list.empty():
            host = self.queue_list.get()
            check_serve_info(host)

def get_ports_from_remote():
    tmp_port = []
    try:
        ports_result = requests.get(url='https://data.telnetscan.org/ports.php', headers=HEADERS, verify=False, timeout=15).json()
        for port in ports_result['data']:
            tmp_port.append(int(port))
        return tmp_port
    except Exception as e:
        print(e)

def check_serve_info(host):
    for k in PORTS:
        try:
            if k == 443:
                aim_url = "https://" + host + ":" + str(k)
            else:
                aim_url = "http://" + host + ":" + str(k)

            response = requests.get(url=aim_url, headers=HEADERS, verify=False, timeout=50)
            for header_item in response.headers:
                if 'erver' in header_item:
                    server_text = response.headers[header_item]
            title_text = re.findall(r'<title>(.*?)</title>', response.content.decode('utf-8'))[0]

            if len(server_text) > 0:
                save_data = {"ip": host, "port": str(k), "server": server_text, "title": title_text}
                print(str(save_data))
                save_data_to_server(save_data)
        except Exception as e:
            # print(e)
            pass

def save_data_to_server(aim_data):
    try:
        result = requests.post(url='https://data.telnetscan.org/insertto.php', headers=HEADERS, verify=False, data=aim_data, timeout=30).json()

        if result['code'] == 0:
            print("Save Success!")
        else:
            print("Save Failed!")

    except Exception as e:
        print(e)

if __name__ == '__main__':
    print('############# HTTP Header Scanner ###########')
    print('                Author 92ez.com')
    print('#############################################\n')

    global SETTHREAD
    global THIS_PID
    global PORTS
    global HEADERS

    HEADERS = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"}

    THIS_PID = os.getpid()
    PORTS = get_ports_from_remote()
    print('[*] This pid is ' + str(THIS_PID))

    try:
        SETTHREAD = sys.argv[1]
        startIp = sys.argv[2].split('-')[0]
        endIp = sys.argv[2].split('-')[1]
        ip_list = ip_range(startIp, endIp)
        print('[Note] Will scan ' + str(len(ip_list)) + " host...\n")
        bThread(ip_list)
    except KeyboardInterrupt:
        print('\n[*] Kill all thread.')
        os.kill(THIS_PID, 9)


text:
namespace operations_research {
void RunWorker(void* data) {
  ThreadPool* const thread_pool = reinterpret_cast<ThreadPool*>(data);
  std::function<void()> work = thread_pool->GetNextTask();
  while (work != nullptr) {
    work();
    work = thread_pool->GetNextTask();
  }
}

ThreadPool::ThreadPool(const std::string& prefix, int num_workers)
    : num_workers_(num_workers) {}

ThreadPool::~ThreadPool() {
  if (started_) {
    std::unique_lock<std::mutex> mutex_lock(mutex_);
    waiting_to_finish_ = true;
    mutex_lock.unlock();
    condition_.notify_all();
    for (int i = 0; i < num_workers_; ++i) {
      all_workers_[i].join();
    }
  }
}

void ThreadPool::SetQueueCapacity(int capacity) {
  CHECK_GT(capacity, num_workers_);
  CHECK(!started_);
  queue_capacity_ = capacity;
}

void ThreadPool::StartWorkers() {
  started_ = true;
  for (int i = 0; i < num_workers_; ++i) {
    all_workers_.push_back(std::thread(&RunWorker, this));
  }
}

std::function<void()> ThreadPool::GetNextTask() {
  std::unique_lock<std::mutex> lock(mutex_);
  for (;;) {
    if (!tasks_.empty()) {
      std::function<void()> task = tasks_.front();
      tasks_.pop_front();
      if (tasks_.size() < queue_capacity_ && waiting_for_capacity_) {
        waiting_for_capacity_ = false;
        capacity_condition_.notify_all();
      }
      return task;
    }
    if (waiting_to_finish_) {
      return nullptr;
    } else {
      condition_.wait(lock);
    }
  }
  return nullptr;
}

void ThreadPool::Schedule(std::function<void()> closure) {
  std::unique_lock<std::mutex> lock(mutex_);
  while (tasks_.size() >= queue_capacity_) {
    waiting_for_capacity_ = true;
    capacity_condition_.wait(lock);
  }
  tasks_.push_back(closure);
  if (started_) {
    lock.unlock();
    condition_.notify_all();
  }
}

}  // namespace operations_research


text:
namespace foundation    { class Logger; }

namespace appleseed {
namespace cli {

class ProgressTileCallbackFactory
  : public renderer::ITileCallbackFactory
{
  public:
    explicit ProgressTileCallbackFactory(foundation::Logger& logger);

    virtual void release() override;

    virtual renderer::ITileCallback* create() override;

  private:
    std::auto_ptr<renderer::ITileCallback> m_callback;
};

}       // namespace cli
}       // namespace appleseed

#endif  // !APPLESEED_CLI_PROGRESSTILECALLBACK_H


text:
Installation on Linux
=====================

.. contents::
   :local:
   :depth: 1

Prerequisites
-------------

This installation instruction describes how to install NNabla using pip
on almost any Linux 64-bit systems.

The supported Python versions for provided binary packages are 3.7, 3.8, 3.9. It is recommended to use `Miniconda <https://conda.io/miniconda.html>`_ as a Python distribution. The following is a simple procedure to install Miniconda Python.

.. code-block:: shell

    wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
    bash Miniconda3-latest-Linux-x86_64.sh -b -p {installation path e.g. ~/miniconda}
    # You have to set an environment variable PATH accordingly
    # to enable the installed ``Python`` and the ``conda`` system.
    echo 'export PATH=<installation path>/bin:$PATH' >> ~/.bashrc
    # Restart your bash or source ~/.bashrc

    # Switch the default Python version
    conda install -y python={version number e.g. 3.7}

Installation
------------

See :ref:`pip-installation-workflow`.

FAQ
---

Q. I want to use another linux distribution.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

We actually tested other linux distributions and versions; Ubuntu 16.04, 18.04, 20.04, CentOS 7, 8 on various environments; Baremetal server, AWS instance, and/or Docker machine. Thus, you can install in almost the same way described here. The details of how-to-install for each are coming soon.


text:
using MasterDevs.ChromeDevTools;

namespace MasterDevs.ChromeDevTools.Protocol.DOM{
	/// <summary>
	/// Shadow root type.
	/// </summary>
	public enum ShadowRootType
	{
			User_agent,
			Author,
	}
}