text:
import itertools
import logging
import os
import platform
import threading
from typing import (
    Callable,
    Dict,
    Generic,
    Iterable,
    Mapping,
    Optional,
    Sequence,
    Set,
    Tuple,
    Type,
    TypeVar,
    Union,
    cast,
)

import attr
from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram, Metric
from prometheus_client.core import (
    REGISTRY,
    GaugeHistogramMetricFamily,
    GaugeMetricFamily,
)

from twisted.python.threadpool import ThreadPool

# This module is imported for its side effects; flake8 needn't warn that it's unused.
import synapse.metrics._reactor_metrics  # noqa: F401
from synapse.metrics._gc import MIN_TIME_BETWEEN_GCS, install_gc_manager
from synapse.metrics._twisted_exposition import MetricsResource, generate_latest
from synapse.metrics._types import Collector
from synapse.util import SYNAPSE_VERSION

logger = logging.getLogger(__name__)

METRICS_PREFIX = "/_synapse/metrics"

all_gauges: Dict[str, Collector] = {}

HAVE_PROC_SELF_STAT = os.path.exists("/proc/self/stat")

class _RegistryProxy:
    @staticmethod
    def collect() -> Iterable[Metric]:
        for metric in REGISTRY.collect():
            if not metric.name.startswith("__"):
                yield metric

# A little bit nasty, but collect() above is static so a Protocol doesn't work.
# _RegistryProxy matches the signature of a CollectorRegistry instance enough
# for it to be usable in the contexts in which we use it.
# TODO Do something nicer about this.
RegistryProxy = cast(CollectorRegistry, _RegistryProxy)

@attr.s(slots=True, hash=True, auto_attribs=True)
class LaterGauge(Collector):
    name: str
    desc: str
    labels: Optional[Sequence[str]] = attr.ib(hash=False)
    # callback: should either return a value (if there are no labels for this metric),
    # or dict mapping from a label tuple to a value
    caller: Callable[
        [], Union[Mapping[Tuple[str, ...], Union[int, float]], Union[int, float]]
    ]

    def collect(self) -> Iterable[Metric]:

        g = GaugeMetricFamily(self.name, self.desc, labels=self.labels)

        try:
            calls = self.caller()
        except Exception:
            logger.exception("Exception running callback for LaterGauge(%s)", self.name)
            yield g
            return

        if isinstance(calls, (int, float)):
            g.add_metric([], calls)
        else:
            for k, v in calls.items():
                g.add_metric(k, v)

        yield g

    def __attrs_post_init__(self) -> None:
        self._register()

    def _register(self) -> None:
        if self.name in all_gauges.keys():
            logger.warning("%s already registered, reregistering" % (self.name,))
            REGISTRY.unregister(all_gauges.pop(self.name))

        REGISTRY.register(self)
        all_gauges[self.name] = self

# `MetricsEntry` only makes sense when it is a `Protocol`,
# but `Protocol` can't be used as a `TypeVar` bound.
MetricsEntry = TypeVar("MetricsEntry")

class InFlightGauge(Generic[MetricsEntry], Collector):
    """Tracks number of things (e.g. requests, Measure blocks, etc) in flight
    at any given time.

    Each InFlightGauge will create a metric called `<name>_total` that counts
    the number of in flight blocks, as well as a metrics for each item in the
    given `sub_metrics` as `<name>_<sub_metric>` which will get updated by the
    callbacks.

    Args:
        name
        desc
        labels
        sub_metrics: A list of sub metrics that the callbacks will update.
    """

    def __init__(
        self,
        name: str,
        desc: str,
        labels: Sequence[str],
        sub_metrics: Sequence[str],
    ):
        self.name = name
        self.desc = desc
        self.labels = labels
        self.sub_metrics = sub_metrics

        # Create a class which have the sub_metrics values as attributes, which
        # default to 0 on initialization. Used to pass to registered callbacks.
        self._metrics_class: Type[MetricsEntry] = attr.make_class(
            "_MetricsEntry",
            attrs={x: attr.ib(default=0) for x in sub_metrics},
            slots=True,
        )

        # Counts number of in flight blocks for a given set of label values
        self._registrations: Dict[
            Tuple[str, ...], Set[Callable[[MetricsEntry], None]]
        ] = {}

        # Protects access to _registrations
        self._lock = threading.Lock()

        self._register_with_collector()

    def register(
        self,
        key: Tuple[str, ...],
        callback: Callable[[MetricsEntry], None],
    ) -> None:
        """Registers that we've entered a new block with labels `key`.

        `callback` gets called each time the metrics are collected. The same
        value must also be given to `unregister`.

        `callback` gets called with an object that has an attribute per
        sub_metric, which should be updated with the necessary values. Note that
        the metrics object is shared between all callbacks registered with the
        same key.

        Note that `callback` may be called on a separate thread.
        """
        with self._lock:
            self._registrations.setdefault(key, set()).add(callback)

    def unregister(
        self,
        key: Tuple[str, ...],
        callback: Callable[[MetricsEntry], None],
    ) -> None:
        """Registers that we've exited a block with labels `key`."""

        with self._lock:
            self._registrations.setdefault(key, set()).discard(callback)

    def collect(self) -> Iterable[Metric]:
        """Called by prometheus client when it reads metrics.

        Note: may be called by a separate thread.
        """
        in_flight = GaugeMetricFamily(
            self.name + "_total", self.desc, labels=self.labels
        )

        metrics_by_key = {}

        # We copy so that we don't mutate the list while iterating
        with self._lock:
            keys = list(self._registrations)

        for key in keys:
            with self._lock:
                callbacks = set(self._registrations[key])

            in_flight.add_metric(key, len(callbacks))

            metrics = self._metrics_class()
            metrics_by_key[key] = metrics
            for callback in callbacks:
                callback(metrics)

        yield in_flight

        for name in self.sub_metrics:
            gauge = GaugeMetricFamily(
                "_".join([self.name, name]), "", labels=self.labels
            )
            for key, metrics in metrics_by_key.items():
                gauge.add_metric(key, getattr(metrics, name))
            yield gauge

    def _register_with_collector(self) -> None:
        if self.name in all_gauges.keys():
            logger.warning("%s already registered, reregistering" % (self.name,))
            REGISTRY.unregister(all_gauges.pop(self.name))

        REGISTRY.register(self)
        all_gauges[self.name] = self

class GaugeBucketCollector(Collector):
    """Like a Histogram, but the buckets are Gauges which are updated atomically.

    The data is updated by calling `update_data` with an iterable of measurements.

    We assume that the data is updated less frequently than it is reported to
    Prometheus, and optimise for that case.
    """

    __slots__ = (
        "_name",
        "_documentation",
        "_bucket_bounds",
        "_metric",
    )

    def __init__(
        self,
        name: str,
        documentation: str,
        buckets: Iterable[float],
        registry: CollectorRegistry = REGISTRY,
    ):
        """
        Args:
            name: base name of metric to be exported to Prometheus. (a _bucket suffix
               will be added.)
            documentation: help text for the metric
            buckets: The top bounds of the buckets to report
            registry: metric registry to register with
        """
        self._name = name
        self._documentation = documentation

        # the tops of the buckets
        self._bucket_bounds = [float(b) for b in buckets]
        if self._bucket_bounds != sorted(self._bucket_bounds):
            raise ValueError("Buckets not in sorted order")

        if self._bucket_bounds[-1] != float("inf"):
            self._bucket_bounds.append(float("inf"))

        # We initially set this to None. We won't report metrics until
        # this has been initialised after a successful data update
        self._metric: Optional[GaugeHistogramMetricFamily] = None

        registry.register(self)

    def collect(self) -> Iterable[Metric]:
        # Don't report metrics unless we've already collected some data
        if self._metric is not None:
            yield self._metric

    def update_data(self, values: Iterable[float]) -> None:
        """Update the data to be reported by the metric

        The existing data is cleared, and each measurement in the input is assigned
        to the relevant bucket.
        """
        self._metric = self._values_to_metric(values)

    def _values_to_metric(self, values: Iterable[float]) -> GaugeHistogramMetricFamily:
        total = 0.0
        bucket_values = [0 for _ in self._bucket_bounds]

        for v in values:
            # assign each value to a bucket
            for i, bound in enumerate(self._bucket_bounds):
                if v <= bound:
                    bucket_values[i] += 1
                    break

            # ... and increment the sum
            total += v

        # now, aggregate the bucket values so that they count the number of entries in
        # that bucket or below.
        accumulated_values = itertools.accumulate(bucket_values)

        return GaugeHistogramMetricFamily(
            self._name,
            self._documentation,
            buckets=list(
                zip((str(b) for b in self._bucket_bounds), accumulated_values)
            ),
            gsum_value=total,
        )

#
# Detailed CPU metrics
#

class CPUMetrics(Collector):
    def __init__(self) -> None:
        ticks_per_sec = 100
        try:
            # Try and get the system config
            ticks_per_sec = os.sysconf("SC_CLK_TCK")
        except (ValueError, TypeError, AttributeError):
            pass

        self.ticks_per_sec = ticks_per_sec

    def collect(self) -> Iterable[Metric]:
        if not HAVE_PROC_SELF_STAT:
            return

        with open("/proc/self/stat") as s:
            line = s.read()
            raw_stats = line.split(") ", 1)[1].split(" ")

            user = GaugeMetricFamily("process_cpu_user_seconds_total", "")
            user.add_metric([], float(raw_stats[11]) / self.ticks_per_sec)
            yield user

            sys = GaugeMetricFamily("process_cpu_system_seconds_total", "")
            sys.add_metric([], float(raw_stats[12]) / self.ticks_per_sec)
            yield sys

REGISTRY.register(CPUMetrics())

#
# Federation Metrics
#

sent_transactions_counter = Counter("synapse_federation_client_sent_transactions", "")

events_processed_counter = Counter("synapse_federation_client_events_processed", "")

event_processing_loop_counter = Counter(
    "synapse_event_processing_loop_count", "Event processing loop iterations", ["name"]
)

event_processing_loop_room_count = Counter(
    "synapse_event_processing_loop_room_count",
    "Rooms seen per event processing loop iteration",
    ["name"],
)

# Used to track where various components have processed in the event stream,
# e.g. federation sending, appservice sending, etc.
event_processing_positions = Gauge("synapse_event_processing_positions", "", ["name"])

# Used to track the current max events stream position
event_persisted_position = Gauge("synapse_event_persisted_position", "")

# Used to track the received_ts of the last event processed by various
# components
event_processing_last_ts = Gauge("synapse_event_processing_last_ts", "", ["name"])

# Used to track the lag processing events. This is the time difference
# between the last processed event's received_ts and the time it was
# finished being processed.
event_processing_lag = Gauge("synapse_event_processing_lag", "", ["name"])

