text:
using System;

namespace LegacyBounce.Framework
{
    public class On : Task
    {
        public static IObsoleteTask Build(Action onBuild)
        {
            return new On(onBuild);
        }

        private Action OnBuild;

        public On(Action onBuild)
        {
            OnBuild = onBuild;
        }

        public override void Build()
        {
            OnBuild();
        }
    }
}


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

redpajama_set_name: RedPajamaGithub


text:
struct ObjectStruct *ObjectStruct_create(void) {
    ObjectStruct *objectStruct = malloc(sizeof(struct ObjectStruct));
    assert(objectStruct != NULL);
    return objectStruct;
}

void GetObjectStruct(ObjectStruct *objectStruct, uint32_t offset, FILE *datFile) {
    fseek(datFile, offset+DATA_BLOCK, SEEK_SET);
    printf("\nbefore getting object, file is at "KRED"%#.08lx"KNRM, ftell(datFile));
    assert(objectStruct != NULL);
    assert(datFile != NULL);
    fread(&objectStruct->stringOffset, sizeof(objectStruct->stringOffset), 1, datFile);
    fread(&objectStruct->nextObjectOffset, sizeof(objectStruct->nextObjectOffset), 1, datFile);
    fread(&objectStruct->materialStructOffset, sizeof(objectStruct->materialStructOffset), 1, datFile);
    fread(&objectStruct->meshStructOffset, sizeof(objectStruct->meshStructOffset), 1, datFile);
    objectStruct->stringOffset=byteswap32(objectStruct->stringOffset);
    objectStruct->nextObjectOffset=byteswap32(objectStruct->nextObjectOffset);
    objectStruct->materialStructOffset=byteswap32(objectStruct->materialStructOffset);
    objectStruct->meshStructOffset=byteswap32(objectStruct->meshStructOffset);
}

void ObjectStruct_print (ObjectStruct *objectStruct) {
    assert(objectStruct != NULL);
    printf("\nobjectStruct->stringOffset "KRED"%#.08x"KNRM, objectStruct->stringOffset);
    printf("\nobjectStruct->nextObjectOffset "KRED"%#.08x"KNRM, objectStruct->nextObjectOffset);
    printf("\nobjectStruct->materialStructOffset "KRED"%#.08x"KNRM, objectStruct->materialStructOffset);
    printf("\nobjectStruct->meshStructOffset "KRED"%#.08x\n"KNRM, objectStruct->meshStructOffset);
}

void ObjectStruct_destroy(ObjectStruct *objectStruct) {
    assert(objectStruct != NULL);
    free(objectStruct);
}


text:
#ifndef FACEPREPROCESSORFACTORY_H
#define FACEPREPROCESSORFACTORY_H

#include <opencv2/core/core.hpp>

#include "facepreprocessor.h"

class FacePreprocessorFactory final
{
    FaceClassifiers classifiers;

public:
    FacePreprocessorFactory();

    FacePreprocessor GetPreprocessor(const cv::Mat& image, bool markFoundFeatures);
};

#endif // FACEPREPROCESSORFACTORY_H


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

import {NativeLayerCros, NativeLayerCrosImpl, PrinterSetupResponse, PrinterStatus, PrinterStatusReason, PrinterStatusSeverity, PrintServersConfig} from 'chrome://print/print_preview.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js';

export function setNativeLayerCrosInstance(): NativeLayerCrosStub {
  const instance = new NativeLayerCrosStub();
  NativeLayerCrosImpl.setInstance(instance);
  return instance;
}

/**
 * Test version of the Chrome OS native layer.
 */
export class NativeLayerCrosStub extends TestBrowserProxy implements
    NativeLayerCros {
  /** The response to be sent on a |setupPrinter| call. */
  private setupPrinterResponse_: PrinterSetupResponse|null = null;

  /** Whether the printer setup request should be rejected. */
  private shouldRejectPrinterSetup_: boolean = false;

  private eulaUrl_: string = '';

  private printerStatusMap_: Map<string, PrinterStatus> = new Map();

  private multiplePrinterStatusRequestsPromise_: PromiseResolver<void>|null =
      null;

  private multiplePrinterStatusRequestsCount_: number = 0;

  private printServersConfig_: PrintServersConfig|
      null = {printServers: [], isSingleServerFetchingMode: false};

  /** When true, all printer status retry requests return NO_ERROR. */
  private simulateStatusRetrySuccesful_: boolean = false;

  constructor() {
    super([
      'getEulaUrl',
      'requestPrinterStatusUpdate',
      'setupPrinter',
      'choosePrintServers',
      'getPrintServersConfig',
      'recordPrinterStatusRetrySuccessHistogram',
    ]);
  }

  getEulaUrl(destinationId: string) {
    this.methodCalled('getEulaUrl', {destinationId: destinationId});

    return Promise.resolve(this.eulaUrl_);
  }

  setupPrinter(printerId: string) {
    this.methodCalled('setupPrinter', printerId);
    return this.shouldRejectPrinterSetup_ ?
        Promise.reject(assert(this.setupPrinterResponse_!)) :
        Promise.resolve(assert(this.setupPrinterResponse_!));
  }

  getAccessToken() {
    return Promise.resolve('123');
  }

  grantExtensionPrinterAccess(provisionalId: string) {
    return Promise.resolve({
      extensionId: 'abc123',
      extensionName: 'my extension',
      id: provisionalId,
      name: provisionalId + '_Name',
    });
  }

  /**
   * @param response The response to send when |setupPrinter| is called.
   * @param opt_reject Whether printSetup requests should be
   *     rejected. Defaults to false (will resolve callback) if not provided.
   */
  setSetupPrinterResponse(
      response: PrinterSetupResponse, opt_reject?: boolean) {
    this.shouldRejectPrinterSetup_ = opt_reject || false;
    this.setupPrinterResponse_ = response;
  }

  /** @param eulaUrl The eulaUrl of the PPD. */
  setEulaUrl(eulaUrl: string) {
    this.eulaUrl_ = eulaUrl;
  }

  requestPrinterStatusUpdate(printerId: string): Promise<PrinterStatus> {
    this.methodCalled('requestPrinterStatusUpdate');
    if (this.multiplePrinterStatusRequestsPromise_) {
      this.multiplePrinterStatusRequestsCount_--;
      if (this.multiplePrinterStatusRequestsCount_ === 0) {
        this.multiplePrinterStatusRequestsPromise_.resolve();
        this.multiplePrinterStatusRequestsPromise_ = null;
      }
    }

    const printerStatus = this.printerStatusMap_.get(printerId)!;

    // When |simulateStatusRetrySuccesful_| is true, force the next status
    // request for |printerId| to return NO_ERROR.
    if (this.simulateStatusRetrySuccesful_) {
      this.addPrinterStatusToMap(printerId, {
        printerId: printerId,
        statusReasons: [{
          reason: PrinterStatusReason.NO_ERROR,
          severity: PrinterStatusSeverity.REPORT
        }],
        timestamp: Date.now(),
      });
    }
    return Promise.resolve(printerStatus);
  }

  addPrinterStatusToMap(printerId: string, printerStatus: PrinterStatus) {
    this.printerStatusMap_.set(printerId, printerStatus);
  }

  /**
   * @param count The number of printer status requests to wait for.
   * @return Promise that resolves after |count| requests.
   */
  waitForMultiplePrinterStatusRequests(count: number): Promise<void> {
    assert(this.multiplePrinterStatusRequestsPromise_ === null);
    this.multiplePrinterStatusRequestsCount_ = count;
    this.multiplePrinterStatusRequestsPromise_ = new PromiseResolver();
    return this.multiplePrinterStatusRequestsPromise_.promise;
  }

  recordPrinterStatusHistogram(
      _statusReason: PrinterStatusReason, _didUserAttemptPrint: boolean) {}

  choosePrintServers(printServerIds: string[]) {
    this.methodCalled('choosePrintServers', printServerIds);
  }

  getPrintServersConfig() {
    this.methodCalled('getPrintServersConfig');
    return Promise.resolve(this.printServersConfig_!);
  }

  recordPrinterStatusRetrySuccessHistogram(retrySuccessful: boolean) {
    this.methodCalled(
        'recordPrinterStatusRetrySuccessHistogram', retrySuccessful);
  }

  setPrintServersConfig(printServersConfig: PrintServersConfig) {
    this.printServersConfig_ = printServersConfig;
  }

  simulateStatusRetrySuccesful() {
    this.simulateStatusRetrySuccesful_ = true;
  }
}


text:
import { ApiClientSubResourceOptions } from '../base/api_client';
import { ResourceClient } from '../base/resource_client';

/**
 * @hideconstructor
 */
export class UserClient extends ResourceClient {
    constructor(options: ApiClientSubResourceOptions) {
        super({
            resourcePath: 'users',
            ...options,
        });
    }

    /**
     * Depending on whether ApifyClient was created with a token,
     * the method will either return public or private user data.
     * https://docs.apify.com/api/v2#/reference/users
     */
    async get(): Promise<User> {
        return this._get() as Promise<User>;
    }
}

export interface User {
    // Public properties
    username: string;
    profile: {
        bio?: string;
        name?: string;
        pictureUrl?: string;
        githubUsername?: string;
        websiteUrl?: string;
        twitterUsername?: string;
    }
    // Private properties
    id?: string;
    email?: string;
    proxy?: UserProxy;
    plan?: UserPlan;
}

export interface UserProxy {
    password: string;
    groups: ProxyGroup[];
}

export interface ProxyGroup {
    name: string;
    description: string;
    availableCount: number;
}

export interface UserPlan {
    id: string;
    description: string;
    isEnabled: boolean;
    monthlyBasePriceUsd: number;
    monthlyUsageCreditsUsd: number;
    usageDiscountPercent: number;
    enabledPlatformFeatures: PlatformFeature[];
    maxMonthlyUsageUsd: number;
    maxActorMemoryGbytes: number;
    maxMonthlyActorComputeUnits: number;
    maxMonthlyResidentialProxyGbytes: number;
    maxMonthlyProxySerps: number;
    maxMonthlyExternalDataTransferGbytes: number;
    maxActorCount: number;
    maxActorTaskCount: number;
    dataRetentionDays: number;
    availableProxyGroups: Record<string, number>;
    teamAccountSeatCount: number;
    supportLevel: string;
    availableAddOns: unknown[];
}

export enum PlatformFeature {
    Actors = 'ACTORS',
    Storage = 'STORAGE',
    ProxySERPS = 'PROXY_SERPS',
    Scheduler = 'SCHEDULER',
    Webhooks = 'WEBHOOKS',
    Proxy = 'PROXY',
    ProxyExternalAccess = 'PROXY_EXTERNAL_ACCESS',
}


text:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by J.D. Isenhart on 6/7/2015
 * 12:56 PM
 */
public class Conversion {
    static HashMap<String, HashMap> saveData = null;

