text:
layout: page
title: Stone Peak Chemical Seminar
date: 2016-05-24
author: Terry Garcia
tags: weekly links, java
status: published
summary: Mauris sit amet urna et tortor scelerisque.
banner: images/banner/people.jpg
booking:
  startDate: 01/31/2019
  endDate: 02/02/2019
  ctyhocn: HLNGAHX
  groupCode: SPCS
published: true
---
Mauris ut hendrerit purus, eu ornare lacus. Donec maximus, felis sit amet eleifend dapibus, ex mi posuere odio, quis rutrum leo mi lacinia ex. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris tempor tellus eget dolor eleifend, vel maximus massa sodales. Morbi venenatis quis metus vel tristique. Donec pulvinar mattis luctus. Duis quis odio eget nibh suscipit viverra rhoncus quis eros.
Vivamus vehicula sed magna sed molestie. Morbi tristique elit ut volutpat molestie. Integer elementum nisl dui, vel consequat metus scelerisque at. Fusce condimentum nec felis quis viverra. Duis lectus velit, ultrices ac ligula in, faucibus tincidunt eros. Nullam condimentum lectus et auctor maximus. In id mi odio. Maecenas sit amet pharetra turpis. Nunc vel odio ante. Donec commodo odio sed augue imperdiet, in mattis nibh euismod. Duis ullamcorper ac orci id feugiat. Nam eleifend ullamcorper nisl, blandit scelerisque lacus molestie non. Mauris eget mi semper erat pellentesque congue ut ut lacus. Donec nec ipsum blandit, egestas neque eget, condimentum ipsum. Ut et luctus tellus, vel cursus sapien. Praesent condimentum mi convallis lectus suscipit blandit.

* Cras convallis libero quis fringilla lobortis
* Pellentesque ac elit in lectus maximus posuere
* Sed congue elit vitae mi condimentum, id egestas nulla ornare
* Mauris viverra ipsum a enim consectetur, a semper risus venenatis.

Etiam accumsan felis a iaculis egestas. Duis eu metus at nibh dapibus faucibus eget in risus. Sed nisi ipsum, sodales sit amet nibh in, cursus laoreet lectus. Curabitur maximus quam ut sollicitudin fermentum. Morbi vitae lectus ac libero rutrum ultricies quis lobortis ex. Nunc ut enim viverra, finibus mauris sit amet, tincidunt sem. Nam enim nulla, dictum et scelerisque sagittis, efficitur vel neque.


text:
package cn.oftenporter.oftendb.db.mongodb;