event_processing_lag_by_event = Histogram(
    "synapse_event_processing_lag_by_event",
    "Time between an event being persisted and it being queued up to be sent to the relevant remote servers",
    ["name"],
)

# Build info of the running server.
build_info = Gauge(
    "synapse_build_info", "Build information", ["pythonversion", "version", "osversion"]
)
build_info.labels(
    " ".join([platform.python_implementation(), platform.python_version()]),
    SYNAPSE_VERSION,
    " ".join([platform.system(), platform.release()]),
).set(1)

# 3PID send info
threepid_send_requests = Histogram(
    "synapse_threepid_send_requests_with_tries",
    documentation="Number of requests for a 3pid token by try count. Note if"
    " there is a request with try count of 4, then there would have been one"
    " each for 1, 2 and 3",
    buckets=(1, 2, 3, 4, 5, 10),
    labelnames=("type", "reason"),
)

threadpool_total_threads = Gauge(
    "synapse_threadpool_total_threads",
    "Total number of threads currently in the threadpool",
    ["name"],
)

threadpool_total_working_threads = Gauge(
    "synapse_threadpool_working_threads",
    "Number of threads currently working in the threadpool",
    ["name"],
)

threadpool_total_min_threads = Gauge(
    "synapse_threadpool_min_threads",
    "Minimum number of threads configured in the threadpool",
    ["name"],
)

threadpool_total_max_threads = Gauge(
    "synapse_threadpool_max_threads",
    "Maximum number of threads configured in the threadpool",
    ["name"],
)

def register_threadpool(name: str, threadpool: ThreadPool) -> None:
    """Add metrics for the threadpool."""

    threadpool_total_min_threads.labels(name).set(threadpool.min)
    threadpool_total_max_threads.labels(name).set(threadpool.max)

    threadpool_total_threads.labels(name).set_function(lambda: len(threadpool.threads))
    threadpool_total_working_threads.labels(name).set_function(
        lambda: len(threadpool.working)
    )

__all__ = [
    "Collector",
    "MetricsResource",
    "generate_latest",
    "LaterGauge",
    "InFlightGauge",
    "GaugeBucketCollector",
    "MIN_TIME_BETWEEN_GCS",
    "install_gc_manager",
]


text:
package kaflib.types;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import kaflib.utils.FileUtils;

/**
 * Provides a convenience type for using Apache's FTP client.
 */
public class FTP {
	private boolean connected;
	private final FTPClient ftp;
	private final FTPClientConfig config;

	public class DirList {
		public Map<String, Long> list;
	}

	public FTP() throws Exception {
		ftp = new FTPClient();
		config = new FTPClientConfig();
		ftp.configure(config);
		connected = false;
	}

	public synchronized boolean connect(final String server,
										final String user,
										final String password) throws Exception {
		if (connected) {
			throw new Exception("Already connected.");
		}

		ftp.connect(server);
		if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
			System.out.println("Connection refused.");
			ftp.disconnect();
			return false;
		}
		if (!ftp.login(user, password)) {
			System.out.println("Login failed.");
			ftp.disconnect();
			return false;
		}

		connected = true;

		return true;
	}

	public void checkFile(final String path) throws Exception {
		if (!isFile(path)) {
			throw new Exception("Not a file: " + path + ".");
		}
	}

	public boolean isConnected() {
		return connected;
	}

	public boolean isFile(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		FTPFile file = ftp.mlistFile(path);
		if (file == null || !file.isFile()) {
			return false;
		}
		else {
			return true;
		}
	}

	public boolean exists(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		FTPFile file = ftp.mlistFile(path);
		if (file == null || file.isUnknown() || !file.isValid()) {
			return false;
		}
		else {
			return true;
		}
	}

	public boolean isDirectory(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		FTPFile file = ftp.mlistFile(path);
		if (file == null || !file.isDirectory()) {
			return false;
		}
		else {
			return true;
		}
	}

	public void checkDirectory(final String path) throws Exception {
		if (!isDirectory(path)) {
			throw new Exception("Not a directory: " + path + ".");
		}
	}

	private int getFileTypeFromExtension(final String fileExtension) throws Exception {
		String extension = fileExtension.toLowerCase();

		if (extension.equals("txt") || extension.equals("html")) {
			return FTPClient.ASCII_FILE_TYPE;
		}
		else if (extension.equals("jpg") || extension.equals("png") ||
				 extension.equals("gif") || extension.equals("bmp") ||
				 extension.equals("tif") || extension.equals("gz")) {
			return FTPClient.BINARY_FILE_TYPE;
		}
		else {
			throw new Exception("Unsupported format: " + extension + ".");
		}

	}

	public int getFileType(final String path) throws Exception {
		int index = path.lastIndexOf(".");
		if (index < 0 || index == path.length() - 1) {
			throw new Exception("No file extension.");
		}
		return getFileTypeFromExtension(path.substring(index + 1));
	}

	public int getFileType(final File file) throws Exception {
		return getFileTypeFromExtension(FileUtils.getExtension(file));
	}

	public DirList createDirList(final String path) throws Exception {
		return createDirList(listFTPFiles(path));
	}

	protected DirList createDirList(final Collection<FTPFile> dirlist) {
		if (dirlist == null) {
			return null;
		}
		Map<String, Long> map = new HashMap<String, Long>();
		for (FTPFile file : dirlist) {
			map.put(file.getName(), file.getSize());
		}
		DirList list = new DirList();
		list.list = map;

		return list;
	}

	public boolean put(final String path,
			   			final File file) throws Exception {
		return put(path, file, false, null);
	}

	public boolean put(final String path,
			   final File file,
			   final DirList dirlist) throws Exception {
		return put(path, file, false, dirlist);
	}

	/**
	 * Writes the specified file to the given path (fully qualified,
	 * including filename).  Checks against an existing file of the same
	 * size, does not re-upload unless force specified.  Takes an optional
	 * directory list to check for the file, otherwise re-checks.
	 * @param path
	 * @param file
	 * @param dirlist
	 * @return
	 * @throws Exception
	 */
	public boolean put(final String path,
					   final File file,
					   boolean force,
					   final DirList dirlist) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}

		if (isDirectory(path)) {
			throw new Exception("Path must be destination file name.");
		}

		// If force isn't specified, check for a match.
		if (!force) {
			// Dirlist provided, check it for a match.
			if (dirlist != null) {
				if (dirlist.list.containsKey(file.getName()) &&
					dirlist.list.get(file.getName()) == file.length()) {
					return true;
				}
			}
			// Dirlist not provided, query.
			else {
				FTPFile remote = ftp.mlistFile(path);
				if (remote != null &&
					remote.isFile() &&
					remote.getSize() == file.length()) {
					return true;
				}
			}
		}

		// Upload the file.
		FileInputStream stream = new FileInputStream(file);
		ftp.setFileType(getFileType(file));
		try {
			boolean success = ftp.storeFile(path, stream);
			stream.close();
			return success;
		}
		catch (Exception e) {
			stream.close();
			System.err.println("Exception uploading: " + file + ".");
			throw e;
		}
	}

	public boolean sync(final String path,
						final Collection<File> files) throws Exception {

		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkDirectory(path);

		Set<File> local = new HashSet<File>();
		local.addAll(files);
		DirList remote = createDirList(path);

		// Iterate over all remove files.
		for (String name : remote.list.keySet()) {
			File match = null;

			// Try to find a local.
			for (File file : local) {
				if (file.getName().equals(name)) {
					match = file;
					break;
				}
			}

			// No local version, delete.
			if (match == null || match.length() != remote.list.get(name)) {
				delete(FileUtils.append(path, name));
			}
			else {
				local.remove(match);
			}
		}

		boolean success = true;
		for (File file : local) {
			success &= put(FileUtils.append(path, file.getName()), file, true, null);
		}
		return success;

	}

	public boolean mput(final String path,
						final Collection<File> files) throws Exception {
		return mput(path, files, false);
	}

	public boolean mput(final String path,
						final Collection<File> files,
						final boolean force) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkDirectory(path);

		DirList dirlist = null;
		if (!force) {
			dirlist = createDirList(path);
		}

		boolean success = true;
		for (File file : files) {
			success &= put(FileUtils.append(path, file.getName()), file, force, dirlist);
		}
		return success;
	}

	protected Set<FTPFile> listFTPFiles(final String path) throws Exception {
		return listFTP(path, true, false, false);
	}

	protected Set<FTPFile> listFTPDirectories(final String path) throws Exception {
		return listFTP(path, false, true, false);
	}

	protected Set<FTPFile> listFTPSymlinks(final String path) throws Exception {
		return listFTP(path, false, false, true);
	}

	/**
	 * Returns a list of all files and directories, not symbolic links,
	 * in path.
	 * @param path
	 * @return
	 * @throws Exception
	 */
	protected Set<FTPFile> listFTP(final String path,
								    final boolean files,
								    final boolean directories,
								    final boolean symlinks) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}

		Set<FTPFile> matches = new HashSet<FTPFile>();
		FTPFile[] array;
		if (path == null) {
			array = ftp.mlistDir();
		}
		else {
			array = ftp.mlistDir(path);
		}
		for (FTPFile file : array) {
			if (file.isFile() && files) {
				matches.add(file);
			}
			else if (file.isDirectory() && directories) {
				matches.add(file);
			}
			else if (file.isSymbolicLink() && symlinks) {
				matches.add(file);
			}
			else {
			}
		}
		return matches;
	}

	public boolean getFiles(final String path, final Directory directory) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkDirectory(path);

		List<String> files = listFiles(path);
		boolean success = true;
		for (String file : files) {
			success &= getFile(FileUtils.append(path, file), new File(directory, file));
		}
		return success;
	}

	public boolean getFile(final String path, final File file) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkFile(path);
		FileOutputStream stream = new FileOutputStream(file);

		ftp.setFileType(getFileType(path));
		boolean success = ftp.retrieveFile(path, stream);
		stream.close();
		return success;
	}

	public boolean makeDir(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		return ftp.makeDirectory(path);
	}

	public void delete(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkFile(path);
		ftp.deleteFile(path);
	}

	public boolean deleteAllFiles(final String path) throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		checkDirectory(path);
		List<String> files = listFiles(path);
		boolean success = true;
		for (String file : files) {
			success &= ftp.deleteFile(FileUtils.append(path, file));
		}
		return success;
	}

	public List<String> list() throws Exception {
		return list(null);
	}

	/**
	 * Lists all files for the specified path.
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public List<String> listFiles(final String path) throws Exception {
		Set<FTPFile> files = listFTPFiles(path);
		List<String> names = new ArrayList<String>();
		for (FTPFile file : files) {
			names.add(file.getName());
		}
		return names;
	}

	/**
	 * Lists all file/directory paths for the given path.
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public List<String> list(final String path) throws Exception {
		Set<FTPFile> files = listFTP(path, true, true, true);
		List<String> names = new ArrayList<String>();
		for (FTPFile file : files) {
			names.add(file.getName());
		}
		return names;
	}

	/**
	 * Disconnects from ftp.
	 * @throws Exception
	 */
	public synchronized void disconnect() throws Exception {
		if (!connected) {
			throw new Exception("Not connected.");
		}
		ftp.logout();
	}

	/**
	 * Test driver.
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			//FTP ftp = new FTP();
			//if (!ftp.connect()) {
			//	System.out.println("Connect failed.");
			//	return;
			//}
			//System.out.println(StringUtils.concatenate(ftp.list(), " "));
			//ftp.disconnect();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.kra.web.struts.authorization.impl;

import org.kuali.kra.web.struts.authorization.WebTaskFactory;

/**
 * Base implementation class for Test Factories.
 */