    public static HashMap checkSaveMap(HashMap<String, HashMap> incomingSaveData) {
        saveData = incomingSaveData;
        checkPlayers();
        checkParty();
        checkLoot();
        checkSpells();
        try {
            FileOutputStream fileOut = new FileOutputStream(String.valueOf(Start.saveFilePath));
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(incomingSaveData);
            out.close();
            fileOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Done checking version of save file!");
        return saveData;
    }

    public static void checkPlayers() {
        for (int i = 0; i < saveData.get("Players").size(); i++) {
            String player = String.valueOf(saveData.get("Players").get(i));
            if (!saveData.get(player).containsKey("BR")) {
                int damageStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Damage")));
                int killStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Kills")));
                int healingStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Healing")));
                int BR = (int) ((damageStat * 2) + ((double) healingStat * 2.1) + (killStat * 6));
                saveData.get(player).put("BR", BR);
            } else {
                int damageStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Damage")));
                int killStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Kills")));
                int healingStat = Integer.parseInt(String.valueOf(saveData.get(player).get("Healing")));
                int BR = (int) ((damageStat * 2) + ((double) healingStat * 2.1)) + (killStat * 6);
                saveData.remove("BR");
                saveData.get(player).put("BR", BR);

            }
            if (!saveData.get(player).containsKey("FriendFire")) {
                int friendFire = 0;
                saveData.get(player).put("FriendFire", friendFire);
            }
            if (!saveData.get(player).containsKey("MaxHealth")) {
                saveData.get(player).put("MaxHealth", 1);
            }
        }
    }

    public static void checkParty() {
        if (!saveData.containsKey("Party")) {
            HashMap partyStats = new HashMap();
            partyStats.put("Dice", 0);
            partyStats.put("Swords", 0);
            partyStats.put("Arrows", 0);
            partyStats.put("Spells", 0);
            partyStats.put("XP", 0);
            partyStats.put("Hits", 0);
            saveData.put("Party", partyStats);
        }
    }

    public static void checkLoot() {
        if (!saveData.containsKey("Loot")) {
            HashMap lootStats = new HashMap();
            lootStats.put("Data", new Object[][]{});
            saveData.put("Loot", lootStats);
        }
    }

    public static void checkSpells() {
        if (!saveData.containsKey("Spells")) {
            HashMap spellHash = new HashMap();
            spellHash.put("SpellList", new ArrayList<String>());
            spellHash.put("Casters", new HashMap<>());
            saveData.put("Spells", spellHash);
        }
    }
}


text:
#include "global.h"
#include "peer.h"
#include "debug.h"

#ifndef WITH_CONTIKI
void peer_init()
{
}

static inline dtls_peer_t *
dtls_malloc_peer() {
  return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
}

void
dtls_free_peer(dtls_peer_t *peer) {
  dtls_handshake_free(peer->handshake_params);
  dtls_security_free(peer->security_params[0]);
  dtls_security_free(peer->security_params[1]);
  free(peer);
}
#else /* WITH_CONTIKI */

#include "memb.h"
MEMB(peer_storage, dtls_peer_t, DTLS_PEER_MAX);

void
peer_init() {
  memb_init(&peer_storage);
}

static inline dtls_peer_t *
dtls_malloc_peer() {
  return memb_alloc(&peer_storage);
}

void
dtls_free_peer(dtls_peer_t *peer) {
  dtls_handshake_free(peer->handshake_params);
  dtls_security_free(peer->security_params[0]);
  dtls_security_free(peer->security_params[1]);
  memb_free(&peer_storage, peer);
}
#endif /* WITH_CONTIKI */

dtls_peer_t *
dtls_new_peer(const session_t *session) {
  dtls_peer_t *peer;

  peer = dtls_malloc_peer();
  if (peer) {
    memset(peer, 0, sizeof(dtls_peer_t));
    memcpy(&peer->session, session, sizeof(session_t));
    peer->security_params[0] = dtls_security_new();

    if (!peer->security_params[0]) {
      dtls_free_peer(peer);
      wilddog_debug_level(WD_DEBUG_ERROR,"New dtls peer failed.");
      return NULL;
    }

    dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "dtls_new_peer", session);
  }

  return peer;
}


text:
package org.apache.flink.tests.util.kafka;

import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.tests.util.AutoClosableProcess;
import org.apache.flink.tests.util.CommandLineWrapper;
import org.apache.flink.tests.util.activation.OperatingSystemRestriction;
import org.apache.flink.tests.util.cache.DownloadCache;
import org.apache.flink.util.OperatingSystem;

import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * {@link KafkaResource} that downloads kafka and sets up a local kafka cluster with the bundled zookeeper.
 */
public class LocalStandaloneKafkaResource implements KafkaResource {

	private static final Logger LOG = LoggerFactory.getLogger(LocalStandaloneKafkaResource.class);
	private static final Pattern ZK_DATA_DIR_PATTERN = Pattern.compile(".*(dataDir=).*");
	private static final Pattern KAFKA_LOG_DIR_PATTERN = Pattern.compile(".*(log\\.dirs=).*");

	private static final String ZOOKEEPER_HOST = "localhost";
	private static final int ZOOKEEPER_PORT = 2181;
	private static final String ZOOKEEPER_ADDRESS = ZOOKEEPER_HOST + ':' + ZOOKEEPER_PORT;
	private static final String KAFKA_HOST = "localhost";
	private static final int KAFKA_PORT = 9092;
	private static final String KAFKA_ADDRESS = KAFKA_HOST + ':' + KAFKA_PORT;

	private final TemporaryFolder tmp = new TemporaryFolder();

	private final DownloadCache downloadCache = DownloadCache.get();
	private final String kafkaVersion;
	private Path kafkaDir;

	LocalStandaloneKafkaResource(final String kafkaVersion) {
		OperatingSystemRestriction.forbid(
			String.format("The %s relies on UNIX utils and shell scripts.", getClass().getSimpleName()),
			OperatingSystem.WINDOWS);
		this.kafkaVersion = kafkaVersion;
	}

	private static String getKafkaDownloadUrl(final String kafkaVersion) {
		return String.format("https://archive.apache.org/dist/kafka/%s/kafka_2.11-%s.tgz", kafkaVersion, kafkaVersion);
	}

	@Override
	public void before() throws Exception {
		tmp.create();
		downloadCache.before();

		this.kafkaDir = tmp.newFolder("kafka").toPath().toAbsolutePath();
		setupKafkaDist();
		setupKafkaCluster();
	}