import cn.oftenporter.oftendb.annotation.*;
import com.mongodb.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class MongodbUtil
{

    /**
     * @param db
     * @param code
     * @param nolock
     * @param args
     * @return
     * @throws MongoException
     */
    public static Object eval(DB db, String code, boolean nolock, Object... args) throws MongoException
    {
        DBObject dbObject = BasicDBObjectBuilder.start().add("$eval", code).add("args", args)
                .add("nolock", nolock).get();
        CommandResult commandResult = db.command(dbObject);
        commandResult.throwOnError();
        return commandResult.get("retval");
    }

    /**
     * 确保普通索引。使用@Index标记,并且必须带有@Key标记。
     *
     * @param collection
     * @param order      1或-1(表示升序或降序)
     * @param forSearch
     */
    public static void createIndex(DBCollection collection, int order, Class<?> forSearch)
    {
        _createIndex(collection, order, false, forSearch, Index.class);
    }

    /**
     * 确保唯一索引.使用@UniqueIndex标记,并且必须带有@Key标记。
     *
     * @param collection
     * @param order      1或-1(表示升序或降序)
     * @param forSearch
     */
    public static void createUniqueIndex(DBCollection collection, int order, Class<?> forSearch)
    {
        _createIndex(collection, order, true, forSearch, UniqueIndex.class);
    }

    /**
     * 确保索引,若不存在则创建索引,必须带有@Key标记 。
     *
     * @param collection      集合
     * @param order           1或-1(表示升序或降序)
     * @param unique          是否是唯一索引
     * @param forSearch       在此类中搜索
     * @param annotationClass 注解
     */

    @SuppressWarnings("unchecked")
    private static void _createIndex(final DBCollection collection, final int order, boolean unique, Class<?> forSearch,
            Class<? extends Annotation> annotationClass)
    {
        final BasicDBObject basicDBObject = new BasicDBObject("unique", unique);

        try
        {
            AnnotationSearch.searchPublicFields(new MyConsumer<Field, Exception>()
            {

                @Override
                public void accept(Field t) throws Exception
                {
                    Key key = t.getAnnotation(Key.class);
                    if (key == null)
                    {
                        return;
                    }
                    String name = key.value().equals("") ? t.getName()
                            : key.value();
                    collection.createIndex(new BasicDBObject(name, order), basicDBObject);
                }
            }, forSearch, null, annotationClass);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 确保索引,若不存在则创建索引,分别建立 。
     *
     * @param collection        集合
     * @param order             1或-1(表示升序或降序)
     * @param unique            是否是唯一索引
     * @param forSearch         在此类中搜索
     * @param annotationClasses 注解
     */

    public static void createIndex(final DBCollection collection, final int order, boolean unique, Class<?> forSearch,
            Class<? extends Annotation>... annotationClasses)
    {
        final BasicDBObject basicDBObject = new BasicDBObject("unique", unique);

        try
        {
            AnnotationSearch.searchPublicFields(new MyConsumer<Field, Exception>()
            {

                @Override
                public void accept(Field t) throws Exception
                {

                    collection.createIndex(new BasicDBObject(t.getName(), order), basicDBObject);
                }
            }, forSearch, null, annotationClasses);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 确保索引,若不存在则创建索引,分别建立 。
     *
     * @param collection mongodb集合名
     * @param order      1或-1(表示升序或降序)
     * @param unique     是否是唯一索引
     * @param keys       要设置的键名
     */
    @SafeVarargs
    public static void createIndex(DBCollection collection, int order, boolean unique, String... keys)
    {
        BasicDBObject basicDBObject = new BasicDBObject("unique", unique);

        /**
         * 索引
         */
        for (String string : keys)
        {
            collection.createIndex(new BasicDBObject(string, order), basicDBObject);
        }

    }

    /**
     * 确保组合索引,若不存在则创建索引 。
     *
     * @param collection
     * @param unique
     * @param oreders    1或-1(表示升序或降序)
     * @param keys
     */
    public static void createCombinIndex(DBCollection collection, boolean unique, int[] oreders, String[] keys)
    {
        BasicDBObject basicDBObject = new BasicDBObject("unique", unique);

        BasicDBObject dbObject = new BasicDBObject();
        for (int i = 0; i < oreders.length; i++)
        {
            dbObject.put(keys[i], oreders[1]);
        }

        collection.createIndex(dbObject, basicDBObject);

    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Drupal\Tests\block_content\Kernel\Migrate;

use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;

/**
 * Tests migration of block content body field display configuration.
 *
 * @group block_content
 */
class MigrateBlockContentEntityDisplayTest extends MigrateDrupal7TestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['block', 'block_content', 'filter', 'text'];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->installEntitySchema('block_content');
    $this->installConfig(static::$modules);
    $this->executeMigrations([
      'block_content_type',
      'block_content_body_field',
      'block_content_entity_display',
    ]);
  }

  /**
   * Asserts a display entity.
   *
   * @param string $id
   *   The entity ID.
   * @param string $component_id
   *   The ID of the display component.
   *
   * @internal
   */
  protected function assertDisplay(string $id, string $component_id): void {
    $component = EntityViewDisplay::load($id)->getComponent($component_id);
    $this->assertIsArray($component);
    $this->assertSame('hidden', $component['label']);
  }

  /**
   * Tests the migrated display configuration.
   */
  public function testMigration() {
    $this->assertDisplay('block_content.basic.default', 'body');
  }

}


text:
/* ELEMENTS */

body {
    width: 100%;
    height: 100%;
    font-family: "Lora", "Helvetica Neue", Helvetica, Arial, sans-serif;
    color: Dimgray;
    background-color: #e6e8ed;
    -webkit-tap-highlight-color: rgba(255, 255, 255, 0.2);
}

html {
    width: 100%;
    height: 100%
}

h1, h2, h3, h6 {
    margin: 0 0 35px;
    text-transform: uppercase;
    font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-weight: 700;
    letter-spacing: 1px;
}

p {
    margin: 0 0 25px;
    font-size: 18px;
    line-height: 1.5;
}

a {
    color: #3c763d;
    -webkit-transition: all .2s ease-in-out;
    -moz-transition: all .2s ease-in-out;
    transition: all .2s ease-in-out;
}

a:hover, a:focus {
    text-decoration: none;
    color: #1d9b6c;
}

.social {
  display: inline-block;
  margin-top: 5px;
  margin-left: 15px;
  width: 18px;
}

footer {
    padding: 50px 0;
}

/* IDs */
 #letterButton {
  font-size: 15px;
  height: 47px;
  color: #3c763d;
  border: 1px solid #3c763d;
  background-color: transparent;
}
#thankButton {
  font-size: 15px;
  height: 47px;
  color: #0000FF;
  border: 1px solid #0000FF;
  background-color: transparent;
}
#spankButton {
  font-size: 15px;
  height: 47px;
  color: #9E0000;
  border: 1px solid #9E0000;
  background-color: transparent;
}
#spankButton:hover, .spank:hover {
  color: white;
  background-color: #9E0000;
}
#thankButton:hover, .thank:hover {
  color: white;
  background-color: #0000FF;
}
#letterButton:hover, .stateRepName:hover {
  color: white;
  background-color: #3c763d;
}
#address {
    color: Dimgray;
    width: 100%;
    margin-bottom: 12px;
}
#addressButton, #nationalButton, #stateButton {
    width: 100%;
    margin-bottom: 12px;
}
#reps {
  margin-top: 35px;
}
#results {
  display: block;
  margin-top: 10px;
  width: 100%;
}
/* CLASSES */
.stateRepName, .repName {
  display: block;
  color: Dimgray;
  outline: none;
  margin: 0;
  margin-bottom: 5px;
  font-size: 14px;
  text-align: center;
  background-color: transparent;
  text-transform: uppercase;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: 400;
  border-radius: 0;
}
.spank {
  border: 1px solid #9E0000;
  color: #9E0000;
}
.thank {
  border: 1px solid #0000FF;
  color: #0000FF;
}
.stateRepName {
  border: 1px solid #3c763d;
  color: #3c763d;
}
.nav-item {
  margin-top: 15px;
}
.navbar {
  height: 80px;
  margin-bottom: 0;
  padding: 0;
  background: rgba(50,52,55,1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  text-transform: uppercase;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  -webkit-transition: background .5s ease-in-out, padding .5s ease-in-out;
  -moz-transition: background .5s ease-in-out, padding .5s ease-in-out;
  transition: background .5s ease-in-out, padding .5s ease-in-out;
}
.navbar-top {
  background: transparent;
}
.navbar-solid {
  background: rgba(50,52,55,1);
}
.navbar-nav {
  z-index: 2;
}
.navbar-toggle {
    padding: 15px 0px;
    margin-top: 13px;
    margin-bottom: 13px;
    font-size: 16px;
    color: white;
}
.navbar-toggle:focus, .navbar-toggle:active {
    outline: none;
}
.navbar-brand {
    padding-right: 0;
    padding-top: 0;
    padding-bottom: 0;
    margin-top: 17.5px;
    margin-bottom: 17.5px;
    text-align: center;
    font-weight: 700;
    height: auto;
}
.navbar-brand:focus {
    outline: none;
}
.navbar-custom a {
    color: white;
}
.navbar-custom .nav li a {
    -webkit-transition: background .3s ease-in-out;
    -moz-transition: background .3s ease-in-out;
    transition: background .3s ease-in-out;
}
.navbar-custom .nav li a:hover {
    color: rgba(255, 255, 255, 0.8);
    outline: none;
    background-color: transparent;
}
.navbar-custom .nav li a:focus, .navbar-custom .nav li a:active {
    outline: none;
    background-color: transparent;
}
.navbar-custom .nav li.active {
    outline: none;
}
.navbar-custom .nav li.active a {
    background-color: rgba(255, 255, 255, 0.3);
}
.navbar-custom .nav li.active a:hover {
    color: white;
}
.intro {
    display: table;
    width: 100%;
    height: 100vh;
    padding: 100px 0;
    text-align: center;
    color: white;
    background: url(../img/intro-background.jpg) no-repeat center scroll;
    background-color: #e6e8ed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

.intro .intro-body {
    display: table-cell;
    vertical-align: middle;
}

.brand-heading {
    font-size: 100px;
}

.btn {
    text-transform: uppercase;
    font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-weight: 400;
    -webkit-transition: background .3s ease-in-out;
    -moz-transition: background .3s ease-in-out;
    transition: background .3s ease-in-out;
    border-radius: 0;
}

input[type=text] {
    display: block;
    border: 1px solid #3c763d;
    color: #ffffff;
    outline: none;
    margin: 0;
    font-size: 18px;
    padding: 10px 16px;
    text-align: center;
    background-color: transparent;
    text-transform: uppercase;
    font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-weight: 400;
    border-radius: 0;
}

.btn-default, .btn-default:focus {
    border: 1px solid #3c763d;
    color: #3c763d;
    background-color: transparent;
    outline: none;
}

.btn-default:hover{
    border: 1px solid #3c763d;
    outline: none;
    color: #e6e8ed;
    background-color: #3c763d;
}

.btn-circle {
    width: 70px;
    height: 70px;
    margin-top: 15px;
    padding: 7px 16px;
    border: 2px solid white;
    border-radius: 100% !important;
    font-size: 40px;
    color: white;
    background: transparent;
    -webkit-transition: background .3s ease-in-out;
    -moz-transition: background .3s ease-in-out;
    transition: background .3s ease-in-out;
}

.btn-circle:hover, .btn-circle:focus {
    outline: none;
    color: white;
    background: rgba(255, 255, 255, 0.1);
}

.btn-circle i.animated {
    -webkit-transition-property: -webkit-transform;
    -webkit-transition-duration: 1s;
    -moz-transition-property: -moz-transform;
    -moz-transition-duration: 1s;
}

.btn-circle:hover i.animated {
    -webkit-animation-name: pulse;
    -moz-animation-name: pulse;
    -webkit-animation-duration: 1.5s;
    -moz-animation-duration: 1.5s;
    -webkit-animation-iteration-count: infinite;
    -moz-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -moz-animation-timing-function: linear;
}

.content-section {
    padding-top: 100px;
}
.light {
    font-weight: 400;
}

/* ANIMATIONS */

@-webkit-keyframes pulse {
    from {
    -webkit-transform: scale(1);
    transform: scale(1);
    }
    50% {
        -webkit-transform: scale(1.2);
        transform: scale(1.2);
    }
    100% {
        -webkit-transform: scale(1);
        transform: scale(1); }
}

@-moz-keyframes pulse {
    from {
    -moz-transform: scale(1);
    transform: scale(1);
    }
    50% {
        -moz-transform: scale(1.2);
        transform: scale(1.2);
    }
    100% {
        -moz-transform: scale(1);
        transform: scale(1); }
}

/* MEDIA QUERIES */

@media (max-width: 550px) {
  h2 {
    font-size: 25px;
  }
  .repName, .stateRepName {
    font-size: 9px;
  }
}

@media (min-width: 551px; max-width: 767px) {
    .repName, .stateRepName {
      font-size: 13px;
    }
}

@media (max-width: 767px) {
  .collapse.in, .collapsing {
    border: none;
    background: rgba(50,52,55,1);
  }
}

@media (min-width: 768px) {
    .intro {
        height: 100%;
        padding: 0;
    }
    p {
        margin: 0 0 35px;
        font-size: 20px;
        line-height: 1.6; }
    ul.banner-social-buttons li {
        display: block;
        margin-bottom: 20px;
        padding: 0;
    }
}

@media (max-width: 1199px) {
    ul.banner-social-buttons {
        margin-top: 15px; }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Wheatley</string>
    <string name="action_add_client">Add client</string>
    <string name="yes">Yes</string>
    <string name="no">No</string>
    <string name="run_as_root">Run as root</string>
    <string name="are_you_sure_root">Are you sure you want this program to run as root?</string>
    <string name="compositor_failed">Failed to start compositor.</string>
</resources>


text:
package org.eclipse.php.internal.debug.core.model;

import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IVariable;

/**
 * Implementors of this interface may act as a "container" for grouping variables
 * (i.e. large sets of array members).
 *
 * @author Bartlomiej Laczkowski
 */
public interface IVirtualPartition extends IVariable, IVariableFacet {

	/**
	 * Partition variables provider.
	 */
	public interface IVariableProvider {

		/**
		 * Returns a set of variables for corresponding partition.
		 *
		 * @return set of variables for corresponding partition
		 * @throws DebugException
		 */
		IVariable[] getVariables() throws DebugException;

	}

	/**
	 * Sets variable provider for this virtual partition.
	 *
	 * @param variableProvider
	 */
	public void setProvider(IVariableProvider variableProvider);

}


text:
<?php
/**
 * TOP API: rds.aliyuncs.com.DescribeFilesForSQLServer.2014-08-15 request
 *
 * @author auto create
 * @since 1.0, 2014-09-13 16:51:05
 */
class Rds20140815DescribeFilesForSQLServerRequest
{
	/**
	 * 实例名
	 **/
	private $dBInstanceId;

	/**
	 * 查询结束时间,格式如:2011-06-11T16:00Z,且大于查询开始时间
	 **/
	private $endTime;

	/**
	 * "页码,大于0,且不超过Integer的最大值
默认值:1"
 支持最大值为:2147483647
 支持最小值为:1
	 **/
	private $pageNumber;

	/**
	 * "每页记录数,取值:30|50|100
默认值:30
 支持最大值为:100
 支持最小值为:1
	 **/
	private $pageSize;

	/**
	 * 查询开始时间,格式如:2011-06-11T15:00Z
	 **/
	private $startTime;

	private $apiParas = array();

	public function setdBInstanceId($dBInstanceId)
	{
		$this->dBInstanceId = $dBInstanceId;
		$this->apiParas["DBInstanceId"] = $dBInstanceId;
	}

	public function getdBInstanceId()
	{
		return $this->dBInstanceId;
	}

	public function setEndTime($endTime)
	{
		$this->endTime = $endTime;
		$this->apiParas["EndTime"] = $endTime;
	}

	public function getEndTime()
	{
		return $this->endTime;
	}

	public function setPageNumber($pageNumber)
	{
		$this->pageNumber = $pageNumber;
		$this->apiParas["PageNumber"] = $pageNumber;
	}

	public function getPageNumber()
	{
		return $this->pageNumber;
	}

	public function setPageSize($pageSize)
	{
		$this->pageSize = $pageSize;
		$this->apiParas["PageSize"] = $pageSize;
	}

	public function getPageSize()
	{
		return $this->pageSize;
	}

	public function setStartTime($startTime)
	{
		$this->startTime = $startTime;
		$this->apiParas["StartTime"] = $startTime;
	}

	public function getStartTime()
	{
		return $this->startTime;
	}

	public function getApiMethodName()
	{
		return "rds.aliyuncs.com.DescribeFilesForSQLServer.2014-08-15";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->dBInstanceId,"dBInstanceId");
		RequestCheckUtil::checkNotNull($this->endTime,"endTime");
		RequestCheckUtil::checkMaxValue($this->pageNumber,2147483647,"pageNumber");
		RequestCheckUtil::checkMinValue($this->pageNumber,1,"pageNumber");
		RequestCheckUtil::checkMaxValue($this->pageSize,100,"pageSize");
		RequestCheckUtil::checkMinValue($this->pageSize,1,"pageSize");
		RequestCheckUtil::checkNotNull($this->startTime,"startTime");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


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

<title>com.thoughtworks.selenium.condition</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.thoughtworks.selenium.condition

Interfaces

ConditionRunner

ConditionRunner.Context

DefaultConditionRunner.Monitor

Classes

Condition

DefaultConditionRunner

DefaultConditionRunner.Log4jMonitor

DefaultConditionRunner.NoOpMonitor

JUnit4AndTestNgConditionRunner

JUnitConditionRunner

Not

Presence

Text


text:
package org.jadira.reflection.cloning.objenesis;

import org.jadira.reflection.access.unsafe.UnsafeOperations;
import org.objenesis.ObjenesisException;
import org.objenesis.instantiator.ObjectInstantiator;

/**
 * Provides the Objenesis API an instantiator implementation that can use Unsafe.
 * You may use this class independently of the cloning framework.
 */
public class UnsafeFactoryInstantiator implements ObjectInstantiator {

	private Class<?> type;

	private static final UnsafeOperations UNSAFE_OPERATIONS = UnsafeOperations.getUnsafeOperations();

	/**
	 * Creates a new instance for the given type
	 * @param type The type to be instantiated by this instance
	 */
	public UnsafeFactoryInstantiator(Class<?> type) {
		this.type = type;
	}

	@Override
	public Object newInstance() {
		try {
			return UNSAFE_OPERATIONS.allocateInstance(type);
		} catch (IllegalStateException e) {
			throw new ObjenesisException(e.getCause());
		}
	}
}


text:
#ifndef POWERMANAGEMENT_HPP
#define POWERMANAGEMENT_HPP
struct ResetMessage
{

};

struct ShutdownMessage
{

};

namespace power
{

void init_power_management();

}

#endif // POWERMANAGEMENT_HPP


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/reporting/storage/storage_queue.h"

#include <cstdint>
#include <initializer_list>
#include <utility>

#include "base/containers/flat_map.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/thread_pool.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "components/reporting/compression/compression_module.h"
#include "components/reporting/compression/test_compression_module.h"
#include "components/reporting/encryption/test_encryption_module.h"
#include "components/reporting/proto/synced/record.pb.h"
#include "components/reporting/resources/resource_interface.h"
#include "components/reporting/storage/storage_configuration.h"
#include "components/reporting/util/status.h"
#include "components/reporting/util/statusor.h"
#include "components/reporting/util/test_support_callbacks.h"
#include "crypto/sha2.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

using ::testing::_;
using ::testing::Between;
using ::testing::Eq;
using ::testing::Invoke;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::Sequence;
using ::testing::StrEq;
using ::testing::WithArg;

namespace reporting {
namespace {

constexpr size_t kTotalQueueStarts = 4;
constexpr size_t kTotalWritesPerStart = 16;
constexpr char kDataPrefix[] = "Rec";

class TestUploadClient : public UploaderInterface {
 public:
  // Mapping of <generation id, sequencing id> to matching record digest.
  // Whenever a record is uploaded and includes last record digest, this map
  // should have that digest already recorded. Only the first record in a
  // generation is uploaded without last record digest.
  using LastRecordDigestMap = base::flat_map<
      std::pair<int64_t /*generation id */, int64_t /*sequencing id*/>,
      absl::optional<std::string /*digest*/>>;

  explicit TestUploadClient(LastRecordDigestMap* last_record_digest_map)
      : last_record_digest_map_(last_record_digest_map) {}

  void ProcessRecord(EncryptedRecord encrypted_record,
                     ScopedReservation scoped_reservation,
                     base::OnceCallback<void(bool)> processed_cb) override {
    WrappedRecord wrapped_record;
    ASSERT_TRUE(wrapped_record.ParseFromString(
        encrypted_record.encrypted_wrapped_record()));
    // Verify generation match.
    const auto& sequence_information = encrypted_record.sequence_information();
    if (!generation_id_.has_value()) {
      generation_id_ = sequence_information.generation_id();
    } else {
      ASSERT_THAT(generation_id_.value(),
                  Eq(sequence_information.generation_id()));
    }

    // Verify digest and its match.
    // Last record digest is not verified yet, since duplicate records are
    // accepted in this test.
    {
      std::string serialized_record;
      wrapped_record.record().SerializeToString(&serialized_record);
      const auto record_digest = crypto::SHA256HashString(serialized_record);
      DCHECK_EQ(record_digest.size(), crypto::kSHA256Length);
      ASSERT_THAT(record_digest, Eq(wrapped_record.record_digest()));
      // Store record digest for the next record in sequence to verify.
      last_record_digest_map_->emplace(
          std::make_pair(sequence_information.sequencing_id(),
                         sequence_information.generation_id()),
          record_digest);
      // If last record digest is present, match it and validate.
      if (wrapped_record.has_last_record_digest()) {
        auto it = last_record_digest_map_->find(
            std::make_pair(sequence_information.sequencing_id() - 1,
                           sequence_information.generation_id()));
        if (it != last_record_digest_map_->end() && it->second.has_value()) {
          ASSERT_THAT(it->second.value(),
                      Eq(wrapped_record.last_record_digest()))
              << "seq_id=" << sequence_information.sequencing_id();
        }
      }
    }

    std::move(processed_cb).Run(true);
  }

  void ProcessGap(SequenceInformation sequence_information,
                  uint64_t count,
                  base::OnceCallback<void(bool)> processed_cb) override {
    ASSERT_TRUE(false) << "There should be no gaps";
  }

  void Completed(Status status) override { ASSERT_OK(status); }

 private:
  absl::optional<int64_t> generation_id_;
  const raw_ptr<LastRecordDigestMap> last_record_digest_map_;

  Sequence test_upload_sequence_;
};

class StorageQueueStressTest : public ::testing::TestWithParam<size_t> {
 public:
  void SetUp() override {
    // Enable compression.
    scoped_feature_list_.InitFromCommandLine(
        {CompressionModule::kCompressReportingFeature}, {});

    ASSERT_TRUE(location_.CreateUniqueTempDir());
    options_.set_directory(base::FilePath(location_.GetPath()));
  }

  void TearDown() override {
    ResetTestStorageQueue();
    // Make sure all memory is deallocated.
    ASSERT_THAT(options_.memory_resource()->GetUsed(), Eq(0u));
    // Make sure all disk is not reserved (files remain, but Storage is not
    // responsible for them anymore).
    ASSERT_THAT(options_.disk_space_resource()->GetUsed(), Eq(0u));
  }

  void CreateTestStorageQueueOrDie(const QueueOptions& options) {
    ASSERT_FALSE(storage_queue_) << "StorageQueue already assigned";
    test_encryption_module_ =
        base::MakeRefCounted<test::TestEncryptionModule>();
    test_compression_module_ =
        base::MakeRefCounted<test::TestCompressionModule>();
    test::TestEvent<Status> key_update_event;
    test_encryption_module_->UpdateAsymmetricKey("DUMMY KEY", 0,
                                                 key_update_event.cb());
    ASSERT_OK(key_update_event.result());
    test::TestEvent<StatusOr<scoped_refptr<StorageQueue>>>
        storage_queue_create_event;
    StorageQueue::Create(
        options,
        base::BindRepeating(&StorageQueueStressTest::AsyncStartTestUploader,
                            base::Unretained(this)),
        test_encryption_module_, test_compression_module_,
        storage_queue_create_event.cb());
    StatusOr<scoped_refptr<StorageQueue>> storage_queue_result =
        storage_queue_create_event.result();
    ASSERT_OK(storage_queue_result) << "Failed to create StorageQueue, error="
                                    << storage_queue_result.status();
    storage_queue_ = std::move(storage_queue_result.ValueOrDie());
  }

  void ResetTestStorageQueue() {
    // Let everything ongoing to finish.
    task_environment_.RunUntilIdle();
    storage_queue_.reset();
    // StorageQueue is destructed on a thread,
    // so we need to wait for it to destruct.
    task_environment_.RunUntilIdle();
  }

  void AsyncStartTestUploader(
      UploaderInterface::UploadReason reason,
      UploaderInterface::UploaderInterfaceResultCb start_uploader_cb) {
    // Ignore reason for stress test.
    std::move(start_uploader_cb)
        .Run(std::make_unique<TestUploadClient>(&last_record_digest_map_));
  }

  void WriteStringAsync(base::StringPiece data,
                        base::OnceCallback<void(Status)> cb) {
    EXPECT_TRUE(storage_queue_) << "StorageQueue not created yet";
    Record record;
    record.mutable_data()->assign(data.data(), data.size());
    record.set_destination(UPLOAD_EVENTS);
    record.set_dm_token("DM TOKEN");
    storage_queue_->Write(std::move(record), std::move(cb));
  }

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  base::test::ScopedFeatureList scoped_feature_list_;
  base::ScopedTempDir location_;
  StorageOptions options_;
  scoped_refptr<test::TestEncryptionModule> test_encryption_module_;
  scoped_refptr<test::TestCompressionModule> test_compression_module_;
  scoped_refptr<StorageQueue> storage_queue_;

  // Test-wide global mapping of <generation id, sequencing id> to record
  // digest. Serves all TestUploadClients created by test fixture.
  TestUploadClient::LastRecordDigestMap last_record_digest_map_;
};

TEST_P(StorageQueueStressTest,
       WriteIntoNewStorageQueueReopenWriteMoreAndUpload) {
  for (size_t iStart = 0; iStart < kTotalQueueStarts; ++iStart) {
    test::TestCallbackWaiter write_waiter;
    base::RepeatingCallback<void(Status)> cb = base::BindRepeating(
        [](test::TestCallbackWaiter* waiter, Status status) {
          EXPECT_OK(status) << status;
          waiter->Signal();
        },
        &write_waiter);

    SCOPED_TRACE(base::StrCat({"Create ", base::NumberToString(iStart)}));
    CreateTestStorageQueueOrDie(
        QueueOptions(options_)
            .set_subdirectory(FILE_PATH_LITERAL("D1"))
            .set_file_prefix(FILE_PATH_LITERAL("F0001"))
            .set_max_single_file_size(GetParam())
            .set_upload_period(base::TimeDelta::Max())
            .set_upload_retry_delay(
                base::TimeDelta()));  // No retry by default.

    // Write into the queue at random order (simultaneously).
    SCOPED_TRACE(base::StrCat({"Write ", base::NumberToString(iStart)}));
    const std::string rec_prefix =
        base::StrCat({kDataPrefix, base::NumberToString(iStart), "_"});
    for (size_t iRec = 0; iRec < kTotalWritesPerStart; ++iRec) {
      write_waiter.Attach();
      base::ThreadPool::PostTask(
          FROM_HERE, {base::TaskPriority::BEST_EFFORT},
          base::BindOnce(
              [](base::StringPiece rec_prefix, size_t iRec,
                 StorageQueueStressTest* test,
                 base::RepeatingCallback<void(Status)> cb) {
                test->WriteStringAsync(
                    base::StrCat({rec_prefix, base::NumberToString(iRec)}), cb);
              },
              rec_prefix, iRec, this, cb));
    }
    write_waiter.Wait();

    SCOPED_TRACE(base::StrCat({"Upload ", base::NumberToString(iStart)}));
    storage_queue_->Flush();

    SCOPED_TRACE(base::StrCat({"Reset ", base::NumberToString(iStart)}));
    ResetTestStorageQueue();
    EXPECT_THAT(last_record_digest_map_.size(),
                Eq((iStart + 1) * kTotalWritesPerStart));

    SCOPED_TRACE(base::StrCat({"Done ", base::NumberToString(iStart)}));
  }
}

INSTANTIATE_TEST_SUITE_P(
    VaryingFileSize,
    StorageQueueStressTest,
    testing::Values(1 * 1024LL, 2 * 1024LL, 3 * 1024LL, 4 * 1024LL));

}  // namespace
}  // namespace reporting


text:
require(["App", "routers/AppRouter", "controllers/Controller", "jquery", "backbone", "marionette", "jqueryui", "bootstrap"],
    function (App, AppRouter, AppController) {
        App.appRouter = new AppRouter({
            controller:new AppController()
        });

        App.start();
    });


text:
<?php
session_start();
require_once 'dbb/Dbb.php';

$Dbb = new Dbb();
	$Dbb->dropbox_auth();

if($Dbb->dropbox_isConnected()){
	//Start Backup
	$uploadResult=$Dbb->backupStart();
	echo "<pre>";
	print_r($uploadResult);
}


text:
@interface MeTableViewModel ()

@end

@implementation MeTableViewModel

- (instancetype)init {
	self = [super init];
	if (self) {
		self.dataSource = [[NSMutableArray alloc] init];
		self.dataSourceUI = [[MeTableViewModelUI alloc] init];
	}
	return self;
}

- (void)setDelegate:(id <VViewModelDelegate> )delegate {
	[super setDelegate:delegate];
	[[HighCBarDataCenter sharedInstance] addObserver:self];
	[[HighCBarDataCenter sharedInstance] networkAddUser:
	 @{
	     NETWORK_BIN:@"user?",
	     NETWORK_PARAMS:@{
	         @"action": @"register",
	         @"deviceid": [NSString UDID],
	         @"username": [NSString UDID],
	         @"nickname": [NSString name],
		 }
	 }];
}

- (void)dataCenter:(VDataCenter *)dataCenter load:(id)change error:(NSError *)err {
	NSString *className = [change objectForKey:VDATA_CENTER_CHANGE_NAME];
	if ([className isEqualToString:[UserEntity className]]) {
		UserEntity *user = [change[VDATA_CENTER_CHANGE_DATA][[UserEntity className]] firstObject];
		self.dataSourceUI.name = user.nickName;
		self.dataSourceUI.avatarURL = user.avatarURL;
		self.dataSourceUI.userInfo = user;
		if ([self.delegate respondsToSelector:@selector(viewModel:load:error:)]) {
			dispatch_async(MAIN_QUEUE, ^{
			    [self.delegate viewModel:self load:@{ VVIEW_MODEL_CHANGE_NAME:[MeTableViewModelUI className], VVIEW_MODEL_CHANGE_DATA: self.dataSourceUI } error:nil];
			});
		}
	}
}

- (void)dealloc {
	[[HighCBarDataCenter sharedInstance] removeObserver:self];
}

@end

@implementation MeTableViewModelUI

@end


text:
<?php
/**
 *	base include file for SimpleTest
 *	@package	SimpleTest
 *	@subpackage	UnitTester
 *	@version	$Id: exceptions.php,v 1.14 2006/12/20 11:17:13 pp11 Exp $
 */

/**#@+
 * Include required SimpleTest files
 */
require_once dirname(__FILE__) . '/invoker.php';
require_once dirname(__FILE__) . '/expectation.php';
/**#@-*/

/**
 *    Extension that traps exceptions and turns them into
 *    an error message. PHP5 only.
 *	  @package SimpleTest
 *	  @subpackage UnitTester
 */
class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator {

	/**
	 *    Stores the invoker to be wrapped.
	 *    @param SimpleInvoker $invoker   Test method runner.
	 */
	function SimpleExceptionTrappingInvoker($invoker) {
		$this->SimpleInvokerDecorator($invoker);
	}

	/**
	 *    Invokes a test method whilst trapping expected
	 *    exceptions. Any left over unthrown exceptions
	 *    are then reported as failures.
	 *    @param string $method    Test method to call.
	 */
	function invoke($method) {
		$trap = SimpleTest::getContext()->get('SimpleExceptionTrap');
		$trap->clear();
		try {
			parent::invoke($method);
		} catch (Exception $exception) {
			if (! $trap->isExpected($this->getTestCase(), $exception)) {
				$this->getTestCase()->exception($exception);
			}
			$trap->clear();
			$this->_invoker->getTestCase()->tearDown();
		}
		if ($message = $trap->getOutstanding()) {
			$this->getTestCase()->fail($message);
		}
	}
}

/**
 *    Tests exceptions either by type or the exact
 *    exception. This could be improved to accept
 *    a pattern expectation to test the error
 *    message, but that will have to come later.
 *	  @package SimpleTest
 *	  @subpackage UnitTester
 */
class ExceptionExpectation extends SimpleExpectation {
	private $expected;

	/**
	 *    Sets up the conditions to test against.
	 *    If the expected value is a string, then
	 *    it will act as a test of the class name.
	 *    An exception as the comparison will
	 *    trigger an identical match. Writing this
	 *    down now makes it look doubly dumb. I hope
	 *    come up with a better scheme later.
	 *    @param mixed $expected   A class name or an actual
	 *                             exception to compare with.
	 *    @param string $message   Message to display.
	 */
	function __construct($expected, $message = '%s') {
		$this->expected = $expected;
		parent::__construct($message);
	}

	/**
	 *    Carry out the test.
	 *    @param Exception $compare    Value to check.
	 *    @return boolean              True if matched.
	 */
	function test($compare) {
		if (is_string($this->expected)) {
			return ($compare instanceof $this->expected);
		}
		if (get_class($compare) != get_class($this->expected)) {
			return false;
		}
		return $compare->getMessage() == $this->expected->getMessage();
	}

	/**
	 *    Create the message to display describing the test.
	 *    @param Exception $compare     Exception to match.
	 *    @return string                Final message.
	 */
	function testMessage($compare) {
		if (is_string($this->expected)) {
			return "Exception [" . $this->describeException($compare) .
					"] should be type [" . $this->expected . "]";
		}
		return "Exception [" . $this->describeException($compare) .
				"] should match [" .
				$this->describeException($this->expected) . "]";
	}

	/**
	 *    Summary of an Exception object.
	 *    @param Exception $compare     Exception to describe.
	 *    @return string                Text description.
	 */
	protected function describeException($exception) {
		return get_class($exception) . ": " . $exception->getMessage();
	}
}

/**
 *    Stores expected exceptions for when they
 *    get thrown. Saves the irritating try...catch
 *    block.
 *	  @package	SimpleTest
 *	  @subpackage	UnitTester
 */
class SimpleExceptionTrap {
	private $expected;
	private $message;

	/**
	 *    Clears down the queue ready for action.
	 */
	function __construct() {
		$this->clear();
	}

	/**
	 *    Sets up an expectation of an exception.
	 *    This has the effect of intercepting an
	 *    exception that matches.
	 *    @param SimpleExpectation $expected    Expected exception to match.
	 *    @param string $message                Message to display.
	 *    @access public
	 */
	function expectException($expected = false, $message = '%s') {
		if ($expected === false) {
			$expected = new AnythingExpectation();
		}
		if (! SimpleExpectation::isExpectation($expected)) {
			$expected = new ExceptionExpectation($expected);
		}
		$this->expected = $expected;
		$this->message = $message;
	}

	/**
	 *    Compares the expected exception with any
	 *    in the queue. Issues a pass or fail and
	 *    returns the state of the test.
	 *    @param SimpleTestCase $test    Test case to send messages to.
	 *    @param Exception $exception    Exception to compare.
	 *    @return boolean                False on no match.
	 */
	function isExpected($test, $exception) {
		if ($this->expected) {
			return $test->assert($this->expected, $exception, $this->message);
		}
		return false;
	}

	/**
	 *    Tests for any left over exception.
	 *    @return string/false     The failure message or false if none.
	 */
	function getOutstanding() {
		return sprintf($this->message, 'Failed to trap exception');
	}

	/**
	 *    Discards the contents of the error queue.
	 */
	function clear() {
		$this->expected = false;
		$this->message = false;
	}
}
?>


text:
#include <errno.h>

int errno;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Subjective Time Perception Experiment</title>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Expires" content="0"/>

<form id="background" action="#" method="POST" onsubmit="return false;">

Subjective Time Perception Experiment

Experiment takes around 5 minutes.

Instructions

Use only Chrome, Safari or Firefox!

Sit 20 cm from the screen.

Click start and fill survey.

When you see gray, red, blue or white screen click left mouse button once every 5 seconds.

Run this experiment two times a day:

- Right after you wake up

- Directly before going to sleep

        <button onclick="fullscreen(); hide('instructions'); show('survey')">Start experiment</button>
        How to run the experiment without internet connection?

User Survey

Email	<input type="email" name="email" placeholder="Email address" maxlength="100" autocomplete="off" required>

When you're doing the experiment?

<input type="radio" name="time" value="after-sleep" required> After wake up

<input type="radio" name="time" value="before-sleep" required> Before sleep

<input type="radio" name="time" value="other" required> Other

Temperature [°C]	<input type="number" step="0.1" placeholder="°C" name="temperature" min="34" max="42" autocomplete="off" required> (use dot "." as a decimal separator)

Heart Rate [bpm]	<input type="number" placeholder="bpm" name="heart_rate" min="40" max="220" autocomplete="off" required>

How do you feel?

<input type="radio" name="condition" value="rested" required> Well rested / Energetic

<input type="radio" name="condition" value="normal" required> Normal

<input type="radio" name="condition" value="tired" required> Tired / Sleepy

Blood Pressure [SYS/DIA]	<input type="number" placeholder="SYS" name="bp_systolic" min="80" max="220" autocomplete="off"> / <input type="number" placeholder="DIA" name="bp_diastolic" min="40" max="160" autocomplete="off"> (optional)

Age [years]	<input type="number" placeholder="Age" name="age" min="1" max="150" autocomplete="off" required>

What is your gender?

<input type="radio" name="gender" value="male" required> Male

<input type="radio" name="gender" value="female" required> Female

<input type="radio" name="gender" value="other" required> Other

        <button onclick="saveSurvey(); fullscreen(); hide('survey'); show('test');">Proceed</button>

You may now proceed to test section

When you see blank screen with color

Click as you were asked

        <button onclick="runAndProceed('test', 'color0')">Run the test!</button>

Color 1 of 3

When you see blank screen with color

Click as you were asked

        <button onclick="runAndProceed('color0', 'color1')">Ok, go!</button>

Color 2 of 3

When you see blank screen with color

Click as you were asked

        <button onclick="runAndProceed('color1', 'color2')">Ok, go!</button>

Color 3 of 3

When you see blank screen with color

Click as you were asked

        <button onclick="runAndProceed('color2', 'end')">Ok, go!</button>

Thank you for participating in the experiment!

Result upload status: Waiting for confirmation...

                    Parameter
                    All
                    Red
                    White
                    Blue

                    Count

                    Tempo

                    Regularity

                    Interval

                    Time Between Clicks

<button onclick="window.location.reload(true);">Start experiment once again</button>

</form>


text:
package motifidentification;

//import java.util.*;

public class KMeansClustering {
	public static void main(String[] args) {

		KMeansClustering kmc = new KMeansClustering();

		int nclusters = 2;
		int pointMatrix[][] = { { 1, 1 }, { 2, 1 }, { 4, 3 }, { 5, 4 } };
		int distanceMatrix[][] = new int[nclusters][pointMatrix.length];
		int centroids[][] = new int[nclusters][2];

		// initialize centroids
		for (int i = 0; i < nclusters; i++) {
			centroids[i][0] = pointMatrix[i][0];
			centroids[i][1] = pointMatrix[i][1];
		}

		for (int k = 0; k < 2; k++) {
			distanceMatrix = kmc.calculateDistanceMatrix(distanceMatrix,
					centroids, pointMatrix);
			distanceMatrix = kmc.adjustDistanceMatrix(distanceMatrix);
			centroids = kmc.calculateCentroids(distanceMatrix, pointMatrix);
		}

		for (int i = 0; i < nclusters; i++) {
			for (int j = 0; j < pointMatrix.length; j++) {
				System.out.print(distanceMatrix[i][j] + " ");
			}
			System.out.println();
		}
	}

	public int[][] calculateCentroids(int distanceMatrix[][],
			int pointMatrix[][]) {
		int centroids[][] = new int[2][distanceMatrix.length];
		int xtemp, ytemp;
		int xcount, ycount;
		for (int i = 0; i < distanceMatrix.length; i++) {
			xtemp = ytemp = 0;
			xcount = ycount = 0;
			for (int j = 0; j < distanceMatrix[i].length; j++) {
				if (distanceMatrix[i][j] == 1) {
					xtemp += pointMatrix[j][0];
					xcount++;
					ytemp += pointMatrix[j][1];
					ycount++;
				}
			}

			centroids[i][0] = xtemp / xcount;
			centroids[i][1] = ytemp / ycount;
		}

		return centroids;
	}

	public int[][] adjustDistanceMatrix(int distanceMatrix[][]) {

		for (int j = 0; j < distanceMatrix[0].length; j++) {
			int mintemp = Integer.MAX_VALUE;
			for (int i = 0; i < distanceMatrix.length; i++) {
				if (distanceMatrix[i][j] < mintemp) {
					mintemp = distanceMatrix[i][j];
				}
			}

			int tcount = 0;
			for (int i = 0; i < distanceMatrix.length; i++) {
				if (distanceMatrix[i][j] != mintemp) {
					distanceMatrix[i][j] = 0;
				} else {
					if (tcount == 0) {
						distanceMatrix[i][j] = 1;
						tcount++;
					} else {
						distanceMatrix[i][j] = 0;
					}
				}
			}
		}
		return distanceMatrix;
	}

	public int[][] calculateDistanceMatrix(int distanceMatrix[][],
			int centroids[][], int pointMatrix[][]) {

		for (int i = 0; i < distanceMatrix.length; i++) {
			for (int j = 0; j < pointMatrix.length; j++) {
				distanceMatrix[i][j] = (int) Math.sqrt(Math.pow(centroids[i][0]
						- pointMatrix[j][0], 2)
						+ Math.pow(centroids[i][1] - pointMatrix[j][1], 2));
			}
		}
		return distanceMatrix;
	}
}


text:
<!DOCTYPE html>

<link rel="help" href="https://drafts.css-houdini.org/css-layout-api/#intrinsic-sizes">
<link rel="match" href="child-replaced-percentage-ref.html">
<meta name="assert" content="This test checks that intrinsicSizes is calculated correctly for a replaced child element with a percentage height." />

    <canvas width=100 height=100 style="height: 100%;"></canvas>


text:
package org.apache.camel.component.stomp;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.camel.AsyncCallback;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.fusesource.hawtbuf.AsciiBuffer;
import org.fusesource.hawtdispatch.Task;
import org.fusesource.stomp.client.Callback;
import org.fusesource.stomp.client.CallbackConnection;
import org.fusesource.stomp.client.Promise;
import org.fusesource.stomp.client.Stomp;
import org.fusesource.stomp.codec.StompFrame;

import static org.fusesource.hawtbuf.UTF8Buffer.utf8;
import static org.fusesource.stomp.client.Constants.DESTINATION;
import static org.fusesource.stomp.client.Constants.DISCONNECT;
import static org.fusesource.stomp.client.Constants.ID;
import static org.fusesource.stomp.client.Constants.SEND;
import static org.fusesource.stomp.client.Constants.SUBSCRIBE;
import static org.fusesource.stomp.client.Constants.UNSUBSCRIBE;

@UriEndpoint(scheme = "stomp", title = "Stomp", syntax = "stomp:destination", consumerClass = StompConsumer.class, label = "messaging")
public class StompEndpoint extends DefaultEndpoint {

    @UriPath(description = "Name of the queue") @Metadata(required = "true")
    private String destination;
    @UriParam
    private StompConfiguration configuration;
    private CallbackConnection connection;
    private Stomp stomp;

    private final List<StompConsumer> consumers = new CopyOnWriteArrayList<StompConsumer>();

    public StompEndpoint(String uri, StompComponent component, StompConfiguration configuration, String destination) {
        super(uri, component);
        this.configuration = configuration;
        this.destination = destination;
    }

    public Producer createProducer() throws Exception {
        return new StompProducer(this);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return new StompConsumer(this, processor);
    }

    public boolean isSingleton() {
        return true;
    }

    @Override
    protected void doStart() throws Exception {
        final Promise<CallbackConnection> promise = new Promise<CallbackConnection>();

        stomp = new Stomp(configuration.getBrokerURL());
        stomp.setLogin(configuration.getLogin());
        stomp.setPasscode(configuration.getPasscode());
        stomp.connectCallback(promise);
        if (configuration.getHost() != null && !configuration.getHost().isEmpty()) {
            stomp.setHost(configuration.getHost());
        }

        connection = promise.await();

        connection.getDispatchQueue().execute(new Task() {
            @Override
            public void run() {
                connection.receive(new Callback<StompFrame>() {
                    @Override
                    public void onFailure(Throwable value) {
                        if (started.get()) {
                            connection.close(null);
                        }
                    }

                    @Override
                    public void onSuccess(StompFrame value) {
                        if (!consumers.isEmpty()) {
                            Exchange exchange = createExchange();
                            exchange.getIn().setBody(value.content());
                            for (StompConsumer consumer : consumers) {
                                consumer.processExchange(exchange);
                            }
                        }
                    }
                });
                connection.resume();
            }
        });
    }

    @Override
    protected void doStop() throws Exception {
        connection.getDispatchQueue().execute(new Task() {
            @Override
            public void run() {
                StompFrame frame = new StompFrame(DISCONNECT);
                connection.send(frame, null);
            }
        });
        connection.close(null);
    }

    protected void send(final Exchange exchange, final AsyncCallback callback) {
        final StompFrame frame = new StompFrame(SEND);
        frame.addHeader(DESTINATION, StompFrame.encodeHeader(destination));
        frame.content(utf8(exchange.getIn().getBody().toString()));

        connection.getDispatchQueue().execute(new Task() {
            @Override
            public void run() {
                connection.send(frame, new Callback<Void>() {
                    @Override
                    public void onFailure(Throwable e) {
                        exchange.setException(e);
                        callback.done(false);
                    }

                    @Override
                    public void onSuccess(Void v) {
                        callback.done(false);
                    }
                });
            }
        });
    }

    void addConsumer(final StompConsumer consumer) {
        connection.getDispatchQueue().execute(new Task() {
            @Override
            public void run() {
                StompFrame frame = new StompFrame(SUBSCRIBE);
                frame.addHeader(DESTINATION, StompFrame.encodeHeader(destination));
                frame.addHeader(ID, consumer.id);
                connection.send(frame, null);
            }
        });
        consumers.add(consumer);
    }

    void removeConsumer(final StompConsumer consumer) {
        connection.getDispatchQueue().execute(new Task() {
            @Override
            public void run() {
                StompFrame frame = new StompFrame(UNSUBSCRIBE);
                frame.addHeader(DESTINATION, StompFrame.encodeHeader(destination));
                frame.addHeader(ID, consumer.id);
                connection.send(frame, null);
            }
        });
        consumers.remove(consumer);
    }

    AsciiBuffer getNextId() {
        return connection.nextId();
    }
}


text:
package org.easyframe.tutorial.lessonb;

import java.sql.SQLException;
import java.util.Collection;

import jef.database.Condition.Operator;
import jef.database.DbUtils;
import jef.database.query.JpqlExpression;

import org.easyframe.enterprise.spring.GenericDaoSupport;
import org.easyframe.tutorial.lesson2.entity.Student;
import org.springframework.stereotype.Repository;

/**
 * 这个类实现了GenericDao<T>接口
 */
@Repository
public class StudentDaoImpl extends GenericDaoSupport<Student> implements StudentDao{

	public void gradeUp(Collection<Integer> ids) {
		Student st=new Student();
		st.getQuery().addCondition(Student.Field.id, Operator.IN, ids);
		st.prepareUpdate(Student.Field.grade, new JpqlExpression("grade+1"));
		try {
			//super.getSession()可以得到EF的Session对象
			getSession().update(st);
		} catch (SQLException e) {
			throw DbUtils.toRuntimeException(e);
		}
	}
}


text:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace EmptyKeys.UserInterface.Generator.Values
{
    /// <summary>
    /// Implements generator for DynamicResourceExtension
    /// </summary>
    public class ResourceExtGeneratorValue : IGeneratorValue
    {
        /// <summary>
        /// Gets the type of the value.
        /// </summary>
        /// <value>
        /// The type of the value.
        /// </value>
        public Type ValueType
        {
            get
            {
                return typeof(DynamicResourceExtension);
            }
        }

        /// <summary>
        /// Generates the specified parent class.
        /// </summary>
        /// <param name="parentClass">The parent class.</param>
        /// <param name="method">The method.</param>
        /// <param name="value">The value.</param>
        /// <param name="baseName">Name of the base.</param>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null)
        {
            DynamicResourceExtension dynamicResource = value as DynamicResourceExtension;
            return new CodeObjectCreateExpression("ResourceReferenceExpression", new CodePrimitiveExpression(dynamicResource.ResourceKey));
        }
    }
}


text:
import fixtures
from six.moves import mox

class MoxStubout(fixtures.Fixture):
    """Deal with code around mox and stubout as a fixture."""

    def setUp(self):
        super(MoxStubout, self).setUp()
        # emulate some of the mox stuff, we can't use the metaclass
        # because it screws with our generators
        self.mox = mox.Mox()
        self.stubs = self.mox.stubs
        self.addCleanup(self.mox.UnsetStubs)
        self.addCleanup(self.mox.VerifyAll)


text:
var express = require('express');
var router = express.Router();
var oauth = require('oauthio');
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;

var Product;
router.use(function(req, res, next) {
  Product = req.app.get('Product');
  next();
});

// get products
// disabled, INSECURE
/*router.get('/', function(req, res, next) {
	Product.find(function(err, products) {
  	if (!err) {
      return res.json(products);
    } else {
      return next(err);
    }
  });
});*/

// add product
router.post('/', function(req, res, next) {
  var newprod = new Product({
    name: 'NewProduct',
    personas: [],
    stories: [],
    permissions: {}
  });
  var userid = req.cookies.userid;
  newprod.permissions.push({
    _id: userid,
    value:10
  });
  return newprod.save(function(err) {
    if (err) { // TODO: convert to next(err)?
      return res.json({
        error: err
      });
    } else {
      return res.json(newprod);
    }
  });
});

router.param('product_id', function(req, res, next, product_id) {
  // TODO: assert product_id is an integer

  //oauth.auth('google', req.session)
  //.then(function (request_object) {
      Product.findById(product_id, function(err, product) {
//         var userid = JSON.parse(req.cookies.userid);
        if (!err) {
          req.product = product;
          // create loookup table for permissions (can't store it directly in the db, annoyingly)
          var permLookup = {};
          for (var i = 0; i < product.permissions.length; i++) {
            permLookup[product.permissions[i]._id] = product.permissions[i].value;
          }
          req.product.permLookup = permLookup;
/*
          if (!(userid in req.product.permLookup) || req.product.permLookup[userid] < 1) {
            var err = new Error("Unauthorized");
            err.status = 401;
            return next(err);
          }
*/
          return next();
        } else {
          return next(err);
        }
      });
  //});
});

// change product details
// - name
router.put('/:product_id', function(req, res, next) {
  var prod = req.product;
//   var userid = JSON.parse(req.cookies.userid);
/*
  if (!(userid in req.product.permLookup) || req.product.permLookup[userid] < 2) {
    var err = new Error("Unauthorized");
    err.status = 401;
    return next(err);
  }
*/
  if (req.body.name) {
    prod.name = req.body.name;
  }
  return prod.save(function(err) {
    if (err) {
      next(err);
    } else {
      // TODO: change products in the users db ~ db.users.find({"products.id": "550cb3c96c2de13ab1cdd5fa"}) etc...
      return res.json(prod);
    }
  });
});

// get product
router.get('/:product_id', function(req, res, next) {
  //var userid = JSON.parse(req.cookies.userid);
  // ...
  return res.json(req.product);
});

// delete product
router.delete('/:product_id', function(req, res, next) {
//   var userid = JSON.parse(req.cookies.userid);
  /*
  if (!(userid in req.product.permLookup) || req.product.permLookup[userid] < 3) {
    var err = new Error("Unauthorized");
    err.status = 401;
    return next(err);
  }
*/
  var prodId = req.product._id;
  var prodUsers = Object.keys(req.product.permLookup);
  req.product.remove(function() {
    req.app.get('User').find({_id: {$in: prodUsers}}, function(err, users) {
      if (!err && users) {
        for (var j = 0; j < users.length; j++) {
          var user = removeUserProduct(users[j], prodId);
          user.save(function(err) {
            if (err) {
              return next(err);
            }
          });
        }
        return res.json({
          success: true
        });
      } else if (err) {
        return next(err);
      } else {
        return next("Oops! Something went wrong!");
      }
    });
  });
});

function removeUserProduct(user, prodId) {
  var index = -1;
  for (var i = 0; i < user.products.length; i++) {
    if (prodId.equals(user.products[i])) {
      index = i;
    }
  }
  if (index >= 0) user.products.splice(index, 1);
  if (user.currentProduct >= user.products.length) {
    user.currentProduct = user.products.length - 1;
  }
  return user;
}

router.use('/:product_id/personas', require('./personas'));

router.use('/:product_id/stories', require('./stories'));

module.exports = router;


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

<title>bankapp.account Class Hierarchy</title>
<meta name="date" content="2017-10-20">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package bankapp.account

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

bankapp.account.Account

bankapp.account.PersonalAccount

bankapp.account.SavingsAccount

bankapp.account.PersonalAccountTest

bankapp.account.SavingsAccountTest

bankapp.account.Transaction

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
fixture_dependencies is an advanced fixture loader, allowing the loading of
models from YAML fixtures, along with their entire dependency graph.  It has
the following features:

- Fixtures specify association names instead of foreign keys
- Support both Sequel and ActiveRecord
- Supports many_to_one/belongs_to, one_to_many/has_many,
  many_to_many/has_and_belongs_to_many, and has_one/one_to_one associations
- Loads a fixture's dependency graph in such a manner that foreign key
  constraints aren't violated
- Has a very simple API (FixtureDependencies.load(:model__fixture))
- Handles almost all cyclic dependencies
- Includes Rails and Sequel test helpers for Test::Unit (and a Sequel test
  helper for RSpec) that load fixtures for every test inside a transaction,
  so fixture data is never left in your database

## Installation

```
  gem install fixture_dependencies
```

## Source

Source is available via github:

```
  http://github.com/jeremyevans/fixture_dependencies
```

You can check it out with git:

```
  git clone git://github.com/jeremyevans/fixture_dependencies.git
```

## Usage

### With Rails/ActiveRecord/Test::Unit:

Add the following to test/test_helper.rb after "require 'test_help'":

```
  require 'fixture_dependencies/test_unit/rails'
```

This overrides the default test helper to load the fixtures inside transactions
and to use FixtureDependencies to load the fixtures.

### With Sequel/Test::Unit:

Somewhere before the test code is loaded:

```
  require 'fixture_dependencies/test_unit/sequel'
```

Make sure the test case classes use FixtureDependencies::SequelTestCase:

```
  class ModelTest < FixtureDependencies::SequelTestCase
```

This runs the test cases inside a Sequel transaction.

### With Sequel/RSpec:

Somewhere before the test code is loaded:

```
  require 'fixture_dependencies/rspec/sequel'
```

This runs each spec inside a separate Sequel transaction.

### With other testing libraries:

You can just use FixtureDependencies.load to handle the loading of fixtures.
The use of transactions is up to you.  One thing you must do if you are
not using the rails test helper is to set the fixture path for
FixtureDependencies:

```
  FixtureDependencies.fixture_path = '/path/to/fixtures'
```

## Changes to Rails default fixtures:

fixture_dependencies is designed to require the least possible changes to
the default YAML fixtures used by Rails (well, at least Rails 1.2 and earlier).
For example, see the following changes:

```
  OLD                       NEW
  asset1:                   asset1:
  id: 1                     id: 1
  employee_id: 2            employee: jeremy
  product_id: 3             product: nx7010
  vendor_id: 2              vendor: lxg_computers
  note: in working order    note: in working order
```

As you can see, you just replace the foreign key attribute and value with the
name of the association and the associations name.  This assumes you have an
employee fixture with a name of jeremy, and products fixture with the name of
nx7010, and a vendors fixture with the name lxg_computers.

Fixture files still use the table_name of the model. Note that you make sure
to hard code primary key values for each fixture, as shown in the example
above.

## ERB Fixtures

Fixtures can also use ERB to preprocess the fixture file, useful if you need
to do any programming inside the fixture file, such as looping to create
multiple records.  For the ERB support to be invoked, your fixture file
should be named #{table_name}.yml.erb instead of #{table_name}.yml. You can
mix ERB fixture files and regular fixture files, but you can not have an
ERB fixture file and a regular fixture file for the same table (the regular
fixture file will be used in that case).

## Changes to the fixtures Class Method:

fixture_dependencies can still use the fixtures class method in your test:

```
  class EmployeeTest < Test::Unit::TestCase
    fixtures :assets
  end
```

In Rails default testing practices, the arguments to fixtures are table names.
fixture_dependencies changes this to underscored model names.  If you are using
Rails' recommended table practices, this shouldn't make a difference.

It is recommended that you do not use the fixtures method, and instead load
individual fixtures as needed (see below).  This makes your tests much more
robust, in case you want to add or remove individual fixtures at a later date.

## Loading individual fixtures with fixtures class method

There is support for loading individual fixtures (and just their dependencies),
using the following syntax:

```
  class EmployeeTest < Test::Unit::TestCase
    fixtures :employee__jeremy # Note the double underscore
  end
```

This would load just the jeremy fixture and its dependencies.  I find this is
much better than loading all fixtures in most of my test suites.  Even better
is loading just the fixtures you want inside every test method (see below).
This leads to the most robust testing.

## Loading fixtures inside test methods

I find that it is often better to skip the use of the fixtures method entirely,
and load the fixtures I want manually in each test method.  This provides for
the loosest coupling possible.  Here's an example:

```
  class EmployeeTest < Test::Unit::TestCase
    def test_employee_name
      # Load the fixture and return the Employee object
      employee = load(:employee__jeremy)
      # Test the employee
    end

    def test_employees
      # Load the fixtures and return two Employee objects
      employee1, employee2 = load(:employees=>[:jeremy, :karl])
      # Test the employees
    end

    def test_award_statistics
      #  Load all fixtures in both tables
      load(:employee_award__jeremy_first, :award__first)
      # Test the award_statistics method
      #  (which pulls data from the tables loaded above)
    end
  end
```

Don't worry about loading the same fixture twice, if a fixture is already
loaded, it won't attempt to load it again.

## one_to_many/many_to_many/has_many/has_and_belongs_to_many assocations

Here's an example of using has_one (logon_information), has_many (assets), and
has_and_belongs_to_many (groups) associations.

```
  jeremy:
  id: 2
  name: Jeremy Evans
  logon_information: jeremy
  assets: [asset1, asset2, asset3]
  groups: [group1]
```

`logon_information` is a has_one association to another table which was split
from the employees table due to database security requirements.  Assets is a
has_many association, where one employee is responsible for the asset.
Employees can be a member of multiple groups, and each group can have multiple
employees.

For `has_*` associations, after fixture_dependencies saves jeremy, it will load
and save logon_information (and its dependencies...), it will load each asset
in the order specified (and their dependencies...), and it will load all of the
groups in the order specified (and their dependencies...).  Note that there
is only a load order inside a specific association, associations are stored
in the same hash as attributes and are loaded in an arbitrary order.

## many_to_many/has_and_belongs_to_many join table fixtures

Another change is that Rails defaults allow you to specify habtm join tables in
fixtures.  That doesn't work with fixture dependencies, as there is no
associated model.  Instead, you use a has_and_belongs_to_many association name
in the the appropriate model fixtures (see above).

## belongs_to/many_to_one polymorphic fixtures

ActiveRecord supports polymorphic associations by default. With Sequel, this
is made via the `sequel_polymorphic` gem.

Here the mapping in Rails:

```
class Animal < ActiveRecord::Base
  has_many :fruits, as: :eater
end
class Fruit < ActiveRcord::Base
  belongs_to :eater, polymorphic: true
end
```

And here on Sequel:

```
require 'sequel_polymorphic'
class Animal < Sequel::Model
  plugin :polymorphic
  ony_to_many :fruits, as: :eater
end
class Fruit < Sequel::Model
  plugin :polymorphic
  many_to_one :eater, polymorphic: true
end
```

In both cases, the fixtures looks like:

`animals.yml`:

```
george:
  id: 1
  name: George
```

`fruits.yml`:

```
apple:
  id: 1
  name: Apple
  eater: george (Animal)
```

In your test, use something like this:

```
apple = load(:fruit__apple)
apple.eater.name.must_equal "George"
```

fixture_dependencies will set the `eater` association in `Fruit` instance `george` instance of `Animal`.

## Cyclic dependencies

fixture_dependencies handles almost all cyclic dependencies.  It handles all
has_many, has_one, and habtm cyclic dependencies.  It handles all
self-referential cyclic dependencies.  It handles all belongs_to cyclic
dependencies except the case where there is a NOT NULL or validates_presence of
constraint on the cyclic dependency's foreign key.

For example, a case that won't work is when employee belongs_to supervisor
(with a NOT NULL or validates_presence_of constraint on supervisor_id), and
john is karl's supervisor and karl is john's supervisor. Since you can't create
john without a valid supervisor_id, you need to create karl first, but you
can't create karl for the same reason (as john doesn't exist yet).

There isn't a generic way to handle the belongs_to cyclic dependency, as far as
I know.  Deferring foreign key checks could work, but may not be enabled (and
one of the main reasons to use the plugin is that it doesn't require them).
For associations like the example above (employee's supervisor is also an
employee), setting the foreign_key to the primary key and then changing it
later is an option, but database checks may prevent it.  For more complex
cyclic dependencies involving multiple model classes (employee belongs_to
division belongs_to head_of_division when the employee is a member of the
division and also the head of the division), even that approach is not
possible.

## Known issues

Currently, the plugin only supports YAML fixtures, but other types of fixtures
would be fairly easy to add (send me a patch if you add support for another
fixture type).

The plugin is significantly slower than the default testing method, because it
loads all fixtures inside of a transaction (one per test method), where Rails
defaults to loading the fixtures once per test suite (outside of a
transaction), and only deletes fixtures from a table when overwriting it with
new fixtures.

Instantiated fixtures are not available with this plugin.  Instead, you should
use load(:model__fixture_name).

## Namespace Issues

By default, fixture dependencies is going to load the model with the camelized
name in the symbol used.  So for :foo_bar__baz, it's going to look for
the fixture with name baz for the model FooBar.  If your model is namespaced,
such as Foo::Bar, this isn't going to work well.  In that case, you can
override the default mapping:

```
  FixtureDependencies.class_map[:bar] = Foo::Bar
```

and then use :bar__baz to load the fixture with name baz for the model
Foo::Bar.

## Troubleshooting

If you run into problems with loading your fixtures, it can be difficult to see
where the problems are.  To aid in debugging an error, add the following to
test/test_helper.rb:

```
  FixtureDependencies.verbose = 3
```

This will give a verbose description of the loading and saving of fixtures for
every test, including the recursive loading of the dependency graph.

## Specs

The specs for fixture dependencies and be run with Rake.  They require
the sequel, activerecord, and sqlite3 gems installed.  The default rake task
runs the specs.  You should run the spec_migrate task first to create the
spec database.

## Similar Ideas

Rails now supports something similar by default.  Honestly, I'm not sure what
the differences are.

fixture_references is a similar plugin.  It uses erb inside yaml, and uses the
foreign key numbers inside of the association names, which leads me to believe
it doesn't support has_* associations.

## License

fixture_dependencies is released under the MIT License.  See the MIT-LICENSE
file for details.

## Author

Jeremy Evans <code@jeremyevans.net>


text:
package nucleus.presenter.delivery;

import rx.Notification;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;

public class DeliverLatestCache<View, T> implements Observable.Transformer<T, Delivery<View, T>> {

    private final Observable<View> view;

    public DeliverLatestCache(Observable<View> view) {
        this.view = view;
    }

    @Override
    public Observable<Delivery<View, T>> call(Observable<T> observable) {
        return Observable
            .combineLatest(
                view,
                observable
                    .materialize()
                    .filter(new Func1<Notification<T>, Boolean>() {
                        @Override
                        public Boolean call(Notification<T> notification) {
                            return !notification.isOnCompleted();
                        }
                    }),
                new Func2<View, Notification<T>, Delivery<View, T>>() {
                    @Override
                    public Delivery<View, T> call(View view, Notification<T> notification) {
                        return view == null ? null : new Delivery<>(view, notification);
                    }
                })
            .filter(new Func1<Delivery<View, T>, Boolean>() {
                @Override
                public Boolean call(Delivery<View, T> delivery) {
                    return delivery != null;
                }
            });
    }
}


text:
module Coffeebox
  class Engine < ::Rails::Engine
  end
end


text:
package com.acl.ax.datasource.core;

public enum FormatStyle {
	ACLStyle, //description is description
	DLStyle;  //description is NOT a description
	public static int MaxTableNameLength = 30;
	public static final String TableFieldConjunctor = "_";
}


text:
package com.ctrip.zeus.model.model;

public class ConditionRuleAttribute {
    private Condition m_condition;

    private ConditionAction m_conditionAction;

    public ConditionRuleAttribute() {
    }

    protected boolean equals(Object o1, Object o2) {
        if (o1 == null) {
            return o2 == null;
        } else if (o2 == null) {
            return false;
        } else {
            return o1.equals(o2);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof ConditionRuleAttribute) {
            ConditionRuleAttribute _o = (ConditionRuleAttribute) obj;

            if (!equals(m_condition, _o.getCondition())) {
                return false;
            }

            if (!equals(m_conditionAction, _o.getConditionAction())) {
                return false;
            }

            return true;
        }

        return false;
    }

    public Condition getCondition() {
        return m_condition;
    }

    public ConditionAction getConditionAction() {
        return m_conditionAction;
    }

    @Override
    public int hashCode() {
        int hash = 0;

        hash = hash * 31 + (m_condition == null ? 0 : m_condition.hashCode());
        hash = hash * 31 + (m_conditionAction == null ? 0 : m_conditionAction.hashCode());

        return hash;
    }

    public ConditionRuleAttribute setCondition(Condition condition) {
        m_condition = condition;
        return this;
    }

    public ConditionRuleAttribute setConditionAction(ConditionAction conditionAction) {
        m_conditionAction = conditionAction;
        return this;
    }

}


text:
<?php

/**
 * This class is accountable of classes autoloading
 */
class Autoloader {

  /**
   * Registers autoloading methods
   */
  public function register() {
    spl_autoload_register(array($this, 'autoload_core'));
    spl_autoload_register(array($this, 'autoload_checks'));
  }

  /**
   * Generic loading by filename
   *
   * @param string $_fl
   */
  protected function _autoload($_fl) {
    if (file_exists($_fl)) {
      include_once $_fl;
    }
  }

  /**
   * Autoloads core classes
   *
   * @param string $classname
   */
  public function autoload_core($classname) {
    $this->_autoload('includes/core/' . $classname . '.php');
  }

  /**
   * Autoloads check classes
   *
   * @param string $classname
   */
  public function autoload_checks($classname) {
    $this->_autoload('includes/checks/' . $classname . '.php');
  }

}


text:
package org.sakaiproject.profile2.tool.pages.panels;

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

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.extensions.markup.html.form.palette.Palette;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.CollectionModel;
import org.apache.wicket.model.util.ListModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.profile2.logic.ProfileWorksiteLogic;
import org.sakaiproject.profile2.logic.SakaiProxy;
import org.sakaiproject.profile2.model.Person;
import org.sakaiproject.profile2.tool.components.ErrorLevelsFeedbackMessageFilter;
import org.sakaiproject.profile2.tool.components.IconWithClueTip;
import org.sakaiproject.profile2.util.ProfileConstants;
import org.sakaiproject.profile2.util.ProfileUtils;
import static org.sakaiproject.site.api.SiteService.SITE_TITLE_MAX_LENGTH;
import org.sakaiproject.site.api.SiteService.SiteTitleValidationStatus;

/**
 * Panel for creating a worksite from a group of people.
 *
 * @author d.b.robinson@lancaster.ac.uk
 */
public class CreateWorksitePanel extends Panel {

	private static final long serialVersionUID = 1L;

	@SpringBean(name="org.sakaiproject.profile2.logic.ProfileWorksiteLogic")
	private ProfileWorksiteLogic worksiteLogic;

	@SpringBean(name="org.sakaiproject.profile2.logic.SakaiProxy")
	private SakaiProxy sakaiProxy;

	/**
	 * Creates an instance of CreateWorksitePanel.
	 *
	 * @param id the wicket id.
	 * @param persons list of users e.g. from connections (and possibly search
	 *            results in the future).
	 */
	public CreateWorksitePanel(final String id, final List<Person> persons) {
		super(id);

		// sort persons
		Collections.sort(persons);

		Form<Void> form = new Form<Void>("form");
		form.setOutputMarkupId(true);
		add(form);

		// form submit feedback
		final Label formFeedback = new Label("formFeedback");
		formFeedback.setOutputMarkupPlaceholderTag(true);
		form.add(formFeedback);

		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		form.add(feedback);

		int[] filteredErrorLevels = new int[] { FeedbackMessage.ERROR };
		feedback.setFilter(new ErrorLevelsFeedbackMessageFilter(
				filteredErrorLevels));

		IChoiceRenderer<Person> renderer = new ChoiceRenderer<Person>("displayName", "uuid");

		final Palette<Person> palette = new Palette<Person>("palette", new ListModel<Person>(
				new ArrayList<Person>()), new CollectionModel<Person>(persons), renderer, 10, true);
		palette.setOutputMarkupId(true);

		form.add(palette);

		Label siteNameLabel = new Label("siteNameLabel", new ResourceModel("worksite.name"));
		form.add(siteNameLabel);

		final TextField<String> siteNameField = new TextField<String>("siteNameField", new Model<String>());
		siteNameField.setOutputMarkupId(true);
		form.add(siteNameField);

		AjaxButton cancelButton = new AjaxButton("cancelButton") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

				resetPanel(target, siteNameField, palette, formFeedback);

			}
		};
		cancelButton.setModel(new ResourceModel("button.worksite.cancel"));
		form.add(cancelButton);

		IndicatingAjaxButton createButton = new IndicatingAjaxButton("createButton", form) {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

				// Site title is editable; cannot but null/empty after HTML stripping, and cannot exceed max length
				String titleOrig = siteNameField.getValue();
				String titleStripped = ProfileUtils.stripHtmlFromText(titleOrig, true, true);
				SiteTitleValidationStatus status = sakaiProxy.validateSiteTitle(titleOrig, titleStripped);

				boolean titleError = false;
				IModel errorMsg = null;
				if (SiteTitleValidationStatus.STRIPPED_TO_EMPTY.equals(status)) {
					errorMsg = new ResourceModel("error.worksite.title.htmlStrippedToEmpty");
					titleError = true;
				} else if (SiteTitleValidationStatus.EMPTY.equals(status)) {
					errorMsg = new ResourceModel("error.worksite.no.title");
					titleError = true;
				} else if (SiteTitleValidationStatus.TOO_LONG.equals(status)) {
					errorMsg = new StringResourceModel("error.worksite.title.maxLength", null, new Object[] {SITE_TITLE_MAX_LENGTH});
					titleError = true;
				}

				if (titleError) {
					formFeedback.setDefaultModel(errorMsg);
					formFeedback.add(new AttributeModifier("class", true, new Model<>("alertMessage")));
					target.add(formFeedback);
					return;
				}

				if (true == worksiteLogic.createWorksite(titleStripped, sakaiProxy.getCurrentUserId(),
						new ArrayList<Person>(palette.getModelCollection()),
						true)) {

					resetPanel(target, siteNameField, palette, formFeedback);

				} else {
					formFeedback.setDefaultModel(new ResourceModel(
							"error.worksite.create.failed"));
					formFeedback.add(new AttributeModifier("class", true,
							new Model<String>("alertMessage")));
					target.add(formFeedback);
					return;
				}
			}

		};
		createButton.setModel(new ResourceModel("button.worksite.create"));
		form.add(createButton);

		form.add(new IconWithClueTip("createWorksiteToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("text.worksite.create")));

		Label refreshLabel = new Label("refreshLabel", new ResourceModel("text.worksite.refresh"));
		form.add(refreshLabel);
	}

	// clears site name field and palette, and slides up
	private void resetPanel(AjaxRequestTarget target,
			final TextField<String> siteNameField,
			final Palette<Person> palette, Label formFeedback) {

		siteNameField.setModelObject("");

		// there is quite possibly a better way of doing this
		List<Person> remove = new ArrayList<Person>();
		for (Person person : palette.getModelCollection()) {
			remove.add(person);
		}
		palette.getModelCollection().removeAll(remove);

		formFeedback.setVisible(false);

		target.add(siteNameField);
		target.appendJavaScript("$('#" + CreateWorksitePanel.this.getMarkupId()
				+ "').slideUp();");
		target.appendJavaScript("fixWindowVertical();");
	}
}


text:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using MS.Internal.PresentationCore;
#if PRESENTATION_CORE
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
#else
using SR=System.Windows.SR;
using SRID=System.Windows.SRID;
#endif

namespace System.Windows
{
    internal static partial class ValidateEnums
    {
        /// <summary>
        ///     Returns whether or not an enumeration instance a valid value.
        ///     This method is designed to be used with ValidateValueCallback, and thus
        ///     matches it's prototype.
        /// </summary>
        /// <param name="valueObject">
        ///     Enumeration value to validate.
        /// </param>
        /// <returns> 'true' if the enumeration contains a valid value, 'false' otherwise. </returns>
        public static bool IsTextDecorationLocationValid(object valueObject)
        {
            TextDecorationLocation value = (TextDecorationLocation) valueObject;

            return (value == TextDecorationLocation.Underline) ||
                   (value == TextDecorationLocation.OverLine) ||
                   (value == TextDecorationLocation.Strikethrough) ||
                   (value == TextDecorationLocation.Baseline);
        }
    }
}


text:
package io.github.revned77.tiles;

import java.util.Arrays;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;

/** A common entry point to both the slice and splice actions. */
public class TileSlicer {

  public static void main(String[] args) throws Exception {
    if (args.length > 0 && args[0].equals("slice")) {
      Slicer slicer = new Slicer();
      if (tryInjectArgs(slicer, args)) {
        slicer.run();
      }
    } else if (args.length > 0 && args[0].equals("splice")) {
      Splicer splicer = new Splicer();
      if (tryInjectArgs(splicer, args)) {
        splicer.run();
      }
    } else {
      System.err.println("Usage:");
      System.err.println("java TileSlicer slice ...");
      System.err.println("java TileSlicer splice ...");
    }
  }

  private static boolean tryInjectArgs(Object o, String[] args) {
    CmdLineParser parser = new CmdLineParser(o);
    parser.setUsageWidth(80);
    try {
      parser.parseArgument(Arrays.copyOfRange(args, 1, args.length));
      return true;
    } catch (CmdLineException e) {
      System.err.println(e.getMessage());
      parser.printUsage(System.err);
      System.err.println();
      return false;
    }
  }
}


text:
import threading

from flask import Flask, request
from flask_cors import CORS

from motey.communication.api_routes.capabilities import Capabilities
from motey.communication.api_routes.nodes import Nodes
from motey.communication.api_routes.nodestatus import NodeStatus
from motey.communication.api_routes.service import Service
from motey.utils.heartbeat import register_callback, register_heartbeat

class APIServer(object):
    """
    Starts a Flask webserver which acts as an REST API to control the Motey service.
    The webserver runs in a separate thread and will not block the main thread.
    """

    def __init__(self, logger, host='127.0.0.1', port=5023):
        """
        Constructor of the webserver.

        :param logger: the DI injected logger instance
        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
                     have the server available externally as well. Defaults to
                     ``'127.0.0.1'``.
        :param port: the port of the webserver. Defaults to ``5023``.
        """
        self.host = host
        self.port = port
        self.logger = logger
        self.webserver = Flask(__name__)
        CORS(self.webserver)
        self.configure_url()
        self.run_server_thread = threading.Thread(target=self.run_server, args=())
        self.run_server_thread.daemon = True

    def start(self):
        """
        Starts the execution thread.
        """
        self.run_server_thread.start()

    def run_server(self):
        """
        Starts the server and add an info to the logs, that the webserver is started.
        """
        self.logger.info('Webserver started')
        self.webserver.run(host=self.host, port=self.port, use_reloader=False)

    def configure_url(self):
        """
        Adds all the configured api endpoints.
        """
        self.webserver.add_url_rule('/v1/capabilities', view_func=Capabilities.as_view('capabilities'))
        self.webserver.add_url_rule('/v1/nodestatus', view_func=NodeStatus.as_view('nodestatus'))
        self.webserver.add_url_rule('/v1/service', view_func=Service.as_view('service'))
        self.webserver.add_url_rule('/v1/nodes', view_func=Nodes.as_view('nodes'))
        register_callback(self.check_heartbeat)
        register_heartbeat(self.webserver)

    def is_running(self):
        """
        Checks if the webserver is still running.
        :return: True if the server is running, otherwise False.
        """
        return request.environ.get('werkzeug.server.shutdown') is not None

    def stop(self):
        """
        Stops the webserver and add an info the logs, that the webserver is stopped.
        """
        self.logger.info('Webserver stopped')

    def check_heartbeat(self):
        """
        Method to get the heartbeat.
        Checks if all the requirements for a healthy webserver are fulfilled.
        :return: True if the service is in a healthy state, otherwise False.
        """
        return self.is_running()


text:
package org.zstack.network.service;

import org.zstack.core.db.Q;
import org.zstack.header.Component;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.network.l3.IpRangeInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.service.NetworkServiceProviderType;
import org.zstack.header.network.service.NetworkServiceType;
import org.zstack.header.network.service.NetworkServiceSnatBackend;
import org.zstack.header.network.service.SnatStruct;
import org.zstack.header.vm.*;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: frank
 * Time: 10:04 PM
 * To change this template use File | Settings | File Templates.
 */
public class SnatExtension extends AbstractNetworkServiceExtension implements Component {
    private final static CLogger logger = Utils.getLogger(SnatExtension.class);

    private Map<NetworkServiceProviderType, NetworkServiceSnatBackend> snatBackends = new HashMap<NetworkServiceProviderType, NetworkServiceSnatBackend>();

    private final String RESULT = String.format("result.%s", SnatExtension.class.getName());

    @Override
    public NetworkServiceType getNetworkServiceType() {
        return NetworkServiceType.SNAT;
    }

    private void doSnat(final Iterator<Map.Entry<NetworkServiceSnatBackend, List<SnatStruct>>> it, final VmInstanceSpec spec, final Completion complete) {
        if (!it.hasNext()) {
            complete.success();
            return;
        }

        Map.Entry<NetworkServiceSnatBackend, List<SnatStruct>> e = it.next();
        NetworkServiceSnatBackend bkd = e.getKey();
        List<SnatStruct> structs = e.getValue();
        bkd.applySnatService(structs, spec, new Completion(complete) {
            @Override
            public void success() {
                doSnat(it, spec, complete);
            }

            @Override
            public void fail(ErrorCode errorCode) {
                complete.fail(errorCode);
            }
        });
    }

    @Override
    public void applyNetworkService(VmInstanceSpec spec, Map<String, Object> data, Completion complete) {
        Map<NetworkServiceSnatBackend, List<SnatStruct>> entries = workoutSnat(spec);
        data.put(RESULT, entries);
        doSnat(entries.entrySet().iterator(), spec, complete);
    }

    @Override
    public void releaseNetworkService(VmInstanceSpec spec, Map<String, Object> data, NoErrorCompletion completion) {
        // never release source nat. once SNAT service is enabled on l3Network, it stays alive all the time
        // during virtual router life cycle. vm stop/destroy won't effect as SNAT is shared by all vms on this
        // network
        completion.done();
    }

    private void populateExtensions() {
        for (NetworkServiceSnatBackend extp : pluginRgty.getExtensionList(NetworkServiceSnatBackend.class)) {
            NetworkServiceSnatBackend old = snatBackends.get(extp.getProviderType());
            if (old != null) {
                throw new CloudRuntimeException(String.format("duplicate NetworkServiceSnatBackend[%s, %s] for type[%s]",
                        extp.getClass().getName(), old.getClass().getName(), extp.getProviderType()));
            }
            snatBackends.put(extp.getProviderType(), extp);
        }
    }

    private SnatStruct makeSnatStruct(VmInstanceSpec spec, L3NetworkInventory l3) {
        VmNicInventory nic = null;
        for (VmNicInventory inv : spec.getDestNics()) {
            if (VmNicHelper.getL3Uuids(inv).contains(l3.getUuid())){
                nic = inv;
                break;
            }
        }

        SnatStruct struct = new SnatStruct();
        struct.setL3Network(l3);
        struct.setGuestGateway(nic.getGateway());
        struct.setGuestIp(nic.getIp());
        struct.setGuestMac(nic.getMac());
        struct.setGuestNetmask(nic.getNetmask());
        return struct;
    }

    private Map<NetworkServiceSnatBackend, List<SnatStruct>> workoutSnat(VmInstanceSpec spec) {
        Map<NetworkServiceSnatBackend, List<SnatStruct>> map = new HashMap<NetworkServiceSnatBackend, List<SnatStruct>>();
        Map<NetworkServiceProviderType, List<L3NetworkInventory>> providerMap = getNetworkServiceProviderMap(NetworkServiceType.SNAT,
                VmNicSpec.getL3NetworkInventoryOfSpec(spec.getL3Networks()));

        for (Map.Entry<NetworkServiceProviderType, List<L3NetworkInventory>> e : providerMap.entrySet()) {
            NetworkServiceProviderType ptype = e.getKey();
            List<SnatStruct> lst = new ArrayList<SnatStruct>();

            for (L3NetworkInventory l3 : e.getValue()) {
                lst.add(makeSnatStruct(spec, l3));
            }

            NetworkServiceSnatBackend bkd = snatBackends.get(ptype);
            if (bkd == null) {
                throw new CloudRuntimeException(String.format("unable to find NetworkServiceSnatBackend[provider type: %s]", ptype));
            }

            if (logger.isTraceEnabled()) {
                logger.trace(String.format("SNAT Backend[%s] is about to apply entries: \n%s", bkd.getClass().getName(), lst));
            }

            map.put(bkd, lst);
        }

        return map;
    }

    @Override
    public boolean start() {
        populateExtensions();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}


text:
function doAtReady() {
	$(function () {
	if ($("#right-float").length > 0){
      var res = "";
      $("div#post-content h1, div#post-content h2, div#post-content h3, div#post-content h4, div#post-content h5, div#post-content h6").each(function(){res = res + '
' + $(this).html() + '
';});
	  $('#right-float').html($('#right-float').html() + '

ToC

' + res + '
');
      //$('#right-float').stickUp();
	}
    if ($("#comments").length != 0) {
        $("#back-to-comment").fadeOut();
    } else {
        $("#back-to-comment").fadeIn();
	}
	});
	/*
	$("a[href='"+location.pathname+"']").addClass('active');
	$("li[data='"+location.pathname+"']").addClass('active');
	$("a[href~='"+location.pathname+"']").removeClass('active');
	$("li[data~='"+location.pathname+"']").removeClass('active');
	*/
	MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}

function jumpToNewPage(href, ifscroll) {
  reg = new RegExp("(.|\\n)*", "gm");
  DISQUS=null;
  NProgress.start();
  $.get(href, function(data){
	$(".content").html(data.match(reg));
	$("title").html(data.match(/<title>(.|\n)*<\/title>/gm)[0].slice(7,-8));
	NProgress.done();
	history.pushState(location.href, null, href);
	doAtReady();
	if (ifscroll) {
	  $('body,html').animate({scrollTop:0},1000);
	}
    $("a").on("click", function(event) {
	  //alert(event.toElement.pathname + '\n' + location.pathname);
      if (event.toElement.pathname != location.pathname) {
  	      //alert("jump -> " + location.pathname);
		  $("a").off("click");
	      jumpToNewPage(event.toElement.href, true);
	      return false;
      }
    });
  });
}

window.onpopstate = function(event) {
  reg = new RegExp("(.|\\n)*", "gm");
  $.get(event.state, function(data){$(".content").html(data.match(reg));});
};

$(document).ready(function(){
	NProgress.configure({ easing: 'ease', speed: 500 });
    $("#back-to-top").hide();
    $(function () {
    $(window).scroll(function(){
        if ($(window).scrollTop()>200){
            $("#back-to-top").fadeIn(500);
        }
        else{
            $("#back-to-top").fadeOut(500);
        }
    });

    $("#back-to-top").click(function(){
        $('body,html').animate({scrollTop:0},1000);
            return false;
        });
    $("#back-to-comment").click(function(){
        $('body,html').animate({scrollTop:$("#comments").offset().top},1000);
            return false;
        });
    if ($("#comments").length == 0) {
        $("#back-to-comment").hide();
    }
    });
$("a").on("click", function(event) {
  //alert(event.toElement.pathname + '\n' + location.pathname);
  if (event.toElement.pathname != location.pathname) {
	  jumpToNewPage(event.toElement.href, true);
	  return false;
  }
});
	doAtReady();
});