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

package org.apache.tapestry5.integration.app1;

import org.testng.annotations.Test;

/**
 * Tests for various Ajax related components, mixins and behaviors.
 */
public class AjaxTests extends App1TestCase
{
    @Test
    public void autocomplete_mixin()
    {
        openLinks("Autocomplete Mixin Demo");

        // And that's as far as we can go currently, because
        // of limitations in Selenium 0.8.3 and bugs in Selenium 0.9.2.

        // also test Autocomplete with context

    }

    @Test
    // TAP5-2440
    public void autocomplete_mixin_on_required_field()
    {
        openLinks("Autocomplete Mixin Demo");

        typeKeys("required", "foo");

        clickAndWait(SUBMIT);

        assertTextPresent("required: foo");
    }

    @Test
    public void form_fragment()
    {
        openLinks("Form Fragment Demo", "Clear Errors");

        type("name", "Fred");

        // Put a value into the sub field, then hide it ...
        type("sub", "subvalue");

        // Really, you can't type in the field because it is not visible, but
        // this checks that invisible fields are not processed.
        type("email", "this field is ignored");

        clickAndWait(SUBMIT);

        assertText("name", "Fred");
        assertText("email", "");

        clickAndWait("link=Back");
        clickAndWait("link=Clear Errors");

        click("subscribeToEmail");
        click("on");

        // Type a value into the "always submit" field ...
        type("sub", "subvalue");

        // And the other fields ...
        type("name", "Barney");
        type("email", "rubble@bedrock.gov");
        type("code", "ABC123");

        // Now turn off the fragment for the "code" field
        click("off");

        // And hide the subcode fields (but they still always submit)
        click("subVisible");

        clickAndWait(SUBMIT);

        assertText("name", "Barney");
        assertText("email", "rubble@bedrock.gov");
        assertText("code", "");

        // .. but it still gets submitted, thanks to alwyassubmit=true
        assertText("sub", "subvalue");
    }

    //TAP5-1551 - triggering hide on the inner fragment was also hiding the outer fragment
    @Test
    public void nested_form_fragment()
    {
        openLinks("Nested Form Fragment Demo");

        assertTrue(isVisible("outertext1"));
        assertTrue(isVisible("innertext1"));
        assertTrue(isChecked("innertrigger1"));

        click("innertrigger1");

        assertTrue(isVisible("outertext1"));
        assertFalse(isVisible("innertext1"));
    }

    /**
     * Disabled; the functionality was not well thought out and has been removed; something similar may replace it
     * in the future.
     */
    @Test(enabled = false)
    public void form_fragment_explicit_visible_bounds()
    {
        openLinks("Form Fragment Explicit Visible Bounds Demo");

        //make sure we're on tab 1...
        switchTabs(1);
        type("value1", "Some text to check");
        switchTabs(2);

        type("value2", "Some other text to check");

        clickAndWait("saveform");

        assertTrue(isVisible("tab2"));

        assertFieldValue("value2", "Some other text to check");

        switchTabs(1);

        assertFieldValue("value1", "Some text to check");

        //make sure they don't save if not revealed...
        type("value1", "new text that shouldn't save");
        click("frag1check");
        waitForInvisible("value1");

        clickAndWait("saveform");
        assertTrue(isVisible("tab1"));
        assertFalse(isVisible("value1"));
        click("frag1check");
        waitForVisible("value1");
        assertFieldValue("value1", "Some text to check");

        switchTabs(2);
        assertFieldValue("value2", "Some other text to check");
        clickAndWait("link=Clear Saved State");
    }

    @Test(enabled = false)
    public void form_fragment_visible_bound_validation()
    {
        openLinks("Form Fragment Explicit Visible Bounds Demo");
        //make sure we're on the correct tab...
        switchTabs(1);
        //and that value1 is blank...
        type("value1", "");
        assertFieldValue("value1", "");
        //submitting should result in error in value1...
        click("saveform");
        assertTextPresent("You must provide a value for Value1.");

        //still wind up being able to submit here b/c there's no (good) way to highlight the error in the invisible tab.
        //but the form should return with errors.
        switchTabs(2);
        clickAndWait("saveform");
        assertTextPresent("You must provide a value for Value1.");

        switchTabs(1);
        click("frag1check");
        waitForInvisible("value1");

        clickAndWait("saveform");
        assertFalse(isTextPresent("You must provide a value for Value1."));

        switchTabs(1);
        clickAndWait("saveform");
        assertFalse(isTextPresent("You must provide a value for Value1."));
        clickAndWait("link=Clear Saved State");
    }

    private void switchTabs(int tab)
    {
        click("link=Show Tab " + tab);
        waitForVisible("tab" + tab);
    }

    @Test
    public void ajax_form_loop()
    {
        openLinks("FormInjector Demo");

        assertText("sum", "0.0");

        click("link=Add another value");

        waitForAjaxRequestsToComplete();

        type("//input[@type='text'][1]", "5.1");

        clickAndWait(SUBMIT);

        assertText("sum", "5.1");

        click("link=remove");

        waitForAjaxRequestsToComplete();

        clickAndWait(SUBMIT);

        assertText("sum", "0.0");
    }

    @Test
    public void remove_ajaxformloop_values_using_buttons_with_nested_elements()
    {
        openLinks("FormInjector Demo");

        assertText("sum", "0.0");

        click("link=Add another value");

        waitForAjaxRequestsToComplete();

        type("//input[@type='text'][1]", "5.1");

        clickAndWait(SUBMIT);

        assertText("sum", "5.1");

        click("css=.glyphicon-trash");

        waitForAjaxRequestsToComplete();

        clickAndWait(SUBMIT);

        assertText("sum", "0.0");
    }

    /**
     * TAP5-240
     */
    @Test
    public void ajax_server_side_exception()
    {
        openLinks("Zone Demo");

        click("link=Failure on the server side");

        // Not more more testing can be done; there's no client-side console
        // because Tapestry now favors the native console (when present),
        // and the iframe containing the server-side Ajax exception is opaque.
    }

    /**
     * TAP5-236
     */
    @Test
    public void progressive_display()
    {
        openLinks("ProgressiveDisplay Demo");

        waitForElementToAppear("content1");
        assertText("content1", "Progressive Display content #1.");

        waitForElementToAppear("content2");
        assertText("content2", "Music Library");
    }

    /**
     * TAP5-2458
     */
    @Test
    public void redirect_from_page_activation_method()
    {
        openLinks("OnActivateRedirect Demo");

        clickAndWait("link");

        assertText("message", "Redirected from XHR");
    }

    /**
     * TAP5-2397
     */
    @Test
    public void add_datefield_in_ajaxformloop()
    {
        openLinks("DateField inside AjaxFormLoop");

        click("link=Add row");

        waitForAjaxRequestsToComplete();

        // now the datefield module is loaded and dom.scanner has been invoked
        // the second insertion is problematic

        click("css=.glyphicon-minus-sign");

        click("link=Add row");

        waitForAjaxRequestsToComplete();

        click("css=.glyphicon-calendar");

        assertTextPresent("Today");

    }

    @Test
    public void publishevent() throws InterruptedException
    {
        openLinks("@PublishEvent Demo");

        waitForAjaxRequestsToComplete();

        final String template = "//table/tbody/tr[%d]/td[%d]";

        for (int i = 1; i <= 8; i++) {
            assertEquals(
                    getText(String.format(template, i, 3)),
                    getText(String.format(template, i, 4)),
                    "Row " + i);
        }

//        // An ugly way of giving time for all the AJAX requests to finish
//        // without adding more JavaScript for that.
//        Thread.sleep(3000);
    }

}


text:
<?php

namespace Drupal\taxonomy\Plugin\migrate;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\Plugin\MigrationDeriverTrait;
use Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Deriver for Drupal 7 taxonomy term migrations based on vocabularies.
 */
class D7TaxonomyTermDeriver extends DeriverBase implements ContainerDeriverInterface {
  use MigrationDeriverTrait;

  /**
   * The base plugin ID this derivative is for.
   *
   * @var string
   */
  protected $basePluginId;

  /**
   * Already-instantiated cckfield plugins, keyed by ID.
   *
   * @var \Drupal\migrate_drupal\Plugin\MigrateCckFieldInterface[]
   */
  protected $cckPluginCache;

  /**
   * The CCK plugin manager.
   *
   * @var \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface
   */
  protected $cckPluginManager;