	private void setupKafkaDist() throws IOException {
		final Path downloadDirectory = tmp.newFolder("getOrDownload").toPath();
		final Path kafkaArchive = downloadCache.getOrDownload(getKafkaDownloadUrl(kafkaVersion), downloadDirectory);

		LOG.info("Kafka location: {}", kafkaDir.toAbsolutePath());
		AutoClosableProcess.runBlocking(CommandLineWrapper
			.tar(kafkaArchive)
			.extract()
			.zipped()
			.strip(1)
			.targetDir(kafkaDir)
			.build());

		LOG.info("Updating ZooKeeper properties");
		final Path zookeeperPropertiesFile = kafkaDir.resolve(Paths.get("config", "zookeeper.properties"));
		final List<String> zookeeperPropertiesFileLines = Files.readAllLines(zookeeperPropertiesFile);
		try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(zookeeperPropertiesFile, StandardOpenOption.TRUNCATE_EXISTING), StandardCharsets.UTF_8.name()))) {
			zookeeperPropertiesFileLines.stream()
				.map(line -> ZK_DATA_DIR_PATTERN.matcher(line).replaceAll("$1" + kafkaDir.resolve("zookeeper").toAbsolutePath()))
				.forEachOrdered(pw::println);
		}

		LOG.info("Updating Kafka properties");
		final Path kafkaPropertiesFile = kafkaDir.resolve(Paths.get("config", "server.properties"));
		final List<String> kafkaPropertiesFileLines = Files.readAllLines(kafkaPropertiesFile);
		try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(kafkaPropertiesFile, StandardOpenOption.TRUNCATE_EXISTING), StandardCharsets.UTF_8.name()))) {
			kafkaPropertiesFileLines.stream()
				.map(line -> KAFKA_LOG_DIR_PATTERN.matcher(line).replaceAll("$1" + kafkaDir.resolve("kafka").toAbsolutePath()))
				.forEachOrdered(pw::println);
		}
	}

	private void setupKafkaCluster() throws IOException {
		LOG.info("Starting zookeeper");
		AutoClosableProcess.runBlocking(
			kafkaDir.resolve(Paths.get("bin", "zookeeper-server-start.sh")).toString(),
			"-daemon",
			kafkaDir.resolve(Paths.get("config", "zookeeper.properties")).toString()
		);
		LOG.info("Starting kafka");
		AutoClosableProcess.runBlocking(
			kafkaDir.resolve(Paths.get("bin", "kafka-server-start.sh")).toString(),
			"-daemon",
			kafkaDir.resolve(Paths.get("config", "server.properties")).toString()
		);

		while (!isZookeeperRunning(kafkaDir) || !isKafkaRunning(kafkaDir)) {
			try {
				LOG.info("Waiting for kafka & zookeeper to start.");
				Thread.sleep(500L);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				break;
			}
		}
	}

	@Override
	public void afterTestSuccess() {
		try {
			AutoClosableProcess.runBlocking(
				kafkaDir.resolve(Paths.get("bin", "kafka-server-stop.sh")).toString()
			);
			while (isKafkaRunning(kafkaDir)) {
				try {
					Thread.sleep(500L);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					break;
				}
			}
		} catch (IOException ioe) {
			LOG.warn("Error while shutting down kafka.", ioe);
		}
		try {
			AutoClosableProcess.runBlocking(
				kafkaDir.resolve(Paths.get("bin", "zookeeper-server-stop.sh")).toString()
			);
			while (isZookeeperRunning(kafkaDir)) {
				try {
					Thread.sleep(500L);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					break;
				}
			}
		} catch (IOException ioe) {
			LOG.warn("Error while shutting down zookeeper.", ioe);
		}
		downloadCache.afterTestSuccess();
		tmp.delete();
	}

	private static boolean isZookeeperRunning(final Path kafkaDir) {
		try {
			queryBrokerStatus(kafkaDir, line -> {});
			return true;
		} catch (final IOException ioe) {
			// we get an exception if zookeeper isn't running
			return false;
		}
	}

	private static boolean isKafkaRunning(final Path kafkaDir) throws IOException {
		try {
			final AtomicBoolean atomicBrokerStarted = new AtomicBoolean(false);
			queryBrokerStatus(kafkaDir, line -> atomicBrokerStarted.compareAndSet(false, line.contains("dataLength =")));
			return atomicBrokerStarted.get();
		} catch (final IOException ioe) {
			// we get an exception if zookeeper isn't running
			return false;
		}
	}

	private static void queryBrokerStatus(final Path kafkaDir, final Consumer<String> stderrProcessor) throws IOException {
		AutoClosableProcess
			.create(
				kafkaDir.resolve(Paths.get("bin", "zookeeper-shell.sh")).toString(),
				ZOOKEEPER_ADDRESS,
				"get",
				"/brokers/ids/0")
			.setStderrProcessor(stderrProcessor)
			.runBlocking();
	}

	@Override
	public void createTopic(int replicationFactor, int numPartitions, String topic) throws IOException {
		AutoClosableProcess.runBlocking(
			kafkaDir.resolve(Paths.get("bin", "kafka-topics.sh")).toString(),
			"--create",
			"--zookeeper",
			ZOOKEEPER_ADDRESS,
			"--replication-factor",
			String.valueOf(replicationFactor),
			"--partitions",
			String.valueOf(numPartitions),
			"--topic",
			topic);
	}

	@Override
	public void sendMessages(String topic, String... messages) throws IOException {
		try (AutoClosableProcess autoClosableProcess = AutoClosableProcess.runNonBlocking(
			kafkaDir.resolve(Paths.get("bin", "kafka-console-producer.sh")).toString(),
			"--broker-list",
			KAFKA_ADDRESS,
			"--topic",
			topic)) {

			try (PrintStream printStream = new PrintStream(autoClosableProcess.getProcess().getOutputStream(), true, StandardCharsets.UTF_8.name())) {
				for (final String message : messages) {
					printStream.println(message);
				}
				printStream.flush();
			}

			try {
				// wait until the process shuts down on it's own
				// this is the only reliable way to ensure the producer has actually processed our input
				autoClosableProcess.getProcess().waitFor();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

	@Override
	public List<String> readMessage(int maxNumMessages, String groupId, String topic) throws IOException {
		final List<String> messages = Collections.synchronizedList(new ArrayList<>(maxNumMessages));

		try (final AutoClosableProcess kafka = AutoClosableProcess
			.create(kafkaDir.resolve(Paths.get("bin", "kafka-console-consumer.sh")).toString(),
				"--bootstrap-server",
				KAFKA_ADDRESS,
				"--from-beginning",
				"--max-messages",
				String.valueOf(maxNumMessages),
				"--topic",
				topic,
				"--consumer-property",
				"group.id=" + groupId)
			.setStdoutProcessor(messages::add)
			.runNonBlocking()) {

			final Deadline deadline = Deadline.fromNow(Duration.ofSeconds(30));
			while (deadline.hasTimeLeft() && messages.size() < maxNumMessages) {
				try {
					LOG.info("Waiting for messages. Received {}/{}.", messages.size(), maxNumMessages);
					Thread.sleep(500);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					break;
				}
			}
			return messages;
		}
	}

	@Override
	public void setNumPartitions(int numPartitions, String topic) throws IOException {
		AutoClosableProcess.runBlocking(
			kafkaDir.resolve(Paths.get("bin", "kafka-topics.sh")).toString(),
			"--alter",
			"--topic",
			topic,
			"--partitions",
			String.valueOf(numPartitions),
			"--zookeeper",
			ZOOKEEPER_ADDRESS
		);
	}

	@Override
	public int getNumPartitions(String topic) throws IOException {
		final Pattern partitionCountPattern = Pattern.compile(".*PartitionCount:([0-9]+).*");
		final AtomicReference<Integer> partitionCountFound = new AtomicReference<>(-1);
		AutoClosableProcess
			.create(kafkaDir.resolve(Paths.get("bin", "kafka-topics.sh")).toString(),
				"--describe",
				"--topic",
				topic,
				"--zookeeper",
				ZOOKEEPER_ADDRESS)
			.setStdoutProcessor(line -> {
				final Matcher matcher = partitionCountPattern.matcher(line);
				if (matcher.matches()) {
					partitionCountFound.compareAndSet(-1, Integer.parseInt(matcher.group(1)));
				}
			})
			.runBlocking();
		return partitionCountFound.get();
	}

	@Override
	public long getPartitionOffset(String topic, int partition) throws IOException {
		final Pattern partitionOffsetPattern = Pattern.compile(".*:.*:([0-9]+)");
		final AtomicReference<Integer> partitionOffsetFound = new AtomicReference<>(-1);
		AutoClosableProcess
			.create(kafkaDir.resolve(Paths.get("bin", "kafka-run-class.sh")).toString(),
				"kafka.tools.GetOffsetShell",
				"--broker-list",
				KAFKA_ADDRESS,
				"--topic",
				topic,
				"--partitions",
				String.valueOf(partition),
				"--time",
				"-1")
			.setStdoutProcessor(line -> {
				final Matcher matcher = partitionOffsetPattern.matcher(line);
				if (matcher.matches()) {
					partitionOffsetFound.compareAndSet(-1, Integer.parseInt(matcher.group(1)));
				}
			})
			.runBlocking();

		final int partitionOffset = partitionOffsetFound.get();
		if (partitionOffset == -1) {
			throw new IOException("Could not determine partition offset.");
		}
		return partitionOffset;
	}

	@Override
	public Collection<InetSocketAddress> getBootstrapServerAddresses() {
		return Collections.singletonList(InetSocketAddress.createUnresolved(KAFKA_HOST, KAFKA_PORT));
	}

	@Override
	public InetSocketAddress getZookeeperAddress() {
		return InetSocketAddress.createUnresolved(KAFKA_HOST, KAFKA_PORT);
	}
}


text:
require 'test_helper'

class TeamMembershipTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
<?php
/**
 * Storefront Powerpack Designer Class
 *
 * @package  Storefront_Powerpack
 * @author   Tiago Noronha
 * @since    1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SP_Designer' ) ) :

	/**
	 * The Designer class
	 */
	class SP_Designer {

		const DESIGNER_SECTION = 'sp_designer_section';

		/**
		 * Setup class.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			add_action( 'customize_register', array( $this, 'customize_register' ), 30 );
			add_action( 'customize_controls_enqueue_scripts', array( $this, 'scripts' ) );
			add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_settings' ) );
			add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
			add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
			add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
			add_action( 'wp_head', array( $this, 'frontend' ), 9999 );
			add_action( 'wp_enqueue_scripts', array( $this, 'frontend_google_fonts' ) );
		}

		/**
		 * Customizer Controls and settings
		 * @param WP_Customize_Manager $wp_customize Theme Customizer object.
		 */
		public function customize_register( $wp_customize ) {
			require_once dirname( __FILE__ ) . '/includes/class-sp-designer-css-setting.php';
			require_once dirname( __FILE__ ) . '/includes/class-sp-designer-css-control.php';
			require_once dirname( __FILE__ ) . '/includes/class-sp-designer-notice-control.php';
			require_once dirname( __FILE__ ) . '/includes/class-sp-designer-action-control.php';

			/**
			 * Register control types
			 */
			$wp_customize->register_control_type( 'SP_Designer_CSS_Control' );

			/**
			 * Add a new section
			 */
			$wp_customize->add_section( self::DESIGNER_SECTION, array(
				'title'    => __( 'Designer', 'storefront-powerpack' ),
				'panel'    => 'sp_panel',
				'priority' => 10,
			) );

			/**
			 * Notice control
			 */
			if ( class_exists( 'SP_Designer_Notice_Control' ) ) {
				$wp_customize->add_control( new SP_Designer_Notice_Control( $wp_customize, 'sp_designer_notice', array(
					'section'  		  => self::DESIGNER_SECTION,
					'priority' 		  => 5,
				) ) );
			}

			/**
			 * Add saved controls
			 */
			$selectors = get_theme_mod( 'sp_designer_css_data' );

			if ( ! empty( $selectors ) ) {
				$priority  = 10;

				foreach ( $selectors as $id => $value ) {
					// Get label
					$saved_selector = $value['selector'];

					$selector_nicename = array_values( array_filter( $this->selectors_map() , function( $selector ) use ( $saved_selector ) {
						return ( $selector['selector'] === $saved_selector );
					} ) );

					$label = $saved_selector;

					if ( ! empty( $selector_nicename ) ) {
						$label = $selector_nicename[0]['name'];
					}

					// Create a setting for each CSS selector.
					$selector_id = 'sp_designer_css_data[' . $id . ']';

					$wp_customize->add_setting( new SP_Designer_CSS_Setting( $wp_customize, $selector_id, array(
						'value' => $value,
					) ) );

					// Create a control for each menu item.
					$wp_customize->add_control( new SP_Designer_CSS_Control( $wp_customize, $selector_id, array(
						'id'       => $id,
						'label'    => $label,
						'section'  => self::DESIGNER_SECTION,
						'priority' => $priority,
					) ) );

					$priority++;
				}
			}

			/**
			 * Action control
			 */
			if ( class_exists( 'SP_Designer_Action_Control' ) ) {
				$wp_customize->add_control( new SP_Designer_Action_Control( $wp_customize, 'sp_designer_action', array(
					'section'  		  => self::DESIGNER_SECTION,
					'priority' 		  => PHP_INT_MAX,
				) ) );
			}
		}

		/**
		 * Enqueue scripts.
		 *
		 * @return void
		 */
		public function scripts() {
			$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
			wp_enqueue_script( 'sp-designer-js', plugins_url( '/assets/js/sp-designer' . $suffix . '.js', __FILE__ ), array( 'jquery', 'wp-backbone', 'customize-controls' ), storefront_powerpack()->version, true );
			wp_enqueue_style( 'sp-designer-css', plugins_url( '/assets/css/sp-designer.css', __FILE__ ), array(), storefront_powerpack()->version, 'all' );

			wp_enqueue_script( 'selectize-js', plugins_url( '/assets/js/vendor/selectize.min.js', __FILE__ ), array( 'jquery', 'wp-backbone', 'customize-controls' ), storefront_powerpack()->version, true );
			wp_enqueue_style( 'selectize-css', plugins_url( '/assets/js/vendor/selectize.min.css', __FILE__ ), array(), storefront_powerpack()->version, 'all' );
		}

		/**
		 * This function is triggered on the initialization of the Previewer in the Customizer.
		 * @access  public
		 * @since   1.0.0
		 * @return  void
		 */
		public function customize_preview_init() {
			add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
		}

		/**
		 * Enqueue scripts for the Customizer preview.
		 * @access  public
		 * @since   1.0.0
		 * @return  void
		 */
		public function customize_preview_enqueue() {
			$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
			wp_enqueue_script( 'sp-designer-preview-js', plugins_url( '/assets/js/sp-designer-preview' . $suffix . '.js', __FILE__ ), array( 'jquery','customize-preview' ), storefront_powerpack()->version, true );
			wp_enqueue_script( 'webfont-js', plugins_url( '/assets/js/vendor/webfont.js', __FILE__ ), array( 'customize-preview' ), '1.6.16', true );

			$web_fonts = array();

			foreach ( self::websafe_fonts() as $font ) {
				$web_fonts[] = $font['family'];
			}

			$settings = array(
				'webSafeFonts' => $web_fonts,
				'selectorsMap' => $this->selectors_map(),
			);

			$data = sprintf( 'var _wpCustomizeSPDesignerPreviewSettings = %s;', wp_json_encode( $settings ) );
			wp_scripts()->add_data( 'sp-designer-preview-js', 'data', $data );

			wp_enqueue_style( 'sp-designer-preview-css', plugins_url( '/assets/css/sp-designer-preview.css', __FILE__ ), array(), storefront_powerpack()->version, 'all' );
		}

		/**
		 * Enqueue Settings.
		 * @access  public
		 * @since   1.0.0
		 * @return  void
		 */
		public function enqueue_settings() {
			$font_variants = array();
			foreach ( self::get_google_web_fonts() as $font ) {
				$variants = array();

				foreach ( $font['variants'] as $variant ) {
					$variants[] = array(
						'id'   => $variant,
						'text' => ucfirst( $variant ),
					);
				}

				$font_variants[] = array(
					'family'       => $font['family'],
					'variants'     => $variants,
				);
			}

			$settings = array(
				'phpIntMax'    => PHP_INT_MAX,
				'section'      => self::DESIGNER_SECTION,
				'fontVariants' => $font_variants,
				'selectorsMap' => $this->selectors_map(),
				'bgImage'      => array(
					'mime_type' => 'image',
					'l10n'      => array(
						'set'    => __( 'Set as background', 'storefront-powerpack' ),
						'choose' => __( 'Choose background', 'storefront-powerpack' ),
					),
				),
			);

			$data = sprintf( 'var _wpCustomizeSPDesignerSettings = %s;', wp_json_encode( $settings ) );

			wp_scripts()->add_data( 'sp-designer-js', 'data', $data );
		}

		/**
		 * Filter a dynamic setting's constructor args.
		 *
		 * For a dynamic setting to be registered, this filter must be employed
		 * to override the default false value with an array of args to pass to
		 * the WP_Customize_Setting constructor.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @param 	false|array $setting_args The arguments to the WP_Customize_Setting constructor.
		 * @param 	string      $setting_id   ID for dynamic setting, usually coming from `$_POST['customized']`.
		 * @return 	array|false
		 */
		public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
			if ( ! class_exists( 'SP_Designer_CSS_Setting' ) ) {
				require_once dirname( __FILE__ ) . '/includes/class-sp-designer-css-setting.php';
			}

			if ( preg_match( SP_Designer_CSS_Setting::ID_PATTERN, $setting_id ) ) {
				$setting_args = array(
					'type' => SP_Designer_CSS_Setting::TYPE,
				);
			}
			return $setting_args;
		}

		/**
		 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @param 	string $setting_class WP_Customize_Setting or a subclass.
		 * @param 	string $setting_id    ID for dynamic setting, usually coming from `$_POST['customized']`.
		 * @param 	array  $setting_args  WP_Customize_Setting or a subclass.
		 * @return 	string
		 */
		public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
			if ( ! class_exists( 'SP_Designer_CSS_Setting' ) ) {
				require_once dirname( __FILE__ ) . '/includes/class-sp-designer-css-setting.php';
			}

			unset( $setting_id );
			if ( ! empty( $setting_args['type'] ) && SP_Designer_CSS_Setting::TYPE === $setting_args['type'] ) {
				$setting_class = 'SP_Designer_CSS_Setting';
			}
			return $setting_class;
		}

		/**
		 * An array of websafe fonts.
		 * Taken from http://www.w3schools.com/cssref/css_websafe_fonts.asp.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	array The list of websafe font combinations.
		 */
		public static function websafe_fonts() {
			return apply_filters( 'sp_designer_websafe_font_combinations', array(
				array(
					'family'   => 'Arial',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Arial Black',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Comic Sans MS',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Courier New',
					'category' => 'monospace',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Georgia',
					'category' => 'serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Impact',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Lucida Console',
					'category' => 'monospace',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Lucida Sans',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Palatino',
					'category' => 'serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Tahoma',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Times New Roman',
					'category' => 'serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Trebuchet MS',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
				array(
					'family'   => 'Verdana',
					'category' => 'sans-serif',
					'variants' => array( 400, 700 ),
				),
			) );
		}

		/**
		 * Loads Google Fonts from google-web-fonts.json.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	mixed Array of Google Fonts or False if it fails to load the list of fonts.
		 */
		public static function get_google_web_fonts() {
			$json = file_get_contents( dirname( __FILE__ ) . '/assets/json/google-web-fonts.json' );

			if ( $json ) {
				$fonts        = json_decode( $json, true );
				$google_fonts = array();

				if ( is_array( $fonts ) ) {
					foreach ( $fonts as $font ) {
						$google_fonts[] = array(
							'family'   => $font['family'],
							'category' => $font['category'],
							'variants' => $font['variants'],
						);
					}
				}

				return apply_filters( 'sp_designer_google_fonts', $google_fonts );
			}

			return false;
		}

		/**
		 * Combines Websafe fonts with the Google Fonts for output in the CSS Control.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	mixed Array of fonts.
		 */
		public static function customize_fonts() {
			$customize_fonts = array();

			// Theme
			$customize_fonts[] = array(
				'text'     => __( 'Theme', 'storefront-powerpack' ),
				'fonts'    => array( __( 'Default', 'storefront-powerpack' ) ),
			);

			// Websafe
			$websafe_fonts = self::websafe_fonts();
			$wf_output     = array();

			if ( $websafe_fonts ) {
				foreach ( $websafe_fonts as $font ) {
					$wf_output[] = $font['family'];
				}
			}

			$customize_fonts[] = array(
				'text'  => __( 'Web Safe Fonts', 'storefront-powerpack' ),
				'fonts' => $wf_output,
			);

			// Google Fonts
			$google_fonts = self::get_google_web_fonts();
			$gf_output    = array();

			if ( $google_fonts ) {
				foreach ( $google_fonts as $font ) {
					$gf_output[] = $font['family'];
				}
			}

			$customize_fonts[] = array(
				'text'  => __( 'Google Web Fonts', 'storefront-powerpack' ),
				'fonts' => $gf_output,
			);

			return apply_filters( 'sp_designer_customize_fonts', $customize_fonts );
		}

		/**
		 * Outputs the custom styles to the frontend.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	void.
		 */
		public function frontend() {
			$selectors = get_theme_mod( 'sp_designer_css_data' );

			if ( ! $selectors || ! is_array( $selectors ) ) {
				return;
			}

			$output = '';

			foreach ( $selectors as $id => $css_properties ) {
				if ( ! isset( $css_properties['selector'] ) || '' === $css_properties['selector'] ) {
					continue;
				}

				// Selector - start
				$output .= $css_properties['selector'] . '{';

				// Font size
				if ( isset( $css_properties['fontSize'] ) && '' !== $css_properties['fontSize'] ) {
					$unit = 'px';
					if ( isset( $css_properties['fontSizeUnit'] ) && '' !== $css_properties['fontSizeUnit'] ) {
						$unit = esc_attr( $css_properties['fontSizeUnit'] );
					}
					$output .= 'font-size:' . esc_attr( $css_properties['fontSize'] ) . esc_attr( $unit ) . ';';
				}

				// Font family
				if ( isset( $css_properties['fontFamily'] ) && '' !== $css_properties['fontFamily'] ) {
					if ( 'Default' === $css_properties['fontFamily'] ) {
						$output .= 'font-family:inherit;';
					} else {
						$output .= 'font-family:' . esc_attr( $css_properties['fontFamily'] ) . ';';
					}
				}

				// Letter spacing
				if ( isset( $css_properties['letterSpacing'] ) && '' !== $css_properties['letterSpacing'] ) {
					$unit = 'px';
					if ( isset( $css_properties['letterSpacingUnit'] ) && '' !== $css_properties['letterSpacingUnit'] ) {
						$unit = $css_properties['letterSpacingUnit'];
					}
					$output .= 'letter-spacing:' . esc_attr( $css_properties['letterSpacing'] ) . esc_attr( $unit ) . ';';
				}

				// Line height
				if ( isset( $css_properties['lineHeight'] ) && '' !== $css_properties['lineHeight'] ) {
					$output .= 'line-height:' . esc_attr( $css_properties['lineHeight'] ) . 'px' . ';';
				}

				// Font style
				if ( isset( $css_properties['fontStyle'] ) && 'italic' === $css_properties['fontStyle'] ) {
					$output .= 'font-style:italic;';
				} else {
					$output .= 'font-style:normal;';
				}

				// Font weight
				if ( isset( $css_properties['fontWeight'] ) && 'bold' === $css_properties['fontWeight'] ) {
					$output .= 'font-weight:700;';
				} else {
					$output .= 'font-weight:400;';
				}

				// Text decoration
				$text_decoration = array();
				if ( isset( $css_properties['textUnderline'] ) && 'underline' === $css_properties['textUnderline'] ) {
					$text_decoration[] = 'underline';
				}

				if ( isset( $css_properties['textLineThrough'] ) && 'line-through' === $css_properties['textLineThrough'] ) {
					$text_decoration[] = 'line-through';
				}

				if ( empty( $text_decoration ) ) {
					$text_decoration[] = 'none';
				}

				$output .= 'text-decoration:' . esc_attr( implode( ' ', $text_decoration ) ) . ';';

				// Margin top
				if ( isset( $css_properties['marginTop'] ) && '' !== $css_properties['marginTop'] ) {
					$unit = 'px';
					if ( isset( $css_properties['marginTopUnit'] ) && '' !== $css_properties['marginTopUnit'] ) {
						$unit = $css_properties['marginTopUnit'];
					}
					$output .= 'margin-top:' . esc_attr( $css_properties['marginTop'] ) . esc_attr( $unit ) . ';';
				}

				// Margin bottom
				if ( isset( $css_properties['marginBottom'] ) && '' !== $css_properties['marginBottom'] ) {
					$unit = 'px';
					if ( isset( $css_properties['marginBottomUnit'] ) && '' !== $css_properties['marginBottomUnit'] ) {
						$unit = $css_properties['marginBottomUnit'];
					}
					$output .= 'margin-bottom:' . esc_attr( $css_properties['marginBottom'] ) . esc_attr( $unit ) . ';';
				}

				// Margin left
				if ( isset( $css_properties['marginLeft'] ) && '' !== $css_properties['marginLeft'] ) {
					$unit = 'px';
					if ( isset( $css_properties['marginLeftUnit'] ) && '' !== $css_properties['marginLeftUnit'] ) {
						$unit = $css_properties['marginLeftUnit'];
					}
					$output .= 'margin-left:' . esc_attr( $css_properties['marginLeft'] ) . esc_attr( $unit ) . ';';
				}

				// Margin right
				if ( isset( $css_properties['marginRight'] ) && '' !== $css_properties['marginRight'] ) {
					$unit = 'px';
					if ( isset( $css_properties['marginRightUnit'] ) && '' !== $css_properties['marginRightUnit'] ) {
						$unit = $css_properties['marginRightUnit'];
					}
					$output .= 'margin-right:' . esc_attr( $css_properties['marginRight'] ) . esc_attr( $unit ) . ';';
				}

				// Padding top
				if ( isset( $css_properties['paddingTop'] ) && '' !== $css_properties['paddingTop'] ) {
					$unit = 'px';
					if ( isset( $css_properties['paddingTopUnit'] ) && '' !== $css_properties['paddingTopUnit'] ) {
						$unit = $css_properties['paddingTopUnit'];
					}
					$output .= 'padding-top:' . esc_attr( $css_properties['paddingTop'] ) . esc_attr( $unit ) . ';';
				}

				// Padding bottom
				if ( isset( $css_properties['paddingBottom'] ) && '' !== $css_properties['paddingBottom'] ) {
					$unit = 'px';
					if ( isset( $css_properties['paddingBottomUnit'] ) && '' !== $css_properties['paddingBottomUnit'] ) {
						$unit = $css_properties['paddingBottomUnit'];
					}
					$output .= 'padding-bottom:' . esc_attr( $css_properties['paddingBottom'] ) . esc_attr( $unit ) . ';';
				}

				// Padding left
				if ( isset( $css_properties['paddingLeft'] ) && '' !== $css_properties['paddingLeft'] ) {
					$unit = 'px';
					if ( isset( $css_properties['paddingLeftUnit'] ) && '' !== $css_properties['paddingLeftUnit'] ) {
						$unit = $css_properties['paddingLeftUnit'];
					}
					$output .= 'padding-left:' . esc_attr( $css_properties['paddingLeft'] ) . esc_attr( $unit ) . ';';
				}

				// Padding right
				if ( isset( $css_properties['paddingRight'] ) && '' !== $css_properties['paddingRight'] ) {
					$unit = 'px';
					if ( isset( $css_properties['paddingRightUnit'] ) && '' !== $css_properties['paddingRightUnit'] ) {
						$unit = $css_properties['paddingRightUnit'];
					}
					$output .= 'padding-right:' . esc_attr( $css_properties['paddingRight'] ) . esc_attr( $unit ) . ';';
				}

				// Color
				if ( isset( $css_properties['color'] ) && '' !== $css_properties['color'] ) {
					$output .= 'color:' . esc_attr( $css_properties['color'] ) . ';';
				}

				// Border width
				if ( isset( $css_properties['borderWidth'] ) && '' !== $css_properties['borderWidth'] ) {
					$unit = 'px';
					if ( isset( $css_properties['borderWidthUnit'] ) && '' !== $css_properties['borderWidthUnit'] ) {
						$unit = $css_properties['borderWidthUnit'];
					}
					$output .= 'border-width:' . esc_attr( $css_properties['borderWidth'] ) . esc_attr( $unit ) . ';';
				}

				// Border radius
				if ( isset( $css_properties['borderRadius'] ) && '' !== $css_properties['borderRadius'] ) {
					$unit = 'px';
					if ( isset( $css_properties['borderRadiusUnit'] ) && '' !== $css_properties['borderRadiusUnit'] ) {
						$unit = $css_properties['borderRadiusUnit'];
					}
					$output .= 'border-radius:' . esc_attr( $css_properties['borderRadius'] ) . esc_attr( $unit ) . ';';
				}

				// Border style
				if ( isset( $css_properties['borderStyle'] ) && '' !== $css_properties['borderStyle'] ) {
					$output .= 'border-style:' . esc_attr( $css_properties['borderStyle'] ) . ';';
				}

				// Border color
				if ( isset( $css_properties['borderColor'] ) && '' !== $css_properties['borderColor'] ) {
					$output .= 'border-color:' . esc_attr( $css_properties['borderColor'] ) . ';';
				}

				// Background color
				if ( isset( $css_properties['backgroundColor'] ) && '' !== $css_properties['backgroundColor'] ) {
					$output .= 'background-color:' . esc_attr( $css_properties['backgroundColor'] ) . ';';
				}

				// Background image
				if ( isset( $css_properties['backgroundImage'] ) ) {
					$bg_image = $css_properties['backgroundImage'];

					if ( isset( $bg_image['id'] ) && false !== wp_get_attachment_image_src( $bg_image['id'] ) ) {
						$output .= 'background-image:url(' . esc_url( $bg_image['url'] ) . ');';

						// Background repeat
						if ( isset( $css_properties['backgroundRepeat'] ) && '' !== $css_properties['backgroundRepeat'] ) {
							$output .= 'background-repeat:' . esc_attr( $css_properties['backgroundRepeat'] ) . ';';
						}

						// Background position
						if ( isset( $css_properties['backgroundPosition'] ) && '' !== $css_properties['backgroundPosition'] ) {
							$output .= 'background-position:' . esc_attr( $css_properties['backgroundPosition'] ) . ';';
						}

						// Background Attachment
						if ( isset( $css_properties['backgroundAttachment'] ) && '' !== $css_properties['backgroundAttachment'] ) {
							$output .= 'background-attachment:' . esc_attr( $css_properties['backgroundAttachment'] ) . ';';
						}
					}
				}

				// Selector end
				$output .= '}';
			}

			if ( '' !== $output ) {
				$output = '<style type="text/css" media="screen">' . esc_html( $output ) . '</style>';

				// Remove line breaks and tabs from the output.
				$output = str_replace( array( "\r", "\n", "\t" ), '', $output );

				echo $output;
			}
		}

		/**
		 * Enqueue Google Fonts for use in the frontend.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	void.
		 */
		public function frontend_google_fonts() {
			$selectors = get_theme_mod( 'sp_designer_css_data' );

			if ( ! $selectors || ! is_array( $selectors ) ) {
				return;
			}

			$font_families = array();

			// Go through all the selectors and figure out which fonts are Google Fonts.
			foreach ( $selectors as $id => $css_properties ) {
				if ( ! isset( $css_properties['selector'] ) || '' === $css_properties['selector'] ) {
					continue;
				}

				if ( isset( $css_properties['fontFamily'] ) && '' !== $css_properties['fontFamily'] ) {
					$google_font = array_filter( self::get_google_web_fonts(), function( $font ) use ( $css_properties ) {
						return ( $font['family'] === $css_properties['fontFamily'] );
					});

					if ( ! empty( $google_font ) ) {
						if ( ! array_key_exists( $css_properties['fontFamily'], $font_families ) ) {
							$font_families[ $css_properties['fontFamily'] ] = array();
						}

						if ( isset( $css_properties['fontVariant'] ) && ! in_array( $css_properties['fontVariant'], $font_families[ $css_properties['fontFamily'] ] ) ) {
							$font_families[ $css_properties['fontFamily'] ][] = $css_properties['fontVariant'];
						}
					}
				}
			}

			// Format font families and variants.
			if ( ! empty( $font_families ) ) {
				$output = '';
				foreach ( $font_families as $family => $variants ) {
					$output .= str_replace( ' ', '+', $family );

					if ( ! empty( $variants ) ) {
						$variants_output = ':';
						foreach ( $variants as $variant ) {
							$variants_output .= $variant . ',';
						}

						$output .= rtrim( $variants_output, ',' );
					}

					$output .= '|';
				}

				$output = rtrim( $output, '|' );

				// Enqueue fonts
				$query_args = array(
					'family' => $output
				);

				wp_enqueue_style( 'sp-google-fonts', add_query_arg( $query_args, '//fonts.googleapis.com/css' ), array(), null );
			}
		}

		/**
		 * A map of the selectors that are custumizable via the point & click interface.
		 *
		 * @access  public
		 * @since   1.0.0
		 * @return 	array $map A map of selectors.
		 */
		public function selectors_map() {
			$map = array();

			// Body
			$map['body'] = array(
				'selector' => 'body',
				'name'     => __( 'Body', 'storefront-powerpack' ),
			);

			// Headings
			for ( $i = 1; $i <= 6; $i++ ) {
				$map[ 'h' . $i ] = array(
					'selector' => '.site-main h' . $i,
					'name'     => __( 'Heading - H' . $i, 'storefront-powerpack' ),
				);
			}

			// Header
			$map['site-header'] = array(
				'selector' => '.site-header',
				'name'     => __( 'Header', 'storefront-powerpack' ),
			);

			$map['site-branding'] = array(
				'selector' => '.site-branding',
				'name'     => __( 'Site title / logo', 'storefront-powerpack' ),
			);

			$map['site-search'] = array(
				'selector' => '.site-search',
				'name'     => __( 'Header search', 'storefront-powerpack' ),
			);

			$map['navigation-wrapper'] = array(
				'selector' => '.storefront-primary-navigation',
				'name'     => __( 'Navigation wrapper', 'storefront-powerpack' ),
			);

			$map['main-navigation'] = array(
				'selector' => '.main-navigation',
				'name'     => __( 'Main navigation', 'storefront-powerpack' ),
			);

			$map['main-navigation-link'] = array(
				'selector' => '.main-navigation ul li a',
				'name'     => __( 'Main navigation link', 'storefront-powerpack' ),
			);

			$map['secondary-navigation'] = array(
				'selector' => '.secondary-navigation',
				'name'     => __( 'Secondary navigation', 'storefront-powerpack' ),
			);

			$map['site-header-cart'] = array(
				'selector' => '.site-header-cart',
				'name'     => __( 'Header cart', 'storefront-powerpack' ),
			);

			// Breadcrumb
			$map['woocommerce-breadcrumb'] = array(
				'selector' => '.woocommerce-breadcrumb',
				'name'     => __( 'Breadcrumb', 'storefront-powerpack' ),
			);

			$map['woocommerce-breadcrumb-link'] = array(
				'selector' => '.woocommerce-breadcrumb a',
				'name'     => __( 'Breadcrumb link', 'storefront-powerpack' ),
			);

			// Main
			$map['site-main'] = array(
				'selector' => '.site-main',
				'name'     => __( 'Main content', 'storefront-powerpack' ),
			);

			$map['site-content'] = array(
				'selector' => '.site-content',
				'name'     => __( 'Content / sidebar wrapper', 'storefront-powerpack' ),
			);

			// Sidebar
			$map['sidebar'] = array(
				'selector' => '.widget-area',
				'name'     => __( 'Sidebar', 'storefront-powerpack' ),
			);

			$map['sidebar-widgets'] = array(
				'selector' => '.widget-area .widget',
				'name'     => __( 'Sidebar Widgets', 'storefront-powerpack' ),
			);

			$map['widget-title'] = array(
				'selector' => '.widget .widget-title',
				'name'     => __( 'Widget title', 'storefront-powerpack' ),
			);

			// Footer
			$map['site-footer'] = array(
				'selector' => '.site-footer',
				'name'     => __( 'Footer', 'storefront-powerpack' ),
			);

			$map['footer-widgets'] = array(
				'selector' => '.footer-widgets .widget',
				'name'     => __( 'Footer Widgets', 'storefront-powerpack' ),
			);

			// Post/Pages
			$map['post-container'] = array(
				'selector' => '.site-main article.type-post, article.type-page',
				'name'     => __( 'Post / Page Container', 'storefront-powerpack' ),
			);

			$map['page-content'] = array(
				'selector' => '.site-main .type-page .entry-content',
				'name'     => __( 'Page Content', 'storefront-powerpack' ),
			);

			$map['post-content'] = array(
				'selector' => '.site-main .type-post .entry-content',
				'name'     => __( 'Post Content', 'storefront-powerpack' ),
			);

			$map['post-meta'] = array(
				'selector' => '.site-main .type-post .entry-meta',
				'name'     => __( 'Post Meta', 'storefront-powerpack' ),
			);

			// Comments / Reviews
			$map['comments'] = array(
				'selector' => '#comments .comment-list .comment-content .comment-text, #reviews .commentlist li .comment_container',
				'name'     => __( 'Comment / Review content', 'storefront-powerpack' ),
			);

			// Buttons
			$map['button'] = array(
				'selector' => '.added_to_cart, .button, button, input[type=button], input[type=reset], input[type=submit]',
				'name'     => __( 'Button', 'storefront-powerpack' ),
			);

			$map['button-alt'] = array(
				'selector' => '.added_to_cart.alt, .button.alt, button.alt, input[type=button].alt, input[type=reset].alt, input[type=submit].alt',
				'name'     => __( 'Alternate Button', 'storefront-powerpack' ),
			);

			// Product Loop
			$map['product-loop'] = array(
				'selector' => 'ul.products',
				'name'     => __( 'Loop Container', 'storefront-powerpack' ),
			);

			$map['loop-product'] = array(
				'selector' => 'ul.products li.product',
				'name'     => __( 'Loop Product', 'storefront-powerpack' ),
			);

			$map['loop-product-image'] = array(
				'selector' => 'ul.products li.product .wp-post-image',
				'name'     => __( 'Loop Product Image', 'storefront-powerpack' ),
			);

			$map['loop-product-title'] = array(
				'selector' => 'ul.products li.product h3',
				'name'     => __( 'Loop Product Title', 'storefront-powerpack' ),
			);

			$map['loop-sale-marker'] = array(
				'selector' => 'ul.products li.product .onsale',
				'name'     => __( 'Loop Sale Marker', 'storefront-powerpack' ),
			);

			$map['loop-price'] = array(
				'selector' => 'ul.products li.product .price',
				'name'     => __( 'Loop Price', 'storefront-powerpack' ),
			);

			// Product Page
			$map['single-product-container'] = array(
				'selector' => '.single-product .type-product',
				'name'     => __( 'Single Product Container', 'storefront-powerpack' ),
			);

			$map['single-image-container'] = array(
				'selector' => '.single-product .images',
				'name'     => __( 'Single Image Container', 'storefront-powerpack' ),
			);

			$map['single-featured-image'] = array(
				'selector' => '.single-product .images img.wp-post-image',
				'name'     => __( 'Single Featured Image', 'storefront-powerpack' ),
			);

			$map['single-thumbnails-container'] = array(
				'selector' => '.single-product .images .thumbnails',
				'name'     => __( 'Single Thumbnails Container', 'storefront-powerpack' ),
			);

			$map['single-thumbnails'] = array(
				'selector' => '.single-product .images .thumbnails img',
				'name'     => __( 'Single Thumbnails', 'storefront-powerpack' ),
			);

			$map['single-product-summary'] = array(
				'selector' => '.single-product .summary',
				'name'     => __( 'Single Product Summary', 'storefront-powerpack' ),
			);

			$map['woocommerce-tabs'] = array(
				'selector' => '.woocommerce-tabs',
				'name'     => __( 'WooCommerce Tabs', 'storefront-powerpack' ),
			);

			return array_values( apply_filters( 'sp_designer_selectors_map', $map ) );
		}
	}

endif;

return new SP_Designer();


text:
namespace chromecast {
namespace media {

MockFrameProvider::MockFrameProvider() : delay_flush_(false) {
}

MockFrameProvider::~MockFrameProvider() {
}

void MockFrameProvider::Configure(
    const std::vector<bool>& delayed_task_pattern,
    std::unique_ptr<FrameGeneratorForTest> frame_generator) {
  delayed_task_pattern_ = delayed_task_pattern;
  pattern_idx_ = 0;

  frame_generator_.reset(frame_generator.release());
}

void MockFrameProvider::SetDelayFlush(bool delay_flush) {
  delay_flush_ = delay_flush;
}

void MockFrameProvider::Read(const ReadCB& read_cb) {
  bool delayed = delayed_task_pattern_[pattern_idx_];
  pattern_idx_ = (pattern_idx_ + 1) % delayed_task_pattern_.size();

  if (delayed) {
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&MockFrameProvider::DoRead, base::Unretained(this), read_cb),
        base::TimeDelta::FromMilliseconds(1));
  } else {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::Bind(&MockFrameProvider::DoRead,
                              base::Unretained(this), read_cb));
  }
}

