text:
document.getElementById("show-more").addEventListener("click", expand);
document.getElementById("show-less").addEventListener("click", collapse);

function expand() {
	$(".incategory-description").removeClass("collapsed");
    	$(".incategory-description").addClass("expanded");
    	$(".incategory-description").css("max-height", "2000px");
    	$("#show-more").removeClass("show");
    	$("#show-more").addClass("hide");
    	$("#show-less").removeClass("hide");
    	$("#show-less").addClass("show")
    	$("#controls").removeClass("fade");
}

function collapse() {
	$(".incategory-description").removeClass("expanded");
    	$(".incategory-description").addClass("collapsed");
    	$(".incategory-description").css("max-height", "180px");
    	$("#show-more").removeClass("hide");
    	$("#show-more").addClass("show");
    	$("#show-less").addClass("hide");
    	$("#show-less").removeClass("show");
    	$("#controls").addClass("fade");
}

function checkHeight() {
	var incatDesc = $(".incategory-description");
	if (incatDesc.height() > 100) {
		$("#show-more").removeClass("hide");
		$("#show-more").addClass("show");
		$(".controls").removeClass("hide");
		$(".controls").addClass("show");
	}
}
checkHeight();

redpajama_set_name: RedPajamaGithub


text:
* Buyable upgrades [done]
* Explosive projectiles (Bomber) [done(kindof)]
* Map props: Cacti and trees
* Cactus texture
* Bomber texture [done]
* Better enemy textures
* Better enemy-waves
* Map editor


text:
import {ɵAnimationEngine, ɵNoopAnimationStyleNormalizer} from '@angular/animations/browser';
import {MockAnimationDriver} from '@angular/animations/browser/testing';
import {NgZone, RendererFactory2} from '@angular/core';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {EventManager, ɵDomRendererFactory2, ɵDomSharedStylesHost} from '@angular/platform-browser';
import {ɵAnimationRendererFactory} from '@angular/platform-browser/animations';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {EventManagerPlugin} from '@angular/platform-browser/src/dom/events/event_manager';

export class SimpleDomEventsPlugin extends EventManagerPlugin {
  constructor(doc: any) { super(doc); }

  supports(eventName: string): boolean { return true; }

  addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
    let callback: EventListener = handler as EventListener;
    element.addEventListener(eventName, callback, false);
    return () => this.removeEventListener(element, eventName, callback);
  }

  removeEventListener(target: any, eventName: string, callback: Function): void {
    return target.removeEventListener.apply(target, [eventName, callback, false]);
  }
}

export function getRendererFactory2(document: any): RendererFactory2 {
  const fakeNgZone: NgZone = new NoopNgZone();
  const eventManager = new EventManager([new SimpleDomEventsPlugin(document)], fakeNgZone);
  const rendererFactory =
      new ɵDomRendererFactory2(eventManager, new ɵDomSharedStylesHost(document));
  const origCreateRenderer = rendererFactory.createRenderer;
  rendererFactory.createRenderer = function() {
    const renderer = origCreateRenderer.apply(this, arguments);
    renderer.destroyNode = () => {};
    return renderer;
  };
  return rendererFactory;
}

export function getAnimationRendererFactory2(document: any): RendererFactory2 {
  const fakeNgZone: NgZone = new NoopNgZone();
  return new ɵAnimationRendererFactory(
      getRendererFactory2(document),
      new ɵAnimationEngine(
          document.body, new MockAnimationDriver(), new ɵNoopAnimationStyleNormalizer()),
      fakeNgZone);
}

// TODO: code duplicated from ../linker/change_detection_integration_spec.ts, to be removed
// START duplicated code
export class RenderLog {
  log: string[] = [];
  loggedValues: any[] = [];

  setElementProperty(el: any, propName: string, propValue: any) {
    this.log.push(`${propName}=${propValue}`);
    this.loggedValues.push(propValue);
  }

  setText(node: any, value: string) {
    this.log.push(`{{${value}}}`);
    this.loggedValues.push(value);
  }

  clear() {
    this.log = [];
    this.loggedValues = [];
  }
}

/**
 * This function patches the DomRendererFactory2 so that it returns a DefaultDomRenderer2
 * which logs some of the DOM operations through a RenderLog instance.
 */
