text:
extern "C" {
#endif

#define ISBLOCK(self) IoObject_hasCloneFunc_(self, (IoTagCloneFunc *)IoBlock_rawClone)

typedef IoObject IoBlock;

typedef struct
{
	IoMessage *message;
	List *argNames;
	IoObject *scope; // if 0x0, then use target as the locals proto
	int passStops;
	clock_t profilerTime;
} IoBlockData;

IoBlock *IoBlock_proto(void *state);
IoBlock *IoBlock_rawClone(IoBlock *self);
IoBlock *IoBlock_new(IoState *state);
void IoBlock_mark(IoBlock *self);
void IoBlock_free(IoBlock *self);
void IoBlock_message_(IoBlock *self, IoMessage *m);

//void IoBlock_writeToStream_(IoBlock *self, BStream *stream);
//void IoBlock_readFromStream_(IoBlock *self, BStream *stream);

// calling

IOVM_API IoObject *IoBlock_activate(IoBlock *self, IoObject *target, IoObject *locals, IoMessage *m, IoObject *slotContext);
IO_METHOD(IoBlock, print);

UArray *IoBlock_justCode(IoBlock *self);
IO_METHOD(IoBlock, code);
IO_METHOD(IoBlock, code_);

IO_METHOD(IoBlock, message);
IO_METHOD(IoBlock, setMessage);

IO_METHOD(IoBlock, argumentNames);
IO_METHOD(IoBlock, argumentNames_);

IO_METHOD(IoBlock, setScope_);
IO_METHOD(IoBlock, scope);

IO_METHOD(IoBlock, setPassStops_);
IO_METHOD(IoBlock, passStops);

IO_METHOD(IoBlock, setProfilerOn);
IO_METHOD(IoBlock, profilerTime);
void IoBlock_rawResetProfilerTime(IoBlock *self);
clock_t IoBlock_rawProfilerTime(IoBlock *self);

// lobby methods

IoObject *IoBlock_method(IoObject *target, IoObject *locals, IoMessage *m);
IoObject *IoObject_block(IoObject *target, IoObject *locals, IoMessage *m);

IO_METHOD(IoBlock, performOn);
IO_METHOD(IoBlock, call);

#ifdef __cplusplus
}
#endif
#endif


text:
namespace Airwave {

class Storage {
public:
	class Prefix {
	public:
		Prefix();
		bool isNull() const;

		std::string name() const;
		bool setName(const std::string& name);

		std::string path() const;
		bool setPath(const std::string& path);

		Prefix next() const;
		bool operator!() const;

	private:
		friend class Storage;
		using PrefixMap = std::map<std::string, std::string>;

		Storage* storage_;
		PrefixMap::iterator it_;

		Prefix(Storage* storage, PrefixMap::iterator it);
	};

	class Loader {
	public:
		Loader();
		bool isNull() const;

		std::string name() const;
		bool setName(const std::string& name);

		std::string path() const;
		bool setPath(const std::string& path);

		Loader next() const;
		bool operator!() const;

	private:
		friend class Storage;
		using LoaderMap = std::map<std::string, std::string>;

		Storage* storage_;
		LoaderMap::iterator it_;

		Loader(Storage* storage, LoaderMap::iterator it);
	};

	struct LinkInfo {
		std::string target;
		std::string prefix;
		std::string loader;
		LogLevel level;
	};

	class Link {
	public:
		Link();
		bool isNull() const;

		std::string path() const;
		bool setPath(const std::string& path);

		std::string target() const;
		bool setTarget(const std::string& path);

		std::string prefix() const;
		bool setPrefix(const std::string& prefix);

		std::string loader() const;
		bool setLoader(const std::string& loader);

		LogLevel logLevel() const;
		void setLogLevel(LogLevel level);

		Link next() const;
		bool operator!() const;

	private:
		friend class Storage;
		using LinkMap = std::map<std::string, LinkInfo>;

		Storage* storage_;
		LinkMap::iterator it_;

		Link(Storage* storage, LinkMap::iterator it);
	};

	Storage();
	~Storage();

	bool reload();
	bool save();

	std::string logSocketPath() const;
	void setLogSocketPath(const std::string& path);

	std::string binariesPath() const;
	void setBinariesPath(const std::string& path);

	LogLevel defaultLogLevel() const;
	void setDefaultLogLevel(LogLevel level);

	Prefix prefix(const std::string& name = std::string());
	Prefix createPrefix(const std::string& name, const std::string& path);
	bool removePrefix(Prefix prefix);

	Loader loader(const std::string& name = std::string());
	Loader createLoader(const std::string& name, const std::string& path);
	bool removeLoader(Loader loader);

	Link link(const std::string& path = std::string());

	Link createLink(const std::string& path, const std::string& target,
			const std::string& prefix, const std::string& loader);

	bool removeLink(Link link);

private:
	friend class Prefix;
	friend class Loader;
	friend class Link;

	bool isChanged_;

	std::string storageFilePath_;
	std::string logSocketPath_;
	std::string binariesPath_;
	LogLevel defaultLogLevel_;

	std::map<std::string, std::string> prefixByName_;
	std::map<std::string, std::string> loaderByName_;
	std::map<std::string, LinkInfo> linkByPath_;
};

} // namespace Airwave

#endif // COMMON_STORAGE_H

redpajama_set_name: RedPajamaGithub


text:
CREATE SCHEMA IF NOT EXISTS `weprovid_iandk`
	DEFAULT CHARACTER SET utf8;
USE `weprovid_iandk`;

CREATE TABLE IF NOT EXISTS `iandk_rsvp` (
	`email`     VARCHAR(255) NOT NULL,
	`name`      VARCHAR(255) NOT NULL,
	`attendees` INT(2)       NOT NULL DEFAULT 1,
	`created`   DATETIME     NOT NULL,
	`updated`   DATETIME     NOT NULL,
	PRIMARY KEY (`email`)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `iandk_wishes` (
    `id`        INT(11)      NOT NULL AUTO_INCREMENT,
	`platform`  VARCHAR(255) NOT NULL,
	`name`      VARCHAR(255) NOT NULL,
	`message`   VARCHAR(255) NOT NULL,
	`created`   DATETIME     NOT NULL,
	`updated`   DATETIME     NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


text:
package org.apache.shindig.expressions.jasper;

import org.apache.shindig.expressions.ExpressionProvider;

import com.google.inject.AbstractModule;
import com.google.inject.Scopes;

/**
 * Creates a module to supply a Jasper Provider
 *
 * @since 2.0.0
 */
public class JasperModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(ExpressionProvider.class).to(JasperProvider.class)
        .in(Scopes.SINGLETON);
  }
}


text:
package com.sample.andremion.musicplayer.listener;

import android.view.View;

public interface ProgressListener {
	public void onProgressListener(boolean isFinish);
}


text:
package org.fluentjava.iwant.entry2;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.security.Permission;

import org.fluentjava.iwant.entry.Iwant;
import org.fluentjava.iwant.entry2.Iwant2.ClassesFromUnmodifiableIwantEssential;
import org.fluentjava.iwant.entrymocks.IwantNetworkMock;
import org.fluentjava.iwant.iwantwsrootfinder.IwantWsRootFinder;
import org.fluentjava.iwant.testarea.TestArea;

import junit.framework.TestCase;

public class Iwant2Test extends TestCase {

	private static final String LINE_SEPARATOR_KEY = "line.separator";

	private TestArea testArea;

	private SecurityManager origSecman;

	private InputStream originalIn;

	private PrintStream originalOut;

	private PrintStream originalErr;

	private ByteArrayOutputStream out;

	private ByteArrayOutputStream err;

	private String originalLineSeparator;

	private IwantNetworkMock network;

	private Iwant2 iwant2;

	private File antJar;

	private File antLauncherJar;

	/**
	 * TODO a reusable main-method testing tools project
	 */
	@Override
	public void setUp() {
		origSecman = System.getSecurityManager();
		System.setSecurityManager(new ExitCatcher());
		originalIn = System.in;
		originalOut = System.out;
		originalErr = System.err;
		originalLineSeparator = System.getProperty(LINE_SEPARATOR_KEY);
		System.setProperty(LINE_SEPARATOR_KEY, "\n");
		startOfOutAndErrCapture();
		testArea = TestArea.forTest(this);
		network = new IwantNetworkMock(testArea);
		useRealAntJars(network);
		iwant2 = Iwant2.using(network);
	}

	private void useRealAntJars(IwantNetworkMock network) {
		Iwant2 iw2 = new Iwant2(Iwant.usingRealNetwork().network());
		antJar = iw2.antJar();
		network.cachesUrlAt(iw2.antJarUrl(), antJar);
		antLauncherJar = iw2.antLauncherJar();
		network.cachesUrlAt(iw2.antLauncherJarUrl(), antLauncherJar);
	}

	private void startOfOutAndErrCapture() {
		out = new ByteArrayOutputStream();
		err = new ByteArrayOutputStream();
		System.setOut(new PrintStream(out));
		System.setErr(new PrintStream(err));
	}

	private static class ExitCalledException extends SecurityException {

		private final int status;

		public ExitCalledException(int status) {
			this.status = status;
		}

		@SuppressWarnings("unused")
		public int status() {
			return status;
		}

	}

	private static class ExitCatcher extends SecurityManager {

		@Override
		public void checkPermission(Permission perm) {
			// everything allowed
		}

		@Override
		public void checkExit(int status) {
			throw new ExitCalledException(status);
		}

	}

	@Override
	public void tearDown() {
		System.setSecurityManager(origSecman);
		System.setIn(originalIn);
		System.setOut(originalOut);
		System.setErr(originalErr);
		System.setProperty(LINE_SEPARATOR_KEY, originalLineSeparator);
		System.err.print("== out:\n" + out());
		System.err.print("== err:\n" + err());
	}

	private String out() {
		return out.toString();
	}

	private String err() {
		return err.toString();
	}

	public void testIwant2CompilesIwantAndCallsIwant3() throws Exception {
		File iwantEssential = IwantWsRootFinder.mockEssential();
		network.cachesAt(
				new ClassesFromUnmodifiableIwantEssential(iwantEssential),
				"all-iwant-classes");

		iwant2.evaluate(iwantEssential, "args", "to be", "passed");

		assertEquals(":       Compiling -> " + testArea.root()
				+ "/all-iwant-classes\n", err());
		assertEquals("Mocked org.fluentjava.iwant.entry3.Iwant3\n" + "args: ["
				+ iwantEssential + ", args, to be, passed]\n", out());
	}

	public void testIwant2CallsIwant3UsingCorrectClasspath() throws Exception {
		File iwantEssential = IwantWsRootFinder.mockEssential();
		network.cachesAt(
				new ClassesFromUnmodifiableIwantEssential(iwantEssential),
				"all-iwant-classes");

		iwant2.evaluate(iwantEssential, "--printClassLoaderUrls");
		assertEquals(":       Compiling -> " + testArea.root()
				+ "/all-iwant-classes\n", err());
		assertEquals("Mocked org.fluentjava.iwant.entry3.Iwant3\n" + "args: ["
				+ iwantEssential + ", --printClassLoaderUrls]\n"
				+ "classloader urls: [file:" + iwantEssential
				+ "/iwant-wsroot-marker/, file:" + testArea.root()
				+ "/all-iwant-classes/, " + antJar.toURI() + ", "
				+ antLauncherJar.toURI() + "]\n", out());
	}