  /**
   * D7TaxonomyTermDeriver constructor.
   *
   * @param string $base_plugin_id
   *   The base plugin ID for the plugin ID.
   * @param \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface $cck_manager
   *   The CCK plugin manager.
   */
  public function __construct($base_plugin_id, MigrateCckFieldPluginManagerInterface $cck_manager) {
    $this->basePluginId = $base_plugin_id;
    $this->cckPluginManager = $cck_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $base_plugin_id,
      $container->get('plugin.manager.migrate.cckfield')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $fields = [];
    try {
      $source_plugin = static::getSourcePlugin('d7_field_instance');
      $source_plugin->checkRequirements();

      // Read all field instance definitions in the source database.
      foreach ($source_plugin as $row) {
        if ($row->getSourceProperty('entity_type') == 'taxonomy_term') {
          $fields[$row->getSourceProperty('bundle')][$row->getSourceProperty('field_name')] = $row->getSource();
        }
      }
    }
    catch (RequirementsException $e) {
      // If checkRequirements() failed then the field module did not exist and
      // we do not have any fields. Therefore, $fields will be empty and below
      // we'll create a migration just for the node properties.
    }

    $vocabulary_source_plugin = static::getSourcePlugin('d7_taxonomy_vocabulary');
    try {
      $vocabulary_source_plugin->checkRequirements();
    }
    catch (RequirementsException $e) {
      // If the d7_taxonomy_vocabulary requirements failed, that means we do not
      // have a Drupal source database configured - there is nothing to
      // generate.
      return $this->derivatives;
    }

    try {
      foreach ($vocabulary_source_plugin as $row) {
        $bundle = $row->getSourceProperty('machine_name');
        $values = $base_plugin_definition;

        $values['label'] = t('@label (@type)', [
          '@label' => $values['label'],
          '@type' => $row->getSourceProperty('name'),
        ]);
        $values['source']['bundle'] = $bundle;
        $values['destination']['default_bundle'] = $bundle;

        /** @var Migration $migration */
        $migration = \Drupal::service('plugin.manager.migration')->createStubMigration($values);
        if (isset($fields[$bundle])) {
          foreach ($fields[$bundle] as $field_name => $info) {
            $field_type = $info['type'];
            try {
              $plugin_id = $this->cckPluginManager->getPluginIdFromFieldType($field_type, ['core' => 7], $migration);
              if (!isset($this->cckPluginCache[$field_type])) {
                $this->cckPluginCache[$field_type] = $this->cckPluginManager->createInstance($plugin_id, ['core' => 7], $migration);
              }
              $this->cckPluginCache[$field_type]
                ->processCckFieldValues($migration, $field_name, $info);
            }
            catch (PluginNotFoundException $ex) {
              $migration->setProcessOfProperty($field_name, $field_name);
            }
          }
        }
        $this->derivatives[$bundle] = $migration->getPluginDefinition();
      }
    }
    catch (DatabaseExceptionWrapper $e) {
      // Once we begin iterating the source plugin it is possible that the
      // source tables will not exist. This can happen when the
      // MigrationPluginManager gathers up the migration definitions but we do
      // not actually have a Drupal 7 source database.
    }

    return $this->derivatives;
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Main extends Controller {

	public function index()
	{
		$template = $this->loadView('main_view');
		$template->render();

	}
  public function preguntas() {
  	$template = $this->loadView('preguntas_view');
  	$template->render();
  }
}

?>


text:
package com.Geisteskranken.TrustWorthyCauldron7;

import org.bukkit.configuration.file.FileConfiguration;

public enum Configuration {

	CONF;

	public static boolean CheckLogin = true;

	public void readConfig(FileConfiguration savedConfig) {

		Configuration.CheckLogin = savedConfig.getBoolean("CheckLogin", true);
	}

}


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

namespace Imagination.LWM2M
{
	internal class HelpCommand : Command
	{
		public HelpCommand()
			: base()
		{
			Name = "help";
		}

		public override void Execute()
		{
			if (Parameters.Count == 0)
			{
				Console.WriteLine("List of possible commands");
				foreach (var item in _Commands)
				{
					Console.Write("  ");
					Console.WriteLine(item.Key);
				}
				Console.WriteLine("For specific information type help [command]");
			}
			else
			{
				foreach (var item in _Commands)
				{
					if (string.Compare(item.Key, Parameters[0], true) == 0)
					{
						item.Value.Help();
						break;
					}
				}
			}
		}
	}
}


text:
package com.dropbox.core.http;

import java.io.Closeable;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import okio.BufferedSink;
import okio.Okio;

final class OkHttpUtil {

    public static void assertNotSameThreadExecutor(ExecutorService executor) {
        Thread current = Thread.currentThread();

        Thread executed;
        try {
            executed = executor.submit(new Callable<Thread>() {
                @Override
                public Thread call() {
                    return Thread.currentThread();
                }
            }).get(2, TimeUnit.MINUTES);
        } catch (InterruptedException ex) {
            // preserve interrupt
            current.interrupt();
            throw new IllegalArgumentException("Unable to verify OkHttp dispatcher executor.", ex);
        } catch (Exception ex) {
            throw new IllegalArgumentException("Unable to verify OkHttp dispatcher executor.", ex);
        }

        if (current.equals(executed)) {
            throw new IllegalArgumentException(
                "OkHttp dispatcher uses same-thread executor. " +
                "This is not supported by the SDK and may result in dead-locks. Please configure " +
                "your Dispatcher to use an ExecutorService that runs tasks on separate threads.");
        }
    }

    public static final class PipedStream implements Closeable {
        private static final int BUFFER_SIZE = 5 << 20; // 5MiB, the max size for JSON requests on server

        private final PipedInputStream in;
        private final PipedOutputStream out;

        public PipedStream() {
            this.in = new PipedInputStream(BUFFER_SIZE);
            try {
                this.out = new PipedOutputStream(in);
            } catch (IOException ex) {
                throw new IllegalStateException("Unable to create piped stream for async upload request.");
            }
        }

        public OutputStream getOutputStream() {
            return out;
        }

        @Override
        public void close() {
            try {
                out.close();
            } catch (IOException ex) {
                // ignore
            }
            try {
                in.close();
            } catch (IOException ex) {
                //ignore
            }
        }

        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeAll(Okio.source(in));
        }
    }
}


text:
package ezbake.locksmith.db;

import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Set;

import com.mongodb.*;
import ezbakehelpers.mongoutils.MongoHelper;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @date 05/21/14
 * @author gdrocella
 * time: 2:07pm
 */
public class MongoDBService {
	private static final Logger log = LoggerFactory.getLogger(MongoDBService.class);

    private MongoHelper mongoHelper;
	private Mongo mongo;
	private DB db;

	public MongoDBService(Properties ezProperties) throws ManagerDbAccessException {
        mongoHelper = new MongoHelper(ezProperties);
        try {
            mongo = mongoHelper.getMongo();
        } catch (UnknownHostException ex) {
            throw new ManagerDbAccessException("Unknown Host when connecting to Mongo: " + ex.getMessage());
        }
		db = mongo.getDB(mongoHelper.getMongoConfigurationHelper().getMongoDBDatabaseName());
	}

    public DB getMongoDB() {
        return db;
    }

	public Set<String> getCollections() {
		return db.getCollectionNames();
	}

	/**
	 * Inserts a document into a collection
	 * @param collection - collection to insert document into
	 * @param doc - the document to be inserted
	 * @return - true on success, false otherwise
	 */
	public ObjectId insertDocumentIntoCollection(String collection, DBObject doc) {
		boolean success = true;
		log.info("Insert Document into collection [{}]", collection);
		DBCollection coll = db.getCollection(collection);
		WriteResult result = coll.insert(doc);

		return (ObjectId) result.getUpsertedId();
	}

	public boolean dropCollectionFromDb(String collection) {
		DBCollection coll = db.getCollection(collection);
		coll.drop();

		return true;
	}

	public DBCursor findInCollection(String collection, DBObject search, DBObject projection) throws NullPointerException {
		DBCollection coll = db.getCollection(collection);

		return coll.find(search, projection);
	}

	public void removeDocumentFromCollection(String collection, BasicDBObject obj) {
		DBCollection coll = db.getCollection(collection);

		coll.remove(obj);
	}

	public boolean collectionExists(String collection) {
		return db.collectionExists(collection);
	}

	public void createCollection(String collection) {
		db.createCollection(collection, new BasicDBObject());
	}