export function patchLoggingRenderer2(rendererFactory: RendererFactory2, log: RenderLog) {
  if ((<any>rendererFactory).__patchedForLogging) {
    return;
  }
  (<any>rendererFactory).__patchedForLogging = true;
  const origCreateRenderer = rendererFactory.createRenderer;
  rendererFactory.createRenderer = function() {
    const renderer = origCreateRenderer.apply(this, arguments);
    if ((<any>renderer).__patchedForLogging) {
      return renderer;
    }
    (<any>renderer).__patchedForLogging = true;
    const origSetProperty = renderer.setProperty;
    const origSetValue = renderer.setValue;
    renderer.setProperty = function(el: any, name: string, value: any): void {
      log.setElementProperty(el, name, value);
      origSetProperty.call(renderer, el, name, value);
    };
    renderer.setValue = function(node: any, value: string): void {
      if (getDOM().isTextNode(node)) {
        log.setText(node, value);
      }
      origSetValue.call(renderer, node, value);
    };
    return renderer;
  };
}
// END duplicated code


text:
package org.jboss.resteasy.plugins.providers.multipart;

import java.util.List;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public interface MultipartInput {

	List<InputPart> getParts();

	String getPreamble();

   /**
    * Call this method to delete any temporary files created from unmarshalling this multipart message
    * Otherwise they will be deleted on Garbage Collection or JVM exit.
    */
   void close();
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <regex.h>
#include <pthread.h>
#include <assert.h>

#include "relay.h"
#include "dispatcher.h"
#include "server.h"
#include "router.h"
#include "aggregator.h"

static pthread_t aggregatorid;
static aggregator *aggregators = NULL;
static aggregator *lastaggr = NULL;
static char keep_running = 1;

/**
 * Allocates a new aggregator setup to hold buckets matching interval
 * and expiry time.
 */
aggregator *
aggregator_new(
		unsigned int interval,
		unsigned int expire,
		enum _aggr_timestamp tswhen)
{
	aggregator *ret = malloc(sizeof(aggregator));

	if (ret == NULL)
		return ret;
	if (interval == 0 || expire == 0) {
		free(ret);
		return NULL;
	}

	if (aggregators == NULL) {
		aggregators = lastaggr = ret;
	} else {
		lastaggr = lastaggr->next = ret;
	}

	ret->interval = interval;
	ret->expire = expire;
	ret->tswhen = tswhen;
	ret->bucketcnt = (expire / interval) * 2 + 1 ;
	ret->received = 0;
	ret->sent = 0;
	ret->dropped = 0;
	ret->computes = NULL;
	ret->next = NULL;

	pthread_mutex_init(&ret->bucketlock, NULL);

	return ret;
}

/**
 * Adds a new compute part to this aggregator.  Returns -1 if type is
 * not a recognised aggregation type.
 */
char
aggregator_add_compute(
		aggregator *s,
		const char *metric,
		const char *type)
{
	struct _aggr_computes *ac = s->computes;
	enum _aggr_compute_type act;

	if (strcmp(type, "sum") == 0) {
		act = SUM;
	} else if (strcmp(type, "count") == 0 || strcmp(type, "cnt") == 0) {
		act = CNT;
	} else if (strcmp(type, "max") == 0) {
		act = MAX;
	} else if (strcmp(type, "min") == 0) {
		act = MIN;
	} else if (strcmp(type, "average") == 0 || strcmp(type, "avg") == 0) {
		act = AVG;
	} else {
		return -1;
	}

	if (ac == NULL) {
		ac = s->computes = malloc(sizeof(*ac));
	} else {
		while (ac->next != NULL)
			ac = ac->next;
		ac = ac->next = malloc(sizeof(*ac));
	}

	ac->type = act;
	ac->metric = strdup(metric);
	memset(ac->invocations_ht, 0, sizeof(ac->invocations_ht));
	ac->next = NULL;

	return 0;
}

/**
 * Adds a new metric to aggregator s.  The value from the metric is put
 * in the bucket matching the epoch contained in the metric.  In cases
 * where the contained epoch is too old or too new, the metric is
 * dropped.
 */
void
aggregator_putmetric(
		aggregator *s,
		const char *metric,
		const char *firstspace,
		size_t nmatch,
		regmatch_t *pmatch)
{
	char *v;
	double val;
	long long int epoch;
	long long int itime;
	int slot;
	struct _bucket *bucket;
	char newmetric[METRIC_BUFSIZ];
	char *newfirstspace = NULL;
	size_t len;
	const char *ometric;
	const char *omp;
	unsigned int omhash;
	unsigned int omhtbucket;
	struct _aggr_computes *compute;
	struct _aggr_invocations *invocation;

	/* get value */
	if ((v = strchr(firstspace + 1, ' ')) == NULL) {
		/* metric includes \n */
		if (mode == DEBUG || mode == DEBUGTEST)
			logerr("aggregator: dropping incorrect metric: %s",
					metric);
		return;
	}

	s->received++;

	val = atof(firstspace + 1);
	epoch = atoll(v + 1);

	pthread_mutex_lock(&s->bucketlock);
	for (compute = s->computes; compute != NULL; compute = compute->next) {
		if (nmatch == 0) {
			ometric = compute->metric;
		} else if ((len = router_rewrite_metric(
						&newmetric, &newfirstspace,
						metric, firstspace,
						compute->metric,
						nmatch, pmatch)) == 0)
		{
			/* fail, skip */
			continue;
		} else {
			*newfirstspace = '\0';
			ometric = newmetric;
		}

		omhash = 2166136261UL;  /* FNV1a */
		for (omp = ometric; *omp != '\0'; omp++)
			omhash = (omhash ^ (unsigned int)*omp) * 16777619;

		omhtbucket =
			((omhash >> AGGR_HT_POW_SIZE) ^ omhash) &
			(((unsigned int)1 << AGGR_HT_POW_SIZE) - 1);
		invocation = compute->invocations_ht[omhtbucket];
		for (; invocation != NULL; invocation = invocation->next)
			if (invocation->hash == omhash &&
					strcmp(ometric, invocation->metric) == 0)  /* match */
				break;
		if (invocation == NULL) {  /* no match, add */
			int i;
			time_t now;

			if ((invocation = malloc(sizeof(*invocation))) == NULL) {
				logerr("aggregator: out of memory creating %s from %s",
						ometric, metric);
				continue;
			}
			if ((invocation->metric = strdup(ometric)) == NULL) {
				logerr("aggregator: out of memory creating %s from %s",
						ometric, metric);
				free(invocation);
				continue;
			}
			invocation->hash = omhash;

			/* Start buckets in the past such that expiry time
			 * conditions are met.  Add a splay to the expiry time to
			 * avoid a thundering herd of expirations when the
			 * aggregator is spammed with metrics, e.g. right after
			 * startup when other relays flush their queues.  This
			 * approach shouldn't affect the timing of the buckets as
			 * requested in issue #72. */
			time(&now);
			now -= s->expire;
			invocation->expire = s->expire + (rand() % s->interval);

			/* allocate enough buckets to hold the past + future */
			invocation->buckets =
				malloc(sizeof(struct _bucket) * s->bucketcnt);
			if (invocation->buckets == NULL) {
				logerr("aggregator: out of memory creating %s from %s",
						ometric, metric);
				free(invocation->metric);
				free(invocation);
				continue;
			}
			for (i = 0; i < s->bucketcnt; i++) {
				invocation->buckets[i].start = now + (i * s->interval);
				invocation->buckets[i].cnt = 0;
			}

			invocation->next = compute->invocations_ht[omhtbucket];
			compute->invocations_ht[omhtbucket] = invocation;
		}

		/* finally, try to do the maths */

		itime = epoch - invocation->buckets[0].start;
		if (itime < 0) {
			/* drop too old metric */
			s->dropped++;
			continue;
		}

		slot = itime / s->interval;
		if (slot >= s->bucketcnt) {
			if (mode == DEBUG || mode == DEBUGTEST)
				logerr("aggregator: dropping metric too far in the "
						"future (%lld > %lld): %s from %s", epoch,
						invocation->buckets[s->bucketcnt - 1].start,
						ometric, metric);
			s->dropped++;
			continue;
		}

		bucket = &invocation->buckets[slot];
		if (bucket->cnt == 0) {
			bucket->cnt = 1;
			bucket->sum = val;
			bucket->max = val;
			bucket->min = val;
		} else {
			bucket->cnt++;
			bucket->sum += val;
			if (bucket->max < val)
				bucket->max = val;
			if (bucket->min > val)
				bucket->min = val;
		}
	}
	pthread_mutex_unlock(&s->bucketlock);

	return;
}

/**
 * Checks if the oldest bucket should be expired, if so, sends out
 * computed aggregate metrics and moves the bucket to the end of the
 * list.  When no buckets are in use for an invocation, it is removed to
 * cleanup resources.
 */
static void *
aggregator_expire(void *sub)
{
	time_t now;
	aggregator *s;
	struct _bucket *b;
	struct _aggr_computes *c;
	struct _aggr_invocations *inv;
	struct _aggr_invocations *lastinv;
	int i;
	int work;
	server *submission = (server *)sub;
	char metric[METRIC_BUFSIZ];
	char isempty;
	long long int ts = 0;

	while (1) {
		work = 0;

		for (s = aggregators; s != NULL; s = s->next) {
			/* send metrics for buckets that are completely past the
			 * expiry time, unless we are shutting down, then send
			 * metrics for all buckets that have completed */
			now = time(NULL) + (keep_running ? 0 : s->expire - s->interval);
			for (c = s->computes; c != NULL; c = c->next) {
				for (i = 0; i < (1 << AGGR_HT_POW_SIZE); i++) {
					lastinv = NULL;
					isempty = 0;
					for (inv = c->invocations_ht[i]; inv != NULL; ) {
						while (inv->buckets[0].start +
								(keep_running ? inv->expire : s->expire) < now)
						{
							/* yay, let's produce something cool */
							b = &inv->buckets[0];
							/* avoid emitting empty/unitialised data */
							isempty = b->cnt == 0;
							if (!isempty) {
								switch (s->tswhen) {
									case TS_START:
										ts = b->start;
										break;
									case TS_MIDDLE:
										ts = b->start + (s->interval / 2);
										break;
									case TS_END:
										ts = b->start + s->interval;
										break;
									default:
										assert(0);
								}
								switch (c->type) {
									case SUM:
										snprintf(metric, sizeof(metric),
												"%s %f %lld\n",
												inv->metric, b->sum, ts);
										break;
									case CNT:
										snprintf(metric, sizeof(metric),
												"%s %zd %lld\n",
												inv->metric, b->cnt, ts);
										break;
									case MAX:
										snprintf(metric, sizeof(metric),
												"%s %f %lld\n",
												inv->metric, b->max, ts);
										break;
									case MIN:
										snprintf(metric, sizeof(metric),
												"%s %f %lld\n",
												inv->metric, b->min, ts);
										break;
									case AVG:
										snprintf(metric, sizeof(metric),
												"%s %f %lld\n",
												inv->metric,
												b->sum / (double)b->cnt, ts);
										break;
								}
								server_send(submission, strdup(metric), 1);
								s->sent++;
							}

							/* move the bucket to the end, to make room for
							 * new ones */
							pthread_mutex_lock(&s->bucketlock);
							memmove(&inv->buckets[0], &inv->buckets[1],
									sizeof(*b) * (s->bucketcnt - 1));
							b = &inv->buckets[s->bucketcnt - 1];
							b->cnt = 0;
							b->start =
								inv->buckets[s->bucketcnt - 2].start +
								s->interval;
							pthread_mutex_unlock(&s->bucketlock);

							work++;
						}

						if (isempty) {
							int j;
							/* see if the remaining buckets are empty too */
							pthread_mutex_lock(&s->bucketlock);
							for (j = 0; j < s->bucketcnt; j++) {
								if (inv->buckets[j].cnt != 0) {
									isempty = 0;
									pthread_mutex_unlock(&s->bucketlock);
									break;
								}
							}
						}
						if (isempty) {
							/* free and unlink */
							free(inv->metric);
							free(inv->buckets);
							if (lastinv != NULL) {
								lastinv->next = inv->next;
								free(inv);
								inv = lastinv->next;
							} else {
								c->invocations_ht[i] = inv->next;
								free(inv);
								inv = c->invocations_ht[i];
							}
							pthread_mutex_unlock(&s->bucketlock);
						} else {
							lastinv = inv;
							inv = inv->next;
						}
					}
				}
			}
		}

		if (work == 0) {
			if (!keep_running)
				break;
			/* nothing done, avoid spinlocking */
			usleep(250 * 1000);  /* 250ms */
		}
	}

	return NULL;
}

/**
 * Returns the number of aggregators defined.
 */
size_t
aggregator_numaggregators(void)
{
	size_t totaggregators = 0;
	aggregator *a;

	for (a = aggregators; a != NULL; a = a->next)
		totaggregators++;

	return totaggregators;
}

/**
 * Returns the total number of computations defined.
 */
size_t
aggregator_numcomputes(void)
{
	size_t totcomputes = 0;
	aggregator *a;
	struct _aggr_computes *c;

	for (a = aggregators; a != NULL; a = a->next)
		for (c = a->computes; c != NULL; c = c->next)
			totcomputes++;

	return totcomputes;
}

/**
 * Initialises and starts the aggregator.  Returns false when starting
 * failed, true otherwise.
 */
int
aggregator_start(server *submission)
{
	if (pthread_create(&aggregatorid, NULL, aggregator_expire, submission) != 0)
		return 0;

	return 1;
}

/**
 * Shuts down the aggregator.
 */
void
aggregator_stop(void)
{
	keep_running = 0;
	pthread_join(aggregatorid, NULL);
}

/**
 * Returns an approximate number of received metrics by all aggregators.
 */
size_t
aggregator_get_received(void)
{
	size_t totreceived = 0;
	aggregator *a;

	for (a = aggregators; a != NULL; a = a->next)
		totreceived += a->received;

	return totreceived;
}

/**
 * Returns an approximate number of metrics sent by all aggregators.
 */
size_t
aggregator_get_sent(void)
{
	size_t totsent = 0;
	aggregator *a;

	for (a = aggregators; a != NULL; a = a->next)
		totsent += a->sent;

	return totsent;
}

/**
 * Returns an approximate number of dropped metrics by all aggregators.
 * Metrics are dropped if they are too much in the past (past expiry
 * time) or if they are too much in the future.
 */
size_t
aggregator_get_dropped(void)
{
	size_t totdropped = 0;
	aggregator *a;

	for (a = aggregators; a != NULL; a = a->next)
		totdropped += a->dropped;

	return totdropped;
}


text:
<?php

namespace Robotusers\Tactician\Event;

use Cake\Core\InstanceConfigTrait;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use InvalidArgumentException;
use League\Tactician\CommandBus;
use Robotusers\Commander\CommandBusAwareInterface;
use Robotusers\Commander\CommandBusInterface;
use Robotusers\Tactician\Bus\TacticianAdapter;

/**
 * Event listener for a command bus.
 *
 * @author Robert Pustułka <r.pustulka@robotusers.com>
 */
class BusListener implements EventListenerInterface
{

    use InstanceConfigTrait;
    /**
     * @var CommandBusInterface
     */
    protected $commandBus;

    /**
     * @var array
     */
    protected $_defaultConfig = [
        'events' => [
            'Controller.initialize',
            'Model.initialize'
        ],
        'adapter' => []
    ];

    /**
     * Constructor.
     *
     * You can configure events using `events` config option.
     *
     * @param CommandBusInterface|CommandBus $commandBus Command bus instance.
     * @param array $config Configuration.
     * @return void
     */
    public function __construct($commandBus, array $config = [])
    {
        $this->setConfig($config);
        $this->setCommandBus($commandBus);
    }

    /**
     * Sets command bus.
     *
     * @param CommandBusInterface|CommandBus $commandBus Command bus instance.
     * @return $this
     * @throws InvalidArgumentException When invalid argument passed.
     */
    public function setCommandBus($commandBus)
    {
        if (!$commandBus instanceof CommandBusInterface) {
            if (!$commandBus instanceof CommandBus) {
                $classes = implode('` or `', [CommandBusInterface::class, CommandBus::class]);
                $type = is_object($commandBus) ? get_class($commandBus) : gettype($commandBus);
                $message = sprintf('Invalid command bus encountered. Expected `%s`, got `%s`.', $classes, $type);

                throw new InvalidArgumentException($message);
            }

            $commandBus = new TacticianAdapter($commandBus, $this->_config['adapter']);
        }

        $this->commandBus = $commandBus;

        return $this;
    }

    /**
     * Returns a command bus instance.
     *
     * @return CommandBusInterface
     */
    public function getCommandBus()
    {
        return $this->commandBus;
    }

    /**
     * Callback.
     *
     * @param Event $event Event instance.
     * @return void
     */
    public function injectCommandBus(Event $event)
    {
        $subject = $event->getSubject();
        if ($subject instanceof CommandBusAwareInterface) {
            $subject->setCommandBus($this->commandBus);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function implementedEvents(): array
    {
        $events = (array)$this->_config['events'];

        return array_fill_keys($events, 'injectCommandBus');
    }
}


text:
package com.benromberg.cordonbleu.data.migration.change0011;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class CommitAuthorBefore {
    @JsonProperty
    private final String name;

    @JsonProperty
    private final String email;

    @JsonCreator
    public CommitAuthorBefore(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }
}


text:
import nltk, re, pprint
from urllib import urlopen

def read_from_url(url, proxies=None):
    #proxies = {'http': 'http://127.0.0.1:8087'}
    raw = urlopen(url, proxies=proxies).read()
    return raw

def tokennize(raw):
    return nltk.word_tokenize(raw)

def find_contents(raw, start_string, end_string):
    beginning = raw.find(start_string)
    end = raw.rfind(end_string)
    raw = raw[beginning: end]
    return raw

if __name__ == "__main__":
    url = "http://www.gutenberg.org/files/2554/2554.txt"
    raw = read_from_url(url)
    tokens = tokennize(raw)
    print tokens[:10]
    print len(tokens)

    text = nltk.Text(tokens)
    print type(text)
    print text[1020:1060]
    # find 20 sequences of words that occur together unusually ofen.
    text.collocations()

    raw = find_contents(raw, "PART I", "End of Project Gutenberg's Crime")
    print len(raw)


text:
react-demo
==========

demos of react


text:
<?php

class DeletePublishFromSlides extends CakeMigration
{
    /**
     * Migration description.
     *
     * @var string
     */
    public $description = 'delete_publish_from_slides';

    /**
     * Actions to be performed.
     *
     * @var array
     */
    public $migration = array(
        'up' => array(
            'drop_field' => array(
                'slides' => array(
                    'publish',
                ),
            ),
        ),
    );

    /**
     * Before migration callback.
     *
     * @param string $direction Direction of migration process (up or down)
     *
     * @return bool Should process continue
     */
    public function before($direction)
    {
        return true;
    }

    /**
     * After migration callback.
     *
     * @param string $direction Direction of migration process (up or down)
     *
     * @return bool Should process continue
     */
    public function after($direction)
    {
        return true;
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\Users\ユーザー名\php-recipe\lib/Language.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\Users\ユーザー名\php-recipe\lib /

Language.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

100.00%

1 / 1

100.00%

2 / 2

      <acronym title="Change Risk Anti-Patterns (CRAP) Index">CRAP</acronym>

100.00%

7 / 7

      Language

100.00%

1 / 1

100.00%

2 / 2

      2

100.00%

7 / 7

       __construct($db)

100.00%

1 / 1

      1

100.00%

2 / 2

       insert($language)

100.00%

1 / 1

      1

100.00%

5 / 5

1
	<?php

2
	# テスト対象のクラスを定義します。

3
	class Language

4
	{

5
	  protected $db;

6

7
	# PDOによるデータベース接続をインスタンス生成時に受け取り、プロパティに保存します。

8
	  public function __construct($db)

9
	  {

10
	    $this->db = $db;

11
	  }

12

13
	# テスト対象のメソッドを定義します。

14
	  public function insert($language)

15
	  {

16
	# レコードを追加☆レシピ265☆(新規レコードを作成したい)します。

17
	    $sql = 'INSERT INTO example (language) VALUES (:language)';

18
	    $prepare = $this->db->prepare($sql);

19
	    $prepare->bindValue(':language', $language, PDO::PARAM_STR);

20
	    $prepare->execute();

21
	  }

22
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.12 using PHP 5.5.1 and PHPUnit 3.7.24 at Fri Aug 16 8:56:16 JST 2013.


text:
<?php

namespace yiiunit\extensions\authclient;

use yii\authclient\Collection;
use yii\authclient\BaseClient;

class CollectionTest extends TestCase
{
	// Tests :

	public function testSetGet()
	{
		$collection = new Collection();

		$clients = [
			'testClient1' => new TestClient(),
			'testClient2' => new TestClient(),
		];
		$collection->setClients($clients);
		$this->assertEquals($clients, $collection->getClients(), 'Unable to setup clients!');
	}

	/**
	 * @depends testSetGet
	 */
	public function testGetProviderById()
	{
		$collection = new Collection();

		$clientId = 'testClientId';
		$client = new TestClient();
		$clients = [
			$clientId => $client
		];
		$collection->setClients($clients);

		$this->assertEquals($client, $collection->getClient($clientId), 'Unable to get client by id!');
	}

	/**
	 * @depends testGetProviderById
	 */
	public function testCreateProvider()
	{
		$collection = new Collection();

		$clientId = 'testClientId';
		$clientClassName = TestClient::className();
		$clients = [
			$clientId => [
				'class' => $clientClassName
			]
		];
		$collection->setClients($clients);

		$provider = $collection->getClient($clientId);
		$this->assertTrue(is_object($provider), 'Unable to create client by config!');
		$this->assertTrue(is_a($provider, $clientClassName), 'Client has wrong class name!');
	}

	/**
	 * @depends testSetGet
	 */
	public function testHasProvider()
	{
		$collection = new Collection();

		$clientName = 'testClientName';
		$clients = [
			$clientName => [
				'class' => 'TestClient1'
			],
		];
		$collection->setClients($clients);

		$this->assertTrue($collection->hasClient($clientName), 'Existing client check fails!');
		$this->assertFalse($collection->hasClient('unExistingClientName'), 'Not existing client check fails!');
	}
}

class TestClient extends BaseClient
{
}


text:
package com.example.dangweather.activity;

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

import com.example.dangweather.R;
import com.example.dangweather.db.dangWeatherDB;
import com.example.dangweather.model.City;
import com.example.dangweather.model.County;
import com.example.dangweather.model.Province;
import com.example.dangweather.util.HttpCallBackListener;
import com.example.dangweather.util.HttpUtil;
import com.example.dangweather.util.Utility;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChooseAreaActivity extends Activity {

	public static final int LEVEL_PROVINCE = 0;
	public static final int LEVEL_CITY = 1;
	public static final int LEVEL_COUNTY = 2;

	private ProgressDialog progressDialog;
	private TextView titleText;
	private ListView listView;
	private ArrayAdapter<String>  arrayAdapter;
	private dangWeatherDB dangWeatherDB;
	private List<String> dataList = new ArrayList<String>();

	private List<Province> provinceList ;
	private List<City> cityList ;
	private List<County> countyList ;
    private Province selectProvince;
    private City     selectCity;
    private int      currentLevel;
    private boolean isFromWeatherActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	//Ñ¡ÔñÁ˳ÇÊв¢ÇÒ²»ÊÇ´ÓweatheractivityÌøת¹ýÀ´
    	if(prefs.getBoolean("city_selected", false)&&!isFromWeatherActivity){
    		Intent intent = new Intent(this,WeatherActivity.class);
    		startActivity(intent);
    		finish();
    		return;
    	}

    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	setContentView(R.layout.choose_area);
    	listView = (ListView) findViewById(R.id.list_view);
    	titleText = (TextView) findViewById(R.id.title_text);
    	arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
    	listView.setAdapter(arrayAdapter);
    	dangWeatherDB = dangWeatherDB.getInstance(this);
    	listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,long arg3) {
					if(currentLevel == LEVEL_PROVINCE){
						selectProvince = provinceList.get(index);
						queryCities();
					}else if(currentLevel == LEVEL_CITY){
						selectCity = cityList.get(index);
						queryCounties();
					}else if(currentLevel == LEVEL_COUNTY){
						String countyCode = countyList.get(index).getCountyCode();
						Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
						intent.putExtra("county_code", countyCode);
						startActivity(intent);
						finish();
					}
			}
		});
    	queryProvinces();
    }

    /**
     * ²éѯʡµÄÊý¾Ý
     */
	private void queryProvinces() {
		provinceList = dangWeatherDB.loadProvince();
		if(provinceList.size()>0){
			dataList.clear();
			for(Province province:provinceList){
				dataList.add(province.getProvinceName());
			}
			arrayAdapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText("Öйú");
			currentLevel = LEVEL_PROVINCE;
		}else{
			queryFromServer(null,"province");
		}
	}

	/**
	 * ²éѯ³ÇÊÐÐÅÏ¢
	 */
	private void queryCities() {
		cityList = dangWeatherDB.loadCities(selectProvince.getId());
		if(cityList.size()>0){
			dataList.clear();
			for(City city:cityList){
				dataList.add(city.getCityName());
			}
			arrayAdapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectProvince.getProvinceName());
			currentLevel = LEVEL_CITY;
		}else{
			queryFromServer(selectProvince.getProvinceCode(),"city");
		}
	}

	/**
	 * ²éѯÏصÄÐÅÏ¢
	 */
	private void queryCounties() {
		countyList = dangWeatherDB.loadCounties(selectCity.getId());
		if(countyList.size()>0){
			dataList.clear();
			for(County county:countyList){
				dataList.add(county.getCountyName());
			}
			arrayAdapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectCity.getCityName());
			currentLevel = LEVEL_COUNTY;
		}else{
			queryFromServer(selectCity.getCityCode(),"county");
		}
	}

	/**
	 * ´Ó·þÎñÆ÷Éϲéѯʡ¡¢ÊС¢ÏØÊý¾Ý
	 */
	private void queryFromServer(final String cityCode, final String type) {
		String address;
		if(!TextUtils.isEmpty(cityCode)){
			address = "http://www.weather.com.cn/data/list3/city"+cityCode+".xml";
		}else{
			address = "http://www.weather.com.cn/data/list3/city.xml";
		}
		showProgressDialog();
		HttpUtil.sendHttpRequest(address, new HttpCallBackListener() {

			@Override
			public void onFinish(String content) {
				boolean result = false;
				if(type.equals("province")){
					result = Utility.handleProvince(dangWeatherDB, content);
				}else if(type.equals("city")){
					result = Utility.handleCities(dangWeatherDB, content,selectProvince.getId());
				}else if(type.equals("county")){
					result = Utility.handleCounties(dangWeatherDB, content,selectCity.getId());
				}

				if(result){
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							closeProgressDialog();
							if("province".equals(type)){
								queryProvinces();
							}else if("city".equals(type)){
								queryCities();
							}else if("county".equals(type)){
								queryCounties();
							}
						}
					});
				}

			}

			@Override
			public void onError(Exception e) {
				runOnUiThread(new  Runnable() {
					public void run() {
						closeProgressDialog();
						Toast.makeText(ChooseAreaActivity.this, "¼ÓÔØʧ°Ü", Toast.LENGTH_SHORT);
					}
				});
			}
		});
	}

	/**
	 * ÏÔʾ½ø¶È¶Ô»°¿ò
	 */
	private void showProgressDialog(){
		if(progressDialog ==null){
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("ÕýÔÚ¼ÓÔØ....");
			progressDialog.setCanceledOnTouchOutside(false);
		}
		progressDialog.show();
	}

	/**
	 * ¹Ø±Õ½ø¶È¶Ô»°¿ò
	 */
	private void closeProgressDialog(){
		if(progressDialog!=null){
			progressDialog.dismiss();
		}
	}

	@Override
	public void onBackPressed() {
		if(currentLevel==LEVEL_COUNTY){
			queryCities();
		}else if(currentLevel==LEVEL_CITY){
			queryProvinces();
		}else{
			if(isFromWeatherActivity){
				Intent intent = new Intent(this, WeatherActivity.class);
				startActivity(intent);
			}
			finish();
		}

	}

}