	public void testIwant2CompilesIwantWithDebugInformation() throws Exception {
		File iwantEssential = IwantWsRootFinder.mockEssential();
		network.cachesAt(
				new ClassesFromUnmodifiableIwantEssential(iwantEssential),
				"all-iwant-classes");

		iwant2.evaluate(iwantEssential);

		File iwantClasses = new File(testArea.root(), "all-iwant-classes");
		File classWithVars = new File(iwantClasses,
				"org/fluentjava/iwant/api/ClassToTestDebugInformation.class");

		// TODO reuse code with JavaClassesTest to read as bytes. This is not
		// robust because we parse binary as String
		String contentOfClass = Iwant2.contentAsString(classWithVars);
		assertTrue(contentOfClass.contains("parameterVariable"));
		assertTrue(contentOfClass.contains("localVariable"));
	}

	public void testFindingJavaFilesUnderSrcDirThatContainsNonJavaAndSvnMetadata() {
		File src = testArea.newDir("src");
		Iwant.mkdirs(new File(src, ".svn"));
		File aJava = Iwant.newTextFile(new File(src, "A.java"), "");

		File pak1 = new File(src, "pak1");
		Iwant.mkdirs(new File(pak1, ".svn"));
		File bJava = Iwant.newTextFile(new File(pak1, "B.java"), "");
		Iwant.newTextFile(new File(pak1, "crap.notjava"), "");

		assertEquals("[" + aJava + ", " + bJava + "]",
				Iwant2.javaFilesRecursivelyUnder(src).toString());
	}

	public void testIwant2CopiesApiBashResourcesToIwantClasses()
			throws Exception {
		File iwantEssential = IwantWsRootFinder.mockEssential();
		network.cachesAt(
				new ClassesFromUnmodifiableIwantEssential(iwantEssential),
				"all-iwant-classes");

		iwant2.evaluate(iwantEssential);

		assertEquals("represents api bash resources\n", testArea.contentOf(
				"all-iwant-classes/org/fluentjava/iwant/api/bash/mock-resource.txt"));
	}

}


text:
<?php

namespace  Liuggio\ExcelBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class FakeController extends Controller
{
    public function streamAction()
    {
        // create an empty object
        $phpExcelObject = $this->createXSLObject();
        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        // create the response
        $response = $this->get('phpexcel')->createStreamedResponse($writer);
        // adding headers
        $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment;filename=stream-file.xls');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');

        return $response;
    }

    public function storeAction()
    {
        // create an empty object
        $phpExcelObject = $this->createXSLObject();
        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        $filename = tempnam(sys_get_temp_dir(), 'xls-') . '.xls';
        // create filename
        $writer->save($filename);

        return new Response($filename, 201);
    }

    public function readAndSaveAction()
    {
        $filename = $this->container->getParameter('xls_fixture_absolute_path');
        // create an object from a filename
        $phpExcelObject = $this->createXSLObject($filename);
        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
        $filename = tempnam(sys_get_temp_dir(), 'xls-') . '.xls';
        // create filename
        $writer->save($filename);

        return new Response($filename, 201);
    }

    /**
     * utility class
     * @return mixed
     */
    private function createXSLObject()
    {
        $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();

        $htmlHelper = $this->get('phpexcel')->createHelperHTML();

        $phpExcelObject->getProperties()->setCreator("liuggio")
            ->setLastModifiedBy("Giulio De Donato")
            ->setTitle("Office 2005 XLSX Test Document")
            ->setSubject("Office 2005 XLSX Test Document")
            ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
            ->setKeywords("office 2005 openxml php")
            ->setCategory("Test result file");
        $phpExcelObject->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C3', $htmlHelper->toRichTextObject('<b>In Bold!</b>'));
        $phpExcelObject->getActiveSheet()->setTitle('Simple');
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $phpExcelObject->setActiveSheetIndex(0);

        return $phpExcelObject;
    }
}


text:
package org.jasig.cas.console.groovy;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import org.apache.commons.io.IOUtils;
import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author Misagh Moayyed
 * @since 4.3
 */
final class GroovyShellThread extends Thread {
    private static final String OUT_KEY = "out";

    private final Socket socket;
    private final Binding binding;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Instantiates a new Groovy shell thread.
     *
     * @param socket  the socket
     * @param binding the binding
     */
    GroovyShellThread(final Socket socket, final Binding binding) {
        super();
        this.socket = socket;
        this.binding = binding;
    }