void MockFrameProvider::Flush(const base::Closure& flush_cb) {
  if (delay_flush_) {
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE, flush_cb, base::TimeDelta::FromMilliseconds(10));
  } else {
    flush_cb.Run();
  }
}

void MockFrameProvider::DoRead(const ReadCB& read_cb) {
  bool has_config = frame_generator_->HasDecoderConfig();

  scoped_refptr<DecoderBufferBase> buffer(frame_generator_->Generate());
  ASSERT_TRUE(buffer.get());

  ::media::AudioDecoderConfig audio_config;
  ::media::VideoDecoderConfig video_config;
  if (has_config) {
    gfx::Size coded_size(640, 480);
    gfx::Rect visible_rect(640, 480);
    gfx::Size natural_size(640, 480);
    video_config = ::media::VideoDecoderConfig(
        ::media::kCodecH264, ::media::VIDEO_CODEC_PROFILE_UNKNOWN,
        ::media::PIXEL_FORMAT_YV12, ::media::COLOR_SPACE_UNSPECIFIED,
        coded_size, visible_rect, natural_size, ::media::EmptyExtraData(),
        ::media::Unencrypted());

    audio_config = ::media::AudioDecoderConfig(
      ::media::kCodecAAC,
      ::media::kSampleFormatS16,
      ::media::CHANNEL_LAYOUT_STEREO,
      44100,
      ::media::EmptyExtraData(),
      ::media::Unencrypted());
  }

  read_cb.Run(buffer, audio_config, video_config);
}

}  // namespace media
}  // namespace chromecast