text:
<?php

require __DIR__.'/../autoload.php';

require __DIR__.'/PHPUnit/ArrayHasSameValuesConstraint.php';
require __DIR__.'/PHPUnit/RedisCommandConstraint.php';
require __DIR__.'/PHPUnit/PredisTestCase.php';
require __DIR__.'/PHPUnit/PredisCommandTestCase.php';
require __DIR__.'/PHPUnit/PredisConnectionTestCase.php';
require __DIR__.'/PHPUnit/PredisProfileTestCase.php';
require __DIR__.'/PHPUnit/PredisDistributorTestCase.php';


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Linn. Soc. London 27: 185 (1869)

#### Original name
Trypethelium uberinum Leight.

### Remarks
null


text:
package org.drools.guvnor.client.explorer.navigation.qa.testscenarios;

import com.google.gwt.user.client.ui.*;
import org.drools.guvnor.client.common.FormStylePopup;
import org.drools.guvnor.client.common.ImageButton;
import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.resources.DroolsGuvnorImageResources;
import org.drools.guvnor.client.resources.DroolsGuvnorImages;
import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine;
import org.drools.ide.common.client.modeldriven.testing.Scenario;
import org.drools.ide.common.client.modeldriven.testing.FactData;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;

class GlobalButton extends ImageButton {