    @Override
    public void run() {
        try (final PrintStream out = new PrintStream(socket.getOutputStream());
             final InputStream in =  socket.getInputStream()) {
            logger.debug("Created socket IO streams...");

            binding.setVariable(OUT_KEY, out);
            logger.debug("Added output stream to binding collection as {}", OUT_KEY);

            final GroovyClassLoader loader = new GroovyClassLoader(this.getContextClassLoader());
            final IO io = new IO(in, out, out);

            final Groovysh gsh = new Groovysh(loader, binding, io);

            try {
                logger.debug("Launching groovy interactive shell");
                gsh.run("");
            } catch (final Exception e) {
                logger.error(e.getMessage(), e);
            }
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (socket != null) {
                IOUtils.closeQuietly(this.socket);
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void destroy() {
        IOUtils.closeQuietly(this.socket);
    }
}


text:
class Channels::ProfilesController < Channels::BaseController
  inherit_resources

  actions :show, :edit, :update
  custom_actions resource: [:how_it_works]

  before_action only: [:edit, :update] do
    authorize!(params[:action], resource)
  end

  def show
    @projects = resource.projects.visible
  end

  def resource
    @profile ||= Channel.find_by_permalink!(request.subdomain.to_s)
  end
end


text:
    containers

 /

    {{container.id | limitTo:12}}

 /

logs

    {{flash.message}}


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

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * A multipart filter that processes only initially dispatched requests.
 * Re-dispatched requests are ignored.
 */
class CamelMultipartFilter implements Filter {
    private Filter wrapped;

    public CamelMultipartFilter(Filter wrapped) {
        this.wrapped = wrapped;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request.getAttribute(CamelContinuationServlet.EXCHANGE_ATTRIBUTE_NAME) == null) {
            wrapped.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
        wrapped.destroy();
    }

    public void init(FilterConfig config) throws ServletException {
        wrapped.init(config);
    }
}


text:
  Agrume Leaflet prototype

    <ba-msg-center></ba-msg-center>


text:
var AbstractPlugin = function() {
};

/**
 * @param {Router} router
 */
AbstractPlugin.prototype.installHttpHandlers = function(router) {
  throw new Error('Not implemented');
};

module.exports = AbstractPlugin;


text:
package edu.chat.impl;

import edu.chat.Chat;
import edu.chat.Input;
import edu.chat.Answer;
import edu.chat.impl.stub.InputStubImpl;
import edu.chat.impl.stub.AnswerStubImpl;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by Nik Bespalov on 2019-03-11.
 *
 * @author Nik Bespalov.
 */
public class ChatImplTest {

    @Test
    public void start() {
        Input input = new InputStubImpl();
        Answer output = new AnswerStubImpl();
        Chat chat = new ChatImpl(input, output);
        chat.start();

        try (BufferedReader reader = new BufferedReader(new FileReader("chat.log"))) {
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("qwe");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("111");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("asd");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("222");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("pause");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("zxc");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("continue");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("333");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("ert");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("444");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("dfg");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("555");
            assertThat(reader.readLine()).isNotNull().isNotEmpty().contains("stop");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
module HBW
  module Fields
    class FileUpload < Ordinary
      def value?
        true
      end

      def coerce(value)
        value
      end
    end
  end
end


text:
var EasyAssess = require('../../easyassess.application');

EasyAssess.directives["esAppIqcHistoryGrid"]
    = EasyAssess.app.directive("esAppIqcHistoryGrid", function ($http, esRequestService) {

    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: function () {
            var tpl = '
'
                + '
'
                + '
<es-spinner></es-spinner>
'
                + '
'
                + ''
                + '

	{{record.date}}
'
                + '
{{plan.owner.name}} - {{plan.planName}}	'
                + '
'
                +   '
'
                +       '{{item.subject}}	'
                +       '{{specimen.number}}: {{specimen.value}} ({{specimen.targetValue}} ±{{specimen.floatValue}})	'
                +   '
'
                + '
'
                + '
'
                +           '
'
                +							'记录标签:	'
                +							'{{record.tags}}	'
                +						'
'
                +   '
'
                +       '{{name}}	'
                +       '{{value}}	'
                +   '
'
                +           '
'
                +							'记录创建时间:	'
                +							'{{record.createdAt}}	'
                +						'
'
                +           '
'
                +							'最后修改时间:	'
                +							'{{record.lastModified}}	'
                +						'
'
                +           '
'
                +							'批注:	'
                +							'{{record.comments}}	'
                +						'
'
                + '
'
                + '
'
                + '
'
                + '	'
                + '
'
                + '
'
                + '
没有匹配的记录
'
                + '
'
                + '

'
                + '

'
                + '

'
                + '
{{n}}{{n}}
'
                + '

'
                + '

'
                + '
	'
                + '

跳转: 	<input class="form-control" style="width: 50px;height:30px;" type="tel" min=1 ng-keyup="go(pageNum, $event)" ng-model="pageNum"/>

	'
                + '

每页显示(行): 	<select class="form-control" ng-change="setPageSize(esPageSize)" ng-model="esPageSize" style="width: 60px;height:30px;"><option selected="selected" value="5">5</option><option value="10">10</option><option value="20">20</option><option value="50">50</option></select>

	'
                + '

'
                + '
';
            return tpl;
        },
        scope: {
            esPageSize: "@",
            esTemplateId: "@",
            esData: "=?"
        },
        controller: ["$scope", function ($scope, $element, $attrs) {

            if (!$scope.esPageSize) {
                $scope.esPageSize = "5";
            }

            var pageCount = 1;

            $scope.pagination = [];
            $scope.pageNum = 1;
            $scope.jump = function (pageNum) {
                if (!pageNum || isNaN(pageNum) || pageNum < 1) pageNum = 1;
                if (pageNum > pageCount) pageNum = pageCount;
                $scope.pageNum = pageNum;
                _loadData($scope.esPageSize, $scope.pageNum, null, null, null);
            };

            $scope.previous = function () {
                if ($scope.pageNum > 1) {
                    $scope.jump($scope.pageNum - 1);
                }
            };

            $scope.next = function () {
                if ($scope.pageNum < pageCount) {
                    $scope.jump($scope.pageNum + 1);
                }
            }

            $scope.first = function () {
                $scope.jump(1);
            }

            $scope.last = function () {
                $scope.jump(pageCount);
            }

            $scope.go = function(pageNumber, e) {
                if (e.key === 'Enter') {
                    $scope.jump(pageNumber);
                }
            }

            $scope.setPageSize = function(size) {
                _loadData($scope.esPageSize, $scope.pageNum, null, null, null);
            }

            function _loadData(pageSize, pageNum, filterBy, filterValue, sortBy) {
                $scope.isLoading = true;
                esRequestService.esGet(EasyAssess.activeEnv.iqc() + "template/" + $scope.esTemplateId + "/record/list", {
                    size: pageSize,
                    page: pageNum - 1,
                    sortBy: sortBy,
                    filterField: filterBy,
                    filterValue: filterValue
                }).then(function (result) {
                    $scope.isLoading = false;
                    if (result.data.content.length > 0) {
                        $scope.esData = angular.copy(result.data, {}).content;
                        $scope.esData.forEach(function(rec, index) {
                            rec.index = index;
                        });
                        $scope.originalData =  result.data.content;
                        $scope.pagination = [];
                        pageCount = result.data.totalPages;
                        if (!pageCount) pageCount = 1;

                        var max = 5;
                        var start = 0;
                        var end = pageCount;
                        if (pageCount > max) {
                            if (($scope.pageNum + max) <= pageCount && ($scope.pageNum - Math.ceil((max / 2)) <= 0)) {
                                start = 0;
                                end = start + max;
                            }
                            else if (($scope.pageNum + max) <= pageCount && ($scope.pageNum - Math.ceil((max / 2)) > 0)) {
                                start = $scope.pageNum - Math.ceil((max / 2));
                                end = start + max;
                            }
                            else {
                                end = pageCount;
                                start = pageCount - max;
                            }
                        }

                        for (var i = start; i < end; i++) {
                            var pageIndex = i + 1;
                            $scope.pagination.push(pageIndex);
                        }
                    } else {
                        $scope.esData = [];
                        $scope.pagination = [];
                    }
                }).then(function (error) {
                    if (error) {
                        $scope.isLoading = false;
                    }
                });
            }

            $scope.isLoading = true;

            _loadData($scope.esPageSize, $scope.pageNum, null, null, null);
        }]
    };
});


text:
define(['leaflet'],
function (leaflet) {

    // -----------------------------------------------------------------------------------------------------------------
    // Private functions
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * @param {number} price
     * @returns {string}
     */
    function formatPrice(price) {
        return "£"+price.toFixed(2);
    }

    /**
     * @param {string} url
     * @param {string} text
     * @returns {string}
     */
    function createLink(url, text)
    {
        return "" + text + "";
    }

    /**
     * @param {Site} site
     * @returns {string}
     */
    function bubbleHtml(site)
    {
        var pub = site.properties.current;
        var history = site.properties.history;
        var text = "" + pub.name + "";
        if (pub.visits.length > 0) {
            var visit = pub.visits[0];
            if (visit.link)
                text = createLink(visit.link, text);
            if (visit.comment)
                text += "
" + visit.comment + "";
            if (visit.price > 0)
                text += "
Price: " + formatPrice(visit.price);
        }
        if (history.length > 0) {
            var previous = [];
            for (var i = 0; i < history.length; ++i) {
                if (history[i].name != pub.name) {
                    if (history[i].visits.length > 0) {
                        previous.push(createLink(
                            history[i].visits[0].link,
                            history[i].name
                        ));
                    }
                    else {
                        previous.push(history[i].name);
                    }
                }
            }
            if (previous.length > 0) {
                text += "
Previously known as " + previous.join(', ') + ".";
            }
        }
        if (pub.tags.length > 0) {
            text += "
Tags: " + pub.tags.join(', ');
        }
        return text;
    }

    // -----------------------------------------------------------------------------------------------------------------
    // SitesView
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * @param {Leaflet.Map} map
     * @constructor
     */
    function SitesView(map)
    {
        this._layer = leaflet.layerGroup();
        this._layer.addTo(map);
        this._icons = {};
    }

    /**
     * @param {SitesModel} sitesModel
     * @param {GroupsModel} groupsModel
     */
    SitesView.prototype.setup = function(sitesModel, groupsModel)
    {
        sitesModel.visibleSites
            .bufferMilliseconds(0)
            .subscribe(function(sites) {
                this._layer.clearLayers();
                sites.forEach(function(site) {
                    var marker = leaflet.marker(
                        site.geometry.coordinates,
                        {
                            title: site.properties.current.name,
                            icon: this._icons[site.properties.group]
                        });
                    marker.bindPopup(bubbleHtml(site));
                    marker.addTo(this._layer);
                }, this);
            }, this);

        groupsModel.groups.subscribe(function(groups)
        {
            this._icons = {};
            groups.forEach(function(group)
            {
                this._icons[group.name] = leaflet.icon({
                    iconUrl: "img/marker-" + group.colour + ".png",
                    iconRetinaUrl: "img/marker-" + group.colour + "-2x.png",
                    iconSize: [25, 39],
                    iconAnchor: [12, 36],
                    popupAnchor: [0, -30]
                });
            }, this);
        }, this);
    };

    return SitesView;

});


text:
using Microsoft.WindowsAzure.Commands.Common.Attributes;

namespace Microsoft.Azure.Commands.Network.Models
{
    public class PSApplicationGatewayAutoscaleConfiguration
    {
        [Ps1Xml(Target = ViewControl.Table)]
        public int MinCapacity { get; set; }
    }
}


text:
<?php

final class PhabricatorEdgeGraph extends AbstractDirectedGraph {

  private $edgeType;

  public function setEdgeType($edge_type) {
    $this->edgeType = $edge_type;
    return $this;
  }

  protected function loadEdges(array $nodes) {
    if (!$this->edgeType) {
      throw new Exception('Set edge type before loading graph!');
    }

    $edges = id(new PhabricatorEdgeQuery())
      ->withSourcePHIDs($nodes)
      ->withEdgeTypes(array($this->edgeType))
      ->execute();

    $results = array_fill_keys($nodes, array());
    foreach ($edges as $src => $types) {
      foreach ($types as $type => $dsts) {
        foreach ($dsts as $dst => $edge) {
          $results[$src][] = $dst;
        }
      }
    }

    return $results;
  }

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hydnochaete philippensis Lloyd

### Remarks
null


text:
package org.apache.hadoop.mapred;

import java.util.LinkedList;
import java.util.Queue;

import org.apache.log4j.FileAppender;
import org.apache.log4j.spi.LoggingEvent;

/**
 * A simple log4j-appender for the task child's map-reduce system logs.
 *
 */
public class TaskLogAppender extends FileAppender {
    private String taskId; // taskId should be managed as String rather than
                           // TaskID object
    // so that log4j can configure it from the configuration(log4j.properties).
    private int maxEvents;
    private Queue<LoggingEvent> tail = null;

    @Override
    public void activateOptions() {
        synchronized (this) {
            if (maxEvents > 0) {
                tail = new LinkedList<LoggingEvent>();
            }
            setFile(TaskLog.getTaskLogFile(TaskAttemptID.forName(taskId), TaskLog.LogName.SYSLOG).toString());
            setAppend(true);
            super.activateOptions();
        }
    }

    @Override
    public void append(LoggingEvent event) {
        synchronized (this) {
            if (tail == null) {
                super.append(event);
            } else {
                if (tail.size() >= maxEvents) {
                    tail.remove();
                }
                tail.add(event);
            }
        }
    }

    public void flush() {
        qw.flush();
    }

    @Override
    public synchronized void close() {
        if (tail != null) {
            for (LoggingEvent event : tail) {
                super.append(event);
            }
        }
        super.close();
    }

    /**
     * Getter/Setter methods for log4j.
     */

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    private static final int EVENT_SIZE = 100;

    public long getTotalLogFileSize() {
        return maxEvents * EVENT_SIZE;
    }

    public void setTotalLogFileSize(long logSize) {
        maxEvents = (int) logSize / EVENT_SIZE;
    }

}


text:
set -eux

TMP=$(mktemp -d)

tar xzf als-prolog-linux.tgz -C $TMP
SRC=$TMP/als-prolog

mkdir $TMP/usr
DST=$TMP/usr

mkdir $DST/bin
mkdir -p $DST/lib/als-prolog
mkdir $DST/include
mkdir -p $DST/share/man/man1
mkdir -p $DST/share/doc/als-prolog

# Binaries symlinks from bin

ln -s ../lib/als-prolog/alspro $DST/bin
ln -s ../lib/als-prolog/alsdev $DST/bin

# Executable files and support in lib

cp -p $SRC/alspro $DST/lib/als-prolog
cp -p $SRC/alspro.pst $DST/lib/als-prolog
cp -p $SRC/alsdev $DST/lib/als-prolog
cp -p $SRC/alsdev.pst $DST/lib/als-prolog
cp -rp $SRC/alsdir $DST/lib/als-prolog

# Headers and libraries

cp -p $SRC/ALS_Prolog_Foreign_SDK/include/alspi.h $DST/include
cp -p $SRC/ALS_Prolog_Foreign_SDK/include/alspi_slib.h $DST/include
cp -p $SRC/libalspro.so $DST/lib
cp -p $SRC/libalspro.a $DST/lib

# Man pages, documentation and examples:

cp -p $SRC/alspro.1 $DST/share/man/man1/

cp -p $SRC/README.txt $DST/share/doc/als-prolog
../format-subst $SRC/LICENSE.txt $DST/share/doc/als-prolog
cp -p $SRC/als-prolog-manual.pdf $DST/share/doc/als-prolog
cp -p $SRC/als-ref-manual.pdf $DST/share/doc/als-prolog
cp -p $SRC/docs $DST/share/doc/als-prolog
cp -rp $SRC/examples $DST/share/doc/als-prolog

VERSION=$(../version)

for FORMAT in deb rpm
do
fpm --force -s dir -t $FORMAT -C $DST \
--name als-prolog --version ${VERSION:1} --architecture i386 --prefix /usr \
--depends "tk >= 8.5"
done

rm -r $TMP


text:
"""Case / Cases Object"""
# standard library
from typing import TYPE_CHECKING, Iterator, Union

# first-party
from tcex.api.tc.v3.api_endpoints import ApiEndpoints
from tcex.api.tc.v3.artifacts.artifact_model import ArtifactModel
from tcex.api.tc.v3.case_attributes.case_attribute_model import CaseAttributeModel
from tcex.api.tc.v3.cases.case_filter import CaseFilter
from tcex.api.tc.v3.cases.case_model import CaseModel, CasesModel
from tcex.api.tc.v3.groups.group_model import GroupModel
from tcex.api.tc.v3.indicators.indicator_model import IndicatorModel
from tcex.api.tc.v3.notes.note_model import NoteModel
from tcex.api.tc.v3.object_abc import ObjectABC
from tcex.api.tc.v3.object_collection_abc import ObjectCollectionABC
from tcex.api.tc.v3.security.user_groups.user_group_model import UserGroupModel
from tcex.api.tc.v3.security.users.user_model import UserModel
from tcex.api.tc.v3.tags.tag_model import TagModel
from tcex.api.tc.v3.tasks.task_model import TaskModel

if TYPE_CHECKING:  # pragma: no cover
    # first-party
    from tcex.api.tc.v3.artifacts.artifact import Artifact
    from tcex.api.tc.v3.case_attributes.case_attribute import CaseAttribute
    from tcex.api.tc.v3.groups.group import Group
    from tcex.api.tc.v3.indicators.indicator import Indicator
    from tcex.api.tc.v3.notes.note import Note
    from tcex.api.tc.v3.tags.tag import Tag
    from tcex.api.tc.v3.tasks.task import Task

class Cases(ObjectCollectionABC):
    """Cases Collection.

    # Example of params input
    {
        'result_limit': 100,  # Limit the retrieved results.
        'result_start': 10,  # Starting count used for pagination.
        'fields': ['caseId', 'summary']  # Select additional return fields.
    }

    Args:
        session (Session): Session object configured with TC API Auth.
        tql_filters (list): List of TQL filters.
        params (dict): Additional query params (see example above).
    """

    def __init__(self, **kwargs):
        """Initialize class properties."""
        super().__init__(
            kwargs.pop('session', None), kwargs.pop('tql_filter', None), kwargs.pop('params', None)
        )
        self._model = CasesModel(**kwargs)
        self.type_ = 'cases'

    def __iter__(self) -> 'Case':
        """Iterate over CM objects."""
        return self.iterate(base_class=Case)

    @property
    def _api_endpoint(self) -> str:
        """Return the type specific API endpoint."""
        return ApiEndpoints.CASES.value

    @property
    def filter(self) -> 'CaseFilter':
        """Return the type specific filter object."""
        return CaseFilter(self.tql)

class Case(ObjectABC):
    """Cases Object.

    Args:
        artifacts (Artifacts, kwargs): A list of Artifacts corresponding to the Case.
        assignee (Assignee, kwargs): The user or group Assignee object for the Case.
        associated_cases (Cases, kwargs): A list of Cases associated with this Case.
        associated_groups (Groups, kwargs): A list of Groups associated with this Case.
        associated_indicators (Indicators, kwargs): A list of Indicators associated with this Case.
        attributes (CaseAttributes, kwargs): A list of Attributes corresponding to the Case.
        case_close_time (str, kwargs): The date and time that the Case was closed.
        case_detection_time (str, kwargs): The date and time that ends the user initiated Case
            duration.
        case_occurrence_time (str, kwargs): The date and time that starts the user initiated Case
            duration.
        case_open_time (str, kwargs): The date and time that the Case was first opened.
        description (str, kwargs): The description of the Case.
        name (str, kwargs): The name of the Case.
        notes (Notes, kwargs): A list of Notes corresponding to the Case.
        resolution (str, kwargs): The Case resolution.
        severity (str, kwargs): The Case severity.
        status (str, kwargs): The Case status.
        tags (Tags, kwargs): A list of Tags corresponding to the Case (NOTE: Setting this parameter
            will replace any existing tag(s) with the one(s) specified).
        tasks (Tasks, kwargs): A list of Tasks corresponding to the Case.
        user_access (Users, kwargs): A list of Users that, when defined, are the only ones allowed
            to view or edit the Case.
        workflow_events (WorkflowEvents, kwargs): A list of workflowEvents (timeline) corresponding
            to the Case.
        workflow_template (WorkflowTemplate, kwargs): The Template that the Case is populated by.
        xid (str, kwargs): The **xid** for the Case.
    """

    def __init__(self, **kwargs):
        """Initialize class properties."""
        super().__init__(kwargs.pop('session', None))

        # properties
        self._model = CaseModel(**kwargs)
        self._nested_field_name = 'cases'
        self._nested_filter = 'has_case'
        self.type_ = 'Case'

    @property
    def _api_endpoint(self) -> str:
        """Return the type specific API endpoint."""
        return ApiEndpoints.CASES.value

    @property
    def model(self) -> 'CaseModel':
        """Return the model data."""
        return self._model

    @model.setter
    def model(self, data: Union['CaseModel', dict]):
        """Create model using the provided data."""
        if isinstance(data, type(self.model)):
            # provided data is already a model, nothing required to change
            self._model = data
        elif isinstance(data, dict):
            # provided data is raw response, load the model
            self._model = type(self.model)(**data)
        else:
            raise RuntimeError(f'Invalid data type: {type(data)} provided.')

    @property
    def as_entity(self) -> dict:
        """Return the entity representation of the object."""
        type_ = self.type_

        return {'type': type_, 'id': self.model.id, 'value': self.model.name}

    @property
    def artifacts(self) -> Iterator['Artifact']:
        """Yield Artifact from Artifacts."""
        # first-party
        from tcex.api.tc.v3.artifacts.artifact import Artifacts

        yield from self._iterate_over_sublist(Artifacts)

    @property
    def associated_cases(self) -> Iterator['Case']:
        """Yield Case from Cases."""
        # Ensure the current item is not returned as a association
        for case in self._iterate_over_sublist(Cases):
            if case.model.id == self.model.id:
                continue
            yield case

    @property
    def associated_groups(self) -> Iterator['Group']:
        """Yield Group from Groups."""
        # first-party
        from tcex.api.tc.v3.groups.group import Groups

        yield from self._iterate_over_sublist(Groups)

    @property
    def associated_indicators(self) -> Iterator['Indicator']:
        """Yield Indicator from Indicators."""
        # first-party
        from tcex.api.tc.v3.indicators.indicator import Indicators

        yield from self._iterate_over_sublist(Indicators)

    @property
    def attributes(self) -> Iterator['CaseAttribute']:
        """Yield Attribute from Attributes."""
        # first-party
        from tcex.api.tc.v3.case_attributes.case_attribute import CaseAttributes

        yield from self._iterate_over_sublist(CaseAttributes)

    @property
    def notes(self) -> Iterator['Note']:
        """Yield Note from Notes."""
        # first-party
        from tcex.api.tc.v3.notes.note import Notes

        yield from self._iterate_over_sublist(Notes)

    @property
    def tags(self) -> Iterator['Tag']:
        """Yield Tag from Tags."""
        # first-party
        from tcex.api.tc.v3.tags.tag import Tags

        yield from self._iterate_over_sublist(Tags)

    @property
    def tasks(self) -> Iterator['Task']:
        """Yield Task from Tasks."""
        # first-party
        from tcex.api.tc.v3.tasks.task import Tasks

        yield from self._iterate_over_sublist(Tasks)

    def stage_artifact(self, data: Union[dict, 'ObjectABC', 'ArtifactModel']):
        """Stage artifact on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = ArtifactModel(**data)

        if not isinstance(data, ArtifactModel):
            raise RuntimeError('Invalid type passed in to stage_artifact')
        data._staged = True
        self.model.artifacts.data.append(data)

    # pylint: disable=redefined-builtin
    def stage_assignee(self, type: str, data: Union[dict, 'ObjectABC', 'ArtifactModel']):
        """Stage artifact on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif type.lower() == 'user' and isinstance(data, dict):
            data = UserModel(**data)
        elif type.lower() == 'group' and isinstance(data, dict):
            data = UserGroupModel(**data)

        if not isinstance(data, (UserModel, UserGroupModel)):
            raise RuntimeError('Invalid type passed in to stage_assignee')
        data._staged = True
        self.model.assignee._staged = True
        self.model.assignee.type = type
        self.model.assignee.data = data

    def stage_associated_case(self, data: Union[dict, 'ObjectABC', 'CaseModel']):
        """Stage case on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = CaseModel(**data)

        if not isinstance(data, CaseModel):
            raise RuntimeError('Invalid type passed in to stage_associated_case')
        data._staged = True
        self.model.associated_cases.data.append(data)

    def stage_associated_group(self, data: Union[dict, 'ObjectABC', 'GroupModel']):
        """Stage group on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = GroupModel(**data)

        if not isinstance(data, GroupModel):
            raise RuntimeError('Invalid type passed in to stage_associated_group')
        data._staged = True
        self.model.associated_groups.data.append(data)

    def stage_associated_indicator(self, data: Union[dict, 'ObjectABC', 'IndicatorModel']):
        """Stage indicator on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = IndicatorModel(**data)

        if not isinstance(data, IndicatorModel):
            raise RuntimeError('Invalid type passed in to stage_associated_indicator')
        data._staged = True
        self.model.associated_indicators.data.append(data)

    def stage_attribute(self, data: Union[dict, 'ObjectABC', 'CaseAttributeModel']):
        """Stage attribute on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = CaseAttributeModel(**data)

        if not isinstance(data, CaseAttributeModel):
            raise RuntimeError('Invalid type passed in to stage_attribute')
        data._staged = True
        self.model.attributes.data.append(data)

    def stage_note(self, data: Union[dict, 'ObjectABC', 'NoteModel']):
        """Stage note on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = NoteModel(**data)

        if not isinstance(data, NoteModel):
            raise RuntimeError('Invalid type passed in to stage_note')
        data._staged = True
        self.model.notes.data.append(data)

    def stage_tag(self, data: Union[dict, 'ObjectABC', 'TagModel']):
        """Stage tag on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = TagModel(**data)

        if not isinstance(data, TagModel):
            raise RuntimeError('Invalid type passed in to stage_tag')
        data._staged = True
        self.model.tags.data.append(data)

    def stage_task(self, data: Union[dict, 'ObjectABC', 'TaskModel']):
        """Stage task on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = TaskModel(**data)

        if not isinstance(data, TaskModel):
            raise RuntimeError('Invalid type passed in to stage_task')
        data._staged = True
        self.model.tasks.data.append(data)

    def stage_user_access(self, data: Union[dict, 'ObjectABC', 'UserModel']):
        """Stage user on the object."""
        if isinstance(data, ObjectABC):
            data = data.model
        elif isinstance(data, dict):
            data = UserModel(**data)

        if not isinstance(data, UserModel):
            raise RuntimeError('Invalid type passed in to stage_user_access')
        data._staged = True
        self.model.user_access.data.append(data)


text:
\documentclass[12pt]{article}

\usepackage{tikz}
\usetikzlibrary{calc,shapes.multipart,chains,arrows}
\usepackage[ruled, vlined]{algorithm2e}
\usepackage{pst-node,pst-plot}
\usepackage{amsmath}
\usepackage{float}

\newcommand{\BigO}[1]{\ensuremath{\operatorname{\mathcal{O}}\bigl(#1\bigr)}}

\begin{document}
\title{Homework 27}
\author{Robbie McKinstry, Jack McQuown, Cyrus Ramavarapu}
\renewcommand{\today}{04 November 2016}
\renewcommand{\baselinestretch}{1.5}
\maketitle

\section*{Problem 21: }
On an EREW PRAM, the leave nodes of an arbitrary tree with $n$ nodes
can be numbered in order in \BigO{\log n} time using $n$ processors
if initially each of the $n$ processors is assigned to a unique node.\\\\
Initially, each processor will have to determine whether or not it is
assigned a leaf node.  This can be done in parallel in \BigO{1} time
by having each processor check if has any children.  If the processor
has children, it will hold the value $0$.  If the processor is
assigned to a leaf node it will hold the value $1$.\\\\
After numbering all the internal nodes as $0$ and all the leaf nodes as
$1$, an \textit{Eulerian Tour} can be performed starting from the root
of the tree headed left.  Each edge will be marked with a $+0$ and the
result of the tour will be a linked list where each node will either
contribute $1$ to the sum, if it is a leaf, or a $0$ if it is an internal
node.  The parallel prefix problem can then be solved on this linked list,
and the resulting sequence of consecutive numbers will number the leaves
from left to right.\\\\
To demonstrate this algorithm, consider the following tree:\\\\
\begin{center}
\begin{tikzpicture}[level distance=1.5cm,
    level 1/.style={sibling distance=3.40cm},
    level 2/.style={sibling distance=1.25cm},
    level 3/.style={sibling distance=1.15cm}]
    \node {$A$}
        child {node {$B$}
            child {node {$C$}}
            child {node {$D$}
                child {node {$E$}}
                child {node {$F$}}
            }
        }
        child {node {$G$}
        };
\end{tikzpicture}
\end{center}
After the initial step that will number each node as either a $0$ or
$1$ depending if the node is a leaf or an internal node, the tree
will look as follows:\\\\
\begin{center}
\begin{tikzpicture}[level distance=1.5cm,
    level 1/.style={sibling distance=3.40cm},
    level 2/.style={sibling distance=1.25cm},
    level 3/.style={sibling distance=1.15cm}]
    \node {$A, 0$}
        child {node {$B, 0$}
            child {node {$C, 1$}}
            child {node {$D, 0$}
                child {node {$E, 1$}}
                child {node {$F, 1$}}
            }
        }
        child {node {$G, 1$}
        };
\end{tikzpicture}
\end{center}
The \textit{Eulerian Tour} of the tree will begin at $A$ and then
track values as makes progress beginning from the left.  This linked
list will look like the following.

Using the pointer doubling technique, the parallel prefix problem on
the linked list can be solved in \BigO{\log n} time.  Since all the
other steps were doable in \BigO{1} time, the overall runtime of the
algorithm will be \BigO{\log n}.

\section*{Problem 22: }
%Fairly sure that this is the same as 21 except do the Eulerian tour
% + on the left/right and - on the right/left (Depending how the balance
% goes.  Should lead to some runtime of log n/2 which is O(log n)
% all nodes will have to contribute 1 to the sum.
On an EREW PRAM, the balance factor for each node of an arbitrary tree with $n$ nodes
can be done in \BigO{\log n} time using $n$ processors
if initially each of the $n$ processors is assigned to a unique node.\\\\
Initially, each processor will have to know the height of the node it is pointing to. In order to find the height of each node in the tree we can do an \textit{Euler Tour} of the tree and have each node hold the value of its respective height like we did in class. The process for finding the height of each node is by keeping a sum which increments when going down a level and decrements when going back up a level. The sum is then stored at each node when the node is visited. This \textit{Euler Tour Technique} can be done in \BigO 1 time, which then leaves the process of finding the balance factor at each node.\\\\
To find the balance factor for each node, we can use a simple equation {$Balance(x) = Height(x.left) - Height(x.right)$}. This Balance(x) calculation can be done in parallel in that we can start from the leaves and work our way up the tree and calculate the balance for every node at a certain level in the tree.\\\\
The leaves of the tree will initially have a balance set to 0, which can be done in \BigO 1 time. We can then progress up the tree and at each level calculate the Balance(x) for each node at that level in parallel. Using this technique we can achieve a runtime of \BigO{ \lg n}.
\end{document}


text:
@extends('layouts.app')

@section('content')

Edit Organization

                            {!! FormBuilder::buildForm('Organization', 'POST', 'updateOrg', 'update', $id) !!}

@endsection


text:
package io.confluent.connect.hdfs.partitioner;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.confluent.connect.hdfs.HdfsSinkConnectorConfig;

import static org.junit.Assert.assertEquals;

public class HourlyPartitionerTest {

  private static final long partitionDurationMs = TimeUnit.HOURS.toMillis(1);

  @Test
  public void testHourlyPartitioner() throws Exception {
    Map<String, Object> config = createConfig();

    HourlyPartitioner partitioner = new HourlyPartitioner();
    partitioner.configure(config);

    String pathFormat = partitioner.getPathFormat();
    String timeZoneString = (String) config.get(HdfsSinkConnectorConfig.TIMEZONE_CONFIG);
    long timestamp = new DateTime(2015, 2, 1, 3, 0, 0, 0, DateTimeZone.forID(timeZoneString)).getMillis();
    String encodedPartition = TimeUtils.encodeTimestamp(partitionDurationMs, pathFormat,
                                                        timeZoneString, timestamp);
    String path = partitioner.generatePartitionedPath("topic", encodedPartition);
    assertEquals("topic/year=2015/month=02/day=01/hour=03/", path);
  }

  private Map<String, Object> createConfig() {
    Map<String, Object> config = new HashMap<>();
    config.put(HdfsSinkConnectorConfig.LOCALE_CONFIG, "en");
    config.put(HdfsSinkConnectorConfig.TIMEZONE_CONFIG, "America/Los_Angeles");
    return config;
  }
}


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

namespace Evbpc.Framework.Windows.Forms
{
    /// <summary>
    /// Provides data for the <see cref="Control.KeyDown"/> or <see cref="Control.KeyUp"/> event.
    /// </summary>
    /// <remarks>
    /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs(v=vs.110).aspx
    /// </remarks>
    public class KeyEventArgs : EventArgs
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyEventArgs"/> class.
        /// </summary>
        /// <param name="keyData">A <see cref="Keys"/> representing the key that was pressed, combined with any modifier flags that indicate which CTRL, SHIFT, and ALT keys were pressed at the same time. Possible values are obtained be applying the bitwise OR (|) operator to constants from the Keys enumeration.</param>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keyeventargs(v=vs.110).aspx
        /// </remarks>
        public KeyEventArgs(Keys keyData)
        {
            Shift = false;
            KeyData = keyData;

            if ((KeyData & Keys.Shift) == Keys.Shift)
            {
                KeyData = KeyData ^ Keys.Shift;
                Shift = true;
            }
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets a value indicating whether the ALT key was pressed.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.alt(v=vs.110).aspx
        /// </remarks>
        public virtual bool Alt => (KeyData & Keys.Alt) == Keys.Alt;

        /// <summary>
        /// Gets a value indicating whether the CTRL key was pressed.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.control(v=vs.110).aspx
        /// </remarks>
        public bool Control => (KeyData & Keys.Control) == Keys.Control;

        /// <summary>
        /// Gets or sets a value indicating whether the event was handled.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled(v=vs.110).aspx
        /// </remarks>
        public bool Handled { get; set; }

        /// <summary>
        /// Gets the keyboard code for a <see cref="Control.KeyDown"/> or <see cref="Control.KeyUp"/> event.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keycode(v=vs.110).aspx
        /// </remarks>
        public Keys KeyCode => KeyData;

        /// <summary>
        /// Gets the key data for a <see cref="Control.KeyDown"/> or <see cref="Control.KeyUp"/> event.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keydata(v=vs.110).aspx
        /// </remarks>
        public Keys KeyData { get; }

        /// <summary>
        /// Gets the keyboard value for a <see cref="Control.KeyDown"/> or <see cref="Control.KeyUp"/> event.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keyvalue(v=vs.110).aspx
        /// </remarks>
        public int KeyValue => (int)KeyData;

        /// <summary>
        /// Gets the modifier flags for a <see cref="Control.KeyDown"/> or <see cref="Control.KeyUp"/> event. The flags indicate which combination of CTRL, SHIFT, and ALT keys was pressed.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers(v=vs.110).aspx
        /// </remarks>
        public Keys Modifiers => KeyData & Keys.Modifiers;

        /// <summary>
        /// Gets a value indicating whether the SHIFT key was pressed.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.shift(v=vs.110).aspx
        /// </remarks>
        public virtual bool Shift { get; }

        /// <summary>
        /// Gets or sets a value indicating whether the key event should be passed on to the underlying control.
        /// </summary>
        /// <remarks>
        /// https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.suppresskeypress(v=vs.110).aspx
        /// </remarks>
        public bool SuppressKeyPress { get; set; }
        #endregion
    }
}


text:
namespace app_list {
class AppListViewDelegate;
}

namespace aura {
class Window;
}

namespace views {
class Widget;
}

namespace ash {

class LauncherDelegate;
class LauncherModel;
struct LauncherItem;
class ScreenshotDelegate;
class SystemTray;
class SystemTrayDelegate;
class UserWallpaperDelegate;

// Delegate of the Shell.
class ASH_EXPORT ShellDelegate {
 public:
  // The Shell owns the delegate.
  virtual ~ShellDelegate() {}

  // Returns true if user has logged in.
  virtual bool IsUserLoggedIn() = 0;

  // Invoked when a user locks the screen.
  virtual void LockScreen() = 0;

  // Unlock the screen. Currently used only for tests.
  virtual void UnlockScreen() = 0;

  // Returns true if the screen is currently locked.
  virtual bool IsScreenLocked() const = 0;

  // Shuts down the environment.
  virtual void Shutdown() = 0;

  // Invoked when the user uses Ctrl-Shift-Q to close chrome.
  virtual void Exit() = 0;

  // Invoked when the user uses Ctrl-N or Ctrl-Shift-N to open a new window.
  virtual void NewWindow(bool incognito) = 0;

  // Invoked when the user presses the Search key.
  virtual void Search() = 0;

  // Invoked when the user uses Ctrl-M to open file manager.
  virtual void OpenFileManager() = 0;

  // Invoked when the user opens Crosh.
  virtual void OpenCrosh() = 0;

  // Invoked when the user needs to set up mobile networking.
  virtual void OpenMobileSetup() = 0;

  // Get the current browser context. This will get us the current profile.
  virtual content::BrowserContext* GetCurrentBrowserContext() = 0;

  // Invoked when the user presses a shortcut to toggle spoken feedback
  // for accessibility.
  virtual void ToggleSpokenFeedback() = 0;

  // Invoked to create an AppListViewDelegate. Shell takes the ownership of
  // the created delegate.
  virtual app_list::AppListViewDelegate* CreateAppListViewDelegate() = 0;

  // Invoked to start taking partial screenshot.
  virtual void StartPartialScreenshot(
      ScreenshotDelegate* screenshot_delegate) = 0;

  // Creates a new LauncherDelegate. Shell takes ownership of the returned
  // value.
  virtual LauncherDelegate* CreateLauncherDelegate(
      ash::LauncherModel* model) = 0;

  // Creates a system-tray delegate. Shell takes ownership of the delegate.
  virtual SystemTrayDelegate* CreateSystemTrayDelegate(SystemTray* tray) = 0;

  // Creates a user wallpaper delegate. Shell takes ownership of the delegate.
  virtual UserWallpaperDelegate* CreateUserWallpaperDelegate() = 0;
};

}  // namespace ash

#endif  // ASH_SHELL_DELEGATE_H_


text:
namespace ke { namespace log
{
    using namespace spdlog; // alias the spdlog namespace to make it our own.
}}

namespace ke
{

    class Log
    {
    public:

#ifdef RUN_UNIT_TESTS
        using log_factory = ke::log::default_factory;
#else
        using log_factory = ke::log::async_factory;
#endif // RUN_UNIT_TESTS

        /// <summary>
        /// Obtain the default logger object.
        /// </summary>
        /// <returns>The logger instance.</returns>
        inline static auto instance() -> auto
        {
            static auto logger = ke::log::stdout_color_mt<log_factory>("default"); // logger object is only constructed when this function is called.
            //return ke::log::get("General");
            return logger;
        }

        /// <summary>
        /// Create an unshared logger object with the given name and default settings.
        /// </summary>
        /// <param name="p_loggerName"></param>
        /// <returns></returns>
        inline static auto createDefaultLogger(char const* const p_loggerName) -> auto
        {
            assert(p_loggerName);
            auto sink = std::make_shared<ke::log::sinks::stdout_color_sink_mt>();

#ifdef RUN_UNIT_TESTS
            auto logger = std::make_shared<ke::log::logger>(p_loggerName, sink);
#else
            // initialise the default spdlog thread pool if it hasn't been created.
            static bool threadpool_init = false;
            static std::mutex tp_lock;
            if (!threadpool_init)
            {
                std::scoped_lock<std::mutex> lock(tp_lock);
                if (!threadpool_init)
                {
                    ke::log::init_thread_pool(8192, 1);  // default values from spdlog doc.
                    threadpool_init = true;
                }
            }

            auto logger = std::make_shared<ke::log::async_logger>(p_loggerName, sink, ke::log::thread_pool());
#endif // RUN_UNIT_TESTS

            return logger;
        }

        inline static auto instance(char const* const p_loggerName) -> auto
        {
            if (p_loggerName == std::string("default"))
            {
                return instance();
            }
            return ke::log::get(p_loggerName);
        }
    };
}


text:
package topotests

import (
	"strings"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/golang/protobuf/proto"
	"vitess.io/vitess/go/vt/topo"
	"vitess.io/vitess/go/vt/topo/memorytopo"

	topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)

// waitForInitialSrvKeyspace waits for the initial SrvKeyspace to
// appear, and match the provided srvKeyspace.
func waitForInitialSrvKeyspace(t *testing.T, ts *topo.Server, cell, keyspace string) (current *topo.WatchSrvKeyspaceData, changes <-chan *topo.WatchSrvKeyspaceData, cancel topo.CancelFunc) {
	ctx := context.Background()
	start := time.Now()
	for {
		current, changes, cancel = ts.WatchSrvKeyspace(ctx, cell, keyspace)
		switch {
		case topo.IsErrType(current.Err, topo.NoNode):
			// hasn't appeared yet
			if time.Now().Sub(start) > 10*time.Second {
				t.Fatalf("time out waiting for file to appear")
			}
			time.Sleep(10 * time.Millisecond)
			continue
		case current.Err == nil:
			return
		default:
			t.Fatalf("watch failed: %v", current.Err)
		}
	}
}

func TestWatchSrvKeyspaceNoNode(t *testing.T) {
	cell := "cell1"
	keyspace := "ks1"
	ctx := context.Background()
	ts := memorytopo.NewServer(cell)

	// No SrvKeyspace -> ErrNoNode
	current, _, _ := ts.WatchSrvKeyspace(ctx, cell, keyspace)
	if !topo.IsErrType(current.Err, topo.NoNode) {
		t.Errorf("Got invalid result from WatchSrvKeyspace(not there): %v", current.Err)
	}
}

func TestWatchSrvKeyspace(t *testing.T) {

	cell := "cell1"
	keyspace := "ks1"
	ctx := context.Background()
	ts := memorytopo.NewServer(cell)

	// Create initial value
	if err := ts.UpdateSrvKeyspace(ctx, cell, keyspace, &topodatapb.SrvKeyspace{}); err != nil {
		t.Fatalf("Update(/keyspaces/ks1/SrvKeyspace) failed: %v", err)
	}

	// Starting the watch should now work, and return an empty
	// SrvKeyspace.
	wanted := &topodatapb.SrvKeyspace{}
	current, changes, cancel := waitForInitialSrvKeyspace(t, ts, cell, keyspace)
	if !proto.Equal(current.Value, wanted) {
		t.Fatalf("got bad data: %v expected: %v", current.Value, wanted)
	}

	// Update the value with good data, wait until we see it
	wanted.ShardingColumnName = "scn1"
	if err := ts.UpdateSrvKeyspace(ctx, cell, keyspace, wanted); err != nil {
		t.Fatalf("Update(/keyspaces/ks1/SrvKeyspace) failed: %v", err)
	}
	for {
		wd, ok := <-changes
		if !ok {
			t.Fatalf("watch channel unexpectedly closed")
		}
		if wd.Err != nil {
			t.Fatalf("watch channel unexpectedly got error: %v", wd.Err)
		}
		if proto.Equal(wd.Value, wanted) {
			break
		}
		if proto.Equal(wd.Value, &topodatapb.SrvKeyspace{}) {
			t.Log("got duplicate empty value, skipping.")
		}
		t.Fatalf("got bad data: %v expected: %v", wd.Value, wanted)
	}

	// Update the value with bad data, wait until error.
	conn, err := ts.ConnForCell(ctx, cell)
	if err != nil {
		t.Fatalf("ConnForCell failed: %v", err)
	}
	if _, err := conn.Update(ctx, "/keyspaces/"+keyspace+"/SrvKeyspace", []byte("BAD PROTO DATA"), nil); err != nil {
		t.Fatalf("Update(/keyspaces/ks1/SrvKeyspace) failed: %v", err)
	}
	for {
		wd, ok := <-changes
		if !ok {
			t.Fatalf("watch channel unexpectedly closed")
		}
		if wd.Err != nil {
			if strings.Contains(wd.Err.Error(), "error unpacking SrvKeyspace object") {
				break
			}
			t.Fatalf("watch channel unexpectedly got unknown error: %v", wd.Err)
		}
		if !proto.Equal(wd.Value, wanted) {
			t.Fatalf("got bad data: %v expected: %v", wd.Value, wanted)
		}
		t.Log("got duplicate right value, skipping.")
	}

	// Cancel should still work here, although it does nothing.
	cancel()

	// Bad data in topo, setting the watch should now fail.
	current, changes, cancel = ts.WatchSrvKeyspace(ctx, cell, keyspace)
	if current.Err == nil || !strings.Contains(current.Err.Error(), "error unpacking initial SrvKeyspace object") {
		t.Fatalf("expected an initial error setting watch on bad content, but got: %v", current.Err)
	}

	// Update content, wait until Watch works again
	if err := ts.UpdateSrvKeyspace(ctx, cell, keyspace, wanted); err != nil {
		t.Fatalf("UpdateSrvKeyspace() failed: %v", err)
	}
	start := time.Now()
	for {
		current, changes, cancel = ts.WatchSrvKeyspace(ctx, cell, keyspace)
		if current.Err != nil {
			if strings.Contains(current.Err.Error(), "error unpacking initial SrvKeyspace object") {
				// hasn't changed yet
				if time.Now().Sub(start) > 10*time.Second {
					t.Fatalf("time out waiting for file to appear")
				}
				time.Sleep(10 * time.Millisecond)
				continue
			}
			t.Fatalf("got unexpected error while setting watch: %v", err)
		}
		if !proto.Equal(current.Value, wanted) {
			t.Fatalf("got bad data: %v expected: %v", current.Value, wanted)
		}
		break
	}

	// Delete node, wait for error (skip any duplicate).
	if err := ts.DeleteSrvKeyspace(ctx, cell, keyspace); err != nil {
		t.Fatalf("DeleteSrvKeyspace() failed: %v", err)
	}
	for {
		wd, ok := <-changes
		if !ok {
			t.Fatalf("watch channel unexpectedly closed")
		}
		if topo.IsErrType(wd.Err, topo.NoNode) {
			break
		}
		if wd.Err != nil {
			t.Fatalf("watch channel unexpectedly got unknown error: %v", wd.Err)
		}
		if !proto.Equal(wd.Value, wanted) {
			t.Fatalf("got bad data: %v expected: %v", wd.Value, wanted)
		}
		t.Log("got duplicate right value, skipping.")
	}
}

func TestWatchSrvKeyspaceCancel(t *testing.T) {
	cell := "cell1"
	keyspace := "ks1"
	ctx := context.Background()
	ts := memorytopo.NewServer(cell)

	// No SrvKeyspace -> ErrNoNode
	current, changes, cancel := ts.WatchSrvKeyspace(ctx, cell, keyspace)
	if !topo.IsErrType(current.Err, topo.NoNode) {
		t.Errorf("Got invalid result from WatchSrvKeyspace(not there): %v", current.Err)
	}

	// Create initial value
	wanted := &topodatapb.SrvKeyspace{
		ShardingColumnName: "scn2",
	}
	if err := ts.UpdateSrvKeyspace(ctx, cell, keyspace, wanted); err != nil {
		t.Fatalf("UpdateSrvKeyspace() failed: %v", err)
	}

	// Starting the watch should now work.
	current, changes, cancel = waitForInitialSrvKeyspace(t, ts, cell, keyspace)
	if !proto.Equal(current.Value, wanted) {
		t.Fatalf("got bad data: %v expected: %v", current.Value, wanted)
	}

	// Cancel watch, wait for error.
	cancel()
	for {
		wd, ok := <-changes
		if !ok {
			t.Fatalf("watch channel unexpectedly closed")
		}
		if topo.IsErrType(wd.Err, topo.Interrupted) {
			break
		}
		if wd.Err != nil {
			t.Fatalf("watch channel unexpectedly got unknown error: %v", wd.Err)
		}
		if !proto.Equal(wd.Value, wanted) {
			t.Fatalf("got bad data: %v expected: %v", wd.Value, wanted)
		}
		t.Log("got duplicate right value, skipping.")
	}

	// Cancel should still work here, although it does nothing.
	cancel()
}


text:
/**
 *
 */
package org.jivesoftware.smack.tcp.client;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author paridhika
 *
 */
public abstract class abstractClientWrapper {
	protected static SortedMap<Double, String> filled_slots_map = Collections.synchronizedSortedMap(new TreeMap<Double, String>());
	protected static List<String> empty_slots_list = Collections.synchronizedList(new ArrayList<String>());
	private static int SIZE = 100;
	protected static int count = 5;
	protected String time[] = new String[2*count];
	protected double mean_wait_time = 3;

	public static void initializeEmptySet(){
		for(int i = 0; i<SIZE; i++){
			for(int j = 0; j < SIZE; j++){
				empty_slots_list.add(i+","+j);
			}
		}
	}

	protected void writeTocsvFile(FileWriter service_time, FileWriter result, double mean,int count) throws IOException{

		//Write the CSV file header
		double avg_service_time = 0;
		service_time.append("Mean");
		service_time.append(",");
		service_time.append("Count");
		service_time.append(",");
		service_time.append("Service Time");
		for(int i = 0; i < count; i++){
			service_time.append("\n");
			service_time.append(String.valueOf(mean));
			service_time.append(",");
			service_time.append(String.valueOf(i));
			service_time.append(",");
			service_time.append(time[i]);
			avg_service_time += Double.parseDouble(time[i]);
		}
		service_time.flush();
		service_time.close();
		result.append("Arrival Rate");
		result.append(",");
		result.append("Service Time");
		result.append(",");
		result.append("Throughput");
		result.append("\n");
		result.append(String.valueOf(mean));
		result.append(",");
		result.append(String.valueOf(avg_service_time/count));
		result.append(",");
		result.append(String.valueOf(count*3600/avg_service_time));
		result.flush();
		result.close();
	}

}


text:
all: resume.pdf

resume.pdf: content.xml styles.xml
	@./run.sh

clean:
	@./run.sh clean


text:
from django.apps import AppConfig
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

class PublicBodyConfig(AppConfig):
    name = 'froide.publicbody'
    verbose_name = _('Public Body')

    def ready(self):
        from froide.account import account_merged
        from froide.account.export import registry
        from froide.helper.search import search_registry
        from .utils import export_user_data

        registry.register(export_user_data)
        account_merged.connect(merge_user)
        search_registry.register(add_search)

def add_search(request):
    return {
        'name': 'publicbody',
        'title': _('Public Bodies'),
        'url': reverse('publicbody-list')
    }

def merge_user(sender, old_user=None, new_user=None, **kwargs):
    from froide.account.utils import move_ownership
    from .models import PublicBody, ProposedPublicBody

    mapping = [
        (PublicBody, '_created_by'),
        (PublicBody, '_updated_by'),
        (ProposedPublicBody, '_created_by'),
        (ProposedPublicBody, '_updated_by'),
    ]

    for model, attr in mapping:
        move_ownership(model, attr, old_user, new_user)


text:
template <typename T>
constexpr T NI_CACHELINE_SIZE = T(64);

#define NI_CACHELINE_ALIGNED alignas(NI_CACHELINE_SIZE<size_t>)

#define NI_PADDING_AFTER(size)                                                 \
  static_assert((size) % NI_CACHELINE_SIZE<size_t> != 0,                       \
                "No need to add padding here!");                               \
  char NI_NEW_VAR(                                                             \
    padding_)[NI_CACHELINE_SIZE<size_t> - (size) % NI_CACHELINE_SIZE<size_t>]


text:
#include "platform/mbed_assert.h"
#include <stdio.h>
#include <stdbool.h>

bool mbed_assert_throw_errors = false;

extern "C" void mbed_assert_internal(const char *expr, const char *file, int line)
{
    fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
    if (mbed_assert_throw_errors) {
        throw 1;
    }
}


text:
/*****  String Representation Type Handler  *****/

/***************************
 *****  Facility Name  *****
 ***************************/

#define FacilityName rtSTRING

/******************************************
 *****  Header and Declaration Files  *****
 ******************************************/

/*****  System  *****/
#include "Vk.h"

/*****  Facility  *****/
#include "m.h"
#include "rslang.h"

#include "venvir.h"
#include "verr.h"
#include "vfac.h"
#include "vstdio.h"
#include "vutil.h"

#include "RTdictionary.h"

/*****  Self  *****/
#include "RTstring.h"

/******************************
 ******************************
 *****                    *****
 *****  Container Handle  *****
 *****                    *****
 ******************************
 ******************************/

/***************************
 ***************************
 *****  Run Time Type  *****
 ***************************
 ***************************/

DEFINE_CONCRETE_RTT (rtSTRING_Handle);

/*************************************************
 *****  Standard CPD Initialization Routine  *****
 *************************************************/

/*---------------------------------------------------------------------------
 *****  Internal routine to initialize a standard CPD for a string.
 *
 *  Argument:
 *	cpd			- the address of the standard CPD to be
 *				  initialized.
 *
 *  Returns:
 *	'cpd'
 *
 *****/
PrivateFnDef void InitStdCPD (M_CPD *cpd) {
    char *string = M_CPD_ContainerBase (cpd);

    rtSTRING_CPD_End (cpd) = (rtSTRING_CPD_Begin (cpd) = string) + strlen (string);
}

/************************************
 *****  Instantiation Routines  *****
 ************************************/

/******************
 *  Instantiator  *
 ******************/

/*---------------------------------------------------------------------------
 *****  Routine to create a new String.
 *
 *  Argument:
 *	string			- the string value for the standard String CPD
 *				  to have.  This string MUST be null delimited.
 *
 *  Returns:
 *	A Standard String CPD for the String created.
 *
 *****/
PublicFnDef M_CPD *rtSTRING_New (M_ASD *pContainerSpace, char const *string) {
    M_CPD *cpd = pContainerSpace->CreateContainer (
	RTYPE_C_String, strlen (string) + 1
    );

    strcpy (rtSTRING_CPD_Begin (cpd) = M_CPD_ContainerBase (cpd), string);
    rtSTRING_CPD_End (cpd) = rtSTRING_CPD_Begin (cpd) + strlen (string);

    return cpd;
}

PublicFnDef M_CPD *rtSTRING_New (char const *pString) {
    return rtSTRING_New (IOBJ_ScratchPad, pString);
}

/*****************************************
 *****  String Manipulation Routines *****
 *****************************************/

/************
 *  Append  *
 ************/

/*---------------------------------------------------------------------------
 *****  Routine to append to a string.
 *
 *  Argument:
 *	orig_cpd		- the address of a standard String CPD for the
 *				  String to be appended to.
 *	new_str			- the address for the string to append to the
 *				  end of the orig_cpd.  This string MUST be
 *				  null delimited.
 *
 *  Returns:
 *	'orig_CPD'
 *
 *****/
PublicFnDef M_CPD *rtSTRING_Append (M_CPD *orig_cpd, char const *new_str) {
    size_t new_sz = strlen (new_str);
    if (new_sz == 0)
	return orig_cpd;

    size_t sz = rtSTRING_CPD_Size (orig_cpd) + new_sz;
    if (sz+1 > (int) M_CPD_Size (orig_cpd))
        orig_cpd->ReallocateContainer (sz+1024);
    memcpy (rtSTRING_CPD_End (orig_cpd), new_str, new_sz);
    rtSTRING_CPD_Begin (orig_cpd)[sz] = '\0';
    rtSTRING_CPD_End (orig_cpd) = rtSTRING_CPD_Begin (orig_cpd) + sz;

    return orig_cpd;
}

/**********
 *  Trim  *
 **********/

/*---------------------------------------------------------------------------
 *****  Routine to remove spaces from the beginning and end of a string.
 *
 *  Argument:
 *	orig_cpd		- the address of a standard String CPD to be
 *				  trimmed.
 *
 *  Returns:
 *	'orig_CPD'
 *
 *  Note:
 *	This routine does NOT give back unused space to the memory manager.
 *
 *****/
PublicFnDef M_CPD *rtSTRING_Trim (M_CPD *orig_cpd) {
    char *str, *sptr, *eptr;

    RTYPE_MustBeA ("rtSTRING_Trim", M_CPD_RType (orig_cpd), RTYPE_C_String);
    str = rtSTRING_CPD_Begin (orig_cpd);

    for (sptr = str; isspace (*sptr); sptr++);

    for (eptr = sptr + strlen (sptr);
	 eptr > sptr && isspace (*(eptr - 1));
	 eptr--);

    *eptr = '\0';
    strcpy (str, sptr);

    return orig_cpd;
}

/*******************************************************************
 *****  Standard Representation Type Handler Service Routines  *****
 *******************************************************************/

/********************
 *  Print Function  *
 ********************/

/*---------------------------------------------------------------------------
 *****  Routine to display a String.
 *
 *  Arguments:
 *	cpd			- the address of a standard CPD for the string
 *				  to be displayed.
 *	full			- a boolean,  if true prints string size
 *				  information in addition to the string value.
 *
 *  Returns:
 *	NOTHING
 *
 *****/
PrivateFnDef void PrintString (M_CPD *cpd, int full) {
    if (full) {
	IO_printf ("String[%u]{", rtSTRING_CPD_Size (cpd));
	IO_puts (rtSTRING_CPD_Begin (cpd));
	IO_puts ("}");
    }
    else IO_puts (rtSTRING_CPD_Begin (cpd));
}

/***************************************
 *****  Internal Debugger Methods  *****
 ***************************************/

/************************
 *  'Instance' Methods  *
 ************************/

IOBJ_DefineUnaryMethod (Size_DM) {
    M_CPD *cpd = RTYPE_QRegisterCPD (self);

    return IOBJ_IntIObject (rtSTRING_CPD_Size (cpd));
}

IOBJ_DefineMethod (Append_DM) {
    M_CPD *newTailCPD = RTYPE_QRegisterCPD (parameterArray[0]);

    RTYPE_MustBeA (
	"'append:' Debug Method", M_CPD_RType (newTailCPD), RTYPE_C_String
    );

    rtSTRING_Append (
	RTYPE_QRegisterCPD (self), rtSTRING_CPD_Begin (newTailCPD)
    );

    return self;
}

IOBJ_DefineUnaryMethod (Compile_DM) {
    M_CPD *pSource = RTYPE_QRegisterCPD (self);
    M_CPD *pDictionary = rtDICTIONARY_New (IOBJ_ScratchPad);
    M_CPD *pProgram = RSLANG_Compile (
	IOBJ_ScratchPad, rtSTRING_CPD_Begin (pSource), pDictionary
    );
    pDictionary->release ();

    return pProgram ? RTYPE_QRegister (pProgram) : IOBJ_TheNilIObject;
}

/**************************************************
 *****  Representation Type Handler Function  *****
 **************************************************/

RTYPE_DefineHandler(rtSTRING_Handler) {
    IOBJ_BeginMD (typeMD)
	IOBJ_MDE ("qprint"	, RTYPE_DisplayTypeIObject)
	IOBJ_MDE ("print"	, RTYPE_DisplayTypeIObject)
    IOBJ_EndMD;

    IOBJ_BeginMD (instanceMD)
	RTYPE_StandardDMDEPackage
	IOBJ_MDE ("size"	, Size_DM)
	IOBJ_MDE ("append:"	, Append_DM)
	IOBJ_MDE ("compile"	, Compile_DM)
    IOBJ_EndMD;

    switch (handlerOperation) {
    case RTYPE_InitializeMData: {
	    M_RTD *rtd = iArgList.arg<M_RTD*>();
	    rtd->SetCPDPointerCountTo	(rtSTRING_CPD_StdPtrCount);
	    M_RTD_CPDInitFn		(rtd) = InitStdCPD;
	    M_RTD_HandleMaker		(rtd) = &rtSTRING_Handle::Maker;
	}
        break;
    case RTYPE_TypeMD:
        *iArgList.arg<IOBJ_MD *>() = typeMD;
        break;
    case RTYPE_InstanceMD:
        *iArgList.arg<IOBJ_MD *>() = instanceMD;
        break;
    case RTYPE_QPrintObject:
	PrintString (iArgList.arg<M_CPD*>(), false);
        break;
    case RTYPE_RPrintObject:
	PrintString (iArgList.arg<M_CPD*>(), true);
        break;
    default:
        return -1;
    }
    return 0;
}

/*********************************
 *****  Facility Definition  *****
 *********************************/

FAC_DefineFacility {
    switch (FAC_RequestTypeField) {
    FAC_FDFCase_FacilityIdAsString (rtSTRING);
    FAC_FDFCase_FacilityDescription ("String Representation Type Handler");
    default:
        break;
    }
}

/************************** SOURCE FILE HISTORY: ************************/
/************************************************************************
  RTstring.c 1 replace /users/jad
  860326 19:54:28 jad creation

 ************************************************************************/
/************************************************************************
  RTstring.c 2 replace /users/jad
  860327 19:11:13 jad made append check the size before asking for more

 ************************************************************************/
/************************************************************************
  RTstring.c 3 replace /users/mjc/system
  860412 13:14:06 mjc Added standard CPD declarations, fixed string stuff

 ************************************************************************/
/************************************************************************
  RTstring.c 4 replace /users/mjc/system
  860412 18:10:57 mjc Deleted terminating CR on debugger display

 ************************************************************************/
/************************************************************************
  RTstring.c 5 replace /users/mjc/system
  860414 12:29:56 mjc Delete 'Browser' initialization from M_InitializeMData case

 ************************************************************************/
/************************************************************************
  RTstring.c 6 replace /users/hjb/system
  860423 00:40:07 hjb done updating calls

 ************************************************************************/
/************************************************************************
  RTstring.c 7 replace /users/mjc/system
  860504 00:00:13 mjc Added 'compile' and 'append:' messages

 ************************************************************************/
/************************************************************************
  RTstring.c 8 replace /users/jad/system
  860513 15:15:20 jad added Trim routine to remove spaces from
both end of a RTstring.

 ************************************************************************/
/************************************************************************
  RTstring.c 9 replace /users/mjc/system
  860526 20:32:55 mjc Return vmachine invocation changes

 ************************************************************************/
/************************************************************************
  RTstring.c 10 replace /users/mjc/system
  860531 10:43:00 mjc Changed 'RSLANG_Compile' to pick up its method dictionary from 'envir'

 ************************************************************************/
/************************************************************************
  RTstring.c 11 replace /users/mjc/system
  860625 17:07:40 mjc Converted 'print' message to produce a more natural representation

 ************************************************************************/
/************************************************************************
  RTstring.c 12 replace /users/mjc/system
  860817 20:15:49 mjc Converted CPD initializer/instantiator/gc routines to expect nothing of new CPDs

 ************************************************************************/
/************************************************************************
  RTstring.c 13 replace /users/jck/system
  870415 09:53:39 jck Release of M_SwapContainers, including changes to
all rtype's 'InitStdCPD' functions. Instead of being void, they now return
a cpd

 ************************************************************************/
/************************************************************************
  RTstring.c 14 replace /users/mjc/translation
  870524 09:35:19 mjc Shortened all identifiers to <= 31 characters

 ************************************************************************/
/************************************************************************
  RTstring.c 15 replace /users/jck/system
  880114 16:11:12 jck Optimized rtSTRING_Append and added short-term fix to PrintString

 ************************************************************************/
/************************************************************************
  RTstring.c 16 replace /users/jck/system
  880419 07:42:25 jck Removed a temporary fix that had circumvented a VAX printf Bug (since fixed by DEC)

 ************************************************************************/
/************************************************************************
  RTstring.c 17 replace /users/m2/backend
  890503 14:52:26 m2 IO_puts() changes

 ************************************************************************/


text:
layout: post
title: "API view from Security Officer perspective"
modified: 2015-08-17T23:31:04+01:00
categories: API API_Security API_Management
permalink: /API-view-from-security-officer-perspective
excerpt:From Security Officer perspective, the different needs for a successful API Management implementation
tags: [API Roles, API Security, API Management, API Success]
image:
  feature:
date: 2015-07-15T19:23:02+01:00
---

Advancing from beginning of I.T. we've been constructing walls, dams, fences, nonces and weapons to defend outer limits of the company from any attack, and even doing business close to those barriers has been a nightmare.

One of the takes from API Management is to make barriers permeable to allow making more and better business. Anyway this has to be taken totally seriously, permeable is not meaning clear and open, but easy to integrate with by using APIs. And this without making a bigger trouble from security perspective, at the end Business perspective.

Which are the common considerations that a Security officer will keep an eye on when talking about API Management ?

One of the first topics to worry about is the channel security between API client and API server. This is usually managed by using SSL over http, there a couple of elements to take here:

+ Although SSL over http might be found secure, it's possible to have intruders using MITM (man in the middle) attack vectors.
+ Depending on the case ( internal APIs / partner APIs ), only certain predefined consumers will be allowed to access the APIs.
+ Other interesting axe regarding channel security is the possibility to forbid usage of broken algorithms in SSL handshake.

Once first line of defence considerations are taken, another worries come into scene when exposing APIs:

+ Is API data manipulated secure?
+ Is API data manipulated allowed to be manipulated?
+ Apart from authentication of API caller, course grain authorization and fine grain authorization.
+ What about API data returned, does it contain information that shouldn't be leaked from our company?

And that's all, isn't it?

Life from a security officer shouldn't be as easy as it seems, don't forget to check that the devices in exposing those business assets (APIs) are secure themselves, and many other topics that cannot be covered in a single post, stay tunned.


text:
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/comprehend/model/DocumentClassifierProperties.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Comprehend
{
namespace Model
{
  class AWS_COMPREHEND_API ListDocumentClassifiersResult
  {
  public:
    ListDocumentClassifiersResult();
    ListDocumentClassifiersResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListDocumentClassifiersResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
A list containing the properties of each job returned.

     */
    inline const Aws::Vector<DocumentClassifierProperties>& GetDocumentClassifierPropertiesList() const{ return m_documentClassifierPropertiesList; }

    /**
     *
A list containing the properties of each job returned.

     */
    inline void SetDocumentClassifierPropertiesList(const Aws::Vector<DocumentClassifierProperties>& value) { m_documentClassifierPropertiesList = value; }

    /**
     *
A list containing the properties of each job returned.

     */
    inline void SetDocumentClassifierPropertiesList(Aws::Vector<DocumentClassifierProperties>&& value) { m_documentClassifierPropertiesList = std::move(value); }

    /**
     *
A list containing the properties of each job returned.

     */
    inline ListDocumentClassifiersResult& WithDocumentClassifierPropertiesList(const Aws::Vector<DocumentClassifierProperties>& value) { SetDocumentClassifierPropertiesList(value); return *this;}

    /**
     *
A list containing the properties of each job returned.

     */
    inline ListDocumentClassifiersResult& WithDocumentClassifierPropertiesList(Aws::Vector<DocumentClassifierProperties>&& value) { SetDocumentClassifierPropertiesList(std::move(value)); return *this;}

    /**
     *
A list containing the properties of each job returned.

     */
    inline ListDocumentClassifiersResult& AddDocumentClassifierPropertiesList(const DocumentClassifierProperties& value) { m_documentClassifierPropertiesList.push_back(value); return *this; }

    /**
     *
A list containing the properties of each job returned.

     */
    inline ListDocumentClassifiersResult& AddDocumentClassifierPropertiesList(DocumentClassifierProperties&& value) { m_documentClassifierPropertiesList.push_back(std::move(value)); return *this; }

    /**
     *
Identifies the next page of results to return.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
Identifies the next page of results to return.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
Identifies the next page of results to return.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
Identifies the next page of results to return.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
Identifies the next page of results to return.

     */
    inline ListDocumentClassifiersResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
Identifies the next page of results to return.

     */
    inline ListDocumentClassifiersResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
Identifies the next page of results to return.

     */
    inline ListDocumentClassifiersResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<DocumentClassifierProperties> m_documentClassifierPropertiesList;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace Comprehend
} // namespace Aws


text:
<?php

/**
 * Very basic 'py.test' unit test engine wrapper.
 */
final class PytestTestEngine extends ArcanistUnitTestEngine {

  private $projectRoot;

  public function run() {
    $working_copy = $this->getWorkingCopy();
    $this->projectRoot = $working_copy->getProjectRoot();

    $junit_tmp = new TempFile();
    $cover_tmp = new TempFile();

    $future = $this->buildTestFuture($junit_tmp, $cover_tmp);
    list($err, $stdout, $stderr) = $future->resolve();

    if (!Filesystem::pathExists($junit_tmp)) {
      throw new CommandException(
        pht('Command failed with error #%s!', $err),
        $future->getCommand(),
        $err,
        $stdout,
        $stderr);
    }

    $future = new ExecFuture('coverage xml -o %s', $cover_tmp);
    $future->setCWD($this->projectRoot);
    $future->resolvex();

    return $this->parseTestResults($junit_tmp, $cover_tmp);
  }

  public function buildTestFuture($junit_tmp, $cover_tmp) {
    $paths = $this->getPaths();

    $cmd_line = csprintf('py.test --junit-xml=%s', $junit_tmp);

    if ($this->getEnableCoverage() !== false) {
      $cmd_line = csprintf(
        'coverage run --source %s -m %C',
        $this->projectRoot,
        $cmd_line);
    }

    return new ExecFuture('%C', $cmd_line);
  }

  public function parseTestResults($junit_tmp, $cover_tmp) {
    $parser = new ArcanistXUnitTestResultParser();
    $results = $parser->parseTestResults(
      Filesystem::readFile($junit_tmp));

    if ($this->getEnableCoverage() !== false) {
      $coverage_report = $this->readCoverage($cover_tmp);
      foreach ($results as $result) {
          $result->setCoverage($coverage_report);
      }
    }

    return $results;
  }

  public function readCoverage($path) {
    $coverage_data = Filesystem::readFile($path);
    if (empty($coverage_data)) {
       return array();
    }

    $coverage_dom = new DOMDocument();
    $coverage_dom->loadXML($coverage_data);

    $paths = $this->getPaths();
    $reports = array();
    $classes = $coverage_dom->getElementsByTagName('class');

    foreach ($classes as $class) {
      // filename is actually python module path with ".py" at the end,
      // e.g.: tornado.web.py
      $relative_path = explode('.', $class->getAttribute('filename'));
      array_pop($relative_path);
      $relative_path = implode('/', $relative_path);

      // first we check if the path is a directory (a Python package), if it is
      // set relative and absolute paths to have __init__.py at the end.
      $absolute_path = Filesystem::resolvePath($relative_path);
      if (is_dir($absolute_path)) {
        $relative_path .= '/__init__.py';
        $absolute_path .= '/__init__.py';
      }

      // then we check if the path with ".py" at the end is file (a Python
      // submodule), if it is - set relative and absolute paths to have
      // ".py" at the end.
      if (is_file($absolute_path.'.py')) {
        $relative_path .= '.py';
        $absolute_path .= '.py';
      }

      if (!file_exists($absolute_path)) {
        continue;
      }

      if (!in_array($relative_path, $paths)) {
        continue;
      }

      // get total line count in file
      $line_count = count(file($absolute_path));

      $coverage = '';
      $start_line = 1;
      $lines = $class->getElementsByTagName('line');
      for ($ii = 0; $ii < $lines->length; $ii++) {
        $line = $lines->item($ii);

        $next_line = intval($line->getAttribute('number'));
        for ($start_line; $start_line < $next_line; $start_line++) {
            $coverage .= 'N';
        }

        if (intval($line->getAttribute('hits')) == 0) {
            $coverage .= 'U';
        } else if (intval($line->getAttribute('hits')) > 0) {
            $coverage .= 'C';
        }

        $start_line++;
      }

      if ($start_line < $line_count) {
        foreach (range($start_line, $line_count) as $line_num) {
          $coverage .= 'N';
        }
      }

      $reports[$relative_path] = $coverage;
    }

    return $reports;
  }

}


text:
Example for using Elm lang to draw lines chasing the mouse. [For Beginners]

[See the demo](http://stormont.github.io/elm-mouse-chaser/demo.html)

To run it locally:

> git clone https://github.com/stormont/elm-mouse-chaser.git

> cd elm-mouse-chaser

> git checkout 2015.10.27.01

> elm-make src/Main.elm --output=demo.html

Then, open **demo.html** in your web browser.

For a walkthrough, [see my blog post](https://voyageintech.wordpress.com/2015/10/28/mouse-chasing-in-elm-beginners/).