public abstract class WebTaskFactoryImpl implements WebTaskFactory {

    private String taskName;

    /**
     * Set the name of the Task.  Injected by the Spring Framework.
     * @param taskName the name of the task
     */
    public final void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    /**
     * Get the name of the task.
     * @return the task's name
     */
    public final String getTaskName() {
        return taskName;
    }

    /**
     * Get the name of the task's group.
     * @return the task's group name
     */
    public abstract String getTaskGroupName();

}


text:
<?php

namespace Ivory\GoogleMap\Helper\Subscriber\Overlay;

use Ivory\GoogleMap\Helper\Collector\Overlay\IconSequenceCollector;
use Ivory\GoogleMap\Helper\Event\MapEvent;
use Ivory\GoogleMap\Helper\Event\MapEvents;
use Ivory\GoogleMap\Helper\Formatter\Formatter;
use Ivory\GoogleMap\Helper\Renderer\Overlay\IconSequenceRenderer;
use Ivory\GoogleMap\Helper\Subscriber\AbstractSubscriber;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class IconSequenceSubscriber extends AbstractSubscriber
{
    /**
     * @var IconSequenceCollector
     */
    private $iconSequenceCollector;

    /**
     * @var IconSequenceRenderer
     */
    private $iconSequenceRenderer;

    /**
     * @param Formatter             $formatter
     * @param IconSequenceCollector $iconSequenceCollector
     * @param IconSequenceRenderer  $iconSequenceRenderer
     */
    public function __construct(
        Formatter $formatter,
        IconSequenceCollector $iconSequenceCollector,
        IconSequenceRenderer $iconSequenceRenderer
    ) {
        parent::__construct($formatter);

        $this->setIconSequenceCollector($iconSequenceCollector);
        $this->setIconSequenceRenderer($iconSequenceRenderer);
    }

    /**
     * @return IconSequenceCollector
     */
    public function getIconSequenceCollector()
    {
        return $this->iconSequenceCollector;
    }

    /**
     * @param IconSequenceCollector $iconSequenceCollector
     */
    public function setIconSequenceCollector(IconSequenceCollector $iconSequenceCollector)
    {
        $this->iconSequenceCollector = $iconSequenceCollector;
    }

    /**
     * @return IconSequenceRenderer
     */
    public function getIconSequenceRenderer()
    {
        return $this->iconSequenceRenderer;
    }

    /**
     * @param IconSequenceRenderer $iconSequenceRenderer
     */
    public function setIconSequenceRenderer(IconSequenceRenderer $iconSequenceRenderer)
    {
        $this->iconSequenceRenderer = $iconSequenceRenderer;
    }

    /**
     * @param MapEvent $event
     */
    public function handleMap(MapEvent $event)
    {
        $formatter = $this->getFormatter();
        $map = $event->getMap();

        foreach ($this->getIconSequenceCollector()->collect($map) as $iconSequence) {
            $event->addCode($formatter->renderContainerAssignment(
                $map,
                $this->iconSequenceRenderer->render($iconSequence),
                'overlays.icon_sequences',
                $iconSequence
            ));
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [MapEvents::JAVASCRIPT_OVERLAY_ICON_SEQUENCE => 'handleMap'];
    }
}


text:
namespace fsa {

// {{{ constants

const uint32_t Automaton::PackedAutomaton::_ALLOC_CELLS;
const uint32_t Automaton::PackedAutomaton::_ALLOC_BLOB;
const uint32_t Automaton::PackedAutomaton::_BACKCHECK;

const Blob Automaton::EMPTY_BLOB("");

// }}}

// {{{ Automaton::TransitionList::operator<()

bool Automaton::TransitionList::operator<(const Automaton::TransitionList& tl) const
{
  if(this==&tl) return false;
  if(_size<tl._size) return true;
  if(_size>tl._size) return false;
  for(unsigned int i=0; i<_size;i++){
    if(_trans[i]._symbol<tl._trans[i]._symbol) return true;
    if(_trans[i]._symbol>tl._trans[i]._symbol) return false;
    if(_trans[i]._state<tl._trans[i]._state) return true;
    if(_trans[i]._state>tl._trans[i]._state) return false;
  }
  return false;
}

// }}}
// {{{ Automaton::TransitionList::operator>()

bool Automaton::TransitionList::operator>(const Automaton::TransitionList& tl) const
{
  if(this==&tl) return false;
  if(_size>tl._size) return true;
  if(_size<tl._size) return false;
  for(unsigned int i=0; i<_size;i++){
    if(_trans[i]._symbol>tl._trans[i]._symbol) return true;
    if(_trans[i]._symbol<tl._trans[i]._symbol) return false;
    if(_trans[i]._state>tl._trans[i]._state) return true;
    if(_trans[i]._state<tl._trans[i]._state) return false;
  }
  return false;
}

// }}}
// {{{ Automaton::TransitionList::operator==()

bool Automaton::TransitionList::operator==(const Automaton::TransitionList& tl) const
{
  if(this==&tl) return true;
  if(_size!=tl._size) return false;
  for(unsigned int i=0; i<_size;i++){
    if(_trans[i]._symbol!=tl._trans[i]._symbol) return false;
    if(_trans[i]._state!=tl._trans[i]._state) return false;
  }
  return true;
}

// }}}

// {{{ Automaton::PackedAutomaton::reset()

void Automaton::PackedAutomaton::reset()
{
  _packable = false;
  _pack_map.clear();
  _blob_map.clear();
  if(_packed_ptr!=NULL){
    free(_packed_ptr);
    _packed_ptr=NULL;
  }
  if(_packed_idx!=NULL){
    if(sizeof(State*)!=sizeof(state_t)){
      free(_packed_idx);
    }
    _packed_idx=NULL;
  }
  if(_symbol!=NULL){
    free(_symbol);
    _symbol=NULL;
  }
  if(_used!=NULL){
    free(_used);
    _used=NULL;
  }
  if(_perf_hash!=NULL){
    free(_perf_hash);
    _perf_hash=NULL;
  }
  if(_totals!=NULL){
    free(_totals);
    _totals=NULL;
  }
  _packed_size=0;
  _last_packed=0;
  if(_blob!=NULL){
    free(_blob);
    _blob=NULL;
  }
  _blob_size=0;
  _blob_used=0;
  _blob_type=FSA::DATA_VARIABLE;
  _fixed_blob_size=0;
  _start_state=0;
}

// }}}
// {{{ Automaton::PackedAutomaton::init()

void Automaton::PackedAutomaton::init()
{
  reset();

  _packed_ptr = (State**)malloc(_ALLOC_CELLS*sizeof(State*));
  if(sizeof(State*)!=sizeof(state_t)){
    _packed_idx = (state_t*)malloc(_ALLOC_CELLS*sizeof(state_t));
  }
  else {
    _packed_idx = (state_t*)_packed_ptr;
  }
  _symbol = (symbol_t*)malloc(_ALLOC_CELLS*sizeof(symbol_t));
  _used = (bool*)malloc(_ALLOC_CELLS*sizeof(bool));
  _packed_size  = _ALLOC_CELLS;

  assert(_packed_ptr!=NULL && _packed_idx!=NULL && _symbol!=NULL && _used!=NULL);

  for(uint32_t i=0;i<_packed_size;i++){
    _used[i] = false;
    _symbol[i] = FSA::EMPTY_SYMBOL;
    _packed_ptr[i] = NULL;
    if(sizeof(State*)!=sizeof(state_t)){
      _packed_idx[i] = 0;
    }
  }

  _blob = (data_t*)malloc(_ALLOC_BLOB);
  _blob_size = _ALLOC_BLOB;

  assert(_blob!=NULL);

  _packable = true;
}

// }}}
// {{{ Automaton::PackedAutomaton::expandCells()

void Automaton::PackedAutomaton::expandCells()
{
  uint32_t i;

  _packed_ptr = (State**)realloc(_packed_ptr,(_packed_size+_ALLOC_CELLS)*sizeof(State*));
  if(sizeof(State*)!=sizeof(state_t)){
    _packed_idx = (state_t*)realloc(_packed_idx,(_packed_size+_ALLOC_CELLS)*sizeof(state_t));
  }
  else {
    _packed_idx = (state_t*)_packed_ptr;
  }
  _symbol = (symbol_t*)realloc(_symbol,(_packed_size+_ALLOC_CELLS)*sizeof(symbol_t));
  _used = (bool*)realloc(_used,(_packed_size+_ALLOC_CELLS)*sizeof(bool));

  assert(_packed_ptr!=NULL && _packed_idx!=NULL && _symbol!=NULL && _used!=NULL);

  for(i=_packed_size;i<_packed_size+_ALLOC_CELLS;i++){
    _used[i] = false;
    _symbol[i] = FSA::EMPTY_SYMBOL;
    _packed_ptr[i] = NULL;
    if(sizeof(State*)!=sizeof(state_t)){
      _packed_idx[i] = 0;
    }
  }
  _packed_size  += _ALLOC_CELLS;
}

// }}}
// {{{ Automaton::PackedAutomaton::expandBlob()

void Automaton::PackedAutomaton::expandBlob(uint32_t minExpand)
{
  uint32_t expand=(minExpand/_ALLOC_BLOB+1)*_ALLOC_BLOB;

  _blob = (data_t*)realloc(_blob,_blob_size+expand);

  assert(_blob!=NULL);

  _blob_size  += expand;
}

// }}}
// {{{ Automaton::PackedAutomaton::getEmptyCell()

uint32_t Automaton::PackedAutomaton::getEmptyCell()
{
  unsigned int cell = _last_packed>_BACKCHECK?_last_packed-_BACKCHECK:1;
  while(_used[cell]){
    cell++;
    if(cell+256>=_packed_size)
      expandCells();
  }

  _used[cell] = true;

  return cell;
}

// }}}
// {{{ Automaton::PackedAutomaton::getCell()

uint32_t Automaton::PackedAutomaton::getCell(Automaton::SymList t)
{
  SymListIterator tit;
  uint32_t cell = _last_packed>_BACKCHECK?_last_packed-_BACKCHECK:1;
  bool found = false;
  while(!found){
    if(!_used[cell]){
      if(cell+256>=_packed_size)
        expandCells();
      for(tit=t.begin();tit!=t.end();++tit){
        if(_symbol[cell+*tit]!=FSA::EMPTY_SYMBOL)
          break;
      }
      if(tit==t.end())
        found=true;
    }
    if(!found){
      cell++;
      if(cell>=_packed_size)
          expandCells();
    }
  }
  _used[cell] = true;
  for(tit=t.begin();tit!=t.end();++tit){
    _symbol[cell+*tit] = *tit;
  }

  return cell;
}

// }}}
// {{{ Automaton::PackedAutomaton::packStartState()

bool Automaton::PackedAutomaton::packStartState(const Automaton::State *s)
{
  return packState(s,true);
}

// }}}
// {{{ Automaton::PackedAutomaton::packState()

bool Automaton::PackedAutomaton::packState(const Automaton::State *s, bool start)
{
  SymList transitions;
  uint32_t cell;
  size_t i;

  if(_packable){
    if(s->getTransitionList().size()==0){
      cell = getEmptyCell();
    }
    else{
      for(i=0; i<s->getTransitionList().size(); i++){
        transitions.push_back(s->getTransitionList()[i]._symbol);
      }
      transitions.sort();
      cell = getCell(transitions);
      for(i=0; i<s->getTransitionList().size(); i++){
        if(s->getTransitionList()[i]._symbol==FSA::FINAL_SYMBOL){
          _packed_idx[cell+FSA::FINAL_SYMBOL] =
            packBlob(s->getTransitionList()[i]._state->getBlob());
        }
        else{
          _packed_ptr[cell+s->getTransitionList()[i]._symbol] =
            s->getTransitionList()[i]._state;
        }
      }
    }

    _pack_map[s] = cell;
    if(cell>_last_packed)
      _last_packed = cell;
    if(start)
      _start_state=(state_t)cell;

    return true;
  }

  return false;

}

// }}}
// {{{ Automaton::PackedAutomaton::packBlob()

static const Blob nullBlob;

uint32_t Automaton::PackedAutomaton::packBlob(const Blob *b)
{
  PackMapIterator pi = _blob_map.find(b);
  if(pi!=_blob_map.end()){
    return pi->second;
  }
  else {
    uint32_t cell=_blob_used;
    _blob_map[b]=cell;
    if(b==NULL){
      b=&nullBlob;
    }
    uint32_t size=b->size();
    if(_blob_used+size+sizeof(uint32_t)>_blob_size)
      expandBlob(size+sizeof(uint32_t));
    memcpy(_blob+_blob_used,&size,sizeof(uint32_t));
    memcpy(_blob+_blob_used+sizeof(uint32_t),b->data(),size);
    _blob_used += size+sizeof(uint32_t);

    return cell;
  }
}

// }}}
// {{{ Automaton::PackedAutomaton::finalize()

void Automaton::PackedAutomaton::finalize()
{
  if(_packable){
    for(uint32_t i=0;i<_last_packed+256;i++){
      if(i>=_packed_size) // this shouldn't happen anymore, but check anyway
        expandCells();
      if(_symbol[i]!=FSA::EMPTY_SYMBOL && _symbol[i]!=FSA::FINAL_SYMBOL){
        _packed_idx[i] = _pack_map[_packed_ptr[i]];
      }
    }

    // compact blobs if the size is constant
    std::map<uint32_t,uint32_t> bcomp;
    std::map<uint32_t,uint32_t>::iterator bcomp_it;
    bcomp[0]=0;
    uint32_t lastsize = *((uint32_t*)(void *)_blob), currsize;
    uint32_t i=lastsize+sizeof(uint32_t);
    uint32_t j=lastsize;
    bool fixedsize = true;
    while(i<_blob_used){
        currsize = Unaligned<uint32_t>::at(_blob+i);
      if(currsize!=lastsize){
        fixedsize = false;
        break;
      }
      bcomp[i]=j;
      i+=currsize+sizeof(uint32_t);
      j+=currsize;
    }
    if(fixedsize){
      _blob_type = FSA::DATA_FIXED;
      _fixed_blob_size = lastsize;
      _blob_used = j;
      for(i=0;i<_last_packed+256;i++){
        if(_symbol[i]==FSA::FINAL_SYMBOL){
          _packed_idx[i] = bcomp[_packed_idx[i]];
        }
      }

      for(bcomp_it = bcomp.begin(); bcomp_it!=bcomp.end(); ++bcomp_it){
        memmove(_blob+(bcomp_it->second),_blob+(bcomp_it->first+sizeof(uint32_t)),lastsize);
      }
    }

    _packable = false;
  }
}

// }}}
// {{{ Automaton::PackedAutomaton::computePerfectHash()

hash_t Automaton::PackedAutomaton::computePerfectHash(state_t state)
{
  symbol_t s;
  hash_t count;

  if(_totals[state]!=0){
    return _totals[state];
  }

  count = (_symbol[state+FSA::FINAL_SYMBOL]==FSA::FINAL_SYMBOL) ? 1 : 0;

  for(s=1;s<=254;s++){
    if(_symbol[state+s]==s){
      _perf_hash[state+s] = count;
      count += computePerfectHash(_packed_idx[state+s]);
    }
  }

  _totals[state] = count;

  return count;
}

// }}}
// {{{ Automaton::PackedAutomaton::addPerfectHash()

void Automaton::PackedAutomaton::addPerfectHash()
{
  if(_last_packed==0 || _packable){
    // do nothing with an empty automaton or one which has not been finalized
    return;
  }

  uint32_t size = _last_packed+256;

  _perf_hash = (hash_t*)malloc(size*sizeof(hash_t));
  _totals    = (hash_t*)malloc(size*sizeof(hash_t));

  assert(_perf_hash!=NULL && _totals!=NULL);

  for(unsigned int i=0;i<size;i++){
    _perf_hash[i] = 0;
    _totals[i] = 0;
  }

  computePerfectHash(_start_state);

  free(_totals); _totals=NULL;
}

// }}}
// {{{ Automaton::PackedAutomaton::lookup()

const data_t* Automaton::PackedAutomaton::lookup(const char *input) const
{
  if(_packable || _start_state==0){
    return NULL;
  }
  state_t state = _start_state;
  const char *p=input;
  while(*p){
    if(_symbol[state+*p]==*p){
      state=_packed_idx[state+*p];
      p++;
    }
    else{
      return NULL;
    }
  }
  if(_symbol[state+FSA::FINAL_SYMBOL]==FSA::FINAL_SYMBOL){
    return _blob+_packed_idx[state+FSA::FINAL_SYMBOL];
  }
  return NULL;
}

// }}}

namespace {

void checkWrite(int fd, const void *buf, size_t len, bool &success) {
    ssize_t writeRes = ::write(fd, buf, len);
    if (writeRes != static_cast<ssize_t>(len)) {
        success = false;
    }
}

}

// {{{ Automaton::PackedAutomaton::write()

bool Automaton::PackedAutomaton::write(const char *filename, uint32_t serial)
{
  if(_packable || _packed_size==0) // must be non-empty and finalized
    return false;

  FSA::Header header;

  header._magic            = FSA::MAGIC;
  header._version          = FSA::VER;
  header._checksum         = 0;
  header._size             = _last_packed+256;
  header._start            = _start_state;
  header._data_size        = _blob_used;
  header._data_type        = _blob_type;
  header._fixed_data_size  = _fixed_blob_size;
  header._has_perfect_hash = (_perf_hash==NULL) ? 0 : 1;
  header._serial           = serial;
  memset(&(header._reserved), 0, sizeof(header._reserved));

  int fd = open(filename,O_CREAT|O_TRUNC|O_RDWR,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  if(fd<0) return false;

  header._checksum += Checksum::compute(_symbol,header._size*sizeof(symbol_t));
  header._checksum += Checksum::compute(_packed_idx,header._size*sizeof(state_t));
  header._checksum += Checksum::compute(_blob,_blob_used);
  if(header._has_perfect_hash){
    header._checksum += Checksum::compute(_perf_hash,header._size*sizeof(hash_t));
  }

  bool success = true;
  checkWrite(fd,&header,sizeof(header), success);
  checkWrite(fd,_symbol,header._size*(sizeof(symbol_t)), success);
  checkWrite(fd,_packed_idx,header._size*(sizeof(state_t)), success);
  checkWrite(fd,_blob,_blob_used, success);
  if(header._has_perfect_hash){
      checkWrite(fd,_perf_hash,header._size*(sizeof(hash_t)), success);
  }
  close(fd);

  return success;
}

// }}}

namespace {

void checkRead(int fd, void *buf, size_t len, bool &success) {
    ssize_t readRes = ::read(fd, buf, len);
    if (readRes != static_cast<ssize_t>(len)) {
        success = false;
    }
}

}

// {{{ Automaton::PackedAutomaton::read()

bool Automaton::PackedAutomaton::read(const char *filename)
{
  FSA::Header header;
  size_t r;

  reset();
  int fd = ::open(filename,O_RDONLY);
  if(fd<0){
    return false;
  }
  r=::read(fd,&header,sizeof(header));
  if(r<sizeof(header) || header._magic!=FSA::MAGIC){
    ::close(fd);
    return false;
  }

  _packable = false;
  _packed_size = header._size;
  _last_packed = _packed_size-256;
  _blob_size = header._data_size;
  _blob_used = header._data_size;
  _blob_type = header._data_type;
  _fixed_blob_size = header._fixed_data_size;
  _start_state = header._start;

  _symbol = (symbol_t*)malloc(_packed_size*sizeof(symbol_t));
  assert(_symbol!=NULL);
  bool success = true;
  checkRead(fd,_symbol,_packed_size*(sizeof(symbol_t)), success);
  _packed_idx = (state_t*)malloc(_packed_size*sizeof(state_t));
  assert(_packed_idx!=NULL);
  checkRead(fd,_packed_idx,_packed_size*(sizeof(state_t)), success);
  _blob = (data_t*)malloc(_blob_used);
  assert(_blob!=NULL);
  checkRead(fd,_blob,_blob_used, success);
  if(header._has_perfect_hash){
    _perf_hash = (hash_t*)malloc(_packed_size*sizeof(hash_t));
    assert(_perf_hash!=NULL);
    checkRead(fd,_perf_hash,_packed_size*(sizeof(hash_t)), success);
  }

  ::close(fd);

  return success;
}

// }}}
// {{{ Automaton::PackedAutomaton::getFSA()

bool Automaton::PackedAutomaton::getFSA(FSA::Descriptor &d)
{
  if(_packable || _packed_size==0) // must be non-empty and finalized
    return false;

  uint32_t size = _last_packed+256;

  _symbol = (symbol_t*)realloc(_symbol,size*sizeof(symbol_t));
  _packed_idx = (state_t*)realloc(_packed_idx,size*sizeof(state_t));
  _blob = (data_t*)realloc(_blob,_blob_used);
  if(_perf_hash!=NULL){
    _perf_hash = (hash_t*)realloc(_perf_hash,size*sizeof(hash_t));
  }

  d._version = FSA::VER;
  d._serial = 0;
  d._state = Unaligned<state_t>::ptr(_packed_idx);
  d._symbol = _symbol;
  d._size = size;
  d._data = _blob;
  d._data_size = _blob_used;
  d._data_type = _blob_type;
  d._fixed_data_size = _fixed_blob_size;
  d._perf_hash = Unaligned<hash_t>::ptr(_perf_hash);
  d._start = _start_state;

  _symbol = NULL;
  _packed_idx = NULL;
  if(sizeof(State*)==sizeof(state_t)){ // _packed_idx and _packed_ptr are overlayed
    _packed_ptr=NULL;
  }
  _blob = NULL;
  _perf_hash = NULL;
  reset();

  return true;
}

// }}}

// {{{ Automaton::cleanUp()

void Automaton::cleanUp()
{
  if(_q0!=NULL){
    finalize(); // make sure all states are in _register
    for(BlobRegisterIterator bi = _blob_register.begin(); bi!=_blob_register.end(); ++bi){
      delete bi->second;
    }
    _blob_register.clear(); // clear _blob_register
    // clear _register and remove all states
    for(RegisterIterator ri = _register.begin(); ri!=_register.end(); ++ri){
      delete ri->second;
    }
    _register.clear();
    delete _q0;
    _q0 = NULL;
    _previous_input.clear();
  }
}

// }}}
// {{{ Automaton::~Automaton()

Automaton::~Automaton()
{
  cleanUp();
}

// }}}
// {{{ Automaton::getCPLength()

unsigned int Automaton::getCPLength(const char *input)
{
  if(_q0==NULL) return 0;

  unsigned int l=0;
  State* state = _q0;
  State* next;
  while(input[l]!=0){
    next = state->child(input[l]);
    if(next==NULL) return l;
    state=next;
    l++;
  }
  return l;
}

// }}}
// {{{ Automaton::getCPLastState()

Automaton::State* Automaton::getCPLastState(const char *input)
{
  if(_q0==NULL) return NULL;

  unsigned int l=0;
  State* state = _q0;
  State* next;
  while(input[l]!=0){
    next = state->child(input[l]);
    if(next==NULL) return state;
    state=next;
    l++;
  }
  return state;
}

// }}}
// {{{ Automaton::addSuffix()

void Automaton::addSuffix(State* state, const char *suffix, const Blob *b)
{
  State* current = state;
  State* child;

  while(*suffix != 0){
    child = current->addEmptyChild(*suffix);
    current = child;
    suffix++;
  }
  BlobRegisterIterator bi;
  if(b!=NULL)
    bi = _blob_register.find(*b);
  else
    bi = _blob_register.find(EMPTY_BLOB);
  if(bi!=_blob_register.end()){
    child = bi->second;
    current->addChild(FSA::FINAL_SYMBOL,child);
  }
  else {
    const Blob *bcopy = (b==NULL) ? new Blob(EMPTY_BLOB) : new Blob(*b);
    assert(bcopy!=NULL);
    child = current->addEmptyChild(FSA::FINAL_SYMBOL,bcopy);
    _blob_register[*bcopy] = child;
  }
}

// }}}
// {{{ Automaton::init()

void Automaton::init()
{
  cleanUp();
  _q0 = new State();
  assert(_q0!=NULL);
  _finalized = false;

  _packed.init();
}

// }}}
// {{{ Automaton::finalize()

void Automaton::finalize()
{
  if(!_finalized && _q0!=NULL){
    replaceOrRegister(_q0);
    _packed.packStartState(_q0);
    _packed.finalize();
    _finalized = true;
  }

}

// }}}
// {{{ Automaton::addPerfectHash()

void Automaton::addPerfectHash()
{
  if(_finalized){
    _packed.addPerfectHash();
  }
}

// }}}
// {{{ Automaton::write()

bool Automaton::write(const char *file, uint32_t serial)
{
  if(!_finalized){
    finalize();
  }
  return _packed.write(file,serial);
}

// }}}
// {{{ Automaton::getFSA()

FSA* Automaton::getFSA()
{
  if(!_finalized){
    finalize();
  }

  FSA::Descriptor d;

  if(!_packed.getFSA(d))
    return NULL;

  FSA *fsa = new FSA(d);

  cleanUp();

  return fsa;
}

// }}}
// {{{ Automaton::insertSortedString()

void Automaton::insertSortedString(const std::string &input)
{
  insertSortedString(input.c_str());
}

void Automaton::insertSortedString(const std::string &input, const std::string &meta)
{
  Blob b(meta);
  insertSortedString(input.c_str(),&b);
}

void Automaton::insertSortedString(const char *input, const Blob& b)
{
  insertSortedString(input,&b);
}

void Automaton::insertSortedString(const char *input, const Blob* b)
{
  if(_q0==NULL || _finalized) return;

  State* lastState = getCPLastState(input);
  const char* currentSuffix = input + getCPLength(input);

  if(lastState->hasChildren()){
    replaceOrRegister(lastState);
  }
  addSuffix(lastState,currentSuffix,b);
}

// }}}
// {{{ Automaton::replaceOrRegister()

void Automaton::replaceOrRegister(Automaton::State* state)
{
  State* child = state->lastChild();
  if(child!=NULL){
    if(child->hasChildren()){
      replaceOrRegister(child);
    }
    RegisterIterator ri = _register.find(TListPtr(&(child->getTransitionList())));
    if(ri!=_register.end() && ri->second!=child){
      state->updateLastChild(ri->second);
      delete child;
    }
    else {
      _register[TListPtr(&(child->getTransitionList()))] = child;
      _packed.packState(child);
    }
  }
}

// }}}

} // namespace fsa


text:
declare const enum Foo {}
declare enum Bar {}


text:
package walpb

import "errors"

var (
	ErrCRCMismatch = errors.New("walpb: crc mismatch")
)

func (rec *Record) Validate(crc uint32) error {
	if rec.Crc == crc {
		return nil
	}
	rec.Reset()
	return ErrCRCMismatch
}


text:
import Post from '../../layouts/essay'

// Components
import P from '../../components/paragraph'
import Meta from '../../components/meta'
import Link from '../../components/link'

export default () => (
  <Post>
    <Meta id="wwdc-2013" />

      Heute Abend war es mal wieder soweit: Apple hielt eine offizielle
      Konferenz ab, auf der neue Entwicklungen und Zukunftspläne vorgestellt
      wurden. Ich konnte das ganze zum Glück live an meinem Rechner
      mitverfolgen. Einige neue Dinge wurden vorgestellt, darunter das
      neue
      {' '}
      <Link href="https://ssl.apple.com/ios/ios7/features/">iOS 7</Link>
      {' '}
      sowie
      der neue Mac Pro.

      Zunächst wurde ein wenig über Apples erreichte Ziele geredet: Mehr
      als 10 Milliarden Dollar für Entwickler, die im Netz mit Hilfe des
      AppStores Einnahmen generieren können, über 900 Tausend Apps
      sowie über 50 Milliarden Downloads.

      Apple hat es anscheinend mal wieder geschafft, seine Nutzer und die, die
      es noch werden wollen, zu begeistern. Meiner Meinung nach viel mehr
      als nur gute Arbeit. Ich meine, man sehe sich nur einmal die
      Veränderung des Mac Pro vom platzraubenden Computer zum jetzigen
      hochleistungs-Tower mit einer Übertragungsrate
      von 60 GB pro Sekunde (!) an. Das ist schon etwas besonderes.

      Ein weiteres Highlight war das neues Betriebssystem {`"`}iOS{`"`}, wessen
      siebte Version im vollen Umfang vorgestellt wurde. Mir
      persönlich gefällt das neue UI-Design sehr, genauso
      wie die verbesserte User-Experience und die neuen Apps.

      Das ganze ist nun im Grunde etwas einfacher aufgebaut, als vorher. Das
      Design wirkt strukturierter und aufgeräumter. Natürlich stehen
      auch die neuen Apps im Vordergrund, wie z.B. AirDrop, mit
      dessen Hilfe die Nutzer dafür vorgesehene Daten kabellos
      zwischen iOS-Geräten übertragen können.

      Weitergehend wurde auch der Airport Extreme sowie die hauseigene
      Netzwerk-Festplatte {`"`}Time Capsule{`"`} weiterentwickelt
      um noch leichter mit den Geräten anderer Hersteller konkurrieren zu können.

      Alles in allem eine sehr gelungene Konferenz! Ich freue mich schon auf
      die nächste Übertragung, und natürlich auf das neue iOS-Update, welches
      den Nutzern laut Apple voraussichtlich ab Herbst diesen Jahres zur
      Verfügung stehen soll. Weitere Informationen gibt´s natürlich auf
      der offiziellen <Link href="https://www.apple.com/de/">Apple-Seite</Link>.

  </Post>
)


text:
package ee.ria.xroad.common.message;

import java.io.InputStream;
import java.util.Map;

/**
 * Describes the SOAP message callback. The message consists of a XML message
 * and optional attachments.
 */
public interface SoapMessageConsumer {

    /**
     * Called when SOAP message is parsed.
     * @param message the SOAP message
     * @param additionalHeaders SOAP part headers
     * @throws Exception if an error occurs
     */
    void soap(SoapMessage message,
            Map<String, String> additionalHeaders) throws Exception;

    /**
     * Called when an attachment is received.
     * @param contentType the content type of the attachment
     * @param content the input stream holding the attachment data
     * @param additionalHeaders any additional headers for the attachment
     * @throws Exception if an error occurs
     */
    void attachment(String contentType, InputStream content,
            Map<String, String> additionalHeaders) throws Exception;
}


text:
<?php

namespace CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProjectType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array('required' => true))
            ->add('basePath', 'text', array('required' => true))
            ->add('playbook', 'text', array('required' => true))
            ->add('inventory', 'text', array('required' => true))
            ->add('verbose', 'checkbox', array('required' => false))
            ->add('check', 'checkbox', array('required' => false))
            ->add('limit', 'text', array('required' => false))
            ->add('username', 'text', array('required' => false))
            ->add('password', 'text', array('required' => false))
            ->add('privateKeyFile', 'text', array('required' => false))
            ->add('vaultPassword', 'text', array('required' => false))
            ->add('vaultPasswordFile', 'text', array('required' => false))
            ->add('suPassword', 'text', array('required' => false))
            ->add('connection', 'text', array('required' => false))
            ->add('forceHandlers', 'checkbox', array('required' => false))
            ->add('modulePath', 'text', array('required' => false))
            ->add('skipPaths', 'text', array('required' => false))
            ->add('startAtTask', 'text', array('required' => false))
            ->add('su', 'text', array('required' => false))
            ->add('suUser', 'text', array('required' => false))
            ->add('sudoUser', 'text', array('required' => false))
            ->add('tags', 'text', array('required' => false))
            ->add('timeout', 'text', array('required' => false))
            ->add('save', 'submit');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'CoreBundle\Entity\Project',
            )
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'asm_project_form';
    }
}