    private final Scenario                   scenario;
    private final ScenarioWidget             parent;

    private final SuggestionCompletionEngine suggestionCompletionEngine;

    public GlobalButton(final Scenario scenario,
                        final ScenarioWidget parent) {
        super( DroolsGuvnorImages.INSTANCE.NewItem(),
               Constants.INSTANCE.AddANewGlobalToThisScenario() );

        this.scenario = scenario;
        this.parent = parent;
        this.suggestionCompletionEngine = parent.suggestionCompletionEngine;

        addGlobalButtonClickHandler();
    }

    private void addGlobalButtonClickHandler() {
        addClickHandler( new ClickHandler() {
            public void onClick(ClickEvent event) {
                final FormStylePopup popup = new NewGlobalPopup();
                popup.show();
            }
        } );
    }

    class NewGlobalPopup extends FormStylePopup {

        final ListBox  factTypes;
        private Button addButton;
        private Widget warning;

        public NewGlobalPopup() {
            super(DroolsGuvnorImages.INSTANCE.RuleAsset(),
                   Constants.INSTANCE.NewGlobal() );

            factTypes = new ListBox();
            addButton = new AddButton();
            warning = getMissingGlobalsWarning();

            fillFactTypes();

            addRow( warning );

            addAttribute( Constants.INSTANCE.GlobalColon(),
                          getHorizontalPanel() );
        }