	public long collectionCount(String collection) {
		DBCollection coll =  db.getCollection(collection);
		return coll.getCount();
	}
}


text:
{-# LANGUAGE TypeFamilies ,DeriveFunctor,DeriveGeneric ,TypeOperators#-}
module Scaling.Time where

import Space.Class
import Exponential.Class
import Multiplicative.Class
import Data.FMonoid.Class
import Data.Monoid
import Linear.V2
import Linear.V1
import Linear.Vector
import Local
import Data.Functor.Product
import MultiLinear.Class
import qualified Prelude as Prelude
import Prelude hiding((*))

newtype Epoch a = Epoch a deriving(Functor,Read,Show)

instance Exponential Epoch where
   logM (Epoch x) = V1 $ log x
   expM (V1 x) = Epoch $ exp x

type instance Local Epoch  = V1

instance Floating a => Multiplicative (Epoch a) where
   one = Epoch 1
   Epoch x * Epoch y =  Epoch $ x Prelude.* y
   inversion (Epoch x) = Epoch $ 1/x

instance Space Epoch where
   x |+|  y =  x * expM y
   x |-|  y =  logM $ inversion y *  x


text:
package org.opensaml.xml.signature.impl;

import org.opensaml.xml.signature.Exponent;

/**
 * Concrete implementation of {@link org.opensaml.xml.signature.Exponent}
 */
public class ExponentImpl extends CryptoBinaryImpl implements Exponent {

    /**
     * Constructor
     *
     * @param namespaceURI
     * @param elementLocalName
     * @param namespacePrefix
     */
    protected ExponentImpl(String namespaceURI, String elementLocalName, String namespacePrefix) {
        super(namespaceURI, elementLocalName, namespacePrefix);
    }

}


text:
package com.appglu.impl.json;

import java.util.List;

import com.appglu.TableChanges;

public class TableChangesBody {

	private List<TableChanges> tables;

	public TableChangesBody(List<TableChanges> tables) {
		super();
		this.tables = tables;
	}

	public List<TableChanges> getTables() {
		return tables;
	}

}


text:
/*
 * null
 *
 * [FhirComposite("SpecimenCollectionComponent")]
 * [Serializable]
 */

#import "FHIRElement.h"

#import "FHIRSpecimen.h"

@class FHIRResource;
@class FHIRString;
@class FHIRElement;
@class FHIRQuantity;
@class FHIRCodeableConcept;

@interface FHIRSpecimenCollectionComponent : FHIRElement

/*
 * Who collected the specimen
 */
@property (nonatomic, strong) FHIRResource *collector;

/*
 * Collector comments
 */
@property (nonatomic, strong) NSArray/*<string>*/ *commentElement;

@property (nonatomic, strong) NSArray /*<NSString>*/ *comment;

/*
 * Collection time
 */
@property (nonatomic, strong) FHIRElement *collected;

/*
 * The quantity of specimen collected
 */
@property (nonatomic, strong) FHIRQuantity *quantity;

/*
 * Technique used to perform collection
 */
@property (nonatomic, strong) FHIRCodeableConcept *method;

/*
 * Anatomical collection site
 */
@property (nonatomic, strong) FHIRCodeableConcept *sourceSite;

- (FHIRErrorList *)validate;

@end


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

namespace DataWebRules
{
    using Microsoft.FxCop.Sdk;

    ///
    /// This rule checks that all methods used in AtomMaterializerInvoker
    /// are available and that there aren't unused methods.
    ///
    public class AtomMaterializerInvokerRule : BaseDataWebRule
    {
        private System.Collections.ArrayList methodsUsedByCompiler;

        /// Initializes a new <see cref="AtomMaterializerInvokerRule"/> instance.
        public AtomMaterializerInvokerRule()
            : base("AtomMaterializerInvokerRule")
        {
        }

        /// Visibility of targets to which this rule commonly applies.
        public override TargetVisibilities TargetVisibility
        {
            get
            {
                return TargetVisibilities.All;
            }
        }

        /// Checks the client module for consistency.
        /// <param name="module">Module to check.</param>
        /// <returns>Problems in the module.</returns>
        public override ProblemCollection Check(ModuleNode module)
        {
            base.Check(module);
            if (!module.Name.EndsWith("Data.Services.Client", System.StringComparison.OrdinalIgnoreCase))
            {
                return null;
            }

            TypeNode compiler = null;
            TypeNode materializer = null;
            TypeNode invoker = null;
            foreach (TypeNode node in module.Types)
            {
                if (node.Name.Name.EndsWith("ODataEntityMaterializerInvoker"))
                {
                    invoker = node;
                }
                else if (node.Name.Name.EndsWith("ODataEntityMaterializer"))
                {
                    materializer = node;
                }
                else if (node.Name.Name.EndsWith("ProjectionPlanCompiler"))
                {
                    compiler = node;
                }

                if (invoker != null && materializer != null && compiler != null)
                {
                    break;
                }
            }

            if (invoker == null || materializer == null || compiler == null)
            {
                Resolution resolution = new Resolution("Unable to find AtomMaterializerInvoker/AtomMaterializer/ProjectionPlanCompiler - check assembly or update rule.");
                Problems.Add(new Problem(resolution));
                return Problems;
            }

            string[] methodNames = GetMethodNamesFromInvoker(invoker);
            string[] usedMethods = GetMethodsUsedByCompiler(compiler);

            // Look for methods that aren't used by compiler.
            for (int i = 0; i < methodNames.Length; i++)
            {
                string methodName = methodNames[i];
                if (methodName == "DirectMaterializePlan" || methodName == "ShallowMaterializePlan")
                {
                    // These are referenced directly so a lambda can be compiled and passed around,
                    // but are not part of projection plan building.
                    continue;
                }

                bool found = System.Array.BinarySearch(usedMethods, methodName) >= 0;
                if (!found)
                {
                    Problems.Add(new Problem(GetResolution(methodName)));
                }
            }

            // TODO: look for methods that aren't implemented by invoker.
            // Harder to do because we gather collection information by just
            // picking up string literals, which gets asserts and other
            // information. A more careful analysis requred code flow analysis,
            // for example the wrappers for DataServiceCollection creation determine
            // the method name through some branching statements.
            //
            // Heuristic: things with no spaces or some other non-identifier characters are method names.
            for (int i = 0; i < usedMethods.Length; i++)
            {
                string usedMethod = usedMethods[i];
                if (usedMethod.Contains(" ") || usedMethod.Contains("|") || usedMethod.Contains("("))
                {
                    continue;
                }

                // There are method name checks in the projection plan compiler used
                // to recognize certain patterns. Skip those.
                if (usedMethod == "Select" || usedMethod == "Create" ||
                    usedMethod == "CreateTracked" || usedMethod == "ToList" ||
                    usedMethod == "ReferenceEquals")
                {
                    continue;
                }

                // There are literals used to create parameter names.
                if (usedMethod == "entry" || usedMethod == "subentry" || usedMethod == "type")
                {
                    continue;
                }

                bool found = System.Array.BinarySearch(methodNames, usedMethod) >= 0;
                if (!found)
                {
                    Resolution resolution = new Resolution("Implement " + usedMethod + " on AtomMaterializerInvoker");
                    Problems.Add(new Problem(resolution));
                }
            }

            return Problems.Count > 0 ? Problems : null;
        }

        private string[] GetMethodsUsedByCompiler(TypeNode compiler)
        {
            System.Collections.ArrayList result = new System.Collections.ArrayList();
            this.methodsUsedByCompiler = result;
            foreach (Member member in compiler.Members)
            {
                if (member.NodeType == NodeType.Method)
                {
                    this.Visit(member);
                }
            }

            this.methodsUsedByCompiler = null;
            result.Sort();
            return (string[])result.ToArray(typeof(string));
        }

        private static string[] GetMethodNamesFromInvoker(TypeNode invoker)
        {
            System.Collections.ArrayList result = new System.Collections.ArrayList(invoker.Members.Count);
            foreach (Member member in invoker.Members)
            {
                if (member.NodeType == NodeType.Method)
                {
                    result.Add(member.Name.Name);
                }
            }

            result.Sort();
            return (string[])result.ToArray(typeof(string));
        }

        public override void VisitLiteral(Literal literal)
        {
            if (literal.Type != null && literal.Type.FullName == "System.String")
            {
                this.methodsUsedByCompiler.Add(literal.Value as string);
            }

            base.VisitLiteral(literal);
        }
    }
}


text:
require 'ostruct'

module YARD
  # Parses text and creates a {Docstring} object to represent documentation
  # for a {CodeObjects::Base}. To create a new docstring, you should initialize
  # the parser and call {#parse} followed by {#to_docstring}.
  #
  # == Subclassing Notes
  #
  # The DocstringParser can be subclassed and subtituted during parsing by
  # setting the {Docstring.default_parser} attribute with the name of the
  # subclass. This allows developers to change the way docstrings are
  # parsed, allowing for completely different docstring syntaxes.
  #
  # @example Creating a Docstring with a DocstringParser
  #   DocstringParser.new.parse("text here").to_docstring
  # @example Creating a Custom DocstringParser
  #   # Parses docstrings backwards!
  #   class ReverseDocstringParser
  #     def parse_content(content)
  #       super(content.reverse)
  #     end
  #   end
  #
  #   # Set the parser as default when parsing
  #   YARD::Docstring.default_parser = ReverseDocstringParser
  # @see #parse_content
  # @since 0.8.0
  class DocstringParser
    # @return [String] the parsed text portion of the docstring,
    #   with tags removed.
    attr_accessor :text

    # @return [String] the complete input string to the parser.
    attr_accessor :raw_text

    # @return [Array<Tag>] the list of meta-data tags identified
    #   by the parser
    attr_accessor :tags

    # @return [Array<Directive>] a list of directives identified
    #   by the parser. This list will not be passed on to the
    #   Docstring object.
    attr_accessor :directives

    # @return [OpenStruct] any arbitrary state to be passed between
    #   tags during parsing. Mainly used by directives to coordinate
    #   behaviour (so that directives can be aware of other directives
    #   used in a docstring).
    attr_accessor :state

    # @return [CodeObjects::Base, nil] the object associated with
    #   the docstring being parsed. May be nil if the docstring is
    #   not attached to any object.
    attr_accessor :object

    # @return [CodeObjects::Base, nil] the object referenced by
    #   the docstring being parsed. May be nil if the docstring doesn't
    #   refer to any object.
    attr_accessor :reference

    # @return [Handlers::Base, nil] the handler parsing this
    #   docstring. May be nil if this docstring parser is not
    #   initialized through
    attr_accessor :handler

    # @return [Tags::Library] the tag library being used to
    #   identify registered tags in the docstring.
    attr_accessor :library

    # The regular expression to match the tag syntax
    META_MATCH = /^@(!)?((?:\w\.?)+)(?:\s+(.*))?$/i

    # @!group Creation and Conversion Methods

    # Creates a new parser to parse docstring data
    #
    # @param [Tags::Library] library a tag library for recognizing
    #   tags.
    def initialize(library = Tags::Library.instance)
      @text = ""
      @raw_text = ""
      @tags = []
      @directives = []
      @library = library
      @object = nil
      @reference = nil
      @handler = nil
      @state = OpenStruct.new
    end

    # @return [Docstring] translates parsed text into
    #   a Docstring object.
    def to_docstring
      Docstring.new!(text, tags, object, raw_text, reference)
    end

    # @!group Parsing Methods

    # Parses all content and returns itself.
    #
    # @param [String] content the docstring text to parse
    # @param [CodeObjects::Base] object the object that the docstring
    #   is attached to. Will be passed to directives to act on
    #   this object.
    # @param [Handlers::Base, nil] handler the handler object that is
    #   parsing this object. May be nil if this parser is not being
    #   called from a {Parser::SourceParser} context.
    # @return [self] the parser object. To get the docstring,
    #   call {#to_docstring}.
    # @see #to_docstring
    def parse(content, object = nil, handler = nil)
      @object = object
      @handler = handler
      @reference, @raw_text = detect_reference(content)
      text = parse_content(@raw_text)
      # Remove trailing/leading whitespace / newlines
      @text = text.gsub(/\A[\r\n\s]+|[\r\n\s]+\Z/, '')
      call_directives_after_parse
      post_process
      self
    end

    # Parses a given block of text.
    #
    # @param [String] content the content to parse
    # @note Subclasses can override this method to perform custom
    #   parsing of content data.
    def parse_content(content)
      content = content.split(/\r?\n/) if content.is_a?(String)
      return '' if !content || content.empty?
      docstring = String.new("")

      indent = content.first[/^\s*/].length
      last_indent = 0
      orig_indent = 0
      directive = false
      last_line = ""
      tag_name = nil
      tag_buf = []

      (content + ['']).each_with_index do |line, index|
        indent = line[/^\s*/].length
        empty = (line =~ /^\s*$/ ? true : false)
        done = content.size == index

        if tag_name && (((indent < orig_indent && !empty) || done ||
            (indent == 0 && !empty)) || (indent <= last_indent && line =~ META_MATCH))
          buf = tag_buf.join("\n")
          if directive || tag_is_directive?(tag_name)
            directive = create_directive(tag_name, buf)
            if directive
              docstring << parse_content(directive.expanded_text).chomp
            end
          else
            create_tag(tag_name, buf)
          end
          tag_name = nil
          tag_buf = []
          directive = false
          orig_indent = 0
        end

        # Found a meta tag
        if line =~ META_MATCH
          directive = $1
          tag_name = $2
          tag_buf = [($3 || '')]
        elsif tag_name && indent >= orig_indent && !empty
          orig_indent = indent if orig_indent == 0
          # Extra data added to the tag on the next line
          last_empty = last_line =~ /^[ \t]*$/ ? true : false

          tag_buf << '' if last_empty
          tag_buf << line.gsub(/^[ \t]{#{orig_indent}}/, '')
        elsif !tag_name
          # Regular docstring text
          docstring << line
          docstring << "\n"
        end

        last_indent = indent
        last_line = line
      end

      docstring
    end

    # @!group Parser Callback Methods

    # Call post processing callbacks on parser.
    # This is called implicitly by parser. Use this when
    # manually configuring a {Docstring} object.
    #
    # @return [void]
    def post_process
      call_after_parse_callbacks
    end

    # @!group Tag Manipulation Methods

    # Creates a tag from the {Tags::DefaultFactory tag factory}.
    #
    # To add an already created tag object, append it to {#tags}.
    #
    # @param [String] tag_name the tag name
    # @param [String] tag_buf the text attached to the tag with newlines removed.
    # @return [Tags::Tag, Tags::RefTag] a tag
    def create_tag(tag_name, tag_buf = '')
      if tag_buf =~ /\A\s*(?:(\S+)\s+)?\(\s*see\s+(\S+)\s*\)\s*\Z/
        return create_ref_tag(tag_name, $1, $2)
      end

      if library.has_tag?(tag_name)
        @tags += [library.tag_create(tag_name, tag_buf)].flatten
      else
        log.warn "Unknown tag @#{tag_name}" +
                 (object ? " in file `#{object.file}` near line #{object.line}" : "")
      end
    rescue Tags::TagFormatError
      log.warn "Invalid tag format for @#{tag_name}" +
               (object ? " in file `#{object.file}` near line #{object.line}" : "")
    end

    # Creates a {Tags::RefTag}
    def create_ref_tag(tag_name, name, object_name)
      @tags << Tags::RefTagList.new(tag_name, P(object, object_name), name)
    end

    # Creates a new directive using the registered {#library}
    # @return [Directive] the directive object that is created
    def create_directive(tag_name, tag_buf)
      if library.has_directive?(tag_name)
        dir = library.directive_create(tag_name, tag_buf, self)
        if dir.is_a?(Tags::Directive)
          @directives << dir
          dir
        end
      else
        log.warn "Unknown directive @!#{tag_name}" +
                 (object ? " in file `#{object.file}` near line #{object.line}" : "")
        nil
      end
    rescue Tags::TagFormatError
      log.warn "Invalid directive format for @!#{tag_name}" +
               (object ? " in file `#{object.file}` near line #{object.line}" : "")
      nil
    end

    # Backward compatibility to detect old tags that should be specified
    # as directives in 0.8 and onward.
    def tag_is_directive?(tag_name)
      list = %w(attribute endgroup group macro method scope visibility)
      list.include?(tag_name)
    end

    # Creates a callback that is called after a docstring is successfully
    # parsed. Use this method to perform sanity checks on a docstring's
    # tag data, or add any extra tags automatically to a docstring.
    #
    # @yield [parser] a block to be called after a docstring is parsed
    # @yieldparam [DocstringParser] parser the docstring parser object
    #   with all directives and tags created.
    # @yieldreturn [void]
    # @return [void]
    def self.after_parse(&block)
      after_parse_callbacks << block
    end

    # @return [Array<Proc>] the {after_parse} callback proc objects
    def self.after_parse_callbacks
      @after_parse_callbacks ||= []
    end

    # Define a callback to check that @param tags are properly named
    after_parse do |parser|
      next unless parser.object
      next unless parser.object.is_a?(CodeObjects::MethodObject)
      next if parser.object.is_alias?
      names = parser.object.parameters.map {|l| l.first.gsub(/\W/, '') }
      seen_names = []
      infile_info = "\n    in file `#{parser.object.file}' " \
                    "near line #{parser.object.line}"
      parser.tags.each do |tag|
        next if tag.is_a?(Tags::RefTagList) # we don't handle this yet
        next unless tag.tag_name == "param"
        if seen_names.include?(tag.name)
          log.warn "@param tag has duplicate parameter name: " \
                   "#{tag.name} #{infile_info}"
        elsif names.include?(tag.name)
          seen_names << tag.name
        else
          log.warn "@param tag has unknown parameter name: " \
                   "#{tag.name} #{infile_info}"
        end
      end
    end

    private

    def namespace
      object && object.namespace
    end

    def detect_reference(content)
      if content =~ /\A\s*\(see (\S+)\s*\)(?:\s|$)/
        path = $1
        extra = $'
        [CodeObjects::Proxy.new(namespace, path), extra]
      else
        [nil, content]
      end
    end

    # @!group Parser Callback Methods

    # Calls the {Tags::Directive#after_parse} callback on all the
    # created directives.
    def call_directives_after_parse
      directives.each(&:after_parse)
    end

    # Calls all {after_parse} callbacks
    def call_after_parse_callbacks
      self.class.after_parse_callbacks.each do |cb|
        cb.call(self)
      end
    end

    # Define a callback to check that @see tags do not use {}.
    after_parse do |parser|
      next unless parser.object

      parser.tags.each_with_index do |tag, i|
        next unless tag.tag_name == "see"
        next unless "#{tag.name}#{tag.text}" =~ /\A\{.*\}\Z/
        infile_info = "\n    in file `#{parser.object.file}' " \
                      "near line #{parser.object.line}"
        log.warn "@see tag (##{i + 1}) should not be wrapped in {} " \
                 "(causes rendering issues): #{infile_info}"
      end
    end
  end
end


text:
<?php

/**
 * Conversation associated to a channel
 */
class AngularTalk_Room
{
    /**
     * Current message provider
     * @var AngularTalk_MessageProvider
     */
    protected $_provider;

    /**
     * Make the room work as a chat
     */
    const MODE_CHAT = 1;
    /**
     * Make the room work as a comment panel
     */
    const MODE_CONVERSATION = 2;

    /**
     * Channel ID
     * @var string
     */
    public $channel;

    /**
     * Current message sender
     * @var AngularTalk_Author
     */
    public $sender;

    /**
     * Room is in read only mode
     * @var bool
     */
    public $readOnly = false;

    /**
     * Show user names above their message
     * @var bool
     */
    public $showUserName;

    /**
     * Group messages by sent time
     * @var bool
     */
    public $groupMessages;

    /**
     * Reverse sender messages, moving it to the right
     * @var bool
     */
    public $reverseSenderMessages;

    /**
     * Allow new messages to be created
     * @var bool
     */
    public $allowNew = true;

    /**
     * If set, URL to the sound that will be played when there is a new message and the current document is not focused.
     * It also can be an array of URLs with multiple versions of the sound for different browsers, in the form array(mime_type => URL)
     * @var string|string[]
     */
    public $soundOnNew;

    /**
     * Show user faces in the message
     * @var bool
     */
    public $showFaces = true;

    /**
     * Show only approved messages by a moderator
     * @var bool
     */
    public $onlyApproved = true;

    /**
     * Allow replies to other messages that will be shown as a tree layout
     * @var bool
     */
    public $allowReplies = true;

    /**
     * Maximun number of reply levels allowed
     * @var int
     */
    public $replyLevels = 2;

    /**
     * Allow users submit a rating about something
     * @var bool
     */
    public $allowRating = false;

    /**
     * Ask sender name
     * @var bool
     */
    public $requireAuthorName = true;

    /**
     * Ask sender email
     * @var bool
     */
    public $requireAuthorEmail = true;

    /**
     * Ask sender URL
     * @var bool
     */
    public $requireAuthorURL = true;

    /**
     * Waiting time (in ms) between update requests
     * @var int
     */
    public $updateInterval;

    /**
     * Ajax endpoint called to update and submit messages
     * @var string
     */
    public $ajaxEndpoint;

    /**
     * Submit new message when Enter key is pressed
     * @var bool
     */
    public $submitOnEnter;

    /**
     * If enabled, verbose error messages and descriptions will be provided
     * @var bool
     */
    public $debug = false;

    /**
     * Strings used in the app
     * @var array
     */
    public $strings = [
        'messagePlaceholder' => 'Enter your message...',
        'submit'             => 'Submit',
        'reply'              => 'Reply',
        'retrySend'          => "This message didn't send. Check your internet connection and click to try again.",
        'emptyRoom'          => '',
        'edit'               => 'Edit',
        'delete'             => 'Delete',
        'save'               => 'Save',
        'cancel'             => 'Cancel',
        'delete_confirm'     => 'Are you sure? This cannot be undone'
    ];

    public function __construct($channel, AngularTalk_MessageProvider $provider)
    {
        $this->_provider = $provider;
        $this->channel = $channel;
        $this->set_mode(self::MODE_CHAT);
    }

    public function set_mode($mode)
    {
        switch ($mode) {
            case self::MODE_CHAT:
                $this->requireAuthorEmail = false;
                $this->requireAuthorName = false;
                $this->requireAuthorURL = false;
                $this->allowReplies = false;
                $this->updateInterval = 3000;
                $this->onlyApproved = false;
                $this->submitOnEnter = true;
                $this->showUserName = false;
                $this->groupMessages = true;
                $this->reverseSenderMessages = true;
                $this->soundOnNew = true;
                $this->showFaces = true;
                break;

            case self::MODE_CONVERSATION:
                $this->requireAuthorEmail = true;
                $this->requireAuthorName = true;
                $this->requireAuthorURL = true;
                $this->allowReplies = true;
                $this->updateInterval = 30000;
                $this->submitOnEnter = false;
                $this->showUserName = true;
                $this->groupMessages = false;
                $this->reverseSenderMessages = false;
                $this->soundOnNew = false;
                $this->showFaces = true;
                break;

            default:
                throw new InvalidArgumentException("Unrecognized room mode '$mode'");
        }
    }

    /**
     * Listen for AngularTalk request
     *
     * @param object    $request    HTTP request body, null to get it from 'php://input'
     * @param int       $message_id ID of the current message, null to get it from request
     * @param bool|true $echo       Send response automatically
     *
     * @return array
     */
    public function listen($request = null, $message_id = null, $echo = true)
    {
        $response = [];

        $http_code = 200;
        try {
            if (!$request) {
                $request_body = file_get_contents('php://input');
                if ($request_body) {
                    $request = json_decode($request_body);
                    if ($request === null) {
                        throw new AngularTalk_RoomException('Invalid request data', 400);
                    }
                } else {
                    $request = null;
                }
            }

            $method = strtoupper($_SERVER['REQUEST_METHOD']);
            switch ($method) {
                case 'GET':
                    $dir = isset($_REQUEST['dir']) && $_REQUEST['dir'] == 'ASC' ? 'ASC' : 'DESC';
                    $since = isset($_REQUEST['since']) ? $_REQUEST['since'] : null;
                    $count = isset($_REQUEST['count']) && is_numeric($_REQUEST['count']) ? $_REQUEST['count'] : 25;
                    $response['data'] = $this->_provider->get($this, $since, $dir, $count);
                    break;

                case 'POST':
                    if (!$this->allowNew) {
                        throw new AngularTalk_RoomException('New message submissions is not allowed', 403);
                    }
                    if (!$request) {
                        throw new AngularTalk_RoomException('Invalid request data', 400);
                    }

                    $message = new AngularTalk_Message();
                    $message->channel = $this->channel;
                    $message->content = $request->content;
                    $message->date = time();
                    $message->approved = false;
                    $message->title = isset($request->title) ? $request->title : '';
                    $message->rating = isset($request->rating) && $this->allowRating ? $request->rating : 0;
                    $message->replyToID = isset($request->replyToID) && $this->allowReplies ? $request->replyToID : null;

                    //Author info
                    $message->author = clone $this->sender;
                    if (isset($request->author->url) && $this->requireAuthorURL) {
                        $message->author->url = $request->author->url;
                    }
                    if (isset($request->author->name) && $this->requireAuthorName) {
                        $message->author->name = $request->author->name;
                    }
                    if (isset($request->author->email) && $this->requireAuthorEmail) {
                        $message->author->url = $request->author->email;
                    }

                    $response['data'] = $this->_provider->create($this, $message);
                    $http_code = 201;
                    break;

                case 'PUT':
                case 'DELETE':
                    //Load current message
                    $id = $message_id;
                    if (!$id) {
                        $id = $request && is_object($request) ? $request->id : $_REQUEST['id'];
                    }

                    $message = $id ? $this->_provider->get($this, $id, 'ID') : false;

                    if (!$message) {
                        throw new AngularTalk_RoomException('Message not found', 404);
                    }

                    if (!($this->sender->isModerator || $message->author->id == $this->sender->id)) {
                        throw new AngularTalk_RoomException('Not authorized to this operation', 403);
                    }

                    if ($method == 'PUT') {
                        //Update message
                        $message->content = $request->content;

                        $response['data'] = $this->_provider->update($this, $message);
                    } elseif (!$this->_provider->delete($this, $message->id)) {
                        //Delete message
                        throw new AngularTalk_RoomException('Delete error', 500);
                    }

                    break;

                default:
                    throw new AngularTalk_RoomException('Unrecognized method', 400);
            }
        } catch (Exception $err) {
            if ($this->debug) {
                $response['message'] = $err->getMessage();
                $response['file'] = $err->getFile();
                $response['line'] = $err->getLine();
            }
        }

        if (isset($err)) {
            $http_code = $err instanceof AngularTalk_RoomException ? $err->getCode() : 500;
        }
        $response['status'] = $http_code;

        if ($echo) {
            //Output response
            header("HTTP/1.1 " . $http_code);
            header('Content-type: application/json');
            echo json_encode($response, JSON_NUMERIC_CHECK);
        }

        return $response;
    }

    /**
     * Deletes the current room and all its associated messages
     */
    public function delete()
    {
        return $this->_provider->delete($this);
    }

    /**
     * Get the current room config for the angularTalk directive
     * @return array
     */
    public function get_config()
    {
        $settings = get_object_vars($this);
        unset($settings['_provider']);

        return $settings;
    }

    /**
     * Renders the current room
     * @return string
     */
    public function render($attr = [])
    {
        //Prepare attributes
        $attr['class'] = 'angular-talk';

        $attr['settings'] = json_encode($this->get_config());

        //Render HTML element
        $html_attrs = [];
        foreach ($attr as $name => $value) {
            $html_attrs[] = $name . '="' . htmlentities($value) . '"';
        }
        return '<div ' . implode(' ', $html_attrs) . '"></div>';
    }
}

class AngularTalk_RoomException extends Exception
{

}


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Calculates any one parameter of the noncentral t distribution give values for the others.</title>

stats_stat_innerproduct

stats_stat_paired_t

Statistic Functions

PHP Manual

stats_stat_noncentral_t

(PECL stats >= 1.0.0)

stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.

Description

   float stats_stat_noncentral_t
    ( float $par1
   , float $par2
   , float $par3
   , int $which
   )

Warning
This function is
currently not documented; only its argument list is available.

Parameters

par1

par2

par3

which

Return Values

stats_stat_innerproduct

stats_stat_paired_t

Statistic Functions

PHP Manual


text:
namespace gfx {
class GLContext;
}

namespace gpu {
class AsyncPixelTransferDelegateShareGroup;
class AsyncPixelTransferUploadStats;

class AsyncPixelTransferManagerShareGroup : public AsyncPixelTransferManager {
 public:
  explicit AsyncPixelTransferManagerShareGroup(gfx::GLContext* context);
  virtual ~AsyncPixelTransferManagerShareGroup();

  // AsyncPixelTransferManager implementation:
  virtual void BindCompletedAsyncTransfers() OVERRIDE;
  virtual void AsyncNotifyCompletion(
      const AsyncMemoryParams& mem_params,
      const CompletionCallback& callback) OVERRIDE;
  virtual uint32 GetTextureUploadCount() OVERRIDE;
  virtual base::TimeDelta GetTotalTextureUploadTime() OVERRIDE;
  virtual void ProcessMorePendingTransfers() OVERRIDE;
  virtual bool NeedsProcessMorePendingTransfers() OVERRIDE;

  // State shared between Managers and Delegates.
  struct SharedState {
    SharedState();
    ~SharedState();

    scoped_refptr<AsyncPixelTransferUploadStats> texture_upload_stats;
    typedef std::list<base::WeakPtr<AsyncPixelTransferDelegateShareGroup> >
        TransferQueue;
    TransferQueue pending_allocations;
  };

 private:
  // AsyncPixelTransferManager implementation:
  virtual AsyncPixelTransferDelegate* CreatePixelTransferDelegateImpl(
      gles2::TextureRef* ref,
      const AsyncTexImage2DParams& define_params) OVERRIDE;

  SharedState shared_state_;

  DISALLOW_COPY_AND_ASSIGN(AsyncPixelTransferManagerShareGroup);
};

}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_SERVICE_ASYNC_PIXEL_TRANSFER_MANAGER_SHARE_GROUP_H_


text:
package com.arialyy.aria.m3u8.live;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.arialyy.aria.core.TaskRecord;
import com.arialyy.aria.core.download.DTaskWrapper;
import com.arialyy.aria.core.inf.IThreadStateManager;
import com.arialyy.aria.core.listener.IEventListener;
import com.arialyy.aria.core.listener.ISchedulers;
import com.arialyy.aria.core.loader.ILoaderVisitor;
import com.arialyy.aria.m3u8.M3U8Listener;
import com.arialyy.aria.m3u8.M3U8TaskOption;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import static com.arialyy.aria.m3u8.M3U8InfoTask.M3U8_INDEX_FORMAT;

final class LiveStateManager implements IThreadStateManager {
  private final String TAG = CommonUtil.getClassName(getClass());

  private M3U8Listener mListener;
  private long mProgress; //当前总进度
  private Looper mLooper;
  private DTaskWrapper mTaskWrapper;
  private M3U8TaskOption mM3U8Option;
  private FileOutputStream mIndexFos;
  private M3U8LiveLoader mLoader;

  /**
   * @param listener 任务事件
   */
  LiveStateManager(DTaskWrapper wrapper, IEventListener listener) {
    mTaskWrapper = wrapper;
    mListener = (M3U8Listener) listener;
    mM3U8Option = (M3U8TaskOption) mTaskWrapper.getM3u8Option();
  }

  private Handler.Callback mCallback = new Handler.Callback() {
    @Override public boolean handleMessage(Message msg) {
      int peerIndex = msg.getData().getInt(ISchedulers.DATA_M3U8_PEER_INDEX);
      switch (msg.what) {
        case STATE_STOP:
          if (mLoader.isBreak()) {
            ALog.d(TAG, "任务停止");
            quitLooper();
          }
          break;
        case STATE_CANCEL:
          if (mLoader.isBreak()) {
            ALog.d(TAG, "任务取消");
            quitLooper();
          }
          break;
        case STATE_COMPLETE:
          mLoader.notifyLock(true, peerIndex);
          if (mM3U8Option.isGenerateIndexFile() && !mLoader.isBreak()) {
            addExtInf(mLoader.getCurExtInfo().url, mLoader.getCurExtInfo().extInf);
          }
          mListener.onPeerComplete(mTaskWrapper.getKey(),
              msg.getData().getString(ISchedulers.DATA_M3U8_PEER_PATH), peerIndex);
          break;
        case STATE_RUNNING:
          Bundle b = msg.getData();
          if (b != null) {
            long len = b.getLong(IThreadStateManager.DATA_ADD_LEN, 0);
            mProgress += len;
          }
          break;
        case STATE_FAIL:
          mLoader.notifyLock(false, peerIndex);
          mListener.onPeerFail(mTaskWrapper.getKey(),
              msg.getData().getString(ISchedulers.DATA_M3U8_PEER_PATH), peerIndex);
          break;
      }
      return true;
    }
  };

  void setLoader(M3U8LiveLoader loader) {
    mLoader = loader;
  }

  /**
   * 退出looper循环
   */
  private void quitLooper() {
    ALog.d(TAG, "quitLooper");
    mLooper.quit();
    if (mIndexFos != null) {
      try {
        mIndexFos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 给索引文件添加extInfo信息
   */
  private void addExtInf(String url, String extInf) {
    File indexFile =
        new File(String.format(M3U8_INDEX_FORMAT, mTaskWrapper.getEntity().getFilePath()));
    if (!indexFile.exists()) {
      ALog.e(TAG, String.format("索引文件【%s】不存在,添加peer的extInf失败", indexFile.getPath()));
      return;
    }
    try {
      if (mIndexFos == null) {
        mIndexFos = new FileOutputStream(indexFile, true);
      }
      mIndexFos.write(extInf.concat("\r\n").getBytes(Charset.forName("UTF-8")));
      mIndexFos.write(url.concat("\r\n").getBytes(Charset.forName("UTF-8")));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override public boolean isFail() {
    return false;
  }

  @Override public boolean isComplete() {
    return false;
  }

  @Override public long getCurrentProgress() {
    return mProgress;
  }

  @Override public void updateCurrentProgress(long currentProgress) {
    mProgress = currentProgress;
  }

  @Override public void setLooper(TaskRecord taskRecord, Looper looper) {
    mLooper = looper;
  }

  @Override public Handler.Callback getHandlerCallback() {
    return mCallback;
  }

  @Override public void accept(ILoaderVisitor visitor) {
    visitor.addComponent(this);
  }
}


text:
classdef MgmtServerDB < handle

	properties
		relayEntries=[];
		clientEntries=[];
		attackEntries=[];
		nextAttackId=1;
        initClientRisk=0;
        useTimeRisk=0;
        assignPeriod=1;
		rEntryTemplate=struct('ID',-1,'Clients',[],'Protected',0);
		cEntryTemplate=struct('ID',-1,'RelayID',-1,'Risk',0,'startTime',0,'Banned',0,'lastAssign',-1);
		aEntryTemplate=struct('ID',-1,'Clients',[],'Risk',[],'RLimit',0);
	end

	methods
		function obj=MgmtServerDB()
			obj.relayEntries=containers.Map('KeyType','uint32','ValueType','any');
			obj.clientEntries=containers.Map('KeyType','uint32','ValueType','any');
			obj.attackEntries=containers.Map('KeyType','uint32','ValueType','any');
		end

		function NewRelay(obj,id)
			nRelay=obj.rEntryTemplate;
			nRelay.ID=id;
			obj.relayEntries(id)=nRelay;
		end

		function id=newAttack(obj)
			id=obj.nextAttackId;
			obj.nextAttackId=obj.nextAttackId+1;
			nAttack=obj.aEntryTemplate;
			nAttack.ID=id;
			obj.attackEntries(id)=nAttack;
		end

		function NewClient(obj,id)
			DSim=dsim.DSim.getInstance();
			time=DSim.currentTime;
			nClient=obj.cEntryTemplate;
			nClient.ID=id;
			nClient.startTime=time;
            nClient.Risk=obj.initClientRisk;
			obj.clientEntries(id)=nClient;
		end

		function exists=doesClientExist(obj,client_ID)
			exists=obj.clientEntries.isKey(client_ID);
		end

		function exists=doesAttackExist(obj,attack_ID)
			exists=obj.attackEntries.isKey(attack_ID);
		end

		function banned=isBannedClient(obj,client_ID)
			Client=obj.clientEntries(client_ID);
			banned=Client.Banned;
		end

		function risk=getClientRisk(obj,client_ID)
			Client=obj.clientEntries(client_ID);
            DSim=dsim.DSim.getInstance();
			time=DSim.currentTime;
			timeDiff=time-Client.startTime;
            if obj.useTimeRisk == 1
                risk=Client.Risk+exp(-timeDiff/20);
            else
                risk=Client.Risk;
            end
        end

        function clientList=getRiskSortedClientList(obj)
            keys=obj.clientEntries.keys;
            risk=[];
            ids=[];
            for k=1:length(keys)
                Client=obj.clientEntries(keys{k});
                risk(end+1)=obj.getClientRisk(Client.ID);
                ids(end+1)=Client.ID;
            end
            [~,IX] = sort(risk);
            clientList=ids(IX);
        end

        function num=getNumUnusedRelay(obj)
            keys=obj.relayEntries.keys;
            num=0;
            for k=1:length(keys)
                Relay=obj.relayEntries(keys{k});
                if isempty(Relay.Clients)
                    num=num+1;
                end
            end
        end

        function num=getNumUnassignedClients(obj)
            keys=obj.clientEntries.keys;
            num=0;
            for k=1:length(keys)
                Client=obj.clientEntries(keys{k});
                if Client.RelayID <= 0
                    num=num+1;
                end
            end
        end

        function setProtectedRelay(obj,relay_id);
            Relay=obj.relayEntries(relay_id);
            Relay.Protected=1;
            obj.relayEntries(relay_id)=Relay;
        end

        function clearProtectedRelay(obj,relay_id)
            Relay=obj.relayEntries(relay_id);
            Relay.Protected=0;
            obj.relayEntries(relay_id)=Relay;
        end
        function setAttackRiskLimit(obj,attack_ID,limit)
            Attack=obj.attackEntries(attack_ID);
            Attack.RLimit=limit;
            obj.attackEntries(attack_ID)=Attack;
        end

        function rebalanceAttacks(obj)
            keys=obj.attackEntries.keys;
            for k=1:length(keys)
                Attack=obj.attackEntries(keys{k});
                clients=Attack.Clients;
                indvRisk=zeros(1,length(clients));
                for i=1:length(clients)
                    indvRisk(i)=obj.getClientRisk(clients(i));
                end
                totalRisk=Attack.RLimit;
                weights=indvRisk./totalRisk;
                newRisks=weights.*Attack.Risk;
                newRisks=newRisks.*totalRisk/sum(newRisks);
                diffRisk=newRisks-Attack.Risk;
                %keyboard
                for i=1:length(clients)
                    obj.setClientRisk(clients(i),indvRisk(i)+diffRisk(i),0,-1);
                end
                Attack.Risk=newRisks;
                obj.attackEntries(keys{k})=Attack;
            end
        end

		function risk=setClientRisk(obj,client_ID,risk,addedRisk,attack_ID)
			Client=obj.clientEntries(client_ID);
			Client.Risk=risk;
			obj.clientEntries(client_ID)=Client;
			if obj.doesAttackExist(attack_ID)
				Attack=obj.attackEntries(attack_ID);
				Attack.Clients(end+1)=Client.ID;
				Attack.Risk(end+1)=addedRisk;
                obj.attackEntries(attack_ID)=Attack;
			end
		end

		function removeRiskFromAttack(obj,attack_ID)
			Attack=obj.attackEntries(attack_ID);
			clients=Attack.Clients;
			risk=Attack.Risk;
			for i=1:length(clients)
				oldRisk=obj.getClientRisk(clients(i));
				newRisk=oldRisk-risk(i);
				obj.setClientRisk(clients(i),newRisk,-1,-1);
            end
            obj.attackEntries.remove(attack_ID);
		end

		function removeRiskFromAttacker(obj,attacker_ID)
			keys=obj.attackEntries.keys;
			for k=1:length(keys)
				Attack=obj.attackEntries(keys{k});
				clients=Attack.Clients;
				for i=1:length(clients)
					if clients(i) == attacker_ID
						obj.removeRiskFromAttack(Attack.ID);
					end
				end
			end
		end

		function banClient(obj,client_ID)
			Client=obj.clientEntries(client_ID);
			Client.Banned=1;
			obj.clientEntries(client_ID)=Client;
		end

		function addClientToRelay(obj,relay_ID,client_ID)
			obj.unassignClient(client_ID);
			Relay=obj.relayEntries(relay_ID);
			Relay.Clients(end+1)=client_ID;
			obj.relayEntries(relay_ID)=Relay;
			Client=obj.clientEntries(client_ID);
			Client.RelayID=relay_ID;
			obj.clientEntries(client_ID)=Client;
		end

		function deleteRelay(obj,relay_ID)
			obj.relayEntries.remove(relay_ID);
		end

		function rlc=getNumRelays(obj)
			keys=obj.relayEntries.keys;
			rlc=length(keys);
		end

		function risk=getTotalRelayRisk(obj)
			keys=obj.relayEntries.keys;
			risk=0;
			for k=1:length(keys)
				risk=risk+obj.getRiskRelay(keys{k});
			end
        end

        function risk=getTotalClientRisk(obj)
			keys=obj.clientEntries.keys;
			risk=0;
			for k=1:length(keys)
                if ~obj.isBannedClient(keys{k})
                    risk=risk+obj.getClientRisk(keys{k});
                end
			end
		end

		function risk=getRiskClient(obj,client_ID)
			Client=obj.clientEntries(client_ID);
			risk=Client.Risk;
		end

		function risk=getRiskRelay(obj,relay_ID)
			Relay=obj.relayEntries(relay_ID);
			risk=0;
			for i=1:length(Relay.Clients)
				risk=risk+obj.getRiskClient(Relay.Clients(i));
			end
		end

		function num=getNumClients(obj,relay_ID)
			Relay=obj.relayEntries(relay_ID);
			num=length(Relay.Clients);
		end

		function CL=getClientList(obj,relay_ID)
			Relay=obj.relayEntries(relay_ID);
			CL=Relay.Clients;
		end

		function RL=getRelayList(obj)
			RL=[];
			keys=obj.relayEntries.keys;
			for k=1:length(keys)
				Relay=obj.relayEntries(keys{k});
				id=Relay.ID;
				if id > 0
					RL(end+1)=id;
				end
			end
        end

        function relay_id = getMinClientRelay(obj)
            relay_id=-1;
            minClients=inf;
            keys=obj.relayEntries.keys;
            for k=1:length(keys)
                Relay=obj.relayEntries(keys{k});
                if Relay.ID > 0
                    nClients=obj.getNumClients(Relay.ID);
                    if nClients < minClients
                        minClients=nClients;
                        relay_id=Relay.ID;
                    end
                end
            end
        end

        function num = getNumAvailRelays(obj)
            num=0;
            keys=obj.relayEntries.keys;
            for k=1:length(keys)
                Relay=obj.relayEntries(keys{k});
                if Relay.ID > 0
                    if Relay.Protected == 0
                        num=num+1;
                    end
                end
            end
        end

		function [relay_id,minRisk]=getMinRiskRelay(obj)
			relay_id=-1;
			minRisk=inf;
			keys=obj.relayEntries.keys;
            nTies=0;
            tiedRelays=[];
			for k=1:length(keys)
				Relay=obj.relayEntries(keys{k});
				if Relay.ID > 0 && Relay.Protected == 0
					risk=obj.getRiskRelay(Relay.ID);
					if risk<minRisk
						minRisk=risk;
						relay_id=Relay.ID;
                        nTies=0;
                        tiedRelays=Relay.ID;
                elseif risk==minRisk
                        nTies=nTies+1;
                        tiedRelays(end+1)=Relay.ID;
                    end

				end
            end
            if nTies > 0
                winner=randi([1 length(tiedRelays)]);
                relay_id=tiedRelays(winner);
            end
        end

        function [relay_id] = getRelaySimilarRisk(obj,client_ID)
            relay_id=-1;
			closeRisk=inf;
			keys=obj.relayEntries.keys;
            clientRisk=obj.getClientRisk(client_ID);
            nTies=0;
            tiedRelays=[];
            newRelay=[];
			for k=1:length(keys)
				Relay=obj.relayEntries(keys{k});
				if Relay.ID > 0
					risk=obj.getRiskRelay(Relay.ID);
                    nClients=obj.getNumClients(Relay.ID);
                    avgRisk=risk/nClients;
                    nCR=abs(avgRisk-clientRisk);

					if nCR < closeRisk
						closeRisk=nCR;
						relay_id=Relay.ID;
                        nTies=0;
                        tiedRelays=Relay.ID;
                    elseif nCR==closeRisk || nClients == 0
                        nTies=nTies+1;
                        tiedRelays(end+1)=Relay.ID;
                    end

				end
            end
            if nTies > 0
                winner=randi([1 length(tiedRelays)]);
                relay_id=tiedRelays(winner);
            end

        end

		function rl=getAssignment(obj,client_ID)
			Client=obj.clientEntries(client_ID);
			rl=Client.RelayID;
		end

		function unassignClient(obj,client_ID)
			rl=obj.getAssignment(client_ID);
			if rl>0
			Relay=obj.relayEntries(rl);
			Relay.Clients(Relay.Clients==client_ID)=[];
			obj.relayEntries(rl)=Relay;
			Client=obj.clientEntries(client_ID);
			Client.RelayID=-1;
			obj.clientEntries(client_ID)=Client;
			end
		end

		function unassignAllClients(obj,relay_ID)
			Relay=obj.relayEntries(relay_ID);
			clients=Relay.Clients;
			for i=1:length(clients)
				obj.unassignClient(clients(i));
			end
        end

        function ret=canAssignNew(obj,checkNum,client_ID)
            Client=obj.clientEntries(client_ID);
            %DSim=dsim.DSim.getInstance();
			%time=DSim.currentTime;
            if checkNum > Client.lastAssign
                Client.lastAssign=checkNum+obj.assignPeriod;
                obj.clientEntries(client_ID)=Client;
                ret=1;
            else
                ret=0;
            end
        end

        function unassignAvailClients(obj,relay_ID,checkNum)
			Relay=obj.relayEntries(relay_ID);
			clients=Relay.Clients;
			for i=1:length(clients)
                if obj.canAssignNew(checkNum,clients(i))
                    obj.unassignClient(clients(i));
                end
			end
        end

	end

end


text:
package org.jconverter.typesolver;

import static org.jcategory.category.Key.key;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;

import org.jcategory.JCategory;
import org.jcategory.category.Key;
import org.junit.Test;

public class TypeSolverTest {

	class ListClass {}

	class UnrecognizedObjectExceptionTypeSolver implements TypeSolver<List> {
		@Override
		public Type inferType(List object) {
			throw new UnrecognizedObjectException();
		}
	}

	class NonGenericTypeSolver implements TypeSolver {
		@Override
		public Type inferType(Object object) {
			return ListClass.class;
		}
	}

	class GenericListTypeSolver implements TypeSolver<List> {
		@Override
		public Type inferType(List object) {
			return ListClass.class;
		}
	}

	class FullGenericListTypeSolver implements TypeSolver<List<List<String>>> {
		@Override
		public Type inferType(List object) {
			return ListClass.class;
		}
	}

	class SingleBoundListTypeSolver<T extends List> implements TypeSolver<T> {
		@Override
		public Type inferType(T object) {
			return ListClass.class;
		}
	}

	class MultipleBoundsListTypeSolver<T extends Iterable & List> implements TypeSolver<T> {
		@Override
		public Type inferType(T object) {
			return ListClass.class;
		}
	}

	@Test
	public void testNonGenericListTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new NonGenericTypeSolver());
		assertEquals(ListClass.class, manager.inferType(key, new Object()));
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testUnrecognizedObjectExceptionTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new NonGenericTypeSolver());
		manager.register(key, new UnrecognizedObjectExceptionTypeSolver());
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testUnrecognizedObjectExceptionTypeSolver2() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new UnrecognizedObjectExceptionTypeSolver());
		try {
			manager.inferType(key(), new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
		manager.register(key, new NonGenericTypeSolver());
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testNoTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		try {
			manager.inferType(key(), new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
	}

	@Test
	public void testGenericListTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new GenericListTypeSolver());
		try {
			manager.inferType(key, new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testFullGenericListTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new FullGenericListTypeSolver());
		try {
			manager.inferType(key, new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testSingleBoundListTypeSolver() {
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new SingleBoundListTypeSolver());
		try {
			manager.inferType(key, new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList()));
	}

	@Test
	public void testMultipleBoundsListTypeSolver() {
		JCategory categorization = new JCategory();
		categorization.forClass(Vector.class);
		TypeSolverManager manager = new TypeSolverManagerImpl(new JCategory());
		Key key = key();
		manager.register(key, new MultipleBoundsListTypeSolver());
		try {
			manager.inferType(key, new Object());
			fail();
		} catch(UnrecognizedObjectException e) {}
		assertEquals(ListClass.class, manager.inferType(key, new Vector())); //trying with a class registered before the bound type solver was added
		assertEquals(ListClass.class, manager.inferType(key, new ArrayList())); //trying with a class registered after the bound type solver was added
		try {
			manager.inferType(key, new HashSet());
			fail();
		} catch(UnrecognizedObjectException e) {}
	}

}


text:
class Appuser < ActiveRecord::Base

  attr_accessible :status, :userType, :email, :appuserid, :lastName, :firstName, :password, :userName,
                  :avatar, :delete_avatar,:charityid,:charityName,:created_at,:updated_at

  # before saving to the DB it will make userName and email to all lowercase Ensuring email uniquenesss
  before_save { |appuser| appuser.userName = userName.downcase}
  before_save { |appuser| appuser.email = email.downcase}
  before_save { |appuser| appuser.charityName = Charity.select("name").where("charityid = ?", appuser.charityid)[0].name}
  before_validation :clear_photo

  validates :password, length:  { minimum: 6 }, :on => :create
  validates :userName, presence: true , length: {maximum: 50 , minimum: 5} , uniqueness: true

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true , format: { with: VALID_EMAIL_REGEX } , uniqueness: true
  validates :lastName, presence: true
  validates :firstName, presence: true
  validates :status, presence: true
  validates :userType, presence: true
  validates :charityid, presence: true
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment :avatar,:content_type => { :content_type => [/^image\/(?:jpeg|gif|png)$/, nil] },
                        :size => { :in => 0..2000.kilobytes }

  self.primary_key = 'appuserid'
  has_many :visits, :foreign_key => 'doctorId'

 def delete_avatar=(value)
    @delete_avatar = !value.to_i.zero?
  end

  def delete_avatar
    !!@delete_avatar
  end
  alias_method :delete_avatar?, :delete_avatar

  # Later in the model
def clear_photo
  self.avatar = nil if delete_avatar? && !avatar.dirty?
end

end


text:
package controllers

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"

	"github.com/revel/revel"
)

// HTTPBackEnd (deal with git smart http protcol)
type HTTPBackEnd struct {
	App
}

// GitUploadPack (deal with git clone)
func (h HTTPBackEnd) GitUploadPack(repo string, group string) revel.Result {

	h.RequireUser()

	h.Response.Out.Header().Add("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
	h.Response.Out.Header().Add("Pragma", "no-cache")
	h.Response.Out.Header().Add("Cache-Control", "no-cache, max-age=0, must-revalidate")
	h.Response.Out.Header().Del("Content-Type")
	h.Response.Out.Header().Add("Content-Type", "application/x-git-upload-pack-result")

	repoRoot, _ := revel.Config.String("repo.root")
	repo = repoRoot + repo
	git, _ := revel.Config.String("git.cmd")
	cmd := exec.Command(git, "upload-pack", "--stateless-rpc", repo)
	out, _ := cmd.StdoutPipe()
	input, _ := cmd.StdinPipe()
	cmd.Stderr = os.Stderr

	go func() {
		var err error
		var bytes = make([]byte, 1024)
		var read int
		for {
			read, err = h.Request.Body.Read(bytes)
			input.Write(bytes[:read])
			if err != nil {
				fmt.Println("read http request err:", err)
				input.Close()
				break
			}

		}
	}()
	cmd.Start()
	var err error
	var bytes = make([]byte, 1024)
	var read int
	for {
		read, err = out.Read(bytes)
		h.Response.Out.Write(bytes[:read])
		if err != nil {
			out.Close()
			fmt.Println("read cmd output err:", err)
			break
		}

	}
	cmd.Wait()

	return nil
}

// GitReceivePack (deal with git push)
func (h HTTPBackEnd) GitReceivePack(repo string, group string) revel.Result {
	h.Response.Out.Header().Add("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
	h.Response.Out.Header().Add("Pragma", "no-cache")
	h.Response.Out.Header().Add("Cache-Control", "no-cache, max-age=0, must-revalidate")
	h.Response.Out.Header().Del("Content-Type")
	h.Response.Out.Header().Add("Content-Type", "application/x-git-receive-pack-result")

	repoRoot, _ := revel.Config.String("repo.root")
	repo = repoRoot + repo
	git, _ := revel.Config.String("git.cmd")
	cmd := exec.Command(git, "receive-pack", "--stateless-rpc", repo)
	out, _ := cmd.StdoutPipe()
	input, _ := cmd.StdinPipe()
	cmd.Stderr = os.Stderr
	go func() {
		var err error
		var bytes = make([]byte, 1024)
		var read int
		for {
			read, err = h.Request.Body.Read(bytes)
			input.Write(bytes[:read])
			if err != nil {
				fmt.Println("read http request err:", err)
				input.Close()
				break
			}

		}
	}()
	cmd.Start()
	var err error
	var bytes = make([]byte, 1024)
	var read int
	for {
		read, err = out.Read(bytes)
		h.Response.Out.Write(bytes[:read])
		if err != nil {
			out.Close()
			fmt.Println("read cmd output err:", err)
			break
		}

	}
	cmd.Wait()

	return nil
}

// GetInfoRefs (got git repo refs)
func (h HTTPBackEnd) GetInfoRefs(service string, repo string, group string) revel.Result {
	//service: git-receive-pack|git-upload-pack
	r, _ := regexp.Compile("git-")
	action := r.ReplaceAllString(service, "")
	r, _ = regexp.Compile("-pack")
	action = r.ReplaceAllString(action, "")
	h.Response.Out.Header().Add("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
	h.Response.Out.Header().Add("Pragma", "no-cache")
	h.Response.Out.Header().Add("Cache-Control", "no-cache, max-age=0, must-revalidate")
	h.Response.Out.Header().Del("Content-Type")
	h.Response.Out.Header().Add("Content-Type", "application/x-git-"+action+"-pack-advertisement")

	repoRoot, _ := revel.Config.String("repo.root")
	repo = repoRoot + repo
	git, _ := revel.Config.String("git.cmd")
	refs, _ := exec.Command(git, action+"-pack", "--stateless-rpc", "--advertise-refs", repo).Output()
	act := "# service=git-" + action + "-pack\n"
	l := len(act) + 4
	s := "00" + fmt.Sprintf("%x", l) + act
	h.Response.Out.Write([]byte(s))
	h.Response.Out.Write([]byte{'0', '0', '0', '0'})
	h.Response.Out.Write(refs)

	return nil
}


text:
self.crawl
===========

self.crawl(url, **kwargs)
-------------------------

`self.crawl` is the main interface to tell pyspider which url(s) should be crawled.

### Parameters:

##### url
the url or url list to be crawled.

##### callback
the method to parse the response. _default: `__call__` _

```python
def on_start(self):
    self.crawl('http://scrapy.org/', callback=self.index_page)
```

the following parameters are optional

##### age

the period of validity of the task. The page would be regarded as not modified during the period. _default: -1(never recrawl)_

```python
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
    ...
```
> Every pages parsed by the callback `index_page` would be regarded not changed within 10 days. If you submit the task within 10 days since last crawled it would be discarded.

##### priority

the priority of task to be scheduled, higher the better. _default: 0_

```python
def index_page(self):
    self.crawl('http://www.example.org/page2.html', callback=self.index_page)
    self.crawl('http://www.example.org/233.html', callback=self.detail_page,
               priority=1)
```
> The page `233.html` would be crawled before `page2.html`. Use this parameter can do a [BFS](http://en.wikipedia.org/wiki/Breadth-first_search) and reduce the number of tasks in queue(which may cost more memory resources).

##### exetime

the executed time of task in unix timestamp. _default: 0(immediately)_

```python
import time
def on_start(self):
    self.crawl('http://www.example.org/', callback=self.callback,
               exetime=time.time()+30*60)
```
> The page would be crawled 30 minutes later.

##### retries

retry times while failed. _default: 3_

##### itag

a marker from frontier page to reveal the potential modification of the task. It will be compared to its last value, recrawl when it's changed. _default: None_

```python
def index_page(self, response):
    for item in response.doc('.item').items():
        self.crawl(item.find('a').attr.url, callback=self.detail_page,
                   itag=item.find('.update-time').text())
```
> In the sample, `.update-time` is used as itag. If it's not changed, the request would be discarded.

Or you can use `itag` with `Handler.crawl_config` to specify the script version if you want to restart all of the tasks.

```python
class Handler(BaseHandler):
    crawl_config = {
        'itag': 'v223'
    }
```
> Change the value of itag after you modified the script and click run button again. It doesn't matter if not set before.

##### auto_recrawl

when enabled, task would be recrawled every `age` time. _default: False_

```python
def on_start(self):
    self.crawl('http://www.example.org/', callback=self.callback,
               age=5*60*60, auto_recrawl=True)
```
> The page would be restarted every `age` 5 hours.

##### method

HTTP method to use. _default: GET_

##### params

dictionary of URL parameters to append to the URL.

```python
def on_start(self):
    self.crawl('http://httpbin.org/get', callback=self.callback,
               params={'a': 123, 'b': 'c'})
    self.crawl('http://httpbin.org/get?a=123&b=c', callback=self.callback)
```
> The two requests are the same.

##### data

the body to attach to the request. If a dictionary is provided, form-encoding will take place.

```python
def on_start(self):
    self.crawl('http://httpbin.org/post', callback=self.callback,
               method='POST', data={'a': 123, 'b': 'c'})
```

##### files

dictionary of `{field: {filename: 'content'}}` files to multipart upload.`

##### headers

dictionary of headers to send.

##### cookies

dictionary of cookies to attach to this request.

##### connect_timeout

timeout for initial connection in seconds. _default: 20_

##### timeout

maximum time in seconds to fetch the page. _default: 120_

##### allow_redirects

follow `30x` redirect _default: True_

##### validate_cert

For HTTPS requests, validate the server's certificate? _default: True_

##### proxy

proxy server of `username:password@hostname:port` to use, only http proxy is supported currently.

```python
class Handler(BaseHandler):
    crawl_config = {
        'proxy': 'localhost:8080'
    }
```
> `Handler.crawl_config` can be used with `proxy` to set a proxy for whole project.

##### etag

use HTTP Etag mechanism to pass the process if the content of the page is not changed. _default: True_

###### last_modified

use HTTP Last-Modified header mechanism to pass the process if the content of the page is not changed. _default: True_

##### fetch_type

set to `js` to enable JavaScript fetcher. _default: None_

##### js_script

JavaScript run before or after page loaded, should been wrapped by a function like `function() { document.write("binux"); }`.

```python
def on_start(self):
    self.crawl('http://www.example.org/', callback=self.callback,
               fetch_type='js', js_script='''
               function() {
                   window.scrollTo(0,document.body.scrollHeight);
                   return 123;
               }
               ''')
```
> The script would scroll the page to bottom. The value returned in function could be captured via `Response.js_script_result`.

##### js_run_at

run JavaScript specified via `js_script` at `document-start` or `document-end`. _default: `document-end`_

##### js_viewport_width/js_viewport_height

set the size of the viewport for the JavaScript fetcher of the layout process.

##### load_images

load images when JavaScript fetcher enabled. _default: False_

##### save

a object pass to the callback method, can be visit via `response.save`.

```python
def on_start(self):
    self.crawl('http://www.example.org/', callback=self.callback,
               save={'a': 123})

def callback(self, response):
    return response.save['a']
```
> `123` would be returned in `callback`

##### taskid

unique id to identify the task, default is the MD5 check code of the URL, can be overridden by method `def get_taskid(self, task)`

```python
import json
from pyspider.libs.utils import md5string
def get_taskid(self, task):
    return md5string(task['url']+json.dumps(task['fetch'].get('data', '')))
```
> Only url is md5 -ed as taskid by default, the code above add `data` of POST request as part of taskid.

##### force_update

force update task params even if the task is in `ACTIVE` status.

##### cancel

cancel a task, should be used with `force_update` to cancel a active task. To cancel an `auto_recrawl` task, you should set `auto_recrawl=False` as well.

cURL command
------------

`self.crawl(curl_command)`

cURL is a command line tool to make a HTTP request. It can easily get form Chrome Devtools > Network panel,  right click the request and "Copy as cURL".

You can use cURL command as the first argument of `self.crawl`. It will parse the command and make the HTTP request just like curl do.

@config(**kwargs)
-----------------
default parameters of `self.crawl` when use the decorated method as callback. For example:

```python
@config(age=15*60)
def index_page(self, response):
    self.crawl('http://www.example.org/list-1.html', callback=self.index_page)
    self.crawl('http://www.example.org/product-233', callback=self.detail_page)

@config(age=10*24*60*60)
def detail_page(self, response):
    return {...}
```

`age` of `list-1.html` is 15min while the `age` of `product-233.html` is 10days. Because the callback of `product-233.html` is `detail_page`, means it's a `detail_page` so it shares the config of `detail_page`.

Handler.crawl_config = {}
-------------------------
default parameters of `self.crawl` for the whole project. The parameters in `crawl_config` for scheduler (priority, retries, exetime, age, itag, force_update, auto_recrawl, cancel) will be joined when the task created, the parameters for fetcher and processor will be joined when executed. You can use this mechanism to change the fetch config (e.g. cookies) afterwards.

```python
class Handler(BaseHandler):
    crawl_config = {
        'headers': {
            'User-Agent': 'GoogleBot',
        }
    }

    ...
```
> crawl_config set a project level user-agent.


text:
.true, .also-true { color: green; }

.false, .also-false { color: red; }


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

#include "chrome/browser/notifications/scheduler/internal/background_task_coordinator.h"

#include <algorithm>
#include <utility>

#include "base/command_line.h"
#include "base/cxx17_backports.h"
#include "base/memory/raw_ptr.h"
#include "base/time/clock.h"
#include "chrome/browser/notifications/scheduler/internal/impression_types.h"
#include "chrome/browser/notifications/scheduler/internal/notification_entry.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_config.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_utils.h"
#include "chrome/browser/notifications/scheduler/public/features.h"
#include "chrome/browser/notifications/scheduler/public/notification_background_task_scheduler.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace notifications {
namespace {

class BackgroundTaskCoordinatorHelper {
 public:
  BackgroundTaskCoordinatorHelper(
      NotificationBackgroundTaskScheduler* background_task,
      const SchedulerConfig* config,
      base::Clock* clock)
      : background_task_(background_task), config_(config), clock_(clock) {}
  BackgroundTaskCoordinatorHelper(const BackgroundTaskCoordinatorHelper&) =
      delete;
  BackgroundTaskCoordinatorHelper& operator=(
      const BackgroundTaskCoordinatorHelper&) = delete;
  ~BackgroundTaskCoordinatorHelper() = default;

  void ScheduleBackgroundTask(
      BackgroundTaskCoordinator::Notifications notifications,
      BackgroundTaskCoordinator::ClientStates client_states) {
    if (notifications.empty()) {
      background_task_->Cancel();
      return;
    }

    BackgroundTaskCoordinator::Notifications unthrottled_notifications;
    BackgroundTaskCoordinator::Notifications throttled_notifications;
    for (auto& pair : notifications) {
      for (auto* notification : pair.second) {
        auto type = pair.first;
        if (notification->schedule_params.priority ==
            ScheduleParams::Priority::kNoThrottle) {
          unthrottled_notifications[type].emplace_back(std::move(notification));
        } else {
          throttled_notifications[type].emplace_back(std::move(notification));
        }
      }
    }
    ProcessUnthrottledNotifications(std::move(unthrottled_notifications));
    ProcessThrottledNotifications(std::move(throttled_notifications),
                                  std::move(client_states));
    ScheduleBackgroundTaskInternal();
  }

 private:
  void ProcessUnthrottledNotifications(
      BackgroundTaskCoordinator::Notifications notifications) {
    for (const auto& pair : notifications) {
      for (const auto* entry : pair.second) {
        DCHECK_EQ(entry->schedule_params.priority,
                  ScheduleParams::Priority::kNoThrottle);
        if (!entry->schedule_params.deliver_time_start.has_value()) {
          continue;
        }
        base::Time deliver_time_start =
            entry->schedule_params.deliver_time_start.value();
        MaybeUpdateBackgroundTaskTime(deliver_time_start);
      }
    }
  }

  void ProcessThrottledNotifications(
      BackgroundTaskCoordinator::Notifications notifications,
      BackgroundTaskCoordinator::ClientStates client_states) {
    base::Time tomorrow;
    base::Time now = clock_->Now();
    bool success = ToLocalHour(0, now, 1 /*day_delta*/, &tomorrow);
    DCHECK(success);

    std::map<SchedulerClientType, int> shown_per_type;
    int shown_total = 0;
    SchedulerClientType last_shown_type = SchedulerClientType::kUnknown;
    NotificationsShownToday(client_states, &shown_per_type, &shown_total,
                            &last_shown_type, clock_);

    for (const auto& pair : notifications) {
      auto type = pair.first;
      auto it = client_states.find(type);
      if (pair.second.empty() || (it == client_states.end()))
        continue;

      const ClientState* client_state = it->second;
      bool reach_max_today =
          shown_per_type[type] >= client_state->current_max_daily_show ||
          shown_total >= config_->max_daily_shown_all_type;

      // Find the eariliest notification to launch the background task.
      for (const auto* entry : pair.second) {
        DCHECK_NE(entry->schedule_params.priority,
                  ScheduleParams::Priority::kNoThrottle);
        // Currently only support deliver time window.
        if (!entry->schedule_params.deliver_time_start.has_value()) {
          continue;
        }

        base::Time deliver_time_start =
            entry->schedule_params.deliver_time_start.value();

        // Consider suppression time.
        if (client_state->suppression_info.has_value() &&
            deliver_time_start <
                client_state->suppression_info->ReleaseTime()) {
          deliver_time_start = client_state->suppression_info->ReleaseTime();
        }

        // Consider daily limit throttling.
        if (reach_max_today && deliver_time_start < tomorrow)
          deliver_time_start = tomorrow;

        // Deliver time window has passed.
        DCHECK(entry->schedule_params.deliver_time_end.has_value());
        if (!entry->schedule_params.deliver_time_end.has_value() ||
            deliver_time_start >
                entry->schedule_params.deliver_time_end.value()) {
          continue;
        }

        MaybeUpdateBackgroundTaskTime(deliver_time_start);
      }
    }
  }

  void MaybeUpdateBackgroundTaskTime(const base::Time& time) {
    if (!background_task_time_.has_value() ||
        time < background_task_time_.value())
      background_task_time_ = time;
  }

  void ScheduleBackgroundTaskInternal() {
    if (!background_task_time_.has_value())
      return;

    base::TimeDelta window_start_time =
        background_task_time_.value() - clock_->Now();
    window_start_time = base::clamp(window_start_time, base::TimeDelta(),
                                    base::TimeDelta::Max());

    // TODO(xingliu): Remove SchedulerTaskTime.
    if (base::CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kNotificationSchedulerImmediateBackgroundTask)) {
      background_task_->Schedule(base::Seconds(30), base::Minutes(1));
      return;
    }

    background_task_->Schedule(
        window_start_time,
        window_start_time + config_->background_task_window_duration);
  }

  raw_ptr<NotificationBackgroundTaskScheduler> background_task_;
  raw_ptr<const SchedulerConfig> config_;
  raw_ptr<base::Clock> clock_;
  absl::optional<base::Time> background_task_time_;
};

}  // namespace

class BackgroundTaskCoordinatorImpl : public BackgroundTaskCoordinator {
 public:
  BackgroundTaskCoordinatorImpl(
      std::unique_ptr<NotificationBackgroundTaskScheduler> background_task,
      const SchedulerConfig* config,
      base::Clock* clock)
      : background_task_(std::move(background_task)),
        config_(config),
        clock_(clock) {}

  BackgroundTaskCoordinatorImpl(const BackgroundTaskCoordinatorImpl&) = delete;
  BackgroundTaskCoordinatorImpl& operator=(
      const BackgroundTaskCoordinatorImpl&) = delete;
  ~BackgroundTaskCoordinatorImpl() override = default;

 private:
  // BackgroundTaskCoordinator implementation.
  void ScheduleBackgroundTask(Notifications notifications,
                              ClientStates client_states) override {
    auto helper = std::make_unique<BackgroundTaskCoordinatorHelper>(
        background_task_.get(), config_, clock_);
    helper->ScheduleBackgroundTask(std::move(notifications),
                                   std::move(client_states));
  }

  // The class that actually schedules platform background task.
  std::unique_ptr<NotificationBackgroundTaskScheduler> background_task_;

  // System configuration.
  raw_ptr<const SchedulerConfig> config_;

  // Clock to query the current timestamp.
  raw_ptr<base::Clock> clock_;
};

// static
std::unique_ptr<BackgroundTaskCoordinator> BackgroundTaskCoordinator::Create(
    std::unique_ptr<NotificationBackgroundTaskScheduler> background_task,
    const SchedulerConfig* config,
    base::Clock* clock) {
  return std::make_unique<BackgroundTaskCoordinatorImpl>(
      std::move(background_task), config, clock);
}

BackgroundTaskCoordinator::~BackgroundTaskCoordinator() = default;

}  // namespace notifications


text:
#ifndef DECISION_PRIV_H
#define DECISION_PRIV_H

#include "decision.h"

typedef struct {
	decision_t base;

	void *user_cb_data;

	decision_exec_t exec;
	decision_dtor_t dtor;

	const char *name;
	void *user;

	char *csv_filename;
} decision_priv_t;

#endif // DECISION_PRIV_H