text:
import gtk
import glib
import re
from bb.ui.crumbs.progressbar import HobProgressBar
from bb.ui.crumbs.hobcolor import HobColors
from bb.ui.crumbs.hobwidget import hic, HobImageButton, HobInfoButton, HobAltButton, HobButton
from bb.ui.crumbs.hoblistmodel import RecipeListModel
from bb.ui.crumbs.hobpages import HobPage
from bb.ui.crumbs.hig.retrieveimagedialog import RetrieveImageDialog

#
# ImageConfigurationPage
#
class ImageConfigurationPage (HobPage):

    __dummy_machine__ = "--select a machine--"
    __dummy_image__   = "--select an image recipe--"
    __custom_image__  = "Select from my image recipes"

    def __init__(self, builder):
        super(ImageConfigurationPage, self).__init__(builder, "Image configuration")

        self.image_combo_id = None
        # we use machine_combo_changed_by_manual to identify the machine is changed by code
        # or by manual. If by manual, all user's recipe selection and package selection are
        # cleared.
        self.machine_combo_changed_by_manual = True
        self.stopping = False
        self.warning_shift = 0
        self.custom_image_selected = None
        self.create_visual_elements()

    def create_visual_elements(self):
        # create visual elements
        self.toolbar = gtk.Toolbar()
        self.toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)
        self.toolbar.set_style(gtk.TOOLBAR_BOTH)

        my_images_button = self.append_toolbar_button(self.toolbar,
            "Images",
            hic.ICON_IMAGES_DISPLAY_FILE,
            hic.ICON_IMAGES_HOVER_FILE,
            "Open previously built images",
            self.my_images_button_clicked_cb)
        settings_button = self.append_toolbar_button(self.toolbar,
            "Settings",
            hic.ICON_SETTINGS_DISPLAY_FILE,
            hic.ICON_SETTINGS_HOVER_FILE,
            "View additional build settings",
            self.settings_button_clicked_cb)

        self.config_top_button = self.add_onto_top_bar(self.toolbar)

        self.gtable = gtk.Table(40, 40, True)
        self.create_config_machine()
        self.create_config_baseimg()
        self.config_build_button = self.create_config_build_button()

    def _remove_all_widget(self):
        children = self.gtable.get_children() or []
        for child in children:
            self.gtable.remove(child)
        children = self.box_group_area.get_children() or []
        for child in children:
            self.box_group_area.remove(child)
        children = self.get_children() or []
        for child in children:
            self.remove(child)

    def _pack_components(self, pack_config_build_button = False):
        self._remove_all_widget()
        self.pack_start(self.config_top_button, expand=False, fill=False)
        self.pack_start(self.group_align, expand=True, fill=True)

        self.box_group_area.pack_start(self.gtable, expand=True, fill=True)
        if pack_config_build_button:
            self.box_group_area.pack_end(self.config_build_button, expand=False, fill=False)
        else:
            box = gtk.HBox(False, 6)
            box.show()
            subbox = gtk.HBox(False, 0)
            subbox.set_size_request(205, 49)
            subbox.show()
            box.add(subbox)
            self.box_group_area.pack_end(box, False, False)

    def show_machine(self):
        self.progress_bar.reset()
        self._pack_components(pack_config_build_button = False)
        self.set_config_machine_layout(show_progress_bar = False)
        self.show_all()

    def update_progress_bar(self, title, fraction, status=None):
        if self.stopping == False:
            self.progress_bar.update(fraction)
            self.progress_bar.set_text(title)
            self.progress_bar.set_rcstyle(status)

    def show_info_populating(self):
        self._pack_components(pack_config_build_button = False)
        self.set_config_machine_layout(show_progress_bar = True)
        self.show_all()

    def show_info_populated(self):
        self.progress_bar.reset()
        self._pack_components(pack_config_build_button = False)
        self.set_config_machine_layout(show_progress_bar = False)
        self.set_config_baseimg_layout()
        self.show_all()

    def show_baseimg_selected(self):
        self.progress_bar.reset()
        self._pack_components(pack_config_build_button = True)
        self.set_config_machine_layout(show_progress_bar = False)
        self.set_config_baseimg_layout()
        self.show_all()
        if self.builder.recipe_model.get_selected_image() == self.builder.recipe_model.__custom_image__:
            self.just_bake_button.hide()

    def add_warnings_bar(self):
        #create the warnings bar shown when recipes parsing generates warnings
        color = HobColors.KHAKI
        warnings_bar = gtk.EventBox()
        warnings_bar.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(color))
        warnings_bar.set_flags(gtk.CAN_DEFAULT)
        warnings_bar.grab_default()

        build_stop_tab = gtk.Table(10, 20, True)
        warnings_bar.add(build_stop_tab)

        icon = gtk.Image()
        icon_pix_buffer = gtk.gdk.pixbuf_new_from_file(hic.ICON_INDI_ALERT_FILE)
        icon.set_from_pixbuf(icon_pix_buffer)
        build_stop_tab.attach(icon, 0, 2, 0, 10)

        label = gtk.Label()
        label.set_alignment(0.0, 0.5)
        warnings_nb = len(self.builder.parsing_warnings)
        if warnings_nb == 1:
            label.set_markup("1 recipe parsing warning")
        else:
            label.set_markup("%s recipe parsing warnings" % warnings_nb)
        build_stop_tab.attach(label, 2, 12, 0, 10)

        view_warnings_button = HobButton("View warnings")
        view_warnings_button.connect('clicked', self.view_warnings_button_clicked_cb)
        build_stop_tab.attach(view_warnings_button, 15, 19, 1, 9)

        return warnings_bar

    def disable_warnings_bar(self):
        if self.builder.parsing_warnings:
            if hasattr(self, 'warnings_bar'):
                self.warnings_bar.hide_all()
            self.builder.parsing_warnings = []

    def create_config_machine(self):
        self.machine_title = gtk.Label()
        self.machine_title.set_alignment(0.0, 0.5)
        mark = "Select a machine" % self.span_tag('x-large', 'bold')
        self.machine_title.set_markup(mark)

        self.machine_title_desc = gtk.Label()
        self.machine_title_desc.set_alignment(0.0, 0.5)
        mark = ("Your selection is the profile of the target machine for which you"
        " are building the image.\n") % (self.span_tag('medium'))
        self.machine_title_desc.set_markup(mark)

        self.machine_combo = gtk.combo_box_new_text()
        self.machine_combo.connect("changed", self.machine_combo_changed_cb)

        icon_file = hic.ICON_LAYERS_DISPLAY_FILE
        hover_file = hic.ICON_LAYERS_HOVER_FILE
        self.layer_button = HobImageButton("Layers", "Add support for machines, software, etc.",
                                icon_file, hover_file)
        self.layer_button.connect("clicked", self.layer_button_clicked_cb)

        markup = "Layers are a powerful mechanism to extend the Yocto Project "
        markup += "with your own functionality.\n"
        markup += "For more on layers, check the reference manual."
        self.layer_info_icon = HobInfoButton("Layers" + "*" + markup, self.get_parent())
        self.progress_bar = HobProgressBar()
        self.stop_button = HobAltButton("Stop")
        self.stop_button.connect("clicked", self.stop_button_clicked_cb)
        self.machine_separator = gtk.HSeparator()

    def set_config_machine_layout(self, show_progress_bar = False):
        self.gtable.attach(self.machine_title, 0, 40, 0, 4)
        self.gtable.attach(self.machine_title_desc, 0, 40, 4, 6)
        self.gtable.attach(self.machine_combo, 0, 12, 7, 10)
        self.gtable.attach(self.layer_button, 14, 36, 7, 12)
        self.gtable.attach(self.layer_info_icon, 36, 40, 7, 11)
        if show_progress_bar:
            #self.gtable.attach(self.progress_box, 0, 40, 15, 18)
            self.gtable.attach(self.progress_bar, 0, 37, 15, 18)
            self.gtable.attach(self.stop_button, 37, 40, 15, 18, 0, 0)
        if self.builder.parsing_warnings:
            self.warnings_bar = self.add_warnings_bar()
            self.gtable.attach(self.warnings_bar, 0, 40, 14, 18)
            self.warning_shift = 4
        else:
            self.warning_shift = 0
        self.gtable.attach(self.machine_separator, 0, 40, 13, 14)

    def create_config_baseimg(self):
        self.image_title = gtk.Label()
        self.image_title.set_alignment(0, 1.0)
        mark = "Select an image recipe" % self.span_tag('x-large', 'bold')
        self.image_title.set_markup(mark)

        self.image_title_desc = gtk.Label()
        self.image_title_desc.set_alignment(0, 0.5)

        mark = ("Image recipes are a starting point for the type of image you want. "
                "You can build them as \n"
                "they are or edit them to suit your needs.\n") % self.span_tag('medium')
        self.image_title_desc.set_markup(mark)

        self.image_combo = gtk.combo_box_new_text()
        self.image_combo.set_row_separator_func(self.combo_separator_func, None)
        self.image_combo_id = self.image_combo.connect("changed", self.image_combo_changed_cb)

        self.image_desc = gtk.Label()
        self.image_desc.set_alignment(0.0, 0.5)
        self.image_desc.set_size_request(256, -1)
        self.image_desc.set_justify(gtk.JUSTIFY_LEFT)
        self.image_desc.set_line_wrap(True)

        # button to view recipes
        icon_file = hic.ICON_RCIPE_DISPLAY_FILE
        hover_file = hic.ICON_RCIPE_HOVER_FILE
        self.view_adv_configuration_button = HobImageButton("Advanced configuration",
                                                                 "Select image types, package formats, etc",
                                                                 icon_file, hover_file)
        self.view_adv_configuration_button.connect("clicked", self.view_adv_configuration_button_clicked_cb)

        self.image_separator = gtk.HSeparator()

    def combo_separator_func(self, model, iter, user_data):
        name = model.get_value(iter, 0)
        if name == "--Separator--":
            return True

    def set_config_baseimg_layout(self):
        self.gtable.attach(self.image_title, 0, 40, 15+self.warning_shift, 17+self.warning_shift)
        self.gtable.attach(self.image_title_desc, 0, 40, 18+self.warning_shift, 22+self.warning_shift)
        self.gtable.attach(self.image_combo, 0, 12, 23+self.warning_shift, 26+self.warning_shift)
        self.gtable.attach(self.image_desc, 0, 12, 27+self.warning_shift, 33+self.warning_shift)
        self.gtable.attach(self.view_adv_configuration_button, 14, 36, 23+self.warning_shift, 28+self.warning_shift)
        self.gtable.attach(self.image_separator, 0, 40, 35+self.warning_shift, 36+self.warning_shift)

    def create_config_build_button(self):
        # Create the "Build packages" and "Build image" buttons at the bottom
        button_box = gtk.HBox(False, 6)

        # create button "Build image"
        self.just_bake_button = HobButton("Build image")
        self.just_bake_button.set_tooltip_text("Build the image recipe as it is")
        self.just_bake_button.connect("clicked", self.just_bake_button_clicked_cb)
        button_box.pack_end(self.just_bake_button, expand=False, fill=False)

        # create button "Edit image recipe"
        self.edit_image_button = HobAltButton("Edit image recipe")
        self.edit_image_button.set_tooltip_text("Customize the recipes and packages to be included in your image")
        self.edit_image_button.connect("clicked", self.edit_image_button_clicked_cb)
        button_box.pack_end(self.edit_image_button, expand=False, fill=False)

        return button_box

    def stop_button_clicked_cb(self, button):
        self.stopping = True
        self.progress_bar.set_text("Stopping recipe parsing")
        self.progress_bar.set_rcstyle("stop")
        self.builder.cancel_parse_sync()

    def view_warnings_button_clicked_cb(self, button):
        self.builder.show_warning_dialog()

    def machine_combo_changed_idle_cb(self):
        self.builder.window.set_cursor(None)

    def machine_combo_changed_cb(self, machine_combo):
        self.stopping = False
        self.builder.parsing_warnings = []
        combo_item = machine_combo.get_active_text()
        if not combo_item or combo_item == self.__dummy_machine__:
            return

        self.builder.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
        self.builder.wait(0.1) #wait for combo and cursor to update

        # remove __dummy_machine__ item from the store list after first user selection
        # because it is no longer valid
        combo_store = machine_combo.get_model()
        if len(combo_store) and (combo_store[0][0] == self.__dummy_machine__):
            machine_combo.remove_text(0)

        self.builder.configuration.curr_mach = combo_item
        if self.machine_combo_changed_by_manual:
            self.builder.configuration.clear_selection()
        # reset machine_combo_changed_by_manual
        self.machine_combo_changed_by_manual = True

        self.builder.configuration.selected_image = None

        # Do reparse recipes
        self.builder.populate_recipe_package_info_async()

        glib.idle_add(self.machine_combo_changed_idle_cb)

    def update_machine_combo(self):
        self.disable_warnings_bar()
        all_machines = [self.__dummy_machine__] + self.builder.parameters.all_machines

        model = self.machine_combo.get_model()
        model.clear()
        for machine in all_machines:
            self.machine_combo.append_text(machine)
        self.machine_combo.set_active(0)

    def switch_machine_combo(self):
        self.disable_warnings_bar()
        self.machine_combo_changed_by_manual = False
        model = self.machine_combo.get_model()
        active = 0
        while active < len(model):
            if model[active][0] == self.builder.configuration.curr_mach:
                self.machine_combo.set_active(active)
                return
            active += 1

        if model[0][0] != self.__dummy_machine__:
            self.machine_combo.insert_text(0, self.__dummy_machine__)

        self.machine_combo.set_active(0)

    def update_image_desc(self):
        desc = ""
        selected_image = self.image_combo.get_active_text()
        if selected_image and selected_image in self.builder.recipe_model.pn_path.keys():
            image_path = self.builder.recipe_model.pn_path[selected_image]
            image_iter = self.builder.recipe_model.get_iter(image_path)
            desc = self.builder.recipe_model.get_value(image_iter, self.builder.recipe_model.COL_DESC)

        mark = ("%s\n") % (self.span_tag('small'), desc)
        self.image_desc.set_markup(mark)

    def image_combo_changed_idle_cb(self, selected_image, selected_recipes, selected_packages):
        self.builder.update_recipe_model(selected_image, selected_recipes)
        self.builder.update_package_model(selected_packages)
        self.builder.window_sensitive(True)

    def image_combo_changed_cb(self, combo):
        self.builder.window_sensitive(False)
        selected_image = self.image_combo.get_active_text()
        if selected_image == self.__custom_image__:
            topdir = self.builder.get_topdir()
            images_dir = topdir + "/recipes/images/custom/"
            self.builder.ensure_dir(images_dir)

            dialog = RetrieveImageDialog(images_dir, "Select from my image recipes",
                            self.builder, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                image_name = dialog.get_filename()
                head, tail = os.path.split(image_name)
                selected_image = os.path.splitext(tail)[0]
                self.custom_image_selected = selected_image
                self.update_image_combo(self.builder.recipe_model, selected_image)
            else:
                selected_image = self.__dummy_image__
                self.update_image_combo(self.builder.recipe_model, None)
            dialog.destroy()
        else:
            if self.custom_image_selected:
                self.custom_image_selected = None
                self.update_image_combo(self.builder.recipe_model, selected_image)

        if not selected_image or (selected_image == self.__dummy_image__):
            self.builder.window_sensitive(True)
            self.just_bake_button.hide()
            self.edit_image_button.hide()
            return

        # remove __dummy_image__ item from the store list after first user selection
        # because it is no longer valid
        combo_store = combo.get_model()
        if len(combo_store) and (combo_store[0][0] == self.__dummy_image__):
            combo.remove_text(0)

        self.builder.customized = False

        selected_recipes = []

        image_path = self.builder.recipe_model.pn_path[selected_image]
        image_iter = self.builder.recipe_model.get_iter(image_path)
        selected_packages = self.builder.recipe_model.get_value(image_iter, self.builder.recipe_model.COL_INSTALL).split()
        self.update_image_desc()

        self.builder.recipe_model.reset()
        self.builder.package_model.reset()

        self.show_baseimg_selected()

        if selected_image == self.builder.recipe_model.__custom_image__:
            self.just_bake_button.hide()

        glib.idle_add(self.image_combo_changed_idle_cb, selected_image, selected_recipes, selected_packages)

    def _image_combo_connect_signal(self):
        if not self.image_combo_id:
            self.image_combo_id = self.image_combo.connect("changed", self.image_combo_changed_cb)

    def _image_combo_disconnect_signal(self):
        if self.image_combo_id:
            self.image_combo.disconnect(self.image_combo_id)
            self.image_combo_id = None

    def update_image_combo(self, recipe_model, selected_image):
        # Update the image combo according to the images in the recipe_model
        # populate image combo
        filter = {RecipeListModel.COL_TYPE : ['image']}
        image_model = recipe_model.tree_model(filter)
        image_model.set_sort_column_id(recipe_model.COL_NAME, gtk.SORT_ASCENDING)
        active = 0
        cnt = 0

        white_pattern = []
        if self.builder.parameters.image_white_pattern:
            for i in self.builder.parameters.image_white_pattern.split():
                white_pattern.append(re.compile(i))

        black_pattern = []
        if self.builder.parameters.image_black_pattern:
            for i in self.builder.parameters.image_black_pattern.split():
                black_pattern.append(re.compile(i))
        black_pattern.append(re.compile("hob-image"))
        black_pattern.append(re.compile("edited(-[0-9]*)*.bb$"))

        it = image_model.get_iter_first()
        self._image_combo_disconnect_signal()
        model = self.image_combo.get_model()
        model.clear()
        # Set a indicator text to combo store when first open
        if not selected_image:
            self.image_combo.append_text(self.__dummy_image__)
            cnt = cnt + 1

        self.image_combo.append_text(self.__custom_image__)
        self.image_combo.append_text("--Separator--")
        cnt = cnt + 2

        topdir = self.builder.get_topdir()
        # append and set active
        while it:
            path = image_model.get_path(it)
            it = image_model.iter_next(it)
            image_name = image_model[path][recipe_model.COL_NAME]
            if image_name == self.builder.recipe_model.__custom_image__:
                continue

            if black_pattern:
                allow = True
                for pattern in black_pattern:
                    if pattern.search(image_name):
                        allow = False
                        break
            elif white_pattern:
                allow = False
                for pattern in white_pattern:
                    if pattern.search(image_name):
                        allow = True
                        break
            else:
                allow = True

            file_name = image_model[path][recipe_model.COL_FILE]
            if file_name and topdir in file_name:
                allow = False

            if allow:
                self.image_combo.append_text(image_name)
                if image_name == selected_image:
                    active = cnt
                cnt = cnt + 1
        self.image_combo.append_text(self.builder.recipe_model.__custom_image__)

        if selected_image == self.builder.recipe_model.__custom_image__:
            active = cnt

        if self.custom_image_selected:
            self.image_combo.append_text("--Separator--")
            self.image_combo.append_text(self.custom_image_selected)
            cnt = cnt + 2
            if self.custom_image_selected == selected_image:
                active = cnt

        self.image_combo.set_active(active)

        if active != 0:
            self.show_baseimg_selected()

        self._image_combo_connect_signal()

    def layer_button_clicked_cb(self, button):
        # Create a layer selection dialog
        self.builder.show_layer_selection_dialog()

    def view_adv_configuration_button_clicked_cb(self, button):
        # Create an advanced settings dialog
        response, settings_changed = self.builder.show_adv_settings_dialog()
        if not response:
            return
        if settings_changed:
            self.builder.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
            self.builder.wait(0.1) #wait for adv_settings_dialog to terminate
            self.builder.reparse_post_adv_settings()
            self.builder.window.set_cursor(None)

    def just_bake_button_clicked_cb(self, button):
        self.builder.parsing_warnings = []
        self.builder.just_bake()

    def edit_image_button_clicked_cb(self, button):
        self.builder.set_base_image()
        self.builder.show_recipes()

    def my_images_button_clicked_cb(self, button):
        self.builder.show_load_my_images_dialog()

    def settings_button_clicked_cb(self, button):
        # Create an advanced settings dialog
        response, settings_changed = self.builder.show_simple_settings_dialog()
        if not response:
            return
        if settings_changed:
            self.builder.reparse_post_adv_settings()


text:
#include "config.h"
#include "Download.h"

#include <WebCore/NotImplemented.h>

using namespace WebCore;

namespace WebKit {

void Download::start()
{
    notImplemented();
}

void Download::startWithHandle(ResourceHandle*, const ResourceResponse&)
{
    notImplemented();
}

void Download::cancel()
{
    notImplemented();
}

void Download::platformInvalidate()
{
    notImplemented();
}

void Download::didDecideDestination(const String& destination, bool allowOverwrite)
{
    notImplemented();
}

void Download::receivedCredential(const AuthenticationChallenge& authenticationChallenge, const Credential& credential)
{
    notImplemented();
}

void Download::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& authenticationChallenge)
{
    notImplemented();
}

void Download::receivedCancellation(const AuthenticationChallenge& authenticationChallenge)
{
    notImplemented();
}

void Download::useCredential(const AuthenticationChallenge&, const Credential&)
{
    notImplemented();
}

void Download::continueWithoutCredential(const AuthenticationChallenge&)
{
    notImplemented();
}

void Download::cancelAuthenticationChallenge(const AuthenticationChallenge&)
{
    notImplemented();
}

} // namespace WebKit