        private HorizontalPanel getHorizontalPanel() {
            HorizontalPanel insertFact = new HorizontalPanel();
            insertFact.add( factTypes );
            insertFact.add( addButton );
            return insertFact;
        }

        private void fillFactTypes() {
            if ( suggestionCompletionEngine.getGlobalVariables().length == 0 ) {
                addButton.setEnabled( false );
                factTypes.setEnabled( false );
                warning.setVisible( true );
            } else {
                addButton.setEnabled( true );
                factTypes.setEnabled( true );
                warning.setVisible( false );
                for ( String globals : suggestionCompletionEngine.getGlobalVariables() ) {
                    factTypes.addItem( globals );
                }
            }
        }

        class AddButton extends Button {

            public AddButton() {
                super( Constants.INSTANCE.Add() );
                addAddClickHandler();
            }

            private void addAddClickHandler() {
                addClickHandler( new ClickHandler() {

                    public void onClick(ClickEvent event) {
                        String text = factTypes.getItemText( factTypes.getSelectedIndex() );
                        if ( scenario.isFactNameReserved( text ) ) {
                            Window.alert( Constants.INSTANCE.TheName0IsAlreadyInUsePleaseChooseAnotherName( text ) );
                        } else {
                            FactData factData = new FactData( suggestionCompletionEngine.getGlobalVariable( text ),
                                                              text,
                                                              false );
                            scenario.getGlobals().add( factData );
                            parent.renderEditor();

                            hide();
                        }
                    }
                } );
            }
        }

    }

    //A simple banner to alert users that no Globals have been defined
    private Widget getMissingGlobalsWarning() {
        HTML warning = new HTML( Constants.INSTANCE.missingGlobalsWarning() );
        warning.getElement().setClassName( "missingGlobalsWarning" );
        return warning;
    }
}