text:
ZfcFacebook
===========

What is it?
-----------
ZfcFacebook is an integration library to enable easy creation of Facebook applications using Zend Framework to. Once completed, we have plans to include everything you'll need to interact with the Facebook Graph and Open Graph APIs, along with view helpers for common javascript tasks.

Where is it?
------------
Currently we only have support for authentication of iframe applications, with Facebook for Websites integration partially completed (formerly "Facebook Connect").

Using it...
-----------
 1. Copy the ZfcFacebook to your module directory
 2. Register the module in your application's application.config.php
 3. Edit the module.config.php to have your Facebook app's App Id and Secret
 4. Tell your iframe app to point to www.yourdomain.com/facebook?a=b
 (You need the a=b because facebook is silly and doesn't allow you to end an url without a ? or /)
 5. You'll see a `facebook` alias added to your service manager, retreiving this will allow you to access the Facebook class from within your controllers and models. Authentication will not occur until `getFacebookId` is called, meaning you can easily set up page that are not covered by the allow process.
 6. Currently there is only one view helper, `ZfcFacebookSignedRequest` (catchy), this allows you to access the signed request parameter from within your views; useful for passing it back to the server in the case of AJAX style applications.

On it's way...
-------
After some delay, I'm actually using this class myself in a project now, so expect some progress. Priority will be given to the view helpers for setting up the Facebook JS SDK, and performing common functions such as posting to stream and inviting friends. Eventually I would hope to have fully proxied access to the Graph API, and a FQL builder class.

Contributing
------------
All help greatly received! Ping me on IRC, Spabby in #zftalk.2 on Freenode, or drop me a mail.


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="priv2html.xsl"?><!-- The whole file was generated using :

 $ wget www.agfa.com/germany/de/binaries/001126_IMPAX_6.2_Solution_tcm181-29471.pdf
 $ pdftotext -layout -nopgbrk -f 82 -l 83 001126_IMPAX_6.2_Solution_tcm181-29471.pdf 001126_IMPAX_6.2_Solution_tcm181-29471.txt
 <some minor manual cleaning>
 $ python txt2xml.py

-->
<!--
  Program: GDCM (Grassroots DICOM). A DICOM library
  Module:  $URL$

  Copyright (c) 2006-2008 Mathieu Malaterre
  All rights reserved.
  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.
-->
<dicts edition="2007" url="http://www.agfa.com/germany/de/binaries/001126_IMPAX_6.2_Solution_tcm181-29471.pdf">
  <dict ref="Table 6.2-1" name="Data Dictionary of Private Attributes">
    <entry group="0029" element="xx00" vr="OB" vm="1" owner="Mitra Object Document 1.0" name="IMPAX object document"/>
    <entry group="0029" element="xx10" vr="OB" vm="1" owner="Mitra Object Document 1.0" name="IMPAX markup XML stored"/>
    <entry group="0029" element="xx00" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup1"/>
    <entry group="0029" element="xx01" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup2"/>
    <entry group="0029" element="xx02" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup3"/>
    <entry group="0029" element="xx03" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup4"/>
    <entry group="0029" element="xx04" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup5"/>
    <entry group="0029" element="xx05" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup6"/>
    <entry group="0029" element="xx06" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup7"/>
    <entry group="0029" element="xx07" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup8"/>
    <entry group="0029" element="xx08" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup9"/>
    <entry group="0029" element="xx09" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup10"/>
    <entry group="0029" element="xx10" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup11"/>
    <entry group="0029" element="xx11" vr="OB" vm="1-n" owner="Mitra Markup 1.0" name="Markup12"/>
    <entry group="0029" element="xx12" vr="OB" vm="1" owner="Mitra Markup 1.0" name="Markup13"/>
    <entry group="0029" element="xx13" vr="OB" vm="1" owner="Mitra Markup 1.0" name="Markup14"/>
    <entry group="0029" element="xx14" vr="OB" vm="1" owner="Mitra Markup 1.0" name="Markup15"/>
    <entry group="0029" element="xx00" vr="CS" vm="1" owner="Mitra Presentation 1.0" name="Mitra Rotation"/>
    <entry group="0029" element="xx01" vr="LO" vm="1" owner="Mitra Presentation 1.0" name="Mitra Window Width"/>
    <entry group="0029" element="xx02" vr="LO" vm="1" owner="Mitra Presentation 1.0" name="Mitra Window Centre"/>
    <entry group="0029" element="xx03" vr="IS" vm="1" owner="Mitra Presentation 1.0" name="Mitra Invert"/>
    <entry group="0029" element="xx04" vr="IS" vm="1" owner="Mitra Presentation 1.0" name="Mitra Has Tabstop"/>
    <entry group="0029" element="xx05" vr="CS" vm="1" owner="Mitra Presentation 1.0" name="Smooth Rotation"/>
  </dict>
</dicts>


text:
package net.mymam.security;

import com.google.common.collect.ImmutableList;
import net.mymam.ejb.MediaFileEJB;
import net.mymam.ejb.PermissionEJB;
import net.mymam.entity.MediaFile;

import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * In the final implementation, we want to have it configurable
 * which actions are allowed anonymously, and which actions require log-in.
 *
 * <p/>
 * This filter redirects unauthenticated users to the login page
 * when {@link #needsLogin(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}
 * is true.
 *
 * @author fstab
 */
// TODO: Use @WebFilter annotation instead of web.xml config
public class SecurityFilter implements Filter {

    @EJB
    private MediaFileEJB mediaFileEJB;

    @EJB
    private PermissionEJB permissionEJB;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    private final List<String> uploadPages = ImmutableList.of("upload.xhtml");
    private final List<String> viewPages = ImmutableList.of("view.xhtml");
    private final List<String> dashboardPages = ImmutableList.of("dashboard.xhtml");

    private MediaFile loadMediaFileFromRequestParameter(HttpServletRequest request, HttpServletResponse response) throws MediaFileRequestFailedException {
        String[] ids = request.getParameterValues("id");
        if (ids.length != 1) {
            String msg = "User tried to access " + request.getRequestURL() + " ";
            msg += ids.length == 0 ? "without id parameter." : "with multiple id parameters.";
            throw new MediaFileRequestFailedException(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        MediaFile result = null;
        try {
            Long id = Long.parseLong(ids[0]);
            result = mediaFileEJB.findById(id);
        } catch (NumberFormatException e) {
            String msg = "User tried to access " + request.getRequestURL() + " with invalid id=\"" + ids[0] + "\"";
            throw new MediaFileRequestFailedException(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        if (result == null) {
            String msg = "User tried to access " + request.getRequestURL() + " with non-existing id=\"" + ids[0] + "\"";
            throw new MediaFileRequestFailedException(HttpServletResponse.SC_NOT_FOUND, msg);
        }
        return result;
    }

    private boolean needsLogin(HttpServletRequest request, HttpServletResponse response) throws MediaFileRequestFailedException {
        if (request.getUserPrincipal() != null) {
            // already logged in
            return false;
        }
        for (String page : uploadPages) {
            if (request.getRequestURL().toString().endsWith(page)) {
                return ! permissionEJB.isAnonymousUploadAllowed();
            }
        }
        for (String page : viewPages) {
            if (request.getRequestURL().toString().endsWith(page)) {
                MediaFile file = loadMediaFileFromRequestParameter(request, response);
                return ! permissionEJB.isAnonymousViewAllowed(file);
            }
        }
        for ( String page : dashboardPages ) {
            if ( request.getRequestURL().toString().endsWith(page) ) {
                return true; // dashboard always needs login.
            }
        }
        return false; // Other content can be requested without log-in.
    }

    private boolean isPermissionGranted(HttpServletRequest request, HttpServletResponse response) {
        // TODO: Use the permissionEJB to check if the user has the access rights to the page.
        return true;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if ((servletRequest instanceof HttpServletRequest) && (servletResponse instanceof HttpServletResponse)) {
            try {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                if (needsLogin(httpServletRequest, httpServletResponse)) {
                    // Redirect to login page.
                    // There are two ways to perform redirection:
                    //   * httpServletResponse.sendRedirect() sends an HTTP redirect to the browser,
                    //     and the browser loads the new page. As a result, the URL "/.../login.xhtml"
                    //     is shown in the address bar.
                    //   * requestDispatcher.forward() performs a server-side redirect, i.e. the
                    //     contents of "login.xhtml" is shown, but the URL is the original target.
                    // We use server-side redirect here.
                    httpServletRequest.getSession().setAttribute("origURL", httpServletRequest.getRequestURI());
                    RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher("/login.xhtml");
                    requestDispatcher.forward(servletRequest, servletResponse);
                    return; // skip filter chain.
//                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.xhtml");
                }
                if ( ! isPermissionGranted(httpServletRequest, httpServletResponse) ) {
                    httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return; // skip filter chain.
                }
            } catch (MediaFileRequestFailedException e) {
                System.out.println(e.getMessage()); // TODO: Use logging.
                ((HttpServletResponse) servletResponse).sendError(e.getError());
                return; // skip filter chain.
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }
}


text:
[![Build Status](https://travis-ci.org/exercism/python.svg?branch=master)](https://travis-ci.org/exercism/python) [![Requirements Status](https://pyup.io/repos/github/exercism/python/shield.svg)](https://pyup.io/repos/github/exercism/python/)
[![Join the chat at https://gitter.im/exercism/python](https://badges.gitter.im/exercism/python.svg)](https://gitter.im/exercism/python?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Exercism exercises in Python

## Contributing Guide

Please see the [contributing guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md)

## Working on the Exercises

We welcome both improvements to the existing exercises and new exercises.
A list of missing exercise can be found here: http://exercism.io/languages/python/todo

### Conventions

- We use minimalistic stub files for all exercises ([#272](https://github.com/exercism/python/issues/272)).
- We use `unittest` (Python Standard Library) and no 3rd-party-framework.
- We use the parameter order `self.assertEqual(actual, expected)` ([#440](https://github.com/exercism/python/issues/440)).
- We use context managers (`with self.assertRaises(\<exception type\>):`) for testing for exceptions ([#477](https://github.com/exercism/python/issues/477)).
- We use `assertIs(actual, True)` and `assertIs(actual, False)` rather than `assertTrue(actual)` or `assertFalse(actual)` ([#419](https://github.com/exercism/python/pull/419)).
- We use a comment string in the test file to reference the version of the exercise's `canonical-data.json` that tests were adapted from (wording can be found in: [#784](https://github.com/exercism/python/issues/784)).

### Testing

All exercises must be compatible with Python versions 2.7 and 3.3 upwards.

To test a single exercise (e.g., with Python 2.7):
```
python2.7 test/check-exercises.py [exercise-name]
```

To test all exercises (e.g., with Python 3):
```
python3 test/check-exercises.py
```

### Code Style

The Python code in this repo is meant to follow the [PEP8 style guide](https://www.python.org/dev/peps/pep-0008/) (a stylized version http://pep8.org).

This repo uses [flake8](http://flake8.readthedocs.org/en/latest/) with default settings to enforce the coding standard.

### CI build

This repo uses `travis-ci` in the following configuration: [travis.yml](https://github.com/exercism/python/blob/master/.travis.yml)

It will automatically check the code style, the problem configuration, and run the unittests with all supported Python versions.

## Pull Requests

We :heart: pull requests!
We even :sparkling_heart: them if they contain well written commit messages!

Please write the first line of your commit message in the following style:

```exercise-name: Change some things```

Please try to follow the [The seven rules of a great Git commit message](https://chris.beams.io/posts/git-commit/#seven-rules) like to capitalize the subject line and use the imperative mood. If there are more details to add, put those into the body of the commit message.

If you're interested, Tim Pope even has an [entire blog post](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) on good commit messages.

If you're new to Git, take a look at [this short guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md#git-basics).

## Python icon
The Python logo is an unregistered trademark. We are using a derived logo with the permission of the Python Software Foundation.

## License
This repository uses the [MIT License](/LICENSE).


text:
var y_axis = new Rickshaw.Graph.Axis.Y( {
        graph: graph,
        orientation: 'left',
        height: {{ height }},
        tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
        element: d3.select("#{{ y_axis_id }}").node()
} );


text:
using System;
using System.Collections;
using System.Collections.Generic;
using Google.GData.Client;

#endregion

//////////////////////////////////////////////////////////////////////
// contains typed collections based on the 1.1 .NET framework
// using typed collections has the benefit of additional code reliability
// and using them in the collection editor
//
//////////////////////////////////////////////////////////////////////

namespace Google.GData.Extensions
{

    ///
    /// base class to take an object pointer with extension information
    /// and expose a localname/namespace subset as a collection
    /// that still works on the original
    ///
    public class ExtensionCollection<T> : IList<T> where T : class, IExtensionElementFactory, new()
    {

        private static readonly Dictionary<Type, IExtensionElementFactory> _cache =
            new Dictionary<Type, IExtensionElementFactory>();

        private readonly List<T> _items = new List<T>();

        /// holds the owning feed
        private readonly IExtensionContainer container;

        ///
        /// protected default constructor, not usable by outside
        ///
        public ExtensionCollection()
        {
        }

        ///
        /// takes the base object, and the localname/ns combo to look for
        /// will copy objects to an internal array for caching. Note that when the external
        /// ExtensionList is modified, this will have no effect on this copy
        ///
        /// <param name="containerElement">the base element holding the extension list</param>
        public ExtensionCollection(IExtensionContainer containerElement)
            : this(containerElement, CtorXmlName(), CtorXmlNS())
        {
        }

        ///
        /// takes the base object, and the localname/ns combo to look for
        /// will copy objects to an internal array for caching. Note that when the external
        /// ExtensionList is modified, this will have no effect on this copy
        ///
        /// <param name="containerElement">the base element holding the extension list</param>
        /// <param name="localName">the local name of the extension</param>
        /// <param name="ns">the namespace</param>
        public ExtensionCollection(IExtensionContainer containerElement, string localName, string ns)
        {
            container = containerElement;
            if (container != null)
            {
                ExtensionList arr = container.FindExtensions(localName, ns);
                foreach (T o in arr)
                {
                    _items.Add(o);
                }
            }
        }

        /// standard typed accessor method
        public T this[int index]
        {
            get { return _items[index]; }
            set { setItem(index, value); }
        }

        ///
        /// inserts an element into the collection by index
        ///
        /// <param name="index"></param>
        /// <param name="value"></param>
        public void Insert(int index, T value)
        {
            if (container != null && container.ExtensionElements.Contains(value))
            {
                container.ExtensionElements.Remove(value);
            }
            container.ExtensionElements.Add(value);
            _items.Insert(index, value);
        }

        /// standard typed indexOf method
        public int IndexOf(T value)
        {
            return (_items.IndexOf(value));
        }

        /// standard typed Contains method
        public bool Contains(T value)
        {
            // If value is not of type AtomEntry, this will return false.
            return (_items.Contains(value));
        }

        #region IList<T> Members

        public void RemoveAt(int index)
        {
            T item = _items[index];
            //_items.RemoveAt(index);
            Remove(item);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        #endregion

        ///
        /// Get the XmlName for the Type
        ///
        /// <returns></returns>
        private static string CtorXmlName()
        {
            IExtensionElementFactory val;
            Type t = typeof (T);
            lock (_cache)
            {
                if (!_cache.TryGetValue(t, out val))
                {
                    val = new T();
                    _cache[t] = val;
                }
            }
            return val.XmlName;
        }

        ///
        /// Get the Xml Namespace for the Type
        ///
        /// <returns></returns>
        private static string CtorXmlNS()
        {
            IExtensionElementFactory val;
            Type t = typeof (T);
            lock (_cache)
            {
                if (!_cache.TryGetValue(t, out val))
                {
                    val = new T();
                    _cache[t] = val;
                }
            }
            return val.XmlNameSpace;
        }

        ///
        /// useful for subclasses that want to overload the set method
        ///
        /// <param name="index">the index in the array</param>
        /// <param name="item">the item to set </param>
        protected void setItem(int index, T item)
        {
            if (_items[index] != null)
            {
                if (container != null)
                {
                    container.ExtensionElements.Remove(_items[index]);
                }
            }
            _items[index] = item;
            if (item != null && container != null)
            {
                container.ExtensionElements.Add(item);
            }
        }

        ///
        /// default untyped add implementation. Adds the object as well to the parent
        /// object ExtensionList
        ///
        /// <param name="value"></param>
        /// <returns></returns>
        public int Add(T value)
        {
            if (container != null)
            {
                container.ExtensionElements.Add(value);
            }
            _items.Add(value);
            return _items.Count - 1;
        }

        ///
        /// removes an element from the collection
        ///
        /// <param name="value"></param>
        public bool Remove(T value)
        {
            bool success = _items.Remove(value);
            if (success && container != null)
            {
                success &= container.ExtensionElements.Remove(value);
            }
            return success;
        }

        /// standard override OnClear, to remove the objects from the extension list
        protected void OnClear()
        {
            if (container != null)
            {
                for (int i = 0; i < Count; i++)
                {
                    container.ExtensionElements.Remove(_items[i]);
                }
            }
        }

        #region ICollection<T> Members

        void ICollection<T>.Add(T item)
        {
            Add(item);
        }

        public void Clear()
        {
            OnClear();
            _items.Clear();
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _items.ToArray().CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _items.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        bool ICollection<T>.Remove(T item)
        {
            return Remove(item);
        }

        #endregion
    }
}


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

public class Test
{
    public static int Main()
    {
        try
        {
            BodyDictionary obj = new BodyDictionary();

            Console.WriteLine("PASS");
            return 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("FAIL: Unexpected exception : " + e);
            return 101;
        }
    }
}

public class BodyDictionary : Dictionary<int, int>
{
    public BodyDictionary()
        : base()
    { }
}


text:
using namespace llvm;

// Upgrade the declarations of the SSE4.1 functions whose arguments have
// changed their type from v4f32 to v2i64.
static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
                                 Function *&NewFn) {
  // Check whether this is an old version of the function, which received
  // v4f32 arguments.
  Type *Arg0Type = F->getFunctionType()->getParamType(0);
  if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
    return false;

  // Yes, it's old, replace it with new version.
  F->setName(F->getName() + ".old");
  NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
  return true;
}

static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
  assert(F && "Illegal to upgrade a non-existent Function.");

  // Quickly eliminate it, if it's not a candidate.
  StringRef Name = F->getName();
  if (Name.size() <= 8 || !Name.startswith("llvm."))
    return false;
  Name = Name.substr(5); // Strip off "llvm."

  switch (Name[0]) {
  default: break;
  case 'a': {
    if (Name.startswith("arm.neon.vclz")) {
      Type* args[2] = {
        F->arg_begin()->getType(),
        Type::getInt1Ty(F->getContext())
      };
      // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
      // the end of the name. Change name from llvm.arm.neon.vclz.* to
      //  llvm.ctlz.*
      FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
      NewFn = Function::Create(fType, F->getLinkage(),
                               "llvm.ctlz." + Name.substr(14), F->getParent());
      return true;
    }
    if (Name.startswith("arm.neon.vcnt")) {
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
                                        F->arg_begin()->getType());
      return true;
    }
    break;
  }
  case 'c': {
    if (Name.startswith("ctlz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
                                        F->arg_begin()->getType());
      return true;
    }
    if (Name.startswith("cttz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
                                        F->arg_begin()->getType());
      return true;
    }
    break;
  }
  case 'x': {
    if (Name.startswith("x86.sse2.pcmpeq.") ||
        Name.startswith("x86.sse2.pcmpgt.") ||
        Name.startswith("x86.avx2.pcmpeq.") ||
        Name.startswith("x86.avx2.pcmpgt.") ||
        Name.startswith("x86.avx.vpermil.") ||
        Name == "x86.avx.movnt.dq.256" ||
        Name == "x86.avx.movnt.pd.256" ||
        Name == "x86.avx.movnt.ps.256" ||
        (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) {
      NewFn = 0;
      return true;
    }
    // SSE4.1 ptest functions may have an old signature.
    if (Name.startswith("x86.sse41.ptest")) {
      if (Name == "x86.sse41.ptestc")
        return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
      if (Name == "x86.sse41.ptestz")
        return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
      if (Name == "x86.sse41.ptestnzc")
        return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
    }
    // frcz.ss/sd may need to have an argument dropped
    if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(),
                                        Intrinsic::x86_xop_vfrcz_ss);
      return true;
    }
    if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(),
                                        Intrinsic::x86_xop_vfrcz_sd);
      return true;
    }
    // Fix the FMA4 intrinsics to remove the 4
    if (Name.startswith("x86.fma4.")) {
      F->setName("llvm.x86.fma" + Name.substr(8));
      NewFn = F;
      return true;
    }
    break;
  }
  }

  //  This may not belong here. This function is effectively being overloaded
  //  to both detect an intrinsic which needs upgrading, and to provide the
  //  upgraded form of the intrinsic. We should perhaps have two separate
  //  functions for this.
  return false;
}

bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
  NewFn = 0;
  bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);

  // Upgrade intrinsic attributes.  This does not change the function.
  if (NewFn)
    F = NewFn;
  if (unsigned id = F->getIntrinsicID())
    F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
  return Upgraded;
}

bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
  // Nothing to do yet.
  return false;
}

// UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
// upgraded intrinsic. All argument and return casting must be provided in
// order to seamlessly integrate with existing context.
void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
  Function *F = CI->getCalledFunction();
  LLVMContext &C = CI->getContext();
  IRBuilder<> Builder(C);
  Builder.SetInsertPoint(CI->getParent(), CI);

  assert(F && "Intrinsic call is not direct?");

  if (!NewFn) {
    // Get the Function's name.
    StringRef Name = F->getName();

    Value *Rep;
    // Upgrade packed integer vector compares intrinsics to compare instructions
    if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
        Name.startswith("llvm.x86.avx2.pcmpeq.")) {
      Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
                                 "pcmpeq");
      // need to sign extend since icmp returns vector of i1
      Rep = Builder.CreateSExt(Rep, CI->getType(), "");
    } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
               Name.startswith("llvm.x86.avx2.pcmpgt.")) {
      Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
                                  "pcmpgt");
      // need to sign extend since icmp returns vector of i1
      Rep = Builder.CreateSExt(Rep, CI->getType(), "");
    } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
               Name == "llvm.x86.avx.movnt.ps.256" ||
               Name == "llvm.x86.avx.movnt.pd.256") {
      IRBuilder<> Builder(C);
      Builder.SetInsertPoint(CI->getParent(), CI);

      Module *M = F->getParent();
      SmallVector<Value *, 1> Elts;
      Elts.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
      MDNode *Node = MDNode::get(C, Elts);

      Value *Arg0 = CI->getArgOperand(0);
      Value *Arg1 = CI->getArgOperand(1);

      // Convert the type of the pointer to a pointer to the stored type.
      Value *BC = Builder.CreateBitCast(Arg0,
                                        PointerType::getUnqual(Arg1->getType()),
                                        "cast");
      StoreInst *SI = Builder.CreateStore(Arg1, BC);
      SI->setMetadata(M->getMDKindID("nontemporal"), Node);
      SI->setAlignment(16);

      // Remove intrinsic.
      CI->eraseFromParent();
      return;
    } else if (Name.startswith("llvm.x86.xop.vpcom")) {
      Intrinsic::ID intID;
      if (Name.endswith("ub"))
        intID = Intrinsic::x86_xop_vpcomub;
      else if (Name.endswith("uw"))
        intID = Intrinsic::x86_xop_vpcomuw;
      else if (Name.endswith("ud"))
        intID = Intrinsic::x86_xop_vpcomud;
      else if (Name.endswith("uq"))
        intID = Intrinsic::x86_xop_vpcomuq;
      else if (Name.endswith("b"))
        intID = Intrinsic::x86_xop_vpcomb;
      else if (Name.endswith("w"))
        intID = Intrinsic::x86_xop_vpcomw;
      else if (Name.endswith("d"))
        intID = Intrinsic::x86_xop_vpcomd;
      else if (Name.endswith("q"))
        intID = Intrinsic::x86_xop_vpcomq;
      else
        llvm_unreachable("Unknown suffix");

      Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
      unsigned Imm;
      if (Name.startswith("lt"))
        Imm = 0;
      else if (Name.startswith("le"))
        Imm = 1;
      else if (Name.startswith("gt"))
        Imm = 2;
      else if (Name.startswith("ge"))
        Imm = 3;
      else if (Name.startswith("eq"))
        Imm = 4;
      else if (Name.startswith("ne"))
        Imm = 5;
      else if (Name.startswith("true"))
        Imm = 6;
      else if (Name.startswith("false"))
        Imm = 7;
      else
        llvm_unreachable("Unknown condition");

      Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
      Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
                                CI->getArgOperand(1), Builder.getInt8(Imm));
    } else {
      bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
      if (Name == "llvm.x86.avx.vpermil.pd.256")
        PD256 = true;
      else if (Name == "llvm.x86.avx.vpermil.pd")
        PD128 = true;
      else if (Name == "llvm.x86.avx.vpermil.ps.256")
        PS256 = true;
      else if (Name == "llvm.x86.avx.vpermil.ps")
        PS128 = true;

      if (PD256 || PD128 || PS256 || PS128) {
        Value *Op0 = CI->getArgOperand(0);
        unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
        SmallVector<Constant*, 8> Idxs;

        if (PD128)
          for (unsigned i = 0; i != 2; ++i)
            Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
        else if (PD256)
          for (unsigned l = 0; l != 4; l+=2)
            for (unsigned i = 0; i != 2; ++i)
              Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
        else if (PS128)
          for (unsigned i = 0; i != 4; ++i)
            Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
        else if (PS256)
          for (unsigned l = 0; l != 8; l+=4)
            for (unsigned i = 0; i != 4; ++i)
              Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
        else
          llvm_unreachable("Unexpected function");

        Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
      } else {
        llvm_unreachable("Unknown function for CallInst upgrade.");
      }
    }

    CI->replaceAllUsesWith(Rep);
    CI->eraseFromParent();
    return;
  }

  std::string Name = CI->getName().str();
  CI->setName(Name + ".old");

  switch (NewFn->getIntrinsicID()) {
  default:
    llvm_unreachable("Unknown function for CallInst upgrade.");

  case Intrinsic::ctlz:
  case Intrinsic::cttz:
    assert(CI->getNumArgOperands() == 1 &&
           "Mismatch between function args and call args");
    CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
                                               Builder.getFalse(), Name));
    CI->eraseFromParent();
    return;

  case Intrinsic::arm_neon_vclz: {
    // Change name from llvm.arm.neon.vclz.* to llvm.ctlz.*
    CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
                                               Builder.getFalse(),
                                               "llvm.ctlz." + Name.substr(14)));
    CI->eraseFromParent();
    return;
  }
  case Intrinsic::ctpop: {
    CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
    CI->eraseFromParent();
    return;
  }

  case Intrinsic::x86_xop_vfrcz_ss:
  case Intrinsic::x86_xop_vfrcz_sd:
    CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
                                              Name));
    CI->eraseFromParent();
    return;

  case Intrinsic::x86_sse41_ptestc:
  case Intrinsic::x86_sse41_ptestz:
  case Intrinsic::x86_sse41_ptestnzc: {
    // The arguments for these intrinsics used to be v4f32, and changed
    // to v2i64. This is purely a nop, since those are bitwise intrinsics.
    // So, the only thing required is a bitcast for both arguments.
    // First, check the arguments have the old type.
    Value *Arg0 = CI->getArgOperand(0);
    if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
      return;

    // Old intrinsic, add bitcasts
    Value *Arg1 = CI->getArgOperand(1);

    Value *BC0 =
      Builder.CreateBitCast(Arg0,
                            VectorType::get(Type::getInt64Ty(C), 2),
                            "cast");
    Value *BC1 =
      Builder.CreateBitCast(Arg1,
                            VectorType::get(Type::getInt64Ty(C), 2),
                            "cast");

    CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
    CI->replaceAllUsesWith(NewCall);
    CI->eraseFromParent();
    return;
  }
  }
}

// This tests each Function to determine if it needs upgrading. When we find
// one we are interested in, we then upgrade all calls to reflect the new
// function.
void llvm::UpgradeCallsToIntrinsic(Function* F) {
  assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");

  // Upgrade the function and check if it is a totaly new function.
  Function *NewFn;
  if (UpgradeIntrinsicFunction(F, NewFn)) {
    if (NewFn != F) {
      // Replace all uses to the old function with the new one if necessary.
      for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
           UI != UE; ) {
        if (CallInst *CI = dyn_cast<CallInst>(*UI++))
          UpgradeIntrinsicCall(CI, NewFn);
      }
      // Remove old function, no longer used, from the module.
      F->eraseFromParent();
    }
  }
}