text:
@interface ZPAnimationView : UIView

- (void)setMask:(CGFloat)d;

@end


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office.impl;
import com.wilutions.com.*;

@SuppressWarnings("all")
@CoClass(guid="{C09B9AD7-A463-DB41-5DAE-69E7A5F7FCBC}")
public class SoftEdgeFormatImpl extends Dispatch implements com.wilutions.mslib.office.SoftEdgeFormat {
  @DeclDISPID(1610743808)  public IDispatch getApplication() throws ComException {
    final Object obj = this._dispatchCall(1610743808,"Application", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (IDispatch)obj;
  }
  @DeclDISPID(1610743809)  public Integer getCreator() throws ComException {
    final Object obj = this._dispatchCall(1610743809,"Creator", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (Integer)obj;
  }
  @DeclDISPID(1)  public com.wilutions.mslib.office.MsoSoftEdgeType getType() throws ComException {
    final Object obj = this._dispatchCall(1,"Type", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return com.wilutions.mslib.office.MsoSoftEdgeType.valueOf((Integer)obj);
  }
  @DeclDISPID(1)  public void setType(final com.wilutions.mslib.office.MsoSoftEdgeType value) throws ComException {
    assert(value != null);
    this._dispatchCall(1,"Type", DISPATCH_PROPERTYPUT,value.value);
  }
  @DeclDISPID(2)  public Float getRadius() throws ComException {
    final Object obj = this._dispatchCall(2,"Radius", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (Float)obj;
  }
  @DeclDISPID(2)  public void setRadius(final Float value) throws ComException {
    assert(value != null);
    this._dispatchCall(2,"Radius", DISPATCH_PROPERTYPUT,value);
  }
  public SoftEdgeFormatImpl(String progId) throws ComException {
    super(progId, "{000C03BC-0000-0000-C000-000000000046}");
  }
  protected SoftEdgeFormatImpl(long ndisp) {
    super(ndisp);
  }
  public String toString() {
    return "[SoftEdgeFormatImpl" + super.toString() + "]";
  }
}


text:
import pygame, math, random
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194

# 3 - Load images
rootImg = "resources/images/basic_game/"
rootAud = "resources/audio/basic_game/"

player = pygame.image.load(rootImg + "dude.png")
grass = pygame.image.load(rootImg + "grass.png")
castle = pygame.image.load(rootImg + "castle.png")
arrow = pygame.image.load(rootImg + "bullet.png")
badguyimg1 = pygame.image.load(rootImg + "badguy.png")
badguyimg=badguyimg1
healthbar = pygame.image.load(rootImg + "healthbar.png")
health = pygame.image.load(rootImg + "health.png")
gameover = pygame.image.load(rootImg + "gameover.png")
youwin = pygame.image.load(rootImg + "youwin.png")

# 3.1 - Load audio
hit = pygame.mixer.Sound(rootAud + "explode.wav")
enemy = pygame.mixer.Sound(rootAud + "enemy.wav")
shoot = pygame.mixer.Sound(rootAud + "shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load(rootAud + 'moonlight.wav')
# pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)

# 4 - keep looping through
running = 1
exitcode = 0
while running:
    badtimer-=1
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    for x in range(width/grass.get_width()+1):
        for y in range(height/grass.get_height()+1):
            screen.blit(grass,(x*100,y*100))
    screen.blit(castle,(0,30))
    screen.blit(castle,(0,135))
    screen.blit(castle,(0,240))
    screen.blit(castle,(0,345))

    # 6.1 - Set player position and rotation
    position = pygame.mouse.get_pos()
    angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
    playerrot = pygame.transform.rotate(player, 360-angle*57.29)
    playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
    screen.blit(playerrot, playerpos1)

    # 6.2 - Draw arrows
    for bullet in arrows:
        index=0
        velx=math.cos(bullet[0])*10
        vely=math.sin(bullet[0])*10
        bullet[1]+=velx
        bullet[2]+=vely
        if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
            arrows.pop(index)
        index+=1
        for projectile in arrows:
            arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
            screen.blit(arrow1, (projectile[1], projectile[2]))

    # 6.3 - Draw badgers
    if badtimer==0:
        badguys.append([640, random.randint(50,430)])
        badtimer=100-(badtimer1*2)
        if badtimer1>=35:
            badtimer1=35
        else:
            badtimer1+=5
    index=0
    for badguy in badguys:
        if badguy[0]<-64:
            badguys.pop(index)
        badguy[0]-=3
        # 6.3.1 - Attack castle
        badrect=pygame.Rect(badguyimg.get_rect())
        badrect.top=badguy[1]
        badrect.left=badguy[0]
        if badrect.left<64:
            # hit.play()
            healthvalue -= random.randint(5,20)
            badguys.pop(index)
        #6.3.2 - Check for collisions
        index1=0
        for bullet in arrows:
            bullrect=pygame.Rect(arrow.get_rect())
            bullrect.left=bullet[1]
            bullrect.top=bullet[2]
            if badrect.colliderect(bullrect):
                # enemy.play()
                acc[0]+=1
                badguys.pop(index)
                arrows.pop(index1)
            index1+=1
        # 6.3.3 - Next bad guy
        index+=1
    for badguy in badguys:
        screen.blit(badguyimg, badguy)

    # 6.4 - Draw clock
    font = pygame.font.Font(None, 24)
    survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
    textRect = survivedtext.get_rect()
    textRect.topright=[635,5]
    screen.blit(survivedtext, textRect)

    # 6.5 - Draw health bar
    screen.blit(healthbar, (5,5))
    for health1 in range(healthvalue):
        screen.blit(health, (health1+8,8))

    # 7 - update the screen
    pygame.display.flip()

    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit()
            exit(0)

        if event.type == pygame.KEYDOWN:
            if event.key==K_w:
                keys[0]=True
            elif event.key==K_a:
                keys[1]=True
            elif event.key==K_s:
                keys[2]=True
            elif event.key==K_d:
                keys[3]=True
        if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                keys[0]=False
            elif event.key==pygame.K_a:
                keys[1]=False
            elif event.key==pygame.K_s:
                keys[2]=False
            elif event.key==pygame.K_d:
                keys[3]=False
        if event.type==pygame.MOUSEBUTTONDOWN:
            # shoot.play()
            position=pygame.mouse.get_pos()
            acc[1]+=1
            arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])

    # 9 - Move player
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    if keys[1]:
        playerpos[0]-=5
    elif keys[3]:
        playerpos[0]+=5

    #10 - Win/Lose check
    if pygame.time.get_ticks()>=90000:
        running=0
        exitcode=1
    if healthvalue<=0:
        running=0
        exitcode=0
    if acc[1]!=0:
        accuracy=acc[0]*1.0/acc[1]*100
    else:
        accuracy=0

# 11 - Win/lose display
if exitcode==0:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery+24
    screen.blit(gameover, (0,0))
    screen.blit(text, textRect)
else:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery+24
    screen.blit(youwin, (0,0))
    screen.blit(text, textRect)
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
    pygame.display.flip()


text:
import sys

success=False
in_ironpython="IronPython" in sys.version

if in_ironpython:
    try:
        from ironpython_keysyms import *
        success=True
    except ImportError,x:
        raise
else:
    try:
        from keysyms import *
        success=True
    except ImportError,x:
        pass

if not success:
    raise ImportError("Could not import keysym for local pythonversion",x)


text:
"""
byceps.blueprints.admin.orga_presence.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from collections import defaultdict
from datetime import datetime
from typing import Dict, Iterable

from flask import abort

from ....services.orga_presence import service as orga_presence_service
from ....services.orga_presence.transfer.models import (
    PartyTimeSlot,
    PresenceTimeSlot,
    TimeSlot,
)
from ....services.party import service as party_service
from ....services.user.transfer.models import User
from ....util.framework.blueprint import create_blueprint
from ....util.framework.templating import templated

from ...authorization.decorators import permission_required
from ...authorization.registry import permission_registry

from .authorization import OrgaPresencePermission

blueprint = create_blueprint('orga_presence', __name__)

permission_registry.register_enum(OrgaPresencePermission)

@blueprint.route('/<party_id>')
@permission_required(OrgaPresencePermission.view)
@templated
def view(party_id):
    """List orga presence and task time slots for that party."""
    party = party_service.find_party(party_id)

    if party is None:
        abort(404)

    party_time_slot = PartyTimeSlot.from_party(party)
    presences = orga_presence_service.get_presences(party.id)
    tasks = orga_presence_service.get_tasks(party.id)

    presences_by_orga = _group_presences_by_orga(presences)

    time_slots = [party_time_slot] + presences + tasks
    hour_ranges = list(orga_presence_service.get_hour_ranges(time_slots))

    days_and_hour_totals = list(
        orga_presence_service.get_days_and_hour_totals(hour_ranges)
    )

    return {
        'party': party,
        'days_and_hour_totals': days_and_hour_totals,
        'hour_ranges': hour_ranges,
        'party_time_slot': party_time_slot,
        'presences_by_orga': presences_by_orga,
        'tasks': tasks,
        'is_instant_contained_in_time_slots': is_instant_contained_in_time_slots,
    }

def _group_presences_by_orga(
    presences: Iterable[PresenceTimeSlot]
) -> Dict[User, PresenceTimeSlot]:
    d = defaultdict(set)

    for presence in presences:
        d[presence.orga].add(presence)

    return d

def is_instant_contained_in_time_slots(
    instant: datetime, time_slots: Iterable[TimeSlot]
) -> bool:
    return any(time_slot.range.contains(instant) for time_slot in time_slots)


text:
<?php

namespace CourseHero\ResponsysPHP\Api\Types;

class GetUpdatedResponse
{

  /**
   *
   * @var GetUpdatedResult $result
   * @access public
   */
  public $result = null;

  /**
   *
   * @param GetUpdatedResult $result
   * @access public
   */
  public function __construct($result = null)
  {
    $this->result = $result;
